Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(cos): unify scheduling — merge Scripts into Jobs, move PR Reviewer to Schedule (#88)

[._.]/ Adam Eivyf6a92207a7e1
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index 1f4ec71876..4740c928ee 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -1,7 +1,6 @@
import {
FileText,
Cpu,
- Terminal,
Brain,
Activity,
Settings,
@@ -18,8 +17,7 @@ export const TABS = [
{ id: 'briefing', label: 'Briefing', icon: Newspaper },
{ 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: 'jobs', label: 'System Tasks', icon: Bot },
{ id: 'schedule', label: 'Schedule', icon: Clock },
{ id: 'digest', label: 'Digest', icon: Calendar },
{ id: 'gsd', label: 'GSD', icon: Compass },
diff --git a/client/src/components/cos/index.js b/client/src/components/cos/index.js
index 555350e39d..b8136ce1f0 100644
--- a/client/src/components/cos/index.js
+++ b/client/src/components/cos/index.js
@@ -26,7 +26,6 @@ export { default as DailyTrendsChart } from './DailyTrendsChart';
export { 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';
export { default as MemoryTab } from './tabs/MemoryTab';
diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsx
index 70ab55dd0d..09dac79f66 100644
--- a/client/src/components/cos/tabs/JobsTab.jsx
+++ b/client/src/components/cos/tabs/JobsTab.jsx
@@ -1,10 +1,11 @@
import { useState, useEffect, useCallback } from 'react';
-import { Plus, RefreshCw, Play, Trash2, ChevronDown, ChevronUp, Clock, ToggleLeft, ToggleRight, Edit3, Save, X } from 'lucide-react';
+import { Plus, RefreshCw, Play, Trash2, ChevronDown, ChevronUp, Clock, ToggleLeft, ToggleRight, Edit3, Save, X, Terminal } 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-2-hours', label: 'Every 2 Hours' },
{ value: 'every-4-hours', label: 'Every 4 Hours' },
{ value: 'every-8-hours', label: 'Every 8 Hours' },
{ value: 'daily', label: 'Daily' },
@@ -21,6 +22,22 @@ const AUTONOMY_OPTIONS = [
{ value: 'yolo', label: 'YOLO', desc: 'Full autonomy, no guardrails' }
];
+const TRIGGER_ACTION_OPTIONS = [
+ { value: 'log-only', label: 'Log Only' },
+ { value: 'spawn-agent', label: 'Spawn Agent' },
+ { value: 'create-task', label: 'Create Task' }
+];
+
+const SHELL_TRIGGER_ACTIONS = new Set(['spawn-agent', 'create-task']);
+const SHELL_TRIGGER_ACTION_OPTIONS = TRIGGER_ACTION_OPTIONS.filter(
+ opt => !SHELL_TRIGGER_ACTIONS.has(opt.value)
+);
+
+const JOB_TYPE_OPTIONS = [
+ { value: 'agent', label: 'AI Agent' },
+ { value: 'shell', label: 'Shell Command' }
+];
+
function formatTimeAgo(dateStr) {
if (!dateStr) return 'Never';
const diff = Date.now() - new Date(dateStr).getTime();
@@ -35,7 +52,6 @@ function formatTimeAgo(dateStr) {
function formatNextDue(lastRun, intervalMs, scheduledTime) {
if (!lastRun) return scheduledTime ? `at ${scheduledTime}` : 'Immediately';
let nextDue = new Date(lastRun).getTime() + intervalMs;
- // If there's a scheduledTime, adjust the next-due to that time of day
if (scheduledTime) {
const [hours, minutes] = scheduledTime.split(':').map(Number);
const nextDate = new Date(nextDue);
@@ -52,27 +68,46 @@ function formatNextDue(lastRun, intervalMs, scheduledTime) {
return `in ${mins}m`;
}
+function getJobTypeLabel(job) {
+ if (job.type === 'shell') return 'Shell';
+ if (job.type === 'script') return 'Script';
+ return 'AI';
+}
+
function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {
const [expanded, setExpanded] = useState(false);
const [editing, setEditing] = useState(false);
const [editData, setEditData] = useState({});
+ const isShell = job.type === 'shell';
+ const isScript = job.type === 'script';
+
const startEditing = () => {
- setEditData({
+ const base = {
name: job.name,
description: job.description,
+ type: job.type || 'agent',
interval: job.interval,
scheduledTime: job.scheduledTime || '',
priority: job.priority,
autonomyLevel: job.autonomyLevel,
- promptTemplate: job.promptTemplate
- });
+ promptTemplate: job.promptTemplate || ''
+ };
+ // Always initialize shell fields so switching type to 'shell' during editing works
+ base.command = job.command || '';
+ base.triggerAction = job.triggerAction || 'log-only';
+ setEditData(base);
setEditing(true);
setExpanded(true);
};
const handleSave = async () => {
- await api.updateCosJob(job.id, editData).catch(err => {
+ const payload = { ...editData };
+ if (payload.type !== 'shell' && payload.type !== 'script') {
+ payload.command = null;
+ payload.triggerAction = null;
+ }
+ await api.updateCosJob(job.id, payload).catch(err => {
toast.error(err.message);
return null;
});
@@ -110,6 +145,13 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {
Due
</span>
)}
+ <span className={`px-1.5 py-0.5 text-xs rounded ${
+ isShell ? 'bg-emerald-500/20 text-emerald-400' :
+ isScript ? 'bg-purple-500/20 text-purple-400' :
+ 'bg-port-bg text-gray-400'
+ }`}>
+ {getJobTypeLabel(job)}
+ </span>
<span className="px-1.5 py-0.5 bg-port-bg text-gray-400 text-xs rounded">
{job.category}
</span>
@@ -127,6 +169,11 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {
</span>
)}
<span>Runs: {job.runCount || 0}</span>
+ {isShell && job.lastExitCode != null && (
+ <span className={job.lastExitCode === 0 ? 'text-port-success' : 'text-port-error'}>
+ Exit: {job.lastExitCode}
+ </span>
+ )}
</div>
</div>
@@ -175,6 +222,17 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {
placeholder="Description"
/>
<div className="flex gap-3">
+ <select
+ value={editData.type}
+ onChange={e => setEditData(d => ({ ...d, type: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ disabled={isScript}
+ >
+ {JOB_TYPE_OPTIONS.map(opt => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ {isScript && <option value="script">Script Handler</option>}
+ </select>
<select
value={editData.interval}
onChange={e => setEditData(d => ({ ...d, interval: e.target.value }))}
@@ -200,22 +258,49 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {
<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>
+ {editData.type !== 'shell' && (
+ <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"
- />
+ {editData.type === 'shell' ? (
+ <>
+ <textarea
+ value={editData.command}
+ onChange={e => setEditData(d => ({ ...d, command: 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-20"
+ placeholder="Shell command"
+ />
+ <select
+ value={editData.triggerAction}
+ onChange={e => setEditData(d => ({ ...d, triggerAction: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ {SHELL_TRIGGER_ACTION_OPTIONS.map(opt => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ </>
+ ) : editData.type === 'script' ? (
+ <div className="space-y-1">
+ <span className="text-xs text-gray-400">Legacy script command (read-only)</span>
+ <pre className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 text-sm font-mono">{editData.command || 'No command'}</pre>
+ </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)}
@@ -234,19 +319,38 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {
) : (
<>
<p className="text-sm text-gray-400">{job.description}</p>
+ {isShell && job.command && (
+ <div className="flex items-center gap-2 text-xs">
+ <Terminal size={12} className="text-emerald-400 shrink-0" />
+ <code className="text-emerald-300 bg-port-bg px-2 py-1 rounded font-mono">{job.command}</code>
+ </div>
+ )}
<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>
+ {!isShell && <span>Autonomy: <span className="text-gray-300">{job.autonomyLevel}</span></span>}
+ {isShell && <span>Action: <span className="text-gray-300">{job.triggerAction || 'log-only'}</span></span>}
+ <span>Created: <span className="text-gray-300">{job.createdAt ? 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>
+ {isShell && job.lastOutput && (
+ <details className="group">
+ <summary className="text-xs text-gray-500 cursor-pointer hover:text-gray-300 transition-colors">
+ Last output (exit {job.lastExitCode})
+ </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.lastOutput}
+ </pre>
+ </details>
+ )}
+ {!isShell && !isScript && (
+ <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)}
@@ -272,11 +376,14 @@ export default function JobsTab() {
name: '',
description: '',
category: 'custom',
+ type: 'agent',
interval: 'daily',
scheduledTime: '',
priority: 'MEDIUM',
autonomyLevel: 'manager',
promptTemplate: '',
+ command: '',
+ triggerAction: 'log-only',
enabled: false
});
@@ -295,25 +402,37 @@ export default function JobsTab() {
useEffect(() => { fetchJobs(); }, [fetchJobs]);
const handleCreate = async () => {
- if (!newJob.name.trim() || !newJob.promptTemplate.trim()) {
- toast.error('Name and prompt template are required');
+ if (!newJob.name.trim()) {
+ toast.error('Name is required');
+ return;
+ }
+ if (newJob.type === 'shell' && !newJob.command.trim()) {
+ toast.error('Command is required for shell jobs');
+ return;
+ }
+ if (newJob.type !== 'shell' && !newJob.promptTemplate.trim()) {
+ toast.error('Prompt template is required for AI jobs');
return;
}
- await api.createCosJob(newJob).catch(err => {
+ const created = await api.createCosJob(newJob).catch(err => {
toast.error(err.message);
return null;
});
+ if (!created) return;
toast.success('Job created');
setNewJob({
name: '',
description: '',
category: 'custom',
+ type: 'agent',
interval: 'daily',
scheduledTime: '',
priority: 'MEDIUM',
autonomyLevel: 'manager',
promptTemplate: '',
+ command: '',
+ triggerAction: 'log-only',
enabled: false
});
setShowCreate(false);
@@ -338,7 +457,12 @@ export default function JobsTab() {
return null;
});
if (result) {
- toast.success('Job triggered — task queued', { id: 'job-trigger' });
+ if (result.success === false) {
+ toast.error(`Job failed (exit ${result.exitCode ?? '?'})`, { id: 'job-trigger' });
+ } else {
+ const msg = result.type === 'shell' || result.type === 'script' ? 'Job executed successfully' : 'Job triggered — task queued';
+ toast.success(msg, { id: 'job-trigger' });
+ }
fetchJobs();
}
};
@@ -355,7 +479,7 @@ export default function JobsTab() {
if (loading) {
return (
<div className="flex items-center justify-center py-12 text-gray-500">
- Loading autonomous jobs...
+ Loading system tasks...
</div>
);
}
@@ -365,9 +489,9 @@ export default function JobsTab() {
{/* Header */}
<div className="flex items-center justify-between">
<div>
- <h3 className="text-lg font-semibold text-white">Autonomous Jobs</h3>
+ <h3 className="text-lg font-semibold text-white">System Tasks</h3>
<p className="text-sm text-gray-500 mt-1">
- Recurring jobs that run on your behalf using your digital twin identity
+ Recurring system-level jobs — AI agents and shell commands
</p>
</div>
<div className="flex items-center gap-2">
@@ -412,6 +536,15 @@ export default function JobsTab() {
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"
/>
+ <select
+ value={newJob.type}
+ onChange={e => setNewJob(j => ({ ...j, type: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ {JOB_TYPE_OPTIONS.map(opt => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
<input
type="text"
placeholder="Category"
@@ -453,22 +586,44 @@ export default function JobsTab() {
<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>
+ {newJob.type !== 'shell' && (
+ <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"
- />
+ {newJob.type === 'shell' ? (
+ <>
+ <textarea
+ placeholder="Shell command *"
+ value={newJob.command}
+ onChange={e => setNewJob(j => ({ ...j, command: 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-20"
+ />
+ <select
+ value={newJob.triggerAction}
+ onChange={e => setNewJob(j => ({ ...j, triggerAction: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ {(newJob.type === 'shell' ? SHELL_TRIGGER_ACTION_OPTIONS : TRIGGER_ACTION_OPTIONS).map(opt => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ </>
+ ) : (
+ <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)}
@@ -491,9 +646,9 @@ export default function JobsTab() {
{/* 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>
+ <div className="text-gray-500 mb-3">No system tasks 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.
+ System tasks let the Chief of Staff act proactively on your behalf — maintaining repositories, running health checks, processing brain ideas, and more.
</p>
</div>
) : (
diff --git a/client/src/components/cos/tabs/ScriptCard.jsx b/client/src/components/cos/tabs/ScriptCard.jsx
deleted file mode 100644
index f013600149..0000000000
--- a/client/src/components/cos/tabs/ScriptCard.jsx
+++ /dev/null
@@ -1,233 +0,0 @@
-import { useState } from 'react';
-import {
- Terminal,
- Play,
- Edit3,
- CheckCircle,
- Ban,
- Trash2,
- Save,
- Zap
-} from 'lucide-react';
-import toast from 'react-hot-toast';
-import * as api from '../../../services/api';
-import { formatTime } from '../../../utils/formatters';
-
-const scheduleLabels = {
- 'on-demand': 'On Demand',
- 'every-5-min': 'Every 5 min',
- 'every-15-min': 'Every 15 min',
- 'every-30-min': 'Every 30 min',
- 'hourly': 'Hourly',
- 'every-6-hours': 'Every 6 hours',
- 'daily': 'Daily',
- 'weekly': 'Weekly'
-};
-
-export default function ScriptCard({ script, onRun, onToggle, onDelete, onUpdate }) {
- const [expanded, setExpanded] = useState(false);
- const [editing, setEditing] = useState(false);
- const [editData, setEditData] = useState({
- name: script.name,
- description: script.description || '',
- command: script.command,
- schedule: script.schedule || 'on-demand',
- triggerAction: script.triggerAction || 'log-only',
- triggerPrompt: script.triggerPrompt || '',
- triggerPriority: script.triggerPriority || 'MEDIUM'
- });
-
- const handleSave = async () => {
- if (!editData.name.trim() || !editData.command.trim()) {
- toast.error('Name and command are required');
- return;
- }
- await api.updateCosScript(script.id, editData).catch(err => toast.error(err.message));
- toast.success('Script updated');
- setEditing(false);
- onUpdate?.();
- };
-
- return (
- <div className={`bg-port-card border rounded-lg overflow-hidden ${
- script.enabled ? 'border-port-border' : 'border-port-border opacity-60'
- }`}>
- <div className="p-4">
- <div className="flex items-center justify-between mb-2">
- <div className="flex items-center gap-2">
- <Terminal size={16} className={script.enabled ? 'text-port-accent' : 'text-gray-500'} />
- <span className="font-medium text-white">{script.name}</span>
- <span className={`px-2 py-0.5 text-xs rounded ${
- script.schedule === 'on-demand' ? 'bg-gray-500/20 text-gray-400' : 'bg-port-accent/20 text-port-accent'
- }`}>
- {scheduleLabels[script.schedule] || script.schedule}
- </span>
- {script.triggerAction === 'spawn-agent' && (
- <span className="px-2 py-0.5 text-xs bg-purple-500/20 text-purple-400 rounded">
- <Zap size={10} className="inline mr-1" />
- Triggers Agent
- </span>
- )}
- </div>
- <div className="flex items-center gap-2">
- <button
- onClick={() => onRun(script.id)}
- className="p-1.5 text-gray-500 hover:text-port-success transition-colors"
- title="Run now"
- >
- <Play size={14} />
- </button>
- <button
- onClick={() => setEditing(true)}
- className="p-1.5 text-gray-500 hover:text-white transition-colors"
- title="Edit"
- >
- <Edit3 size={14} />
- </button>
- <button
- onClick={() => onToggle(script)}
- className={`p-1.5 transition-colors ${
- script.enabled ? 'text-port-success hover:text-gray-500' : 'text-gray-500 hover:text-port-success'
- }`}
- title={script.enabled ? 'Disable' : 'Enable'}
- >
- {script.enabled ? <CheckCircle size={14} /> : <Ban size={14} />}
- </button>
- <button
- onClick={() => onDelete(script.id)}
- className="p-1.5 text-gray-500 hover:text-port-error transition-colors"
- title="Delete"
- >
- <Trash2 size={14} />
- </button>
- </div>
- </div>
-
- {/* Edit Form */}
- {editing ? (
- <div className="space-y-3 mt-3">
- <div className="flex gap-3">
- <input
- type="text"
- placeholder="Script name *"
- value={editData.name}
- onChange={e => setEditData(d => ({ ...d, name: e.target.value }))}
- className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- />
- <select
- value={editData.schedule}
- onChange={e => setEditData(d => ({ ...d, schedule: e.target.value }))}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- >
- <option value="on-demand">On Demand</option>
- <option value="every-5-min">Every 5 min</option>
- <option value="every-15-min">Every 15 min</option>
- <option value="hourly">Hourly</option>
- <option value="daily">Daily</option>
- <option value="weekly">Weekly</option>
- </select>
- </div>
- <input
- type="text"
- placeholder="Description"
- 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"
- />
- <textarea
- placeholder="Shell command *"
- value={editData.command}
- onChange={e => setEditData(d => ({ ...d, command: 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-20"
- />
- <div className="flex gap-3">
- <select
- value={editData.triggerAction}
- onChange={e => setEditData(d => ({ ...d, triggerAction: e.target.value }))}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- >
- <option value="log-only">Log Only</option>
- <option value="spawn-agent">Spawn Agent</option>
- </select>
- <select
- value={editData.triggerPriority}
- onChange={e => setEditData(d => ({ ...d, triggerPriority: e.target.value }))}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- >
- <option value="LOW">LOW</option>
- <option value="MEDIUM">MEDIUM</option>
- <option value="HIGH">HIGH</option>
- <option value="CRITICAL">CRITICAL</option>
- </select>
- </div>
- {editData.triggerAction === 'spawn-agent' && (
- <textarea
- placeholder="Prompt for agent when triggered"
- value={editData.triggerPrompt}
- onChange={e => setEditData(d => ({ ...d, triggerPrompt: e.target.value }))}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm h-16"
- />
- )}
- <div className="flex justify-end gap-2">
- <button
- onClick={() => setEditing(false)}
- className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"
- >
- Cancel
- </button>
- <button
- onClick={handleSave}
- className="flex items-center gap-1 px-3 py-1.5 bg-port-success/20 hover:bg-port-success/30 text-port-success rounded-lg text-sm transition-colors"
- >
- <Save size={14} />
- Save
- </button>
- </div>
- </div>
- ) : (
- <>
- {script.description && (
- <p className="text-sm text-gray-400 mb-2">{script.description}</p>
- )}
-
- <div className="flex items-center gap-4 text-xs text-gray-500">
- <span>Last run: {formatTime(script.lastRun)}</span>
- {script.lastExitCode !== null && (
- <span className={script.lastExitCode === 0 ? 'text-port-success' : 'text-port-error'}>
- Exit: {script.lastExitCode}
- </span>
- )}
- <span>Runs: {script.runCount || 0}</span>
- {script.lastOutput && (
- <button
- onClick={() => setExpanded(!expanded)}
- className="text-port-accent hover:text-port-accent/80"
- >
- {expanded ? 'Hide' : 'Show'} output
- </button>
- )}
- </div>
- </>
- )}
- </div>
-
- {/* Command preview */}
- {!editing && (
- <div className="px-4 pb-3">
- <code className="text-xs text-gray-500 font-mono bg-port-bg/50 px-2 py-1 rounded block truncate">
- {script.command}
- </code>
- </div>
- )}
-
- {/* Expanded output */}
- {expanded && script.lastOutput && (
- <div className="border-t border-port-border bg-port-bg/50 p-3 max-h-48 overflow-y-auto">
- <pre className="text-xs font-mono text-gray-400 whitespace-pre-wrap">
- {script.lastOutput}
- </pre>
- </div>
- )}
- </div>
- );
-}
diff --git a/client/src/components/cos/tabs/ScriptsTab.jsx b/client/src/components/cos/tabs/ScriptsTab.jsx
deleted file mode 100644
index 5996280242..0000000000
--- a/client/src/components/cos/tabs/ScriptsTab.jsx
+++ /dev/null
@@ -1,201 +0,0 @@
-import { useState } from 'react';
-import { Plus, RefreshCw } from 'lucide-react';
-import toast from 'react-hot-toast';
-import * as api from '../../../services/api';
-import ScriptCard from './ScriptCard';
-
-export default function ScriptsTab({ scripts, onRefresh }) {
- const [showCreate, setShowCreate] = useState(false);
- const [newScript, setNewScript] = useState({
- name: '',
- description: '',
- command: '',
- schedule: 'on-demand',
- cronExpression: '',
- triggerAction: 'log-only',
- triggerPrompt: '',
- triggerPriority: 'MEDIUM'
- });
-
- const handleCreate = async () => {
- if (!newScript.name.trim() || !newScript.command.trim()) {
- toast.error('Name and command are required');
- return;
- }
-
- await api.createCosScript(newScript).catch(err => {
- toast.error(err.message);
- return;
- });
-
- toast.success('Script created');
- setNewScript({
- name: '',
- description: '',
- command: '',
- schedule: 'on-demand',
- cronExpression: '',
- triggerAction: 'log-only',
- triggerPrompt: '',
- triggerPriority: 'MEDIUM'
- });
- setShowCreate(false);
- onRefresh();
- };
-
- const handleRun = async (id) => {
- toast.loading('Running script...', { id: 'script-run' });
- const result = await api.runCosScript(id).catch(err => {
- toast.error(err.message, { id: 'script-run' });
- return null;
- });
- if (result) {
- if (result.success) {
- toast.success('Script completed', { id: 'script-run' });
- } else {
- toast.error(`Script failed: ${result.error || 'Unknown error'}`, { id: 'script-run' });
- }
- onRefresh();
- }
- };
-
- const handleToggle = async (script) => {
- await api.updateCosScript(script.id, { enabled: !script.enabled }).catch(err => toast.error(err.message));
- toast.success(script.enabled ? 'Script disabled' : 'Script enabled');
- onRefresh();
- };
-
- const handleDelete = async (id) => {
- await api.deleteCosScript(id).catch(err => toast.error(err.message));
- toast.success('Script deleted');
- onRefresh();
- };
-
- return (
- <div className="space-y-6">
- <div className="flex items-center justify-between mb-3">
- <h3 className="text-lg font-semibold text-white">Scheduled Scripts</h3>
- <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 Script
- </button>
- <button
- onClick={onRefresh}
- className="text-gray-500 hover:text-white transition-colors"
- >
- <RefreshCw size={16} />
- </button>
- </div>
- </div>
-
- {/* Create Script Form */}
- {showCreate && (
- <div className="bg-port-card border border-port-accent/50 rounded-lg p-4 mb-4">
- <div className="space-y-3">
- <div className="flex gap-3">
- <input
- type="text"
- placeholder="Script name *"
- value={newScript.name}
- onChange={e => setNewScript(s => ({ ...s, name: e.target.value }))}
- className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- />
- <select
- value={newScript.schedule}
- onChange={e => setNewScript(s => ({ ...s, schedule: e.target.value }))}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- >
- <option value="on-demand">On Demand</option>
- <option value="every-5-min">Every 5 min</option>
- <option value="every-15-min">Every 15 min</option>
- <option value="hourly">Hourly</option>
- <option value="daily">Daily</option>
- <option value="weekly">Weekly</option>
- </select>
- </div>
- <input
- type="text"
- placeholder="Description"
- value={newScript.description}
- onChange={e => setNewScript(s => ({ ...s, description: e.target.value }))}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- />
- <textarea
- placeholder="Shell command *"
- value={newScript.command}
- onChange={e => setNewScript(s => ({ ...s, command: 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-20"
- />
- <div className="flex gap-3">
- <select
- value={newScript.triggerAction}
- onChange={e => setNewScript(s => ({ ...s, triggerAction: e.target.value }))}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- >
- <option value="log-only">Log Only</option>
- <option value="spawn-agent">Spawn Agent</option>
- </select>
- <select
- value={newScript.triggerPriority}
- onChange={e => setNewScript(s => ({ ...s, triggerPriority: e.target.value }))}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- >
- <option value="LOW">LOW</option>
- <option value="MEDIUM">MEDIUM</option>
- <option value="HIGH">HIGH</option>
- <option value="CRITICAL">CRITICAL</option>
- </select>
- </div>
- {newScript.triggerAction === 'spawn-agent' && (
- <textarea
- placeholder="Prompt for agent when triggered"
- value={newScript.triggerPrompt}
- onChange={e => setNewScript(s => ({ ...s, triggerPrompt: e.target.value }))}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm h-16"
- />
- )}
- <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
- </button>
- </div>
- </div>
- </div>
- )}
-
- {/* Scripts List */}
- {scripts.length === 0 ? (
- <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">
- No scripts configured. Create a script to automate tasks.
- </div>
- ) : (
- <div className="space-y-2">
- {scripts.map(script => (
- <ScriptCard
- key={script.id}
- script={script}
- onRun={handleRun}
- onToggle={handleToggle}
- onDelete={handleDelete}
- onUpdate={onRefresh}
- />
- ))}
- </div>
- )}
- </div>
- );
-}
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index 196da5a172..9e567f59e3 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -27,7 +27,6 @@ import {
TasksTab,
AgentsTab,
JobsTab,
- ScriptsTab,
ScheduleTab,
DigestTab,
GsdTab,
@@ -43,12 +42,12 @@ import { resolveDynamicAvatar } from '../components/cos/constants';
export default function ChiefOfStaff() {
const { tab } = useParams();
const navigate = useNavigate();
- const activeTab = tab || 'tasks';
+ const validTabIds = useMemo(() => new Set(TABS.map(t => t.id)), []);
+ const activeTab = (tab && validTabIds.has(tab)) ? tab : 'tasks';
const [status, setStatus] = useState(null);
const [tasks, setTasks] = useState({ user: null, cos: null });
const [agents, setAgents] = useState([]);
- const [scripts, setScripts] = useState([]);
const [health, setHealth] = useState(null);
const [providers, setProviders] = useState([]);
const [apps, setApps] = useState([]);
@@ -110,11 +109,10 @@ export default function ChiefOfStaff() {
}, []);
const fetchData = useCallback(async () => {
- const [statusData, tasksData, agentsData, scriptsData, healthData, providersData, appsData, learningSummaryData] = await Promise.all([
+ const [statusData, tasksData, agentsData, healthData, providersData, appsData, learningSummaryData] = await Promise.all([
api.getCosStatus().catch(() => null),
api.getCosTasks().catch(() => ({ user: null, cos: null })),
api.getCosAgents().catch(() => []),
- api.getCosScripts().catch(() => ({ scripts: [] })),
api.getCosHealth().catch(() => null),
api.getProviders().catch(() => ({ providers: [] })),
api.getApps().catch(() => []),
@@ -123,7 +121,6 @@ export default function ChiefOfStaff() {
setStatus(statusData);
setTasks(tasksData);
setAgents(agentsData);
- setScripts(scriptsData.scripts || []);
setHealth(healthData);
setProviders(providersData.providers || []);
// Filter out PortOS Autofixer (it's part of PortOS project)
@@ -141,6 +138,13 @@ export default function ChiefOfStaff() {
setActiveAgentMeta(runningAgent?.metadata || null);
}, [deriveAgentState]);
+ // Redirect unknown tab IDs to the default tab
+ useEffect(() => {
+ if (tab && !validTabIds.has(tab)) {
+ navigate('/cos/tasks', { replace: true });
+ }
+ }, [tab, validTabIds, navigate]);
+
useEffect(() => {
fetchData();
// Reduced polling since most updates come via socket events
@@ -812,11 +816,6 @@ export default function ChiefOfStaff() {
<JobsTab />
</div>
)}
- {activeTab === 'scripts' && (
- <div role="tabpanel" id="tabpanel-scripts" aria-labelledby="tab-scripts">
- <ScriptsTab scripts={scripts} onRefresh={fetchData} />
- </div>
- )}
{activeTab === 'schedule' && (
<div role="tabpanel" id="tabpanel-schedule" aria-labelledby="tab-schedule">
<ScheduleTab apps={apps} />
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 88dcbbbbc4..3a92e4ceba 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -717,22 +717,6 @@ export const updateCosTaskTemplate = (id, data) => request(`/cos/templates/${id}
});
export const deleteCosTaskTemplate = (id) => request(`/cos/templates/${id}`, { method: 'DELETE' });
-// CoS Scripts
-export const getCosScripts = () => request('/cos/scripts');
-export const getCosScript = (id) => request(`/cos/scripts/${id}`);
-export const createCosScript = (data) => request('/cos/scripts', {
- method: 'POST',
- body: JSON.stringify(data)
-});
-export const updateCosScript = (id, data) => request(`/cos/scripts/${id}`, {
- method: 'PUT',
- body: JSON.stringify(data)
-});
-export const deleteCosScript = (id) => request(`/cos/scripts/${id}`, { method: 'DELETE' });
-export const runCosScript = (id) => request(`/cos/scripts/${id}/run`, { method: 'POST' });
-export const getCosScriptRuns = (id) => request(`/cos/scripts/${id}/runs`);
-export const getCosScriptPresets = () => request('/cos/scripts/presets');
-
// Weekly Digest
export const getCosWeeklyDigest = (weekId = null) => {
if (weekId) return request(`/cos/digest/${weekId}`);
@@ -807,6 +791,7 @@ export const deleteCosScheduleTemplate = (templateId) => request(`/cos/schedule/
export const getCosJobs = () => request('/cos/jobs');
export const getCosJobsDue = () => request('/cos/jobs/due');
export const getCosJobIntervals = () => request('/cos/jobs/intervals');
+export const getCosJobAllowedCommands = () => request('/cos/jobs/allowed-commands');
export const getCosJob = (id) => request(`/cos/jobs/${id}`);
export const createCosJob = (data) => request('/cos/jobs', {
method: 'POST',
diff --git a/data.sample/prompts/skills/schedule/pr-reviewer.md b/data.sample/prompts/skills/schedule/pr-reviewer.md
new file mode 100644
index 0000000000..2d75449fa7
--- /dev/null
+++ b/data.sample/prompts/skills/schedule/pr-reviewer.md
@@ -0,0 +1,98 @@
+# PR Reviewer
+
+Scheduled task that checks managed apps for open PRs/MRs by other contributors and posts code reviews on any that lack a review since the last commit. Runs every 2 hours on weekdays.
+
+## Prompt Template
+
+You are acting as my Chief of Staff, reviewing pull requests and merge requests across managed apps.
+
+## Steps
+
+### Phase 0 — Prerequisites
+
+0. **Ensure slash-do is installed**
+ - Run `command -v slash-do` to check availability
+ - If not found, install it with `npm install -g slash-do@latest` to make `/do:` commands available
+
+### Phase 1 — Discover PRs
+
+1. **Find apps with repos**
+ - Call `GET /api/apps` to get all managed apps
+ - For each app with a `repoPath`, cd into the repo directory
+ - Skip archived apps
+
+2. **Detect SCM provider**
+ - Run `git remote get-url origin` in the repo
+ - If remote contains `github.com` -> use `gh` CLI
+ - If remote contains `gitlab` -> use `glab` CLI
+
+3. **List open PRs/MRs by others**
+ - GitHub: `gh pr list --state open --json number,author,headRefName,updatedAt,title`
+ - GitLab: `glab mr list --state opened -F json`
+ - Filter out PRs/MRs authored by my username (`atomantic`)
+
+### Phase 2 — Check Review Status
+
+4. **Determine if review is needed**
+ - For each PR/MR from other contributors:
+ - GitHub: `gh pr view <number> --json reviews,commits` — extract my reviews and compare timestamps against the latest commit
+ - GitLab: `glab mr view <iid> -F json` — check notes/approvals vs last commit date
+ - Skip PRs where I already have a review posted **after** the most recent commit push
+
+### Phase 3 — Review
+
+5. **Run code review and post**
+ - For each PR/MR needing review:
+ - cd into the app's `repoPath`
+ - Run `/do:review` to perform a deep code review of the changed files
+ - Post the review output as a comment:
+ - GitHub: `gh pr review <number> --comment --body "<review>"`
+ - GitLab: `glab mr note <iid> --message "<review>"`
+
+### Phase 4 — Report
+
+6. **Generate summary report** covering:
+ - Apps checked and PR/MR counts per app
+ - Reviews posted (with links to the PR/MR)
+ - PRs skipped (already reviewed since last commit)
+ - Any errors encountered (auth issues, missing CLI tools, etc.)
+
+## API Endpoints Used
+
+| Endpoint | Method | Purpose |
+|----------|--------|---------|
+| `/api/apps` | GET | List all managed apps with repoPath |
+
+## CLI Tools Used
+
+| Tool | Purpose |
+|------|---------|
+| `gh pr list` | List open GitHub PRs |
+| `gh pr view` | Get PR details including reviews and commits |
+| `gh pr review --comment` | Post review comment on GitHub PR |
+| `glab mr list` | List open GitLab MRs |
+| `glab mr view` | Get MR details including notes and commits |
+| `glab mr note` | Post review comment on GitLab MR |
+| `/do:review` | Run deep code review of changed files |
+
+## Expected Outputs
+
+1. **Review Comments** - Posted directly on each PR/MR needing review
+2. **Summary Report** - Saved via CoS reporting system
+
+## Success Criteria
+
+- All managed apps with repos are checked
+- SCM provider (GitHub/GitLab) is correctly detected per repo
+- Only PRs by other contributors are considered
+- PRs already reviewed since the last commit are skipped
+- `/do:review` is used for thorough code analysis
+- Review is posted as a comment on the PR/MR
+- Report provides clear visibility into review activity
+
+## Schedule Metadata
+
+- **Category**: pr-reviewer
+- **Interval**: Every 2 hours (weekdays only)
+- **Priority**: HIGH
+- **Autonomy Level**: manager (reviews and posts comments but does not approve/merge)
diff --git a/server/index.js b/server/index.js
index 55ec0c4810..b4af6272b9 100644
--- a/server/index.js
+++ b/server/index.js
@@ -30,7 +30,6 @@ import agentToolsRoutes from './routes/agentTools.js';
import cosRoutes from './routes/cos.js';
import featureAgentsRoutes from './routes/featureAgents.js';
import gsdRoutes from './routes/gsd.js';
-import scriptsRoutes from './routes/scripts.js';
import memoryRoutes from './routes/memory.js';
import notificationsRoutes from './routes/notifications.js';
import standardizeRoutes from './routes/standardize.js';
@@ -62,7 +61,6 @@ import { initSyncLog } from './services/brainSyncLog.js';
import { backfillOriginInstanceId } from './services/brainStorage.js';
import { initSyncOrchestrator } from './services/syncOrchestrator.js';
import { initSocket } from './services/socket.js';
-import { initScriptRunner } from './services/scriptRunner.js';
import { errorMiddleware, setupProcessErrorHandlers, asyncHandler } from './lib/errorHandler.js';
import { initAutoFixer } from './services/autoFixer.js';
import { initTaskLearning } from './services/taskLearning.js';
@@ -221,7 +219,6 @@ app.use('/api/agents/tools', agentToolsRoutes);
// Existing running agents routes (process management)
app.use('/api/agents', agentsRoutes);
app.use('/api/cos/gsd', gsdRoutes);
-app.use('/api/cos/scripts', scriptsRoutes); // Mount before /api/cos to avoid route conflicts
app.use('/api/cos', cosRoutes);
app.use('/api/feature-agents', featureAgentsRoutes);
app.use('/api/memory', memoryRoutes);
@@ -248,9 +245,6 @@ app.use('/api/github', githubRoutes);
app.use('/api/settings', settingsRoutes);
app.use('/api/update', updateRoutes);
-// Initialize script runner
-initScriptRunner().catch(err => console.error(`❌ Script runner init failed: ${err.message}`));
-
// Initialize agent automation scheduler and action executor
automationScheduler.init().catch(err => console.error(`❌ Agent scheduler init failed: ${err.message}`));
agentActionExecutor.init();
diff --git a/server/lib/commandSecurity.js b/server/lib/commandSecurity.js
index a088a6bb00..c42a786951 100644
--- a/server/lib/commandSecurity.js
+++ b/server/lib/commandSecurity.js
@@ -12,6 +12,72 @@ export const ALLOWED_COMMANDS = new Set([
'brew'
]);
+// Pre-sorted list for API responses
+export const ALLOWED_COMMANDS_SORTED = Array.from(ALLOWED_COMMANDS).sort();
+
// Shell metacharacters that could be used for command injection
// Security: Reject any command containing these to prevent injection via pipes, chaining, etc.
export const DANGEROUS_SHELL_CHARS = /[;|&`$(){}[\]<>\\!#*?~]/;
+
+/**
+ * Parse command string into args, respecting quoted strings.
+ * e.g. 'git commit -m "msg with spaces"' → ['git', 'commit', '-m', 'msg with spaces']
+ */
+function parseCommandArgs(str) {
+ const args = [];
+ let current = '';
+ let inQuote = null;
+ let hasQuote = false;
+ for (const ch of str) {
+ if (inQuote) {
+ if (ch === inQuote) { inQuote = null; continue; }
+ current += ch;
+ } else if (ch === '"' || ch === "'") {
+ inQuote = ch;
+ hasQuote = true;
+ } else if (/\s/.test(ch)) {
+ if (current || hasQuote) { args.push(current); current = ''; hasQuote = false; }
+ } else {
+ current += ch;
+ }
+ }
+ if (inQuote) return str.split(/\s+/); // fallback on unmatched quotes
+ if (current || hasQuote) args.push(current);
+ return args;
+}
+
+/**
+ * Validate a command against the allowlist.
+ * Returns { valid, error?, baseCommand?, args? }
+ */
+export function validateCommand(command) {
+ if (!command || typeof command !== 'string') {
+ return { valid: false, error: 'Command is required' };
+ }
+ const trimmed = command.trim();
+ if (!trimmed) return { valid: false, error: 'Command cannot be empty' };
+ if (DANGEROUS_SHELL_CHARS.test(trimmed)) {
+ return { valid: false, error: 'Command contains disallowed shell characters' };
+ }
+ const parts = parseCommandArgs(trimmed);
+ const baseCommand = parts[0];
+ if (!ALLOWED_COMMANDS.has(baseCommand)) {
+ return { valid: false, error: `Command '${baseCommand}' is not in the allowlist. Allowed: ${ALLOWED_COMMANDS_SORTED.join(', ')}` };
+ }
+ return { valid: true, baseCommand, args: parts.slice(1) };
+}
+
+// Patterns matching sensitive env var values in command output
+const SENSITIVE_ENV_PATTERN = /("(?:[a-z0-9]+_)*(?:KEY|SECRET|TOKEN|PASSWORD|PASSPHRASE|MACAROON|CERT|CREDENTIAL|AUTH)(?:_[a-z0-9]+)*":\s*)"[^"]+"/gi;
+
+/**
+ * Redact sensitive env var values from command output before persisting.
+ * Only redacts JSON key/value patterns (e.g. "SECRET_KEY": "value"). Shell-level
+ * leaks (env expansion, command substitution) are not covered — acceptable for
+ * PortOS's single-user, private-network deployment where the operator is the
+ * only user and shell output is not exposed to external consumers.
+ */
+export function redactOutput(output) {
+ if (!output) return output;
+ return output.replace(SENSITIVE_ENV_PATTERN, '$1"[REDACTED]"');
+}
diff --git a/server/routes/cos.js b/server/routes/cos.js
index 4830341213..68cd19758a 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -827,6 +827,11 @@ router.get('/jobs/intervals', (req, res) => {
res.json({ intervals: autonomousJobs.INTERVAL_OPTIONS });
});
+// GET /api/cos/jobs/allowed-commands - Get allowed commands for shell jobs
+router.get('/jobs/allowed-commands', (req, res) => {
+ res.json({ commands: autonomousJobs.getAllowedCommands() });
+});
+
// 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);
@@ -838,15 +843,22 @@ router.get('/jobs/:id', asyncHandler(async (req, res) => {
// POST /api/cos/jobs - Create a new autonomous job
router.post('/jobs', asyncHandler(async (req, res) => {
- const { name, description, category, interval, intervalMs, scheduledTime, enabled, priority, autonomyLevel, promptTemplate } = req.body;
+ const { name, description, category, type, interval, intervalMs, scheduledTime, enabled, priority, autonomyLevel, promptTemplate, command, triggerAction } = req.body;
- if (!name || !promptTemplate) {
- throw new ServerError('name and promptTemplate are required', { status: 400, code: 'VALIDATION_ERROR' });
+ // Shell jobs require command, agent jobs require promptTemplate
+ if (!name) {
+ throw new ServerError('name is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (type === 'shell' && !command?.trim()) {
+ throw new ServerError('command is required for shell jobs', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (type !== 'shell' && !promptTemplate) {
+ throw new ServerError('promptTemplate is required for agent jobs', { status: 400, code: 'VALIDATION_ERROR' });
}
const job = await autonomousJobs.createJob({
- name, description, category, interval, intervalMs, scheduledTime,
- enabled, priority, autonomyLevel, promptTemplate
+ name, description, category, type, interval, intervalMs, scheduledTime,
+ enabled, priority, autonomyLevel, promptTemplate, command, triggerAction
});
res.json({ success: true, job });
}));
@@ -876,18 +888,37 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {
throw new ServerError('Job not found', { status: 404, code: 'NOT_FOUND' });
}
+ // Shell jobs execute the command directly
+ if (autonomousJobs.isShellJob(job)) {
+ const result = await autonomousJobs.executeShellJob(job).catch(err => ({
+ success: false,
+ exitCode: err.exitCode ?? 1,
+ output: err.message
+ }));
+ return res.json({ success: result.success !== false, type: 'shell', ...result });
+ }
+
+ // Script jobs run their built-in handler directly
+ if (autonomousJobs.isScriptJob(job)) {
+ const result = await autonomousJobs.executeScriptJob(job).catch(err => ({
+ success: false,
+ error: err.message
+ }));
+ return res.json({ success: result.success !== false, type: 'script', ...result });
+ }
+
// Generate task and add to CoS internal task queue
// Job execution is recorded via the job:spawned event when the agent actually starts
// Manual triggers always bypass approval — the user explicitly requested execution
const task = await autonomousJobs.generateTaskFromJob(job);
- const result = await cos.addTask({
+ const taskResult = await cos.addTask({
description: task.description,
priority: task.priority,
context: `Manually triggered autonomous job: ${job.name}`,
approvalRequired: false
}, 'internal');
- res.json({ success: true, task: result });
+ res.json({ success: true, type: 'agent', taskId: taskResult.id });
}));
// DELETE /api/cos/jobs/:id - Delete a job
diff --git a/server/routes/scripts.js b/server/routes/scripts.js
deleted file mode 100644
index 472ea8dbdb..0000000000
--- a/server/routes/scripts.js
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * Scripts API Routes
- *
- * Endpoints for managing scheduled scripts
- */
-
-import { Router } from 'express';
-import * as scriptRunner from '../services/scriptRunner.js';
-import { asyncHandler } from '../lib/errorHandler.js';
-
-const router = Router();
-
-// GET /api/cos/scripts - List all scripts
-router.get('/', asyncHandler(async (req, res) => {
- const scripts = await scriptRunner.listScripts();
- res.json({ scripts });
-}));
-
-// GET /api/cos/scripts/presets - Get available schedule presets
-router.get('/presets', (req, res) => {
- res.json({ presets: scriptRunner.getSchedulePresets() });
-});
-
-// GET /api/cos/scripts/allowed-commands - Get allowed commands for scripts
-router.get('/allowed-commands', (req, res) => {
- res.json({ commands: scriptRunner.getAllowedScriptCommands() });
-});
-
-// GET /api/cos/scripts/jobs - Get scheduled job info
-router.get('/jobs', (req, res) => {
- res.json({ jobs: scriptRunner.getScheduledJobs() });
-});
-
-// POST /api/cos/scripts - Create a new script
-router.post('/', asyncHandler(async (req, res) => {
- const { name, description, command, schedule, cronExpression, enabled, triggerAction, triggerPrompt, triggerPriority } = req.body;
-
- if (!name) {
- return res.status(400).json({ error: 'name is required', code: 'VALIDATION_ERROR' });
- }
-
- if (!command) {
- return res.status(400).json({ error: 'command is required', code: 'VALIDATION_ERROR' });
- }
-
- const script = await scriptRunner.createScript({
- name,
- description,
- command,
- schedule,
- cronExpression,
- enabled,
- triggerAction,
- triggerPrompt,
- triggerPriority
- });
-
- res.status(201).json(script);
-}));
-
-// GET /api/cos/scripts/:id - Get a specific script
-router.get('/:id', asyncHandler(async (req, res) => {
- const script = await scriptRunner.getScript(req.params.id);
-
- if (script === null) {
- return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });
- }
-
- res.json(script);
-}));
-
-// PUT /api/cos/scripts/:id - Update a script
-router.put('/:id', asyncHandler(async (req, res) => {
- const script = await scriptRunner.updateScript(req.params.id, req.body);
-
- if (script === null) {
- return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });
- }
-
- res.json(script);
-}));
-
-// DELETE /api/cos/scripts/:id - Delete a script
-router.delete('/:id', asyncHandler(async (req, res) => {
- const deleted = await scriptRunner.deleteScript(req.params.id);
-
- if (deleted === false) {
- return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });
- }
-
- res.status(204).send();
-}));
-
-// POST /api/cos/scripts/:id/run - Execute a script immediately
-router.post('/:id/run', asyncHandler(async (req, res) => {
- const result = await scriptRunner.executeScript(req.params.id);
-
- if (result?.error === 'Script not found') {
- return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });
- }
-
- res.json(result);
-}));
-
-// GET /api/cos/scripts/:id/runs - Get script run history
-router.get('/:id/runs', asyncHandler(async (req, res) => {
- const limit = parseInt(req.query.limit, 10) || 10;
- const runs = await scriptRunner.getScriptRuns(req.params.id, limit);
-
- res.json({ runs });
-}));
-
-export default router;
diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.js
index 2368b235ae..75ac06deb5 100644
--- a/server/services/autonomousJobs.js
+++ b/server/services/autonomousJobs.js
@@ -14,15 +14,17 @@
* - Custom user-defined jobs
*/
-import { writeFile, readFile, rename } from 'fs/promises'
+import { writeFile, readFile, rename, readdir, stat, rm } from 'fs/promises'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
+import { existsSync } from 'fs'
import { v4 as uuidv4 } from 'uuid'
import { spawn } from 'child_process'
import { cosEvents } from './cosEvents.js'
import { DAY, ensureDir, HOUR, PATHS, readJSONFile } from '../lib/fileUtils.js'
import { createMutex } from '../lib/asyncMutex.js'
import { checkAndPrompt as autobiographyCheckAndPrompt } from './autobiography.js'
+import { validateCommand, redactOutput, ALLOWED_COMMANDS_SORTED } from '../lib/commandSecurity.js'
/**
* Run the moltworld-explore.mjs script as a child process (no AI agent needed).
@@ -67,9 +69,43 @@ function runMoltworldExploration() {
* Registry of script handlers for jobs that execute functions directly
* instead of spawning AI agents. Key is the scriptHandler name, value is the function.
*/
+/**
+ * Remove completed agent data directories older than 7 days.
+ */
+async function agentDataCleanup() {
+ const agentsDir = join(PATHS.cos, 'agents')
+ if (!existsSync(agentsDir)) return { cleaned: 0 }
+
+ const entries = await readdir(agentsDir)
+ const cutoff = Date.now() - 7 * DAY
+ let cleaned = 0
+
+ // Get active agent IDs so we never delete data for running agents
+ const { getActiveAgentIds } = await import('./subAgentSpawner.js')
+ const activeIds = new Set(getActiveAgentIds())
+
+ for (const entry of entries) {
+ if (activeIds.has(entry)) continue
+ const entryPath = join(agentsDir, entry)
+ const info = await stat(entryPath).catch(() => null)
+ if (!info?.isDirectory()) continue
+ if (info.mtimeMs < cutoff) {
+ const removed = await rm(entryPath, { recursive: true, force: true }).then(() => true, (err) => {
+ console.warn(`⚠️ Failed to clean agent dir ${entry}: ${err.message}`)
+ return false
+ })
+ if (removed) cleaned++
+ }
+ }
+
+ console.log(`🧹 Agent data cleanup: removed ${cleaned} directories older than 7 days`)
+ return { cleaned }
+}
+
const SCRIPT_HANDLERS = {
'autobiography-prompt': autobiographyCheckAndPrompt,
- 'moltworld-exploration': runMoltworldExploration
+ 'moltworld-exploration': runMoltworldExploration,
+ 'agent-data-cleanup': agentDataCleanup
}
const __filename = fileURLToPath(import.meta.url)
@@ -321,27 +357,179 @@ Phase 4 — Report:
createdAt: null,
updatedAt: null
},
+ {
+ id: 'job-system-health-check',
+ name: 'System Health Check',
+ description: 'Check PM2 process status.',
+ category: 'system-health',
+ interval: 'custom',
+ intervalMs: 15 * 60 * 1000,
+ enabled: true,
+ priority: 'LOW',
+ type: 'shell',
+ command: 'pm2 jlist',
+ triggerAction: 'log-only',
+ lastRun: null,
+ runCount: 0,
+ createdAt: null,
+ updatedAt: null
+ },
+ {
+ id: 'job-agent-data-cleanup',
+ name: 'Agent Data Cleanup',
+ description: 'Remove completed agent data older than 7 days.',
+ category: 'agent-data-cleanup',
+ interval: 'daily',
+ intervalMs: DAY,
+ enabled: true,
+ priority: 'LOW',
+ type: 'script',
+ scriptHandler: 'agent-data-cleanup',
+ lastRun: null,
+ runCount: 0,
+ createdAt: null,
+ updatedAt: null
+ },
]
+let initPromise = null
+
/**
- * Load jobs from disk
- * @returns {Promise<Object>} Jobs data
+ * Initialize jobs — called once at startup. Handles migration and default merging.
+ * Guarded by initPromise to prevent concurrent init from parallel requests.
*/
-async function loadJobs() {
+async function initJobs() {
await ensureDir(DATA_DIR)
const loaded = await readJSONFile(JOBS_FILE, null)
if (!loaded) {
const initial = createDefaultJobsData()
+ await migrateScriptsState(initial)
await saveJobs(initial)
return initial
}
- // Merge with defaults to ensure all default jobs exist
+ const jobCountBefore = loaded.jobs.length
const merged = mergeWithDefaults(loaded)
+ const migrated = await migrateScriptsState(merged)
+ if (!migrated && merged.jobs.length !== jobCountBefore) {
+ await saveJobs(merged)
+ }
return merged
}
+/**
+ * Load jobs from disk. On first call, runs one-time init (migration + defaults).
+ * Subsequent calls are read-only with in-memory default merging.
+ * @returns {Promise<Object>} Jobs data
+ */
+async function loadJobs() {
+ if (!initPromise) {
+ initPromise = initJobs()
+ }
+ await initPromise
+ const loaded = await readJSONFile(JOBS_FILE, null)
+ if (!loaded) return createDefaultJobsData()
+ return mergeWithDefaults(loaded)
+}
+
+/**
+ * Migrate scripts-state.json entries into jobs (one-time migration)
+ */
+async function migrateScriptsState(jobsData) {
+ const scriptsFile = join(DATA_DIR, 'scripts-state.json')
+ const raw = await readFile(scriptsFile, 'utf-8').catch(() => null)
+ if (!raw) return false
+
+ let scriptsState
+ try {
+ scriptsState = JSON.parse(raw)
+ } catch (err) {
+ console.warn(`⚠️ scripts-state.json is corrupted, skipping migration: ${err.message}`)
+ const failedSuffix = `.failed-${Date.now()}`
+ await rename(scriptsFile, scriptsFile + failedSuffix)
+ return false
+ }
+ const scripts = scriptsState.scripts ? Object.values(scriptsState.scripts) : []
+ if (scripts.length === 0) {
+ const migrateSuffix = `.migrated-${Date.now()}`
+ await rename(scriptsFile, scriptsFile + migrateSuffix)
+ return false
+ }
+
+ const now = new Date().toISOString()
+ const existingIds = new Set(jobsData.jobs.map(j => j.id))
+
+ // Map legacy schedule values to valid interval values
+ const VALID_INTERVALS = new Set(['hourly', 'every-2-hours', 'every-4-hours', 'every-8-hours', 'daily', 'weekly', 'biweekly', 'monthly', 'custom'])
+ const LEGACY_SCHEDULE_MAP = {
+ 'every-5-min': 'hourly',
+ 'every-10-min': 'hourly',
+ 'every-15-min': 'hourly',
+ 'every-30-min': 'hourly',
+ 'every-hour': 'hourly',
+ 'every-3-hours': 'every-4-hours',
+ 'every-6-hours': 'every-8-hours',
+ 'every-12-hours': 'daily',
+ 'twice-daily': 'daily'
+ }
+ const mapLegacySchedule = (schedule, scriptName) => {
+ if (!schedule || schedule === 'on-demand' || schedule === 'startup') return 'daily'
+ if (VALID_INTERVALS.has(schedule)) return schedule
+ if (LEGACY_SCHEDULE_MAP[schedule]) {
+ console.log(`📦 Mapped legacy schedule '${schedule}' for '${scriptName}' to '${LEGACY_SCHEDULE_MAP[schedule]}'`)
+ return LEGACY_SCHEDULE_MAP[schedule]
+ }
+ console.warn(`⚠️ Legacy schedule '${schedule}' for script '${scriptName}' not recognized, defaulting to 'daily'`)
+ return 'daily'
+ }
+
+ for (const script of scripts) {
+ const jobId = `job-migrated-${script.id}`
+ if (existingIds.has(jobId)) continue
+
+ const mappedInterval = mapLegacySchedule(script.schedule, script.name)
+ if (script.cronExpression) {
+ console.warn(`⚠️ Legacy cron expression '${script.cronExpression}' for script '${script.name}' not supported by job scheduler, using interval '${mappedInterval}' instead`)
+ }
+ const isOnDemandOrStartup = script.schedule === 'on-demand' || script.schedule === 'startup'
+
+ // Validate command against allowlist — disable jobs with invalid commands
+ let commandValid = true
+ if (script.command) {
+ const cmdValidation = validateCommand(script.command)
+ if (!cmdValidation.valid) {
+ console.warn(`⚠️ Migrated script '${script.name}' has invalid command, disabling: ${cmdValidation.error}`)
+ commandValid = false
+ }
+ }
+
+ jobsData.jobs.push({
+ id: jobId,
+ name: script.name,
+ description: script.description || '',
+ category: 'migrated-script',
+ type: 'shell',
+ command: commandValid ? script.command : null,
+ interval: mappedInterval,
+ intervalMs: resolveIntervalMs(mappedInterval),
+ enabled: commandValid ? (isOnDemandOrStartup ? false : (script.enabled || false)) : false,
+ priority: script.triggerPriority || 'MEDIUM',
+ triggerAction: 'log-only',
+ lastRun: script.lastRun || null,
+ runCount: script.runCount || 0,
+ createdAt: script.createdAt || now,
+ updatedAt: now
+ })
+ }
+
+ await saveJobs(jobsData)
+ const migrateSuffix = `.migrated-${Date.now()}`
+ await rename(scriptsFile, scriptsFile + migrateSuffix)
+ console.log(`📦 Migrated ${scripts.length} scripts to jobs`)
+ return true
+}
+
/**
* Create initial jobs data with defaults
*/
@@ -362,6 +550,9 @@ function createDefaultJobsData() {
* Merge loaded data with defaults (add any missing default jobs)
*/
function mergeWithDefaults(loaded) {
+ // Migration: remove pr-reviewer job (moved to Schedule system)
+ loaded.jobs = loaded.jobs.filter(j => j.id !== 'job-pr-reviewer')
+
const existingById = new Map(loaded.jobs.map(j => [j.id, j]))
const now = new Date().toISOString()
@@ -493,11 +684,35 @@ async function createJob(jobData) {
const data = await loadJobs()
const now = new Date().toISOString()
+ // Validate shell command at creation time
+ if (jobData.type === 'shell') {
+ if (!jobData.command || !jobData.command.trim()) {
+ const err = new Error('Shell jobs require a non-empty command')
+ err.status = 400
+ throw err
+ }
+ const validation = validateCommand(jobData.command)
+ if (!validation.valid) {
+ const err = new Error(`Invalid command: ${validation.error}`)
+ err.status = 400
+ throw err
+ }
+ }
+
+ const jobType = jobData.type || 'agent'
+
+ // Strip agent-specific triggerAction values from shell jobs
+ const agentOnlyActions = ['spawn-agent', 'create-task']
+ const triggerAction = (jobType === 'shell' && agentOnlyActions.includes(jobData.triggerAction))
+ ? 'log-only'
+ : (jobData.triggerAction || null)
+
const job = {
id: jobData.id || `job-${uuidv4().slice(0, 8)}`,
name: jobData.name,
description: jobData.description || '',
category: jobData.category || 'custom',
+ type: jobType,
interval: jobData.interval || 'weekly',
intervalMs: resolveIntervalMs(jobData.interval || 'weekly', jobData.intervalMs),
scheduledTime: jobData.scheduledTime || null,
@@ -506,6 +721,8 @@ async function createJob(jobData) {
priority: jobData.priority || 'MEDIUM',
autonomyLevel: jobData.autonomyLevel || 'manager',
promptTemplate: jobData.promptTemplate || '',
+ command: jobData.command || null,
+ triggerAction,
lastRun: null,
runCount: 0,
createdAt: now,
@@ -534,9 +751,21 @@ async function updateJob(jobId, updates) {
const job = data.jobs.find(j => j.id === jobId)
if (!job) return null
+ // Normalize falsy command values to empty string for consistent validation
+ if (updates.command !== undefined && !updates.command) {
+ updates.command = ''
+ }
+
+ // If type is being changed away from shell, allow clearing the command
+ const effectiveType = updates.type ?? job.type
+ if (effectiveType !== 'shell' && updates.command === '') {
+ updates.command = null
+ }
+
const updatableFields = [
- 'name', 'description', 'category', 'interval', 'intervalMs',
- 'scheduledTime', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate'
+ 'name', 'description', 'category', 'type', 'interval', 'intervalMs',
+ 'scheduledTime', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate',
+ 'command', 'triggerAction'
]
for (const field of updatableFields) {
@@ -550,6 +779,27 @@ async function updateJob(jobId, updates) {
job.intervalMs = resolveIntervalMs(updates.interval, updates.intervalMs)
}
+ // Validate shell jobs have a valid command after all fields are applied
+ if (job.type === 'shell') {
+ if (!job.command || !job.command.trim()) {
+ const err = new Error('Shell jobs require a non-empty command')
+ err.status = 400
+ throw err
+ }
+ const cmdValidation = validateCommand(job.command)
+ if (!cmdValidation.valid) {
+ const err = new Error(`Invalid command: ${cmdValidation.error}`)
+ err.status = 400
+ throw err
+ }
+ }
+
+ // Strip agent-specific triggerAction values from shell jobs
+ const agentOnlyActions = ['spawn-agent', 'create-task']
+ if (job.type === 'shell' && agentOnlyActions.includes(job.triggerAction)) {
+ job.triggerAction = 'log-only'
+ }
+
job.updatedAt = new Date().toISOString()
await saveJobs(data)
@@ -810,6 +1060,7 @@ async function getNextDueJob() {
function resolveIntervalMs(interval, customMs) {
switch (interval) {
case 'hourly': return HOUR
+ case 'every-2-hours': return 2 * HOUR
case 'every-4-hours': return 4 * HOUR
case 'every-8-hours': return 8 * HOUR
case 'daily': return DAY
@@ -826,6 +1077,7 @@ function resolveIntervalMs(interval, customMs) {
*/
const INTERVAL_OPTIONS = [
{ value: 'hourly', label: 'Every Hour', ms: HOUR },
+ { value: 'every-2-hours', label: 'Every 2 Hours', ms: 2 * 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 },
@@ -867,6 +1119,162 @@ async function executeScriptJob(job) {
return result
}
+
+/**
+ * Execute a shell job directly (no AI agent needed)
+ */
+async function executeShellJob(job) {
+ const validation = validateCommand(job.command)
+ if (!validation.valid) {
+ throw new Error(`Invalid shell command: ${validation.error}`)
+ }
+
+ console.log(`🐚 Executing shell job: ${job.name}`)
+
+ const SHELL_JOB_TIMEOUT_MS = 5 * 60 * 1000
+ const timeoutMs = SHELL_JOB_TIMEOUT_MS
+
+ return new Promise((resolve, reject) => {
+ let killed = false
+ const child = spawn(validation.baseCommand, validation.args || [], {
+ cwd: join(__dirname, '../../'),
+ shell: false,
+ windowsHide: true
+ })
+
+ const timer = setTimeout(() => {
+ if (child.exitCode !== null) return
+ killed = true
+ child.kill('SIGKILL')
+ console.error(`⏰ Shell job timed out after ${timeoutMs}ms: ${job.name}`)
+ }, timeoutMs)
+
+ const MAX_OUTPUT_BYTES = 512 * 1024 // 512KB buffer limit
+ const outChunks = []
+ const errChunks = []
+ let outBytes = 0
+ let errBytes = 0
+
+ child.stdout.on('data', (data) => {
+ if (outBytes < MAX_OUTPUT_BYTES) { outChunks.push(data.toString()); outBytes += data.length }
+ })
+ child.stderr.on('data', (data) => {
+ if (errBytes < MAX_OUTPUT_BYTES) { errChunks.push(data.toString()); errBytes += data.length }
+ })
+
+ child.on('close', (rawCode, signal) => {
+ const code = rawCode ?? (signal ? 128 : 1)
+ clearTimeout(timer)
+ if (killed) {
+ const persistTimeout = async () => {
+ await withLock(async () => {
+ const data = await loadJobs()
+ const j = data.jobs.find(x => x.id === job.id)
+ if (j) {
+ j.lastOutput = `Process killed after ${timeoutMs}ms timeout`
+ j.lastExitCode = -1
+ j.lastResult = 'timeout'
+ await saveJobs(data)
+ }
+ })
+ await recordJobExecution(job.id)
+ }
+ persistTimeout().then(() => {
+ const err = new Error(`Shell job "${job.name}" timed out after ${timeoutMs}ms`)
+ err.exitCode = -1
+ reject(err)
+ }).catch((persistErr) => {
+ console.error(`❌ Shell job ${job.name} failed to persist timeout state: ${persistErr.message}`)
+ const err = new Error(`Shell job "${job.name}" timed out after ${timeoutMs}ms`)
+ err.exitCode = -1
+ reject(err)
+ })
+ return
+ }
+ const output = outChunks.join('')
+ const error = errChunks.join('')
+ const fullOutput = output + (error ? `\n[stderr]\n${error}` : '')
+ const redactedOutput = redactOutput(fullOutput)
+
+ // Persist output/exit code and record execution in a single lock cycle
+ const persist = async () => {
+ await withLock(async () => {
+ const data = await loadJobs()
+ const j = data.jobs.find(x => x.id === job.id)
+ if (j) {
+ j.lastOutput = redactedOutput.substring(0, 10000)
+ j.lastExitCode = code
+ j.lastRun = new Date().toISOString()
+ j.lastResult = code === 0 ? 'success' : 'failure'
+ j.runCount = (j.runCount || 0) + 1
+ j.updatedAt = j.lastRun
+ await saveJobs(data)
+ console.log(`🤖 Shell job executed: ${j.name} (run #${j.runCount})`)
+ cosEvents.emit('jobs:executed', { id: job.id, runCount: j.runCount })
+ }
+ })
+ }
+
+ persist().then(() => {
+ if (code !== 0) {
+ console.error(`❌ Shell job failed: ${job.name} (exit ${code})`)
+ cosEvents.emit('jobs:shell-executed', { id: job.id, exitCode: code })
+ const err = new Error(`Shell job "${job.name}" exited with code ${code}: ${redactedOutput.substring(0, 500)}`)
+ err.exitCode = code
+ reject(err)
+ return
+ }
+
+ console.log(`✅ Shell job completed: ${job.name} (exit ${code})`)
+ cosEvents.emit('jobs:shell-executed', { id: job.id, exitCode: code })
+ resolve({ success: true, exitCode: code, output: redactedOutput })
+ }).catch((persistErr) => {
+ console.error(`❌ Shell job ${job.name} failed to persist state: ${persistErr.message}`)
+ reject(persistErr)
+ })
+ })
+
+ child.on('error', (err) => {
+ clearTimeout(timer)
+ console.error(`❌ Shell job ${job.name} error: ${err.message}`)
+ const persistError = async () => {
+ await withLock(async () => {
+ const data = await loadJobs()
+ const j = data.jobs.find(x => x.id === job.id)
+ if (j) {
+ j.lastOutput = err.message
+ j.lastExitCode = -1
+ j.lastRun = new Date().toISOString()
+ j.lastResult = 'error'
+ await saveJobs(data)
+ }
+ })
+ await recordJobExecution(job.id)
+ }
+ persistError().then(() => {
+ reject(new Error(`Shell job "${job.name}" spawn error: ${err.message}`))
+ }).catch((persistErr) => {
+ console.error(`❌ Shell job ${job.name} failed to persist error state: ${persistErr.message}`)
+ reject(new Error(`Shell job "${job.name}" spawn error: ${err.message}`))
+ })
+ })
+ })
+}
+
+/**
+ * Check if a job is a shell command job
+ */
+function isShellJob(job) {
+ return job.type === 'shell'
+}
+
+/**
+ * Get list of allowed commands for shell jobs
+ */
+function getAllowedCommands() {
+ return ALLOWED_COMMANDS_SORTED
+}
+
export {
getAllJobs,
getJob,
@@ -889,5 +1297,9 @@ export {
getJobEffectivePrompt,
JOB_SKILL_MAP,
isScriptJob,
- executeScriptJob
+ executeScriptJob,
+ isShellJob,
+ executeShellJob,
+ getAllowedCommands,
+ validateCommand
}
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
index 6a3739714e..319f99b66e 100644
--- a/server/services/autonomousJobs.test.js
+++ b/server/services/autonomousJobs.test.js
@@ -136,7 +136,7 @@ describe('autonomousJobs', () => {
// Verify only expected test jobs plus any default jobs are present
const testJobIds = new Set(['job-test-1', 'job-1', 'job-2'])
- const defaultJobPrefixes = ['job-github-', 'job-brain-', 'job-daily-', 'job-moltworld-', 'job-jira-', 'job-autobiography-']
+ const defaultJobPrefixes = ['job-github-', 'job-brain-', 'job-daily-', 'job-moltworld-', 'job-jira-', 'job-autobiography-', 'job-system-', 'job-agent-', 'job-datadog-']
const unexpectedJobs = due.filter(j => !testJobIds.has(j.id) && !defaultJobPrefixes.some(p => j.id.startsWith(p)))
expect(unexpectedJobs).toHaveLength(0)
})
@@ -215,6 +215,19 @@ describe('autonomousJobs', () => {
expect(job.intervalMs).toBe(7 * 24 * 60 * 60 * 1000)
expect(job.interval).toBe('weekly')
})
+
+ it('every-2-hours interval produces correct intervalMs', async () => {
+ const jobData = {
+ name: 'Bi-Hourly Job',
+ interval: 'every-2-hours',
+ promptTemplate: 'Do bi-hourly thing'
+ }
+
+ const job = await createJob(jobData)
+
+ expect(job.intervalMs).toBe(2 * 60 * 60 * 1000)
+ expect(job.interval).toBe('every-2-hours')
+ })
})
describe('INTERVAL_OPTIONS', () => {
diff --git a/server/services/cos.js b/server/services/cos.js
index 4bac7cad0d..8a446b7cc4 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -21,7 +21,7 @@ import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSumma
import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats } from './eventScheduler.js';
import { createMutex } from '../lib/asyncMutex.js';
import { generateProactiveTasks as generateMissionTasks, getStats as getMissionStats } from './missions.js';
-import { generateTaskFromJob, recordJobExecution, isScriptJob, executeScriptJob } from './autonomousJobs.js';
+import { generateTaskFromJob, recordJobExecution, isScriptJob, executeScriptJob, isShellJob, executeShellJob } from './autonomousJobs.js';
import { formatDuration, safeJSONParse } from '../lib/fileUtils.js';
import { addNotification, NOTIFICATION_TYPES } from './notifications.js';
import { recordDecision, DECISION_TYPES } from './decisionLog.js';
@@ -3635,12 +3635,19 @@ async function executeScheduledJob(jobId) {
return;
}
- // Script jobs execute directly without spawning an AI agent
+ // Script jobs and shell jobs execute directly without spawning an AI agent
if (isScriptJob(job)) {
- await executeScriptJob(job).catch(err => {
+ const scriptOk = await executeScriptJob(job).then(() => true, err => {
emitLog('error', `Script job failed: ${job.name} - ${err.message}`, { jobId: job.id });
+ return false;
});
- emitLog('info', `Script job executed: ${job.name}`, { jobId: job.id });
+ if (scriptOk) emitLog('info', `Script job executed: ${job.name}`, { jobId: job.id });
+ } else if (isShellJob(job)) {
+ const shellOk = await executeShellJob(job).then(() => true, err => {
+ emitLog('error', `Shell job failed: ${job.name} - ${err.message}`, { jobId: job.id });
+ return false;
+ });
+ if (shellOk) emitLog('info', `Shell job executed: ${job.name}`, { jobId: job.id });
} else {
// Check if this job is already being spawned or has a running agent
if (spawningJobIds.has(jobId)) {
@@ -3795,6 +3802,10 @@ async function init() {
if (daemonRunning) setImmediate(() => dequeueNextTask());
});
+ cosEvents.on('task:on-demand-requested', () => {
+ if (daemonRunning) setImmediate(() => dequeueNextTask());
+ });
+
// Autonomous job lifecycle → re-register/cancel individual job timers
cosEvents.on('jobs:toggled', async ({ id }) => {
if (daemonRunning) await registerSingleJobSchedule(id);
diff --git a/server/services/scriptRunner.js b/server/services/scriptRunner.js
deleted file mode 100644
index 6c75afb310..0000000000
--- a/server/services/scriptRunner.js
+++ /dev/null
@@ -1,483 +0,0 @@
-/**
- * Script Runner Service
- *
- * Manages scheduled scripts that can trigger LLM agents
- * when they detect issues requiring investigation.
- */
-
-import { spawn } from 'child_process';
-import { join, dirname } from 'path';
-import { fileURLToPath } from 'url';
-import { existsSync } from 'fs';
-import { writeFile, mkdir, readdir, rm } from 'fs/promises';
-import { v4 as uuidv4 } from 'uuid';
-import Cron from 'croner';
-import { cosEvents } from './cosEvents.js';
-import { readJSONFile } from '../lib/fileUtils.js';
-import { ALLOWED_COMMANDS, DANGEROUS_SHELL_CHARS } from '../lib/commandSecurity.js';
-
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = dirname(__filename);
-const SCRIPTS_DIR = join(__dirname, '../../data/cos/scripts');
-const SCRIPTS_STATE_FILE = join(__dirname, '../../data/cos/scripts-state.json');
-
-// Active scheduled jobs
-const scheduledJobs = new Map();
-
-// Execution lock to prevent duplicate runs (tracks last execution time)
-const executionLock = new Map();
-
-// Patterns matching sensitive environment variable values in command output (e.g., pm2 jlist)
-// Keys must be underscore-delimited segments to avoid false positives like "monkey" or "keymetrics"
-const SENSITIVE_ENV_PATTERN = /("(?:[a-z0-9]+_)*(?:KEY|SECRET|TOKEN|PASSWORD|PASSPHRASE|MACAROON|CERT|CREDENTIAL|AUTH)(?:_[a-z0-9]+)*":\s*)"[^"]+"/gi;
-
-/**
- * Redact sensitive env vars from command output before persisting.
- * Matches JSON key-value pairs where the key contains secret-like words.
- */
-function redactSensitiveOutput(output) {
- if (!output) return output;
- return output.replace(SENSITIVE_ENV_PATTERN, '$1"[REDACTED]"');
-}
-
-/**
- * Validate a script command against the allowlist
- * Returns { valid: boolean, error?: string, baseCommand?: string, args?: string[] }
- *
- * Security measures:
- * 1. Base command must be in allowlist
- * 2. Command cannot contain shell metacharacters that enable injection
- */
-function validateScriptCommand(command) {
- if (!command || typeof command !== 'string') {
- return { valid: false, error: 'Command is required' };
- }
-
- const trimmed = command.trim();
- if (!trimmed) {
- return { valid: false, error: 'Command cannot be empty' };
- }
-
- // Security: Check for dangerous shell metacharacters that could enable command injection
- // This prevents attacks like: npm; rm -rf / or npm && malicious_cmd or npm | cat /etc/passwd
- if (DANGEROUS_SHELL_CHARS.test(trimmed)) {
- return {
- valid: false,
- error: 'Command contains disallowed shell characters (security restriction). Pipes, semicolons, and other shell operators are not allowed.'
- };
- }
-
- // Extract the base command (first word before space)
- const parts = trimmed.split(/\s+/);
- const baseCommand = parts[0];
-
- if (!ALLOWED_COMMANDS.has(baseCommand)) {
- return {
- valid: false,
- error: `Command '${baseCommand}' is not in the allowlist. Allowed: ${Array.from(ALLOWED_COMMANDS).sort().join(', ')}`
- };
- }
-
- return { valid: true, baseCommand, args: parts.slice(1) };
-}
-
-// Schedule presets to cron expressions
-const SCHEDULE_PRESETS = {
- 'every-5-min': '*/5 * * * *',
- 'every-15-min': '*/15 * * * *',
- 'every-30-min': '*/30 * * * *',
- 'hourly': '0 * * * *',
- 'every-6-hours': '0 */6 * * *',
- 'daily': '0 9 * * *',
- 'weekly': '0 9 * * 1',
- 'on-demand': null
-};
-
-/**
- * Initialize the script runner
- */
-export async function initScriptRunner() {
- await ensureScriptsDir();
- const scripts = await listScripts();
-
- // Schedule all enabled scripts
- for (const script of scripts) {
- if (script.enabled && script.schedule !== 'on-demand') {
- scheduleScript(script);
- }
- }
-
- console.log(`📜 Script runner initialized with ${scripts.length} scripts`);
-}
-
-/**
- * Ensure scripts directory exists
- */
-async function ensureScriptsDir() {
- if (!existsSync(SCRIPTS_DIR)) {
- await mkdir(SCRIPTS_DIR, { recursive: true });
- }
-}
-
-/**
- * Load scripts state
- */
-async function loadScriptsState() {
- return readJSONFile(SCRIPTS_STATE_FILE, { scripts: {} });
-}
-
-/**
- * Save scripts state
- */
-async function saveScriptsState(state) {
- await writeFile(SCRIPTS_STATE_FILE, JSON.stringify(state, null, 2));
-}
-
-/**
- * Convert schedule to cron expression
- */
-function scheduleToCron(schedule, customCron = null) {
- if (customCron) return customCron;
- return SCHEDULE_PRESETS[schedule] || null;
-}
-
-/**
- * Schedule a script
- */
-export function scheduleScript(script) {
- // Stop existing job if any
- unscheduleScript(script.id);
-
- const cronExpr = scheduleToCron(script.schedule, script.cronExpression);
- if (!cronExpr) return; // on-demand scripts don't get scheduled
-
- const job = new Cron(cronExpr, async () => {
- await executeScript(script.id);
- });
-
- scheduledJobs.set(script.id, job);
- console.log(`⏰ Scheduled script ${script.name} (${script.id}) with cron: ${cronExpr}`);
-}
-
-/**
- * Unschedule a script
- */
-export function unscheduleScript(scriptId) {
- const job = scheduledJobs.get(scriptId);
- if (job) {
- job.stop();
- scheduledJobs.delete(scriptId);
- }
-}
-
-/**
- * Create a new script
- */
-export async function createScript(data) {
- // Security: Validate command against allowlist before creating
- const validation = validateScriptCommand(data.command);
- if (!validation.valid) {
- throw new Error(`Invalid script command: ${validation.error}`);
- }
-
- const id = `script-${uuidv4().slice(0, 8)}`;
-
- const script = {
- id,
- name: data.name,
- description: data.description || '',
- command: data.command,
- schedule: data.schedule || 'on-demand',
- cronExpression: data.cronExpression || null,
- enabled: data.enabled === true,
- triggerAction: data.triggerAction || 'log-only', // 'spawn-agent' | 'create-task' | 'log-only'
- triggerPrompt: data.triggerPrompt || '',
- triggerPriority: data.triggerPriority || 'MEDIUM',
- createdAt: new Date().toISOString(),
- lastRun: null,
- lastOutput: null,
- lastExitCode: null,
- lastTriggered: null,
- runCount: 0
- };
-
- const state = await loadScriptsState();
- state.scripts[id] = script;
- await saveScriptsState(state);
-
- // Schedule if enabled
- if (script.enabled && script.schedule !== 'on-demand') {
- scheduleScript(script);
- }
-
- cosEvents.emit('script:created', script);
- return script;
-}
-
-/**
- * Update a script
- */
-export async function updateScript(id, data) {
- // Security: Validate command against allowlist if being updated
- if (data.command !== undefined) {
- const validation = validateScriptCommand(data.command);
- if (!validation.valid) {
- throw new Error(`Invalid script command: ${validation.error}`);
- }
- }
-
- const state = await loadScriptsState();
- const script = state.scripts[id];
-
- if (!script) {
- return null;
- }
-
- // Update fields
- const updatedScript = {
- ...script,
- name: data.name ?? script.name,
- description: data.description ?? script.description,
- command: data.command ?? script.command,
- schedule: data.schedule ?? script.schedule,
- cronExpression: data.cronExpression ?? script.cronExpression,
- enabled: data.enabled ?? script.enabled,
- triggerAction: data.triggerAction ?? script.triggerAction,
- triggerPrompt: data.triggerPrompt ?? script.triggerPrompt,
- triggerPriority: data.triggerPriority ?? script.triggerPriority,
- updatedAt: new Date().toISOString()
- };
-
- state.scripts[id] = updatedScript;
- await saveScriptsState(state);
-
- // Reschedule if needed
- if (updatedScript.enabled && updatedScript.schedule !== 'on-demand') {
- scheduleScript(updatedScript);
- } else {
- unscheduleScript(id);
- }
-
- cosEvents.emit('script:updated', updatedScript);
- return updatedScript;
-}
-
-/**
- * Delete a script
- */
-export async function deleteScript(id) {
- unscheduleScript(id);
-
- const state = await loadScriptsState();
- if (!state.scripts[id]) {
- return false;
- }
-
- delete state.scripts[id];
- await saveScriptsState(state);
-
- cosEvents.emit('script:deleted', { id });
- return true;
-}
-
-/**
- * Get a script by ID
- */
-export async function getScript(id) {
- const state = await loadScriptsState();
- return state.scripts[id] || null;
-}
-
-/**
- * List all scripts
- */
-export async function listScripts() {
- const state = await loadScriptsState();
- return Object.values(state.scripts).sort((a, b) =>
- new Date(b.createdAt) - new Date(a.createdAt)
- );
-}
-
-/**
- * Execute a script
- */
-export async function executeScript(scriptId) {
- // De-duplication: prevent duplicate execution within 5 seconds
- const now = Date.now();
- const lastExecution = executionLock.get(scriptId);
- if (lastExecution && (now - lastExecution) < 5000) {
- console.log(`⏭️ Skipping duplicate execution of ${scriptId} (last run ${now - lastExecution}ms ago)`);
- return { success: false, error: 'Duplicate execution prevented', skipped: true };
- }
- executionLock.set(scriptId, now);
-
- const state = await loadScriptsState();
- const script = state.scripts[scriptId];
-
- if (!script) {
- executionLock.delete(scriptId);
- return { success: false, error: 'Script not found' };
- }
-
- // Security: Defense in depth - validate command at execution time
- // (in case state file was manually modified)
- const validation = validateScriptCommand(script.command);
- if (!validation.valid) {
- console.error(`❌ Script ${script.name} has invalid command: ${validation.error}`);
- executionLock.delete(scriptId);
- return { success: false, error: `Invalid command: ${validation.error}` };
- }
-
- console.log(`▶️ Executing script: ${script.name} (${scriptId})`);
- cosEvents.emit('script:started', { scriptId, name: script.name });
-
- const startTime = Date.now();
-
- return new Promise((resolve) => {
- // Security: Use spawn with array of args (shell:false) to prevent shell injection
- // The validation function ensures no metacharacters are present
- const child = spawn(validation.baseCommand, validation.args || [], {
- cwd: join(__dirname, '../../'),
- timeout: 60000, // 1 minute timeout
- shell: false,
- windowsHide: true
- });
-
- let output = '';
- let error = '';
-
- child.stdout.on('data', (data) => {
- output += data.toString();
- });
-
- child.stderr.on('data', (data) => {
- error += data.toString();
- });
-
- child.on('close', async (code) => {
- const duration = Date.now() - startTime;
- const fullOutput = output + (error ? `\n[stderr]\n${error}` : '');
- const redactedOutput = redactSensitiveOutput(fullOutput);
-
- // Update script state
- script.lastRun = new Date().toISOString();
- script.lastOutput = redactedOutput.substring(0, 10000);
- script.lastExitCode = code;
- script.runCount = (script.runCount || 0) + 1;
-
- state.scripts[scriptId] = script;
- await saveScriptsState(state);
-
- // Clear execution lock after completion
- executionLock.delete(scriptId);
-
- console.log(`✅ Script ${script.name} completed with code ${code} in ${duration}ms`);
-
- // Handle trigger action
- if (script.triggerAction === 'spawn-agent' && script.triggerPrompt) {
- console.log(`🚀 Triggering agent for script ${script.name}`);
- script.lastTriggered = new Date().toISOString();
- state.scripts[scriptId] = script;
- await saveScriptsState(state);
-
- cosEvents.emit('task:ready', {
- id: `script-${scriptId}-${Date.now()}`,
- priority: script.triggerPriority,
- description: script.triggerPrompt,
- taskType: 'internal',
- metadata: {
- context: `Script Output:\n\`\`\`\n${redactedOutput.substring(0, 5000)}\n\`\`\``,
- source: 'script',
- scriptId,
- scriptName: script.name
- }
- });
- }
-
- cosEvents.emit('script:completed', {
- scriptId,
- name: script.name,
- exitCode: code,
- duration,
- outputLength: redactedOutput.length
- });
-
- resolve({
- success: code === 0,
- exitCode: code,
- output: redactedOutput,
- duration
- });
- });
-
- child.on('error', async (err) => {
- console.error(`❌ Script ${script.name} error: ${err.message}`);
-
- script.lastRun = new Date().toISOString();
- script.lastOutput = `Error: ${err.message}`;
- script.lastExitCode = -1;
- state.scripts[scriptId] = script;
- await saveScriptsState(state);
-
- // Clear execution lock on error
- executionLock.delete(scriptId);
-
- cosEvents.emit('script:error', { scriptId, error: err.message });
-
- resolve({
- success: false,
- error: err.message
- });
- });
- });
-}
-
-/**
- * Get script run history (from state)
- */
-export async function getScriptRuns(scriptId, limit = 10) {
- // For now, we only store the last run in state
- // Could be extended to store full history
- const script = await getScript(scriptId);
- if (!script) return [];
-
- if (script.lastRun) {
- return [{
- timestamp: script.lastRun,
- output: script.lastOutput,
- exitCode: script.lastExitCode,
- triggered: script.lastTriggered
- }];
- }
-
- return [];
-}
-
-/**
- * Get available schedule presets
- */
-export function getSchedulePresets() {
- return Object.keys(SCHEDULE_PRESETS);
-}
-
-/**
- * Get scheduled job info
- */
-export function getScheduledJobs() {
- const jobs = [];
- for (const [scriptId, job] of scheduledJobs) {
- jobs.push({
- scriptId,
- nextRun: job.nextRun()?.toISOString(),
- isRunning: job.isRunning()
- });
- }
- return jobs;
-}
-
-/**
- * Get list of allowed commands for scripts
- */
-export function getAllowedScriptCommands() {
- return Array.from(ALLOWED_COMMANDS).sort();
-}
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 0e7b27214b..904edee1df 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -110,7 +110,7 @@ async function getPerformanceAdjustedInterval(taskType, baseIntervalMs) {
}
// ============================================================
-// Unified DEFAULT_TASK_PROMPTS (14 task types)
+// Unified DEFAULT_TASK_PROMPTS (15 task types)
// All prompts use {appName} and {repoPath} template variables
// ============================================================
@@ -499,15 +499,55 @@ Summarize:
- Number of review iterations needed
- Any unresolved issues
-IMPORTANT: Always use \`git pull --rebase --autostash\` before pushing (dev branch gets auto-bumped by CI). Never use \`git push\` alone.`
+IMPORTANT: Always use \`git pull --rebase --autostash\` before pushing (dev branch gets auto-bumped by CI). Never use \`git push\` alone.`,
+
+ 'pr-reviewer': `[Improvement: {appName}] PR Review — Check Open PRs
+
+Review open pull requests / merge requests on {appName} from other contributors and post code reviews on any that lack a review since the last commit.
+
+Repository: {repoPath}
+
+## Phase 0 — Prerequisites
+
+0. Ensure slash-do is installed by running \`command -v slash-do\`. If not found, install it with \`npm install -g slash-do@latest\`.
+
+## Phase 1 — Discover PRs
+
+1. cd into {repoPath}
+2. Detect SCM provider from git remote URL:
+ - Contains "github.com" -> use \`gh\` CLI
+ - Contains "gitlab" -> use \`glab\` CLI
+3. List open PRs/MRs authored by others (not by atomantic):
+ - GitHub: \`gh pr list --state open --json number,author,headRefName,updatedAt,title\`
+ - GitLab: \`glab mr list --state opened -F json\`
+
+## Phase 2 — Check Review Status
+
+4. For each PR/MR from other contributors:
+ - GitHub: \`gh pr view <number> --json reviews,commits\` — check if I have a review newer than the latest commit
+ - GitLab: \`glab mr view <iid> -F json\` — check notes/approvals vs last commit date
+5. Skip PRs where I already have a review posted after the most recent commit push
+
+## Phase 3 — Review
+
+6. For each PR/MR needing review:
+ - cd into {repoPath}
+ - Run \`/do:review\` to perform a deep code review of the changed files
+ - Post the review:
+ - GitHub: \`gh pr review <number> --comment --body "<review>"\`
+ - GitLab: \`glab mr note <iid> --message "<review>"\`
+
+## Phase 4 — Report
+
+7. Summarize: apps checked, PRs reviewed (with links), PRs skipped (already reviewed)`
};
-// Unified default interval settings for all 14 task types
+// Unified default interval settings for all 15 task types
export const SELF_IMPROVEMENT_TASK_TYPES = [
'security', 'code-quality', 'test-coverage', 'performance',
'accessibility', 'console-errors', 'dependency-updates', 'documentation',
'ui-bugs', 'mobile-responsive', 'feature-ideas', 'error-handling',
- 'typing', 'release-check'
+ 'typing', 'release-check', 'pr-reviewer'
];
const DEFAULT_TASK_INTERVALS = {
@@ -524,7 +564,8 @@ const DEFAULT_TASK_INTERVALS = {
'feature-ideas': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null },
'error-handling': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },
'typing': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null },
- 'release-check': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null }
+ 'release-check': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null },
+ 'pr-reviewer': { type: INTERVAL_TYPES.CUSTOM, intervalMs: 7200000, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null }
};
/**
@@ -768,6 +809,14 @@ export async function shouldRunTask(taskType, appId = null) {
return { shouldRun: false, reason: 'disabled' };
}
+ // Weekday-only tasks skip weekends
+ if (interval.weekdaysOnly) {
+ const day = new Date().getDay();
+ if (day === 0 || day === 6) {
+ return { shouldRun: false, reason: 'weekday-only' };
+ }
+ }
+
// Check per-app override
if (appId) {
const enabledForApp = await isTaskTypeEnabledForApp(appId, taskType);
@@ -1232,7 +1281,8 @@ function getTaskTypeDescription(taskType) {
'dependency-updates': 'Update dependencies',
'release-check': 'Check dev for release readiness',
'error-handling': 'Improve error handling',
- 'typing': 'Improve TypeScript types'
+ 'typing': 'Improve TypeScript types',
+ 'pr-reviewer': 'Review open PRs from contributors'
};
return descriptions[taskType] || taskType.replace(/-/g, ' ');
}
diff --git a/update.ps1 b/update.ps1
index 90bfa10b25..bb5fa42876 100644
--- a/update.ps1
+++ b/update.ps1
@@ -64,6 +64,27 @@ Write-Host ""
node scripts/setup-ghostty.js
Write-Host ""
+# Check for slash-do (optional, used by the PR Reviewer schedule task)
+$slashDoFound = Get-Command slash-do -ErrorAction SilentlyContinue
+if (-not $slashDoFound) {
+ Write-Host "slash-do is not installed. It is used by the PR Reviewer schedule task." -ForegroundColor Yellow
+ if ([Environment]::UserInteractive) {
+ $reply = Read-Host "Install slash-do now? [y/N]"
+ if ($reply -match "^[Yy]$") {
+ Write-Host "Installing slash-do..." -ForegroundColor Yellow
+ npm install -g slash-do@latest 2>&1
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "⚠️ Failed to install slash-do. Continuing without it." -ForegroundColor Red
+ }
+ } else {
+ Write-Host "Skipping slash-do install. You can install later with: npm install -g slash-do@latest"
+ }
+ } else {
+ Write-Host "Skipping slash-do prompt (non-interactive). Install later with: npm install -g slash-do@latest"
+ }
+ Write-Host ""
+}
+
# Build UI assets for production serving
Write-Host "Building UI assets..." -ForegroundColor Yellow
npm run build
diff --git a/update.sh b/update.sh
index a844bfb689..9ef2e7866f 100755
--- a/update.sh
+++ b/update.sh
@@ -61,6 +61,26 @@ echo ""
node scripts/setup-ghostty.js
echo ""
+# Check for slash-do (optional, used by the PR Reviewer schedule task)
+if ! command -v slash-do >/dev/null 2>&1; then
+ echo "slash-do is not installed. It is used by the PR Reviewer schedule task."
+ if [ -t 0 ]; then
+ read -p "Install slash-do now? [y/N] " -n 1 -r
+ echo ""
+ if [[ $REPLY =~ ^[Yy]$ ]]; then
+ echo "Installing slash-do..."
+ if ! npm install -g slash-do@latest; then
+ echo "⚠️ Failed to install slash-do. Continuing without it."
+ fi
+ else
+ echo "Skipping slash-do install. You can install later with: npm install -g slash-do@latest"
+ fi
+ else
+ echo "Skipping slash-do prompt (non-interactive). Install later with: npm install -g slash-do@latest"
+ fi
+ echo ""
+fi
+
# Build UI assets for production serving
echo "Building UI assets..."
npm run build