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 autonomous jobs system for proactive CoS operation
Adam Eivy9f495d7426ce
diff --git a/.changelog/v0.11.x.md b/.changelog/v0.11.x.mdindex d6e082ff86..542678cf88 100644--- a/.changelog/v0.11.x.md+++ b/.changelog/v0.11.x.md@@ -116,6 +116,27 @@ This release focuses on security improvements, bug fixes for the AI runner syste- **Priority Preserved**: Dequeue on slot free checks user tasks first, then auto-approved system tasks, maintaining the existing priority order- **Evaluation Interval Preserved**: The periodic evaluation interval continues to handle system task generation, idle reviews, and mission tasks — immediate execution is specifically for dequeuing pending work+### Autonomous Jobs (M37)+- **Recurring Proactive Jobs**: The CoS can now run scheduled recurring jobs on your behalf — maintaining repositories, processing brain ideas, generating daily briefings, and reviewing projects+- **Digital Twin Integration**: Jobs execute using your digital twin identity, so the CoS acts with your preferences and values in mind+- **4 Built-in Jobs**: Ships with Git Repo Maintenance (weekly), Brain Inbox Processing (daily), Daily Briefing (daily), and Brain Project Review (weekly) — all disabled by default for opt-in+- **Jobs Tab UI**: New "Jobs" tab on the `/cos/jobs` page with toggle controls, interval configuration, manual trigger, inline editing, and prompt template visibility+- **Custom Jobs**: Create your own recurring jobs with custom prompt templates, intervals (hourly to monthly), priority levels, and autonomy levels (standby/assistant/manager/yolo)+- **Evaluation Integration**: Due jobs are checked during each CoS evaluation cycle at Priority 3.5 (between missions and idle review), only when no user tasks are pending+- **Full CRUD API**: REST endpoints at `/api/cos/jobs` for listing, creating, updating, toggling, triggering, and deleting jobs++**Files Added**:+- `server/services/autonomousJobs.js` — Job management service with scheduling, execution tracking, and task generation+- `client/src/components/cos/tabs/JobsTab.jsx` — Jobs tab UI component++**Files Modified**:+- `server/services/cos.js` — Added autonomous jobs to evaluation loop (Priority 3.5), added `autonomousJobsEnabled` config+- `server/routes/cos.js` — Added `/api/cos/jobs` REST endpoints+- `client/src/services/api.js` — Added autonomous jobs API functions+- `client/src/components/cos/constants.js` — Added Jobs tab to navigation+- `client/src/components/cos/index.js` — Export JobsTab component+- `client/src/pages/ChiefOfStaff.jsx` — Render Jobs tab+## 🔧 Improvements### Live Output Streaming for Claude CLI Agentsdiff --git a/PLAN.md b/PLAN.mdindex 15ccc35bdf..c5b4bd42cd 100644--- a/PLAN.md+++ b/PLAN.md@@ -63,6 +63,7 @@ pm2 logs- [x] **M35**: Chief of Staff Enhancement - Proactive autonomous agent with hybrid memory, missions, LM Studio, thinking levels. See [CoS Enhancement](./docs/features/cos-enhancement.md)- [x] **M35.1**: CoS UI - Added Arcane Sigil (3D) avatar style option alongside Cyberpunk 3D- [x] **M36**: Browser Management - CDP/Playwright browser page with status, controls, config, and logs+- [x] **M37**: Autonomous Jobs - Recurring scheduled jobs that the CoS executes proactively using digital twin identity### Planneddiff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 0c306419c3..6c957be29a 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -7,12 +7,14 @@ import {Settings,Calendar,Clock,- GraduationCap+ GraduationCap,+ Bot} from 'lucide-react';export const TABS = [{ id: 'tasks', label: 'Tasks', icon: FileText },{ id: 'agents', label: 'Agents', icon: Cpu },+ { id: 'jobs', label: 'Jobs', icon: Bot },{ id: 'scripts', label: 'Scripts', icon: Terminal },{ id: 'schedule', label: 'Schedule', icon: Clock },{ id: 'digest', label: 'Digest', icon: Calendar },diff --git a/client/src/components/cos/index.js b/client/src/components/cos/index.jsindex 823fd9d24b..0df33a2472 100644--- a/client/src/components/cos/index.js+++ b/client/src/components/cos/index.js@@ -21,6 +21,7 @@ export { default as EventLog } from './EventLog';// Tab Componentsexport { default as TasksTab } from './tabs/TasksTab';export { default as AgentsTab } from './tabs/AgentsTab';+export { default as JobsTab } from './tabs/JobsTab';export { default as ScriptsTab } from './tabs/ScriptsTab';export { default as ScheduleTab } from './tabs/ScheduleTab';export { default as LearningTab } from './tabs/LearningTab';diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsxnew file mode 100644index 0000000000..e3a5c8168e--- /dev/null+++ b/client/src/components/cos/tabs/JobsTab.jsx@@ -0,0 +1,490 @@+import { useState, useEffect, useCallback } from 'react';+import { Plus, RefreshCw, Play, Trash2, ChevronDown, ChevronUp, Clock, ToggleLeft, ToggleRight, Edit3, Save, X } from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';++const INTERVAL_OPTIONS = [+ { value: 'hourly', label: 'Every Hour' },+ { value: 'every-4-hours', label: 'Every 4 Hours' },+ { value: 'every-8-hours', label: 'Every 8 Hours' },+ { value: 'daily', label: 'Daily' },+ { value: 'weekly', label: 'Weekly' },+ { value: 'biweekly', label: 'Every 2 Weeks' },+ { value: 'monthly', label: 'Monthly' }+];++const PRIORITY_OPTIONS = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];+const AUTONOMY_OPTIONS = [+ { value: 'standby', label: 'Standby', desc: 'Creates tasks but waits for approval' },+ { value: 'assistant', label: 'Assistant', desc: 'Creates tasks, notifies you' },+ { value: 'manager', label: 'Manager', desc: 'Executes tasks autonomously' },+ { value: 'yolo', label: 'YOLO', desc: 'Full autonomy, no guardrails' }+];++function formatTimeAgo(dateStr) {+ if (!dateStr) return 'Never';+ const diff = Date.now() - new Date(dateStr).getTime();+ const hours = Math.floor(diff / 3600000);+ const days = Math.floor(hours / 24);+ if (days > 0) return `${days}d ago`;+ if (hours > 0) return `${hours}h ago`;+ const mins = Math.floor(diff / 60000);+ return mins > 0 ? `${mins}m ago` : 'Just now';+}++function formatNextDue(lastRun, intervalMs) {+ if (!lastRun) return 'Immediately';+ const nextDue = new Date(lastRun).getTime() + intervalMs;+ const diff = nextDue - Date.now();+ if (diff <= 0) return 'Now';+ const hours = Math.floor(diff / 3600000);+ const days = Math.floor(hours / 24);+ if (days > 0) return `in ${days}d`;+ if (hours > 0) return `in ${hours}h`;+ const mins = Math.floor(diff / 60000);+ return `in ${mins}m`;+}++function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {+ const [expanded, setExpanded] = useState(false);+ const [editing, setEditing] = useState(false);+ const [editData, setEditData] = useState({});++ const startEditing = () => {+ setEditData({+ name: job.name,+ description: job.description,+ interval: job.interval,+ priority: job.priority,+ autonomyLevel: job.autonomyLevel,+ promptTemplate: job.promptTemplate+ });+ setEditing(true);+ setExpanded(true);+ };++ const handleSave = async () => {+ await api.updateCosJob(job.id, editData).catch(err => {+ toast.error(err.message);+ return null;+ });+ toast.success('Job updated');+ setEditing(false);+ onUpdate();+ };++ const isDue = job.enabled && (+ !job.lastRun || (Date.now() - new Date(job.lastRun).getTime() >= job.intervalMs)+ );++ return (+ <div className={`bg-port-card border rounded-lg transition-colors ${+ job.enabled ? 'border-port-border' : 'border-port-border/50 opacity-60'+ }`}>+ <div className="flex items-center gap-3 p-4">+ {/* Toggle */}+ <button+ onClick={() => onToggle(job.id)}+ className={`flex-shrink-0 transition-colors ${+ job.enabled ? 'text-port-success' : 'text-gray-600'+ }`}+ title={job.enabled ? 'Disable job' : 'Enable job'}+ >+ {job.enabled ? <ToggleRight size={24} /> : <ToggleLeft size={24} />}+ </button>++ {/* Info */}+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-white font-medium truncate">{job.name}</span>+ {isDue && (+ <span className="px-1.5 py-0.5 bg-port-warning/20 text-port-warning text-xs rounded">+ Due+ </span>+ )}+ <span className="px-1.5 py-0.5 bg-port-bg text-gray-400 text-xs rounded">+ {job.category}+ </span>+ </div>+ <div className="flex items-center gap-3 text-xs text-gray-500 mt-1">+ <span className="flex items-center gap-1">+ <Clock size={10} />+ {INTERVAL_OPTIONS.find(i => i.value === job.interval)?.label || job.interval}+ </span>+ <span>Last: {formatTimeAgo(job.lastRun)}</span>+ {job.enabled && (+ <span className={isDue ? 'text-port-warning' : 'text-gray-500'}>+ Next: {formatNextDue(job.lastRun, job.intervalMs)}+ </span>+ )}+ <span>Runs: {job.runCount || 0}</span>+ </div>+ </div>++ {/* Actions */}+ <div className="flex items-center gap-1">+ <button+ onClick={() => onTrigger(job.id)}+ className="p-1.5 text-gray-500 hover:text-port-accent transition-colors"+ title="Run now"+ >+ <Play size={14} />+ </button>+ <button+ onClick={startEditing}+ className="p-1.5 text-gray-500 hover:text-white transition-colors"+ title="Edit"+ >+ <Edit3 size={14} />+ </button>+ <button+ onClick={() => setExpanded(!expanded)}+ className="p-1.5 text-gray-500 hover:text-white transition-colors"+ >+ {expanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}+ </button>+ </div>+ </div>++ {/* Expanded content */}+ {expanded && (+ <div className="border-t border-port-border p-4 space-y-3">+ {editing ? (+ <>+ <input+ type="text"+ value={editData.name}+ onChange={e => setEditData(d => ({ ...d, name: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ placeholder="Job name"+ />+ <input+ type="text"+ value={editData.description}+ onChange={e => setEditData(d => ({ ...d, description: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ placeholder="Description"+ />+ <div className="flex gap-3">+ <select+ value={editData.interval}+ onChange={e => setEditData(d => ({ ...d, interval: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ {INTERVAL_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value}>{opt.label}</option>+ ))}+ </select>+ <select+ value={editData.priority}+ onChange={e => setEditData(d => ({ ...d, priority: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ {PRIORITY_OPTIONS.map(p => (+ <option key={p} value={p}>{p}</option>+ ))}+ </select>+ <select+ value={editData.autonomyLevel}+ onChange={e => setEditData(d => ({ ...d, autonomyLevel: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ {AUTONOMY_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value}>{opt.label}</option>+ ))}+ </select>+ </div>+ <textarea+ value={editData.promptTemplate}+ onChange={e => setEditData(d => ({ ...d, promptTemplate: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono h-40"+ placeholder="Prompt template for the agent"+ />+ <div className="flex justify-end gap-2">+ <button+ onClick={() => setEditing(false)}+ className="flex items-center gap-1 px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"+ >+ <X size={14} /> Cancel+ </button>+ <button+ onClick={handleSave}+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors"+ >+ <Save size={14} /> Save+ </button>+ </div>+ </>+ ) : (+ <>+ <p className="text-sm text-gray-400">{job.description}</p>+ <div className="flex gap-4 text-xs text-gray-500">+ <span>Priority: <span className="text-gray-300">{job.priority}</span></span>+ <span>Autonomy: <span className="text-gray-300">{job.autonomyLevel}</span></span>+ <span>Created: <span className="text-gray-300">{new Date(job.createdAt).toLocaleDateString()}</span></span>+ </div>+ <details className="group">+ <summary className="text-xs text-gray-500 cursor-pointer hover:text-gray-300 transition-colors">+ View prompt template+ </summary>+ <pre className="mt-2 p-3 bg-port-bg border border-port-border rounded-lg text-xs text-gray-400 font-mono whitespace-pre-wrap max-h-48 overflow-y-auto">+ {job.promptTemplate}+ </pre>+ </details>+ <div className="flex justify-end">+ <button+ onClick={() => onDelete(job.id)}+ className="flex items-center gap-1 px-2 py-1 text-xs text-red-400/60 hover:text-red-400 transition-colors"+ >+ <Trash2 size={12} /> Delete+ </button>+ </div>+ </>+ )}+ </div>+ )}+ </div>+ );+}++export default function JobsTab() {+ const [jobs, setJobs] = useState([]);+ const [stats, setStats] = useState(null);+ const [loading, setLoading] = useState(true);+ const [showCreate, setShowCreate] = useState(false);+ const [newJob, setNewJob] = useState({+ name: '',+ description: '',+ category: 'custom',+ interval: 'daily',+ priority: 'MEDIUM',+ autonomyLevel: 'manager',+ promptTemplate: '',+ enabled: false+ });++ const fetchJobs = useCallback(async () => {+ const data = await api.getCosJobs().catch(err => {+ toast.error(`Failed to load jobs: ${err.message}`);+ return null;+ });+ if (data) {+ setJobs(data.jobs || []);+ setStats(data.stats || null);+ }+ setLoading(false);+ }, []);++ useEffect(() => { fetchJobs(); }, [fetchJobs]);++ const handleCreate = async () => {+ if (!newJob.name.trim() || !newJob.promptTemplate.trim()) {+ toast.error('Name and prompt template are required');+ return;+ }++ await api.createCosJob(newJob).catch(err => {+ toast.error(err.message);+ return null;+ });+ toast.success('Job created');+ setNewJob({+ name: '',+ description: '',+ category: 'custom',+ interval: 'daily',+ priority: 'MEDIUM',+ autonomyLevel: 'manager',+ promptTemplate: '',+ enabled: false+ });+ setShowCreate(false);+ fetchJobs();+ };++ const handleToggle = async (jobId) => {+ const result = await api.toggleCosJob(jobId).catch(err => {+ toast.error(err.message);+ return null;+ });+ if (result) {+ toast.success(result.job.enabled ? 'Job enabled' : 'Job disabled');+ fetchJobs();+ }+ };++ const handleTrigger = async (jobId) => {+ toast.loading('Triggering job...', { id: 'job-trigger' });+ const result = await api.triggerCosJob(jobId).catch(err => {+ toast.error(err.message, { id: 'job-trigger' });+ return null;+ });+ if (result) {+ toast.success('Job triggered — task queued', { id: 'job-trigger' });+ fetchJobs();+ }+ };++ const handleDelete = async (jobId) => {+ await api.deleteCosJob(jobId).catch(err => {+ toast.error(err.message);+ return null;+ });+ toast.success('Job deleted');+ fetchJobs();+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center py-12 text-gray-500">+ Loading autonomous jobs...+ </div>+ );+ }++ return (+ <div className="space-y-6">+ {/* Header */}+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-lg font-semibold text-white">Autonomous Jobs</h3>+ <p className="text-sm text-gray-500 mt-1">+ Recurring jobs that run on your behalf using your digital twin identity+ </p>+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => setShowCreate(!showCreate)}+ className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors"+ >+ <Plus size={16} />+ New Job+ </button>+ <button+ onClick={fetchJobs}+ className="text-gray-500 hover:text-white transition-colors"+ >+ <RefreshCw size={16} />+ </button>+ </div>+ </div>++ {/* Stats bar */}+ {stats && (+ <div className="flex gap-4 text-xs text-gray-500">+ <span>{stats.enabled} enabled / {stats.total} total</span>+ <span>{stats.totalRuns} total runs</span>+ {stats.nextDue && (+ <span className={stats.nextDue.isDue ? 'text-port-warning' : ''}>+ Next: {stats.nextDue.jobName} ({stats.nextDue.isDue ? 'due now' : new Date(stats.nextDue.nextDueAt).toLocaleString()})+ </span>+ )}+ </div>+ )}++ {/* Create form */}+ {showCreate && (+ <div className="bg-port-card border border-port-accent/50 rounded-lg p-4">+ <div className="space-y-3">+ <div className="flex gap-3">+ <input+ type="text"+ placeholder="Job name *"+ value={newJob.name}+ onChange={e => setNewJob(j => ({ ...j, name: e.target.value }))}+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <input+ type="text"+ placeholder="Category"+ value={newJob.category}+ onChange={e => setNewJob(j => ({ ...j, category: e.target.value }))}+ className="w-40 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ </div>+ <input+ type="text"+ placeholder="Description"+ value={newJob.description}+ onChange={e => setNewJob(j => ({ ...j, description: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <div className="flex gap-3">+ <select+ value={newJob.interval}+ onChange={e => setNewJob(j => ({ ...j, interval: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ {INTERVAL_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value}>{opt.label}</option>+ ))}+ </select>+ <select+ value={newJob.priority}+ onChange={e => setNewJob(j => ({ ...j, priority: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ {PRIORITY_OPTIONS.map(p => (+ <option key={p} value={p}>{p}</option>+ ))}+ </select>+ <select+ value={newJob.autonomyLevel}+ onChange={e => setNewJob(j => ({ ...j, autonomyLevel: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ {AUTONOMY_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value}>{opt.label} — {opt.desc}</option>+ ))}+ </select>+ </div>+ <textarea+ placeholder="Prompt template for the agent *"+ value={newJob.promptTemplate}+ onChange={e => setNewJob(j => ({ ...j, promptTemplate: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono h-32"+ />+ <div className="flex justify-end gap-2">+ <button+ onClick={() => setShowCreate(false)}+ className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={handleCreate}+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors"+ >+ <Plus size={14} />+ Create Job+ </button>+ </div>+ </div>+ </div>+ )}++ {/* Jobs list */}+ {jobs.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">+ <div className="text-gray-500 mb-3">No autonomous jobs configured.</div>+ <p className="text-xs text-gray-600 max-w-md mx-auto">+ Autonomous jobs let the Chief of Staff act proactively on your behalf — maintaining repositories, processing brain ideas, and more.+ </p>+ </div>+ ) : (+ <div className="space-y-2">+ {jobs.map(job => (+ <JobCard+ key={job.id}+ job={job}+ onToggle={handleToggle}+ onTrigger={handleTrigger}+ onDelete={handleDelete}+ onUpdate={fetchJobs}+ />+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 7179ed246c..e550d1064e 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -22,6 +22,7 @@ import {EventLog,TasksTab,AgentsTab,+ JobsTab,ScriptsTab,ScheduleTab,DigestTab,@@ -544,6 +545,11 @@ export default function ChiefOfStaff() {<AgentsTab agents={agents} onRefresh={fetchData} liveOutputs={liveOutputs} providers={providers} apps={apps} /></div>)}+ {activeTab === 'jobs' && (+ <div role="tabpanel" id="tabpanel-jobs" aria-labelledby="tab-jobs">+ <JobsTab />+ </div>+ )}{activeTab === 'scripts' && (<div role="tabpanel" id="tabpanel-scripts" aria-labelledby="tab-scripts"><ScriptsTab scripts={scripts} onRefresh={fetchData} />diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 0a03a13e8f..3ed4ee5a43 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -461,6 +461,23 @@ export const addCosScheduleTemplate = (template) => request('/cos/schedule/templ});export const deleteCosScheduleTemplate = (templateId) => request(`/cos/schedule/templates/${templateId}`, { method: 'DELETE' });+// Autonomous Jobs+export const getCosJobs = () => request('/cos/jobs');+export const getCosJobsDue = () => request('/cos/jobs/due');+export const getCosJobIntervals = () => request('/cos/jobs/intervals');+export const getCosJob = (id) => request(`/cos/jobs/${id}`);+export const createCosJob = (data) => request('/cos/jobs', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateCosJob = (id, data) => request(`/cos/jobs/${id}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const toggleCosJob = (id) => request(`/cos/jobs/${id}/toggle`, { method: 'POST' });+export const triggerCosJob = (id) => request(`/cos/jobs/${id}/trigger`, { method: 'POST' });+export const deleteCosJob = (id) => request(`/cos/jobs/${id}`, { method: 'DELETE' });+// Memoryexport const getMemories = (options = {}) => {const params = new URLSearchParams();diff --git a/server/routes/cos.js b/server/routes/cos.jsindex bfe7bce1dc..e8d3d68593 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -9,6 +9,7 @@ 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 * as autonomousJobs from '../services/autonomousJobs.js';import { enhanceTaskPrompt } from '../services/taskEnhancer.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';@@ -660,4 +661,97 @@ router.get('/schedule/interval-types', (req, res) => {});});+// ============================================================+// Autonomous Jobs Routes+// ============================================================++// GET /api/cos/jobs - Get all autonomous jobs+router.get('/jobs', asyncHandler(async (req, res) => {+ const jobs = await autonomousJobs.getAllJobs();+ const stats = await autonomousJobs.getJobStats();+ res.json({ jobs, stats });+}));++// GET /api/cos/jobs/due - Get jobs that are due to run+router.get('/jobs/due', asyncHandler(async (req, res) => {+ const due = await autonomousJobs.getDueJobs();+ res.json({ due });+}));++// GET /api/cos/jobs/intervals - Get available interval options+router.get('/jobs/intervals', (req, res) => {+ res.json({ intervals: autonomousJobs.INTERVAL_OPTIONS });+});++// GET /api/cos/jobs/:id - Get a single job+router.get('/jobs/:id', asyncHandler(async (req, res) => {+ const job = await autonomousJobs.getJob(req.params.id);+ if (!job) {+ throw new ServerError('Job not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(job);+}));++// POST /api/cos/jobs - Create a new autonomous job+router.post('/jobs', asyncHandler(async (req, res) => {+ const { name, description, category, interval, intervalMs, enabled, priority, autonomyLevel, promptTemplate } = req.body;++ if (!name || !promptTemplate) {+ throw new ServerError('name and promptTemplate are required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ const job = await autonomousJobs.createJob({+ name, description, category, interval, intervalMs,+ enabled, priority, autonomyLevel, promptTemplate+ });+ res.json({ success: true, job });+}));++// PUT /api/cos/jobs/:id - Update a job+router.put('/jobs/:id', asyncHandler(async (req, res) => {+ const job = await autonomousJobs.updateJob(req.params.id, req.body);+ if (!job) {+ throw new ServerError('Job not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json({ success: true, job });+}));++// POST /api/cos/jobs/:id/toggle - Toggle job enabled/disabled+router.post('/jobs/:id/toggle', asyncHandler(async (req, res) => {+ const job = await autonomousJobs.toggleJob(req.params.id);+ if (!job) {+ throw new ServerError('Job not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json({ success: true, job });+}));++// POST /api/cos/jobs/:id/trigger - Manually trigger a job now+router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {+ const job = await autonomousJobs.getJob(req.params.id);+ if (!job) {+ throw new ServerError('Job not found', { status: 404, code: 'NOT_FOUND' });+ }++ // Generate task and add to CoS task queue+ const task = autonomousJobs.generateTaskFromJob(job);+ const result = await cos.addTask({+ description: task.description,+ priority: task.priority,+ context: `Manually triggered autonomous job: ${job.name}`,+ ...task.metadata+ }, 'cos');+ await autonomousJobs.recordJobExecution(job.id);++ res.json({ success: true, task: result });+}));++// DELETE /api/cos/jobs/:id - Delete a job+router.delete('/jobs/:id', asyncHandler(async (req, res) => {+ const deleted = await autonomousJobs.deleteJob(req.params.id);+ if (!deleted) {+ throw new ServerError('Job not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json({ success: true });+}));+export default router;diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.jsnew file mode 100644index 0000000000..dd247eea24--- /dev/null+++ b/server/services/autonomousJobs.js@@ -0,0 +1,534 @@+/**+ * Autonomous Jobs Service+ *+ * Manages recurring scheduled jobs that the CoS executes proactively+ * on behalf of the user, using their digital twin identity to make decisions.+ *+ * Jobs are different from tasks:+ * - Tasks are one-shot work items (TASKS.md)+ * - Jobs are recurring schedules that generate tasks when due+ *+ * Job types:+ * - git-maintenance: Maintain user's git repositories+ * - brain-processing: Process and act on brain ideas/inbox+ * - Custom user-defined jobs+ */++import { promises as fs } from 'fs'+import { existsSync } from 'fs'+import path from 'path'+import { fileURLToPath } from 'url'+import { v4 as uuidv4 } from 'uuid'+import { cosEvents } from './cosEvents.js'+import { readJSONFile } from '../lib/fileUtils.js'++const __filename = fileURLToPath(import.meta.url)+const __dirname = path.dirname(__filename)+const DATA_DIR = path.join(__dirname, '../../data/cos')+const JOBS_FILE = path.join(DATA_DIR, 'autonomous-jobs.json')++// Time constants+const HOUR = 60 * 60 * 1000+const DAY = 24 * HOUR+const WEEK = 7 * DAY++/**+ * Default job definitions+ */+const DEFAULT_JOBS = [+ {+ id: 'job-git-maintenance',+ name: 'Git Repository Maintenance',+ description: 'Review and maintain my open source repositories on GitHub. Check for stale issues, outdated dependencies, and merge-worthy PRs.',+ category: 'git-maintenance',+ interval: 'weekly',+ intervalMs: WEEK,+ enabled: false,+ priority: 'MEDIUM',+ autonomyLevel: 'manager',+ promptTemplate: `[Autonomous Job] Git Repository Maintenance++You are acting as my Chief of Staff, maintaining my GitHub repositories.++My GitHub username is: atomantic++Tasks to perform:+1. Check my local git repositories for uncommitted changes or stale branches+2. Look for repositories that haven't been updated recently+3. Review any obvious maintenance needs (outdated README, missing license, etc.)+4. If there are simple cleanups to make, create tasks for them++Focus on practical, actionable maintenance. Don't make changes directly — create CoS tasks for anything that needs doing.++Report a summary of the repository health status when done.`,+ lastRun: null,+ runCount: 0,+ createdAt: null,+ updatedAt: null+ },+ {+ id: 'job-brain-processing',+ name: 'Brain Inbox Processing',+ description: 'Review brain inbox items that need attention, process ideas into actionable tasks, and surface patterns.',+ category: 'brain-processing',+ interval: 'daily',+ intervalMs: DAY,+ enabled: false,+ priority: 'MEDIUM',+ autonomyLevel: 'manager',+ promptTemplate: `[Autonomous Job] Brain Inbox Processing++You are acting as my Chief of Staff, processing my brain inbox.++Tasks to perform:+1. Call GET /api/brain/inbox?status=needs_review to find items needing review+2. Call GET /api/brain/summary to understand the current brain state+3. For items in needs_review status, analyze the content and suggest classifications+4. Look for patterns across recent brain captures — recurring themes, related ideas+5. For high-value ideas that could become projects, create CoS tasks to explore them+6. Generate a brief summary of insights from the brain inbox++Focus on surfacing actionable insights. Don't just classify — think about what these ideas mean and how they connect.`,+ lastRun: null,+ runCount: 0,+ createdAt: null,+ updatedAt: null+ },+ {+ id: 'job-daily-briefing',+ name: 'Daily Briefing',+ description: 'Generate a morning briefing with task priorities, calendar awareness, and proactive suggestions.',+ category: 'daily-briefing',+ interval: 'daily',+ intervalMs: DAY,+ enabled: false,+ priority: 'LOW',+ autonomyLevel: 'assistant',+ promptTemplate: `[Autonomous Job] Daily Briefing++You are acting as my Chief of Staff, preparing a daily briefing.++Tasks to perform:+1. Review pending user tasks (GET /api/cos/tasks/user) and summarize priorities+2. Check brain digest (GET /api/brain/digest/latest) for recent thought patterns+3. Review CoS learning insights (GET /api/cos/learning/insights) for system health+4. Check which agents completed work recently (GET /api/cos/agents)+5. Suggest 2-3 focus areas for today based on open tasks and recent activity++Write the briefing in a concise, actionable format. Save it as a CoS report.`,+ lastRun: null,+ runCount: 0,+ createdAt: null,+ updatedAt: null+ },+ {+ id: 'job-project-review',+ name: 'Brain Project Review',+ description: 'Review active brain projects, check progress, suggest next actions, and identify stalled projects.',+ category: 'project-review',+ interval: 'weekly',+ intervalMs: WEEK,+ enabled: false,+ priority: 'LOW',+ autonomyLevel: 'assistant',+ promptTemplate: `[Autonomous Job] Brain Project Review++You are acting as my Chief of Staff, reviewing active projects from my brain.++Tasks to perform:+1. Call GET /api/brain/projects to get all active projects+2. For each active project:+ - Assess if the next action is still relevant+ - Check if there are related brain captures since last review+ - Suggest updated next actions if stale+3. Identify projects that might be stalled (no activity in 2+ weeks)+4. Look for connections between projects that could be leveraged+5. For any actionable suggestions, create CoS tasks++Report a project health summary when done.`,+ lastRun: null,+ runCount: 0,+ createdAt: null,+ updatedAt: null+ }+]++/**+ * Ensure data directory exists+ */+async function ensureDataDir() {+ if (!existsSync(DATA_DIR)) {+ await fs.mkdir(DATA_DIR, { recursive: true })+ }+}++/**+ * Load jobs from disk+ * @returns {Promise<Object>} Jobs data+ */+async function loadJobs() {+ await ensureDataDir()++ const loaded = await readJSONFile(JOBS_FILE, null)+ if (!loaded) {+ const initial = createDefaultJobsData()+ await saveJobs(initial)+ return initial+ }++ // Merge with defaults to ensure all default jobs exist+ const merged = mergeWithDefaults(loaded)+ return merged+}++/**+ * Create initial jobs data with defaults+ */+function createDefaultJobsData() {+ const now = new Date().toISOString()+ return {+ version: 1,+ lastUpdated: now,+ jobs: DEFAULT_JOBS.map(j => ({+ ...j,+ createdAt: now,+ updatedAt: now+ }))+ }+}++/**+ * Merge loaded data with defaults (add any missing default jobs)+ */+function mergeWithDefaults(loaded) {+ const existingIds = new Set(loaded.jobs.map(j => j.id))+ const now = new Date().toISOString()++ for (const defaultJob of DEFAULT_JOBS) {+ if (!existingIds.has(defaultJob.id)) {+ loaded.jobs.push({+ ...defaultJob,+ createdAt: now,+ updatedAt: now+ })+ }+ }++ return loaded+}++/**+ * Save jobs to disk+ */+async function saveJobs(data) {+ await ensureDataDir()+ data.lastUpdated = new Date().toISOString()+ await fs.writeFile(JOBS_FILE, JSON.stringify(data, null, 2))+}++/**+ * Get all jobs+ * @returns {Promise<Array>} All jobs+ */+async function getAllJobs() {+ const data = await loadJobs()+ return data.jobs+}++/**+ * Get a single job by ID+ * @param {string} jobId+ * @returns {Promise<Object|null>}+ */+async function getJob(jobId) {+ const data = await loadJobs()+ return data.jobs.find(j => j.id === jobId) || null+}++/**+ * Get enabled jobs+ * @returns {Promise<Array>} Enabled jobs+ */+async function getEnabledJobs() {+ const data = await loadJobs()+ return data.jobs.filter(j => j.enabled)+}++/**+ * Get jobs that are due to run+ * @returns {Promise<Array>} Due jobs with reason+ */+async function getDueJobs() {+ const enabledJobs = await getEnabledJobs()+ const now = Date.now()+ const due = []++ for (const job of enabledJobs) {+ const lastRun = job.lastRun ? new Date(job.lastRun).getTime() : 0+ const timeSinceLastRun = now - lastRun++ if (timeSinceLastRun >= job.intervalMs) {+ due.push({+ ...job,+ reason: job.lastRun ? `${job.interval}-due` : 'never-run',+ overdueBy: timeSinceLastRun - job.intervalMs+ })+ }+ }++ // Sort by overdue time (most overdue first)+ due.sort((a, b) => b.overdueBy - a.overdueBy)++ return due+}++/**+ * Create a new job+ * @param {Object} jobData+ * @returns {Promise<Object>} Created job+ */+async function createJob(jobData) {+ const data = await loadJobs()+ const now = new Date().toISOString()++ const job = {+ id: jobData.id || `job-${uuidv4().slice(0, 8)}`,+ name: jobData.name,+ description: jobData.description || '',+ category: jobData.category || 'custom',+ interval: jobData.interval || 'weekly',+ intervalMs: resolveIntervalMs(jobData.interval, jobData.intervalMs),+ enabled: jobData.enabled !== undefined ? jobData.enabled : false,+ priority: jobData.priority || 'MEDIUM',+ autonomyLevel: jobData.autonomyLevel || 'manager',+ promptTemplate: jobData.promptTemplate || '',+ lastRun: null,+ runCount: 0,+ createdAt: now,+ updatedAt: now+ }++ data.jobs.push(job)+ await saveJobs(data)++ console.log(`🤖 Autonomous job created: ${job.name}`)+ cosEvents.emit('jobs:created', { id: job.id, name: job.name })++ return job+}++/**+ * Update an existing job+ * @param {string} jobId+ * @param {Object} updates+ * @returns {Promise<Object|null>} Updated job or null+ */+async function updateJob(jobId, updates) {+ const data = await loadJobs()+ const job = data.jobs.find(j => j.id === jobId)+ if (!job) return null++ const updatableFields = [+ 'name', 'description', 'category', 'interval', 'intervalMs',+ 'enabled', 'priority', 'autonomyLevel', 'promptTemplate'+ ]++ for (const field of updatableFields) {+ if (updates[field] !== undefined) {+ job[field] = updates[field]+ }+ }++ // Recalculate intervalMs if interval changed+ if (updates.interval) {+ job.intervalMs = resolveIntervalMs(updates.interval, updates.intervalMs)+ }++ job.updatedAt = new Date().toISOString()+ await saveJobs(data)++ console.log(`🤖 Autonomous job updated: ${job.name}`)+ cosEvents.emit('jobs:updated', { id: job.id, updates })++ return job+}++/**+ * Delete a job+ * @param {string} jobId+ * @returns {Promise<boolean>}+ */+async function deleteJob(jobId) {+ const data = await loadJobs()+ const idx = data.jobs.findIndex(j => j.id === jobId)+ if (idx === -1) return false++ const deleted = data.jobs.splice(idx, 1)[0]+ await saveJobs(data)++ console.log(`🗑️ Autonomous job deleted: ${deleted.name}`)+ cosEvents.emit('jobs:deleted', { id: jobId })++ return true+}++/**+ * Record a job execution+ * @param {string} jobId+ * @returns {Promise<Object|null>} Updated job+ */+async function recordJobExecution(jobId) {+ const data = await loadJobs()+ const job = data.jobs.find(j => j.id === jobId)+ if (!job) return null++ job.lastRun = new Date().toISOString()+ job.runCount = (job.runCount || 0) + 1+ job.updatedAt = job.lastRun++ await saveJobs(data)++ console.log(`🤖 Job executed: ${job.name} (run #${job.runCount})`)+ cosEvents.emit('jobs:executed', { id: jobId, runCount: job.runCount })++ return job+}++/**+ * Toggle a job's enabled state+ * @param {string} jobId+ * @returns {Promise<Object|null>}+ */+async function toggleJob(jobId) {+ const data = await loadJobs()+ const job = data.jobs.find(j => j.id === jobId)+ if (!job) return null++ job.enabled = !job.enabled+ job.updatedAt = new Date().toISOString()++ await saveJobs(data)++ const stateLabel = job.enabled ? 'enabled' : 'disabled'+ console.log(`🤖 Autonomous job ${stateLabel}: ${job.name}`)+ cosEvents.emit('jobs:toggled', { id: jobId, enabled: job.enabled })++ return job+}++/**+ * Generate a CoS task from a due job+ * @param {Object} job - The job to generate a task for+ * @returns {Object} Task data suitable for cos.addTask()+ */+function generateTaskFromJob(job) {+ return {+ id: `${job.id}-${Date.now().toString(36)}`,+ description: job.promptTemplate,+ priority: job.priority,+ metadata: {+ autonomousJob: true,+ jobId: job.id,+ jobName: job.name,+ jobCategory: job.category,+ autonomyLevel: job.autonomyLevel+ },+ taskType: 'internal',+ autoApprove: job.autonomyLevel === 'yolo'+ }+}++/**+ * Get job statistics+ * @returns {Promise<Object>}+ */+async function getJobStats() {+ const jobs = await getAllJobs()++ return {+ total: jobs.length,+ enabled: jobs.filter(j => j.enabled).length,+ disabled: jobs.filter(j => !j.enabled).length,+ byCategory: jobs.reduce((acc, j) => {+ acc[j.category] = (acc[j.category] || 0) + 1+ return acc+ }, {}),+ totalRuns: jobs.reduce((sum, j) => sum + (j.runCount || 0), 0),+ nextDue: await getNextDueJob()+ }+}++/**+ * Get the next job that will be due+ * @returns {Promise<Object|null>}+ */+async function getNextDueJob() {+ const enabledJobs = await getEnabledJobs()+ if (enabledJobs.length === 0) return null++ let earliest = null+ let earliestTime = Infinity++ for (const job of enabledJobs) {+ const lastRun = job.lastRun ? new Date(job.lastRun).getTime() : 0+ const nextDue = lastRun + job.intervalMs++ if (nextDue < earliestTime) {+ earliestTime = nextDue+ earliest = {+ jobId: job.id,+ jobName: job.name,+ nextDueAt: new Date(nextDue).toISOString(),+ isDue: Date.now() >= nextDue+ }+ }+ }++ return earliest+}++/**+ * Resolve interval string to milliseconds+ */+function resolveIntervalMs(interval, customMs) {+ switch (interval) {+ case 'hourly': return HOUR+ case 'every-4-hours': return 4 * HOUR+ case 'every-8-hours': return 8 * HOUR+ case 'daily': return DAY+ case 'weekly': return WEEK+ case 'biweekly': return 2 * WEEK+ case 'monthly': return 30 * DAY+ case 'custom': return customMs || DAY+ default: return DAY+ }+}++/**+ * Available interval options for UI+ */+const INTERVAL_OPTIONS = [+ { value: 'hourly', label: 'Every Hour', ms: HOUR },+ { value: 'every-4-hours', label: 'Every 4 Hours', ms: 4 * HOUR },+ { value: 'every-8-hours', label: 'Every 8 Hours', ms: 8 * HOUR },+ { value: 'daily', label: 'Daily', ms: DAY },+ { value: 'weekly', label: 'Weekly', ms: WEEK },+ { value: 'biweekly', label: 'Every 2 Weeks', ms: 2 * WEEK },+ { value: 'monthly', label: 'Monthly', ms: 30 * DAY }+]++export {+ getAllJobs,+ getJob,+ getEnabledJobs,+ getDueJobs,+ createJob,+ updateJob,+ deleteJob,+ recordJobExecution,+ toggleJob,+ generateTaskFromJob,+ getJobStats,+ getNextDueJob,+ INTERVAL_OPTIONS+}diff --git a/server/services/cos.js b/server/services/cos.jsindex 36e9887047..f5c9495f06 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -19,6 +19,7 @@ import { getActiveApps } from './apps.js';import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights } from './taskLearning.js';import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats } from './eventScheduler.js';import { generateProactiveTasks as generateMissionTasks, getStats as getMissionStats } from './missions.js';+import { getDueJobs, generateTaskFromJob, recordJobExecution } from './autonomousJobs.js';import { formatDuration } from '../lib/fileUtils.js';// Import and re-export cosEvents from separate module to avoid circular dependenciesimport { cosEvents as _cosEvents } from './cosEvents.js';@@ -102,6 +103,7 @@ const DEFAULT_CONFIG = {comprehensiveAppImprovement: true, // Use comprehensive analysis for managed apps (same as PortOS self-improvement)immediateExecution: true, // Execute new tasks immediately, don't wait for intervalproactiveMode: true, // Be proactive about finding work+ autonomousJobsEnabled: true, // Enable recurring autonomous jobs (git maintenance, brain processing, etc.)autonomyLevel: 'manager', // Default autonomy level preset (standby/assistant/manager/yolo)rehabilitationGracePeriodDays: 7, // Days before auto-retrying skipped task types (learning-based)autoFixThresholds: {@@ -658,6 +660,25 @@ export async function evaluateTasks() {}}+ // Priority 3.5: Autonomous jobs (recurring scheduled jobs)+ if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks && state.config.autonomousJobsEnabled) {+ const dueJobs = await getDueJobs().catch(err => {+ emitLog('debug', `Autonomous jobs check failed: ${err.message}`);+ return [];+ });++ for (const job of dueJobs) {+ if (tasksToSpawn.length >= availableSlots) break;+ const task = generateTaskFromJob(job);+ tasksToSpawn.push(task);+ await recordJobExecution(job.id);+ emitLog('info', `Autonomous job due: ${job.name} (${job.reason})`, {+ jobId: job.id,+ category: job.category+ });+ }+ }+// Priority 4: Only generate direct idle task if:// 1. Nothing to spawn// 2. No pending user tasks (even on cooldown)