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(feature-agents): add persistent AI developer personas for managed apps

Adam Eivyd5294812bc9b
diff --git a/client/src/App.jsx b/client/src/App.jsx
index e7960c623b..c92edb9153 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -44,6 +44,8 @@ const AgentsPage = lazyWithReload(() => import('./pages/DevTools').then(m => ({
const GitHub = lazyWithReload(() => import('./pages/GitHub'));
const CyberCity = lazyWithReload(() => import('./pages/CyberCity'));
const AppDetail = lazyWithReload(() => import('./pages/AppDetail'));
+const FeatureAgents = lazyWithReload(() => import('./pages/FeatureAgents'));
+const FeatureAgentDetail = lazyWithReload(() => import('./pages/FeatureAgentDetail'));
// Loading fallback for lazy-loaded pages
const PageLoader = () => (
@@ -81,6 +83,10 @@ export default function App() {
<Route path="brain/:tab" element={<Brain />} />
<Route path="digital-twin" element={<Navigate to="/digital-twin/overview" replace />} />
<Route path="digital-twin/:tab" element={<DigitalTwin />} />
+ <Route path="feature-agents" element={<FeatureAgents />} />
+ <Route path="feature-agents/create" element={<FeatureAgentDetail />} />
+ <Route path="feature-agents/:id" element={<Navigate to="overview" replace />} />
+ <Route path="feature-agents/:id/:tab" element={<FeatureAgentDetail />} />
<Route path="apps/create" element={<CreateApp />} />
<Route path="apps/:appId" element={<AppDetail />} />
<Route path="apps/:appId/:tab" element={<AppDetail />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 16bc96ad4a..40eeef4b28 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -56,6 +56,7 @@ import {
Link2,
Database,
Shield,
+ Wand2,
Zap
} from 'lucide-react';
/* global __APP_VERSION__ */
@@ -150,6 +151,7 @@ const navItems = [
{ to: '/digital-twin/test', label: 'Test', icon: CheckCircle }
]
},
+ { to: '/feature-agents', label: 'Feature Agents', icon: Wand2, single: true },
{ to: '/insights/overview', label: 'Insights', icon: Lightbulb, single: true },
{ to: '/instances', label: 'Instances', icon: Network, single: true },
{
@@ -599,6 +601,7 @@ export default function Layout() {
const isFullWidth = location.pathname.startsWith('/cos') ||
location.pathname.startsWith('/brain') ||
location.pathname.startsWith('/digital-twin') ||
+ location.pathname.startsWith('/feature-agents') ||
location.pathname.startsWith('/insights') ||
location.pathname.startsWith('/meatspace') ||
location.pathname.startsWith('/agents') ||
diff --git a/client/src/components/feature-agents/ConfigTab.jsx b/client/src/components/feature-agents/ConfigTab.jsx
new file mode 100644
index 0000000000..489be935ea
--- /dev/null
+++ b/client/src/components/feature-agents/ConfigTab.jsx
@@ -0,0 +1,291 @@
+import { useState, useEffect, useCallback } from 'react';
+import { Save } from 'lucide-react';
+import toast from 'react-hot-toast';
+import * as api from '../../services/api';
+
+function ArrayInput({ label, value, onChange, placeholder }) {
+ const [text, setText] = useState((value || []).join('\n'));
+
+ useEffect(() => {
+ setText((value || []).join('\n'));
+ }, [value]);
+
+ const handleBlur = () => {
+ const items = text.split('\n').map(s => s.trim()).filter(Boolean);
+ onChange(items);
+ };
+
+ return (
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">{label}</label>
+ <textarea
+ value={text}
+ onChange={e => setText(e.target.value)}
+ onBlur={handleBlur}
+ placeholder={placeholder}
+ rows={3}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-hidden focus:border-port-accent resize-y"
+ />
+ <p className="text-xs text-gray-600 mt-0.5">One per line</p>
+ </div>
+ );
+}
+
+export default function ConfigTab({ agent, isCreate, apps, onSave }) {
+ const [form, setForm] = useState({
+ name: '',
+ description: '',
+ persona: '',
+ appId: '',
+ featureScope: { directories: [], filePatterns: [], excludePatterns: [] },
+ git: { branchName: '', baseBranch: 'main', autoMergeBase: true, autoPR: true, prTemplate: '' },
+ schedule: { mode: 'continuous', cronExpression: '', intervalMs: 3600000, pauseBetweenRunsMs: 60000 },
+ playwright: { testUrls: [], baseUrl: '', startCommand: '', viewport: { width: 1280, height: 720 } },
+ goals: [],
+ constraints: [],
+ providerId: '',
+ model: '',
+ autonomyLevel: 'assistant',
+ priority: 'MEDIUM'
+ });
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ if (agent && !isCreate) {
+ setForm({
+ name: agent.name || '',
+ description: agent.description || '',
+ persona: agent.persona || '',
+ appId: agent.appId || '',
+ featureScope: agent.featureScope || { directories: [], filePatterns: [], excludePatterns: [] },
+ git: agent.git || { branchName: '', baseBranch: 'main', autoMergeBase: true, autoPR: true, prTemplate: '' },
+ schedule: agent.schedule || { mode: 'continuous', cronExpression: '', intervalMs: 3600000, pauseBetweenRunsMs: 60000 },
+ playwright: agent.playwright || { testUrls: [], baseUrl: '', startCommand: '', viewport: { width: 1280, height: 720 } },
+ goals: agent.goals || [],
+ constraints: agent.constraints || [],
+ providerId: agent.providerId || '',
+ model: agent.model || '',
+ autonomyLevel: agent.autonomyLevel || 'assistant',
+ priority: agent.priority || 'MEDIUM'
+ });
+ }
+ }, [agent, isCreate]);
+
+ const set = useCallback((path, value) => {
+ setForm(prev => {
+ const parts = path.split('.');
+ if (parts.length === 1) return { ...prev, [path]: value };
+ const [parent, child] = parts;
+ return { ...prev, [parent]: { ...prev[parent], [child]: value } };
+ });
+ }, []);
+
+ const handleSubmit = async (e) => {
+ e.preventDefault();
+ setSaving(true);
+
+ const payload = {
+ ...form,
+ providerId: form.providerId || null,
+ model: form.model || null
+ };
+
+ if (isCreate) {
+ const created = await api.createFeatureAgent(payload).catch(() => null);
+ setSaving(false);
+ if (created) {
+ toast.success('Feature agent created');
+ onSave?.(created);
+ }
+ } else {
+ const updated = await api.updateFeatureAgent(agent.id, payload).catch(() => null);
+ setSaving(false);
+ if (updated) {
+ toast.success('Config saved');
+ onSave?.(updated);
+ }
+ }
+ };
+
+ const inputCls = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-hidden focus:border-port-accent';
+ const selectCls = 'bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white focus:outline-hidden focus:border-port-accent';
+
+ return (
+ <form onSubmit={handleSubmit} className="space-y-6 max-w-3xl">
+ {/* Basic Info */}
+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Basic Info</h3>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Name</label>
+ <input value={form.name} onChange={e => set('name', e.target.value)} className={inputCls} placeholder="Audio Generator Guardian" required />
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Description</label>
+ <textarea value={form.description} onChange={e => set('description', e.target.value)} className={`${inputCls} resize-y`} rows={2} placeholder="What this agent owns and iterates on" required />
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Persona (system prompt)</label>
+ <textarea value={form.persona} onChange={e => set('persona', e.target.value)} className={`${inputCls} resize-y`} rows={4} placeholder="You are a meticulous developer who..." />
+ </div>
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">App</label>
+ <select value={form.appId} onChange={e => set('appId', e.target.value)} className={selectCls} required>
+ <option value="">Select app...</option>
+ {(apps || []).map(app => (
+ <option key={app.id} value={app.id}>{app.name}</option>
+ ))}
+ </select>
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Priority</label>
+ <select value={form.priority} onChange={e => set('priority', e.target.value)} className={selectCls}>
+ <option value="LOW">Low</option>
+ <option value="MEDIUM">Medium</option>
+ <option value="HIGH">High</option>
+ <option value="CRITICAL">Critical</option>
+ </select>
+ </div>
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Autonomy Level</label>
+ <select value={form.autonomyLevel} onChange={e => set('autonomyLevel', e.target.value)} className={selectCls}>
+ <option value="standby">Standby - Only when triggered</option>
+ <option value="assistant">Assistant - Follows instructions closely</option>
+ <option value="manager">Manager - Makes independent decisions</option>
+ <option value="yolo">YOLO - Full autonomy</option>
+ </select>
+ </div>
+ </div>
+
+ {/* Feature Scope */}
+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Feature Scope</h3>
+ <ArrayInput label="Directories" value={form.featureScope.directories} onChange={v => set('featureScope', { ...form.featureScope, directories: v })} placeholder="src/audio&#10;lib/generators" />
+ <ArrayInput label="File Patterns (globs)" value={form.featureScope.filePatterns} onChange={v => set('featureScope', { ...form.featureScope, filePatterns: v })} placeholder="**/*.ts&#10;**/*.test.js" />
+ <ArrayInput label="Exclude Patterns" value={form.featureScope.excludePatterns} onChange={v => set('featureScope', { ...form.featureScope, excludePatterns: v })} placeholder="node_modules/**&#10;dist/**" />
+ </div>
+
+ {/* Git */}
+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Git</h3>
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Branch Name</label>
+ <input value={form.git.branchName} onChange={e => set('git', { ...form.git, branchName: e.target.value })} className={inputCls} placeholder="feature-agent/audio-generator" required />
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Base Branch</label>
+ <input value={form.git.baseBranch} onChange={e => set('git', { ...form.git, baseBranch: e.target.value })} className={inputCls} placeholder="main" />
+ </div>
+ </div>
+ <div className="flex items-center gap-6">
+ <label className="flex items-center gap-2 text-sm text-gray-400 cursor-pointer">
+ <input type="checkbox" checked={form.git.autoMergeBase} onChange={e => set('git', { ...form.git, autoMergeBase: e.target.checked })} className="rounded" />
+ Auto-merge base before runs
+ </label>
+ <label className="flex items-center gap-2 text-sm text-gray-400 cursor-pointer">
+ <input type="checkbox" checked={form.git.autoPR} onChange={e => set('git', { ...form.git, autoPR: e.target.checked })} className="rounded" />
+ Auto-create PR when ready
+ </label>
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">PR Template (optional)</label>
+ <textarea value={form.git.prTemplate} onChange={e => set('git', { ...form.git, prTemplate: e.target.value })} className={`${inputCls} resize-y`} rows={3} placeholder="## Changes&#10;- ..." />
+ </div>
+ </div>
+
+ {/* Schedule */}
+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Schedule</h3>
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Mode</label>
+ <select value={form.schedule.mode} onChange={e => set('schedule', { ...form.schedule, mode: e.target.value })} className={selectCls}>
+ <option value="continuous">Continuous</option>
+ <option value="interval">Interval</option>
+ <option value="cron">Cron</option>
+ </select>
+ </div>
+ {form.schedule.mode === 'interval' && (
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Interval (minutes)</label>
+ <input type="number" value={Math.round((form.schedule.intervalMs || 3600000) / 60000)} onChange={e => set('schedule', { ...form.schedule, intervalMs: parseInt(e.target.value) * 60000 })} className={inputCls} min={1} />
+ </div>
+ )}
+ {form.schedule.mode === 'cron' && (
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Cron Expression</label>
+ <input value={form.schedule.cronExpression} onChange={e => set('schedule', { ...form.schedule, cronExpression: e.target.value })} className={inputCls} placeholder="0 */4 * * *" />
+ </div>
+ )}
+ {form.schedule.mode === 'continuous' && (
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Pause Between Runs (seconds)</label>
+ <input type="number" value={Math.round((form.schedule.pauseBetweenRunsMs || 60000) / 1000)} onChange={e => set('schedule', { ...form.schedule, pauseBetweenRunsMs: parseInt(e.target.value) * 1000 })} className={inputCls} min={0} />
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Playwright */}
+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Playwright Testing</h3>
+ <ArrayInput label="Test URLs" value={form.playwright.testUrls} onChange={v => set('playwright', { ...form.playwright, testUrls: v })} placeholder="http://localhost:3000&#10;http://localhost:3000/settings" />
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Base URL</label>
+ <input value={form.playwright.baseUrl} onChange={e => set('playwright', { ...form.playwright, baseUrl: e.target.value })} className={inputCls} placeholder="http://localhost:3000" />
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Start Command</label>
+ <input value={form.playwright.startCommand} onChange={e => set('playwright', { ...form.playwright, startCommand: e.target.value })} className={inputCls} placeholder="npm run dev" />
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Viewport Width</label>
+ <input type="number" value={form.playwright.viewport?.width || 1280} onChange={e => set('playwright', { ...form.playwright, viewport: { ...form.playwright.viewport, width: parseInt(e.target.value) } })} className={inputCls} />
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Viewport Height</label>
+ <input type="number" value={form.playwright.viewport?.height || 720} onChange={e => set('playwright', { ...form.playwright, viewport: { ...form.playwright.viewport, height: parseInt(e.target.value) } })} className={inputCls} />
+ </div>
+ </div>
+ </div>
+
+ {/* Goals & Constraints */}
+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Goals & Constraints</h3>
+ <ArrayInput label="Goals (success criteria)" value={form.goals} onChange={v => setForm(prev => ({ ...prev, goals: v }))} placeholder="All audio tests pass&#10;Generate at least 3 sample formats" />
+ <ArrayInput label="Constraints (things NOT to do)" value={form.constraints} onChange={v => setForm(prev => ({ ...prev, constraints: v }))} placeholder="Don't modify the API contract&#10;Don't add new dependencies without approval" />
+ </div>
+
+ {/* AI Provider Override */}
+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">AI Provider (optional override)</h3>
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Provider ID</label>
+ <input value={form.providerId || ''} onChange={e => set('providerId', e.target.value)} className={inputCls} placeholder="Leave empty for default" />
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Model</label>
+ <input value={form.model || ''} onChange={e => set('model', e.target.value)} className={inputCls} placeholder="Leave empty for default" />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex justify-end">
+ <button
+ type="submit"
+ disabled={saving}
+ className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 transition-colors disabled:opacity-50"
+ >
+ <Save size={16} />
+ {saving ? 'Saving...' : isCreate ? 'Create Agent' : 'Save Config'}
+ </button>
+ </div>
+ </form>
+ );
+}
diff --git a/client/src/components/feature-agents/FeatureAgentCard.jsx b/client/src/components/feature-agents/FeatureAgentCard.jsx
new file mode 100644
index 0000000000..18a6dc8eb0
--- /dev/null
+++ b/client/src/components/feature-agents/FeatureAgentCard.jsx
@@ -0,0 +1,91 @@
+import { Link } from 'react-router-dom';
+import { Play, Pause, Square, Zap, Trash2 } from 'lucide-react';
+import { STATUS_COLORS, STATUS_BG, PRIORITY_COLORS, SCHEDULE_LABELS } from './constants';
+
+function timeAgo(dateStr) {
+ if (!dateStr) return 'never';
+ const seconds = Math.floor((Date.now() - new Date(dateStr).getTime()) / 1000);
+ if (seconds < 60) return 'just now';
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
+ return `${Math.floor(seconds / 86400)}d ago`;
+}
+
+export default function FeatureAgentCard({ agent, onStart, onPause, onResume, onStop, onTrigger, onDelete }) {
+ const statusColor = STATUS_COLORS[agent.status] || 'text-gray-400';
+ const statusBg = STATUS_BG[agent.status] || 'bg-gray-400/10';
+ const priorityColor = PRIORITY_COLORS[agent.priority] || 'text-gray-400';
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-5 hover:border-port-accent/30 transition-colors">
+ <div className="flex items-start justify-between mb-3">
+ <Link to={`/feature-agents/${agent.id}/overview`} className="flex-1 min-w-0">
+ <h3 className="text-white font-medium truncate hover:text-port-accent transition-colors">
+ {agent.name}
+ </h3>
+ <p className="text-sm text-gray-500 mt-1 line-clamp-2">{agent.description}</p>
+ </Link>
+ <div className="flex items-center gap-2 ml-3 shrink-0">
+ <span className={`inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full ${statusColor} ${statusBg}`}>
+ {agent.status}
+ </span>
+ <span className={`text-xs ${priorityColor}`}>{agent.priority}</span>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-4 text-xs text-gray-500 mb-3">
+ <span>Runs: {agent.runCount || 0}</span>
+ <span>Last: {timeAgo(agent.lastRunAt)}</span>
+ <span>{SCHEDULE_LABELS[agent.schedule?.mode] || 'Continuous'}</span>
+ {agent.git?.branchName && (
+ <span className="text-gray-600 truncate max-w-[200px]">{agent.git.branchName}</span>
+ )}
+ </div>
+
+ {agent.goals?.length > 0 && (
+ <div className="flex flex-wrap gap-1 mb-3">
+ {agent.goals.slice(0, 3).map((goal, i) => (
+ <span key={i} className="text-[10px] bg-port-border/50 text-gray-400 rounded px-1.5 py-0.5 truncate max-w-[200px]">
+ {goal}
+ </span>
+ ))}
+ {agent.goals.length > 3 && (
+ <span className="text-[10px] text-gray-600">+{agent.goals.length - 3} more</span>
+ )}
+ </div>
+ )}
+
+ <div className="flex items-center gap-1 pt-2 border-t border-port-border">
+ {agent.status === 'draft' && (
+ <button onClick={() => onStart(agent.id)} className="flex items-center gap-1 px-2 py-1 text-xs text-port-success hover:bg-port-success/10 rounded transition-colors">
+ <Play size={12} /> Start
+ </button>
+ )}
+ {agent.status === 'active' && (
+ <>
+ <button onClick={() => onPause(agent.id)} className="flex items-center gap-1 px-2 py-1 text-xs text-port-warning hover:bg-port-warning/10 rounded transition-colors">
+ <Pause size={12} /> Pause
+ </button>
+ <button onClick={() => onTrigger(agent.id)} className="flex items-center gap-1 px-2 py-1 text-xs text-port-accent hover:bg-port-accent/10 rounded transition-colors">
+ <Zap size={12} /> Trigger
+ </button>
+ </>
+ )}
+ {agent.status === 'paused' && (
+ <button onClick={() => onResume(agent.id)} className="flex items-center gap-1 px-2 py-1 text-xs text-port-success hover:bg-port-success/10 rounded transition-colors">
+ <Play size={12} /> Resume
+ </button>
+ )}
+ {(agent.status === 'active' || agent.status === 'paused') && (
+ <button onClick={() => onStop(agent.id)} className="flex items-center gap-1 px-2 py-1 text-xs text-gray-400 hover:bg-port-border/50 rounded transition-colors">
+ <Square size={12} /> Stop
+ </button>
+ )}
+ <div className="flex-1" />
+ <button onClick={() => onDelete(agent.id)} className="flex items-center gap-1 px-2 py-1 text-xs text-port-error hover:bg-port-error/10 rounded transition-colors">
+ <Trash2 size={12} />
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/feature-agents/GitTab.jsx b/client/src/components/feature-agents/GitTab.jsx
new file mode 100644
index 0000000000..1e4ad59594
--- /dev/null
+++ b/client/src/components/feature-agents/GitTab.jsx
@@ -0,0 +1,49 @@
+import { GitBranch, ExternalLink } from 'lucide-react';
+
+export default function GitTab({ agent }) {
+ const git = agent.git || {};
+
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="bg-port-card border border-port-border rounded-xl p-5">
+ <div className="flex items-center gap-2 mb-4">
+ <GitBranch size={16} className="text-port-accent" />
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Branch Info</h3>
+ </div>
+ <div className="space-y-3 text-sm">
+ <div className="flex items-center justify-between py-2 border-b border-port-border">
+ <span className="text-gray-500">Feature Branch</span>
+ <span className="text-white font-mono">{git.branchName || 'not set'}</span>
+ </div>
+ <div className="flex items-center justify-between py-2 border-b border-port-border">
+ <span className="text-gray-500">Base Branch</span>
+ <span className="text-white font-mono">{git.baseBranch || 'main'}</span>
+ </div>
+ <div className="flex items-center justify-between py-2 border-b border-port-border">
+ <span className="text-gray-500">Auto Merge Base</span>
+ <span className={git.autoMergeBase !== false ? 'text-port-success' : 'text-gray-500'}>
+ {git.autoMergeBase !== false ? 'Enabled' : 'Disabled'}
+ </span>
+ </div>
+ <div className="flex items-center justify-between py-2 border-b border-port-border">
+ <span className="text-gray-500">Auto PR</span>
+ <span className={git.autoPR !== false ? 'text-port-success' : 'text-gray-500'}>
+ {git.autoPR !== false ? 'Enabled' : 'Disabled'}
+ </span>
+ </div>
+ <div className="flex items-center justify-between py-2">
+ <span className="text-gray-500">Worktree Path</span>
+ <span className="text-gray-400 font-mono text-xs">data/cos/feature-agents/{agent.id}/worktree</span>
+ </div>
+ </div>
+ </div>
+
+ {git.prTemplate && (
+ <div className="bg-port-card border border-port-border rounded-xl p-5">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">PR Template</h3>
+ <pre className="text-xs text-gray-400 bg-port-bg rounded p-3 overflow-auto whitespace-pre-wrap">{git.prTemplate}</pre>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/feature-agents/OutputTab.jsx b/client/src/components/feature-agents/OutputTab.jsx
new file mode 100644
index 0000000000..38c2d6c4f5
--- /dev/null
+++ b/client/src/components/feature-agents/OutputTab.jsx
@@ -0,0 +1,73 @@
+import { useState, useEffect, useRef } from 'react';
+import { Terminal, RefreshCw } from 'lucide-react';
+import * as api from '../../services/api';
+import socket from '../../services/socket';
+
+export default function OutputTab({ agent }) {
+ const [output, setOutput] = useState('');
+ const [agentId, setAgentId] = useState(null);
+ const bottomRef = useRef(null);
+
+ useEffect(() => {
+ const fetch = () => {
+ api.getFeatureAgentOutput(agent.id).then(data => {
+ if (data) {
+ setOutput(data.output || '');
+ setAgentId(data.agentId);
+ }
+ }).catch(() => {});
+ };
+ fetch();
+
+ const handler = (data) => {
+ if (data.agentId === agent.currentAgentId || data.featureAgentId === agent.id) {
+ setOutput(prev => prev + (data.chunk || data.output || ''));
+ }
+ };
+ socket.on('cos:agent:output', handler);
+ socket.on('cos:feature-agent:output', handler);
+
+ return () => {
+ socket.off('cos:agent:output', handler);
+ socket.off('cos:feature-agent:output', handler);
+ };
+ }, [agent.id, agent.currentAgentId]);
+
+ useEffect(() => {
+ bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
+ }, [output]);
+
+ if (!agent.currentAgentId && !output) {
+ return (
+ <div className="text-center py-16">
+ <Terminal size={48} className="mx-auto text-gray-600 mb-4" />
+ <h3 className="text-lg font-medium text-gray-400 mb-2">No Active Run</h3>
+ <p className="text-sm text-gray-600">Output will appear here when the agent is running.</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <div className="text-sm text-gray-500">
+ {agent.currentAgentId ? (
+ <span className="text-port-success">Running: {agent.currentAgentId}</span>
+ ) : (
+ <span>Last run output{agentId ? ` (${agentId})` : ''}</span>
+ )}
+ </div>
+ <button
+ onClick={() => api.getFeatureAgentOutput(agent.id).then(d => d && setOutput(d.output || '')).catch(() => {})}
+ className="p-1.5 text-gray-400 hover:text-white hover:bg-port-border/50 rounded transition-colors"
+ >
+ <RefreshCw size={14} />
+ </button>
+ </div>
+ <div className="bg-port-bg border border-port-border rounded-lg p-4 font-mono text-xs text-gray-300 max-h-[600px] overflow-auto whitespace-pre-wrap">
+ {output || 'No output yet...'}
+ <div ref={bottomRef} />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/feature-agents/OverviewTab.jsx b/client/src/components/feature-agents/OverviewTab.jsx
new file mode 100644
index 0000000000..6ad4d2eecb
--- /dev/null
+++ b/client/src/components/feature-agents/OverviewTab.jsx
@@ -0,0 +1,194 @@
+import { Play, Pause, Square, Zap, Clock, Target, GitBranch, AlertTriangle } from 'lucide-react';
+import { STATUS_COLORS, STATUS_BG, PRIORITY_COLORS, SCHEDULE_LABELS, AUTONOMY_LABELS } from './constants';
+
+function timeAgo(dateStr) {
+ if (!dateStr) return 'never';
+ const seconds = Math.floor((Date.now() - new Date(dateStr).getTime()) / 1000);
+ if (seconds < 60) return 'just now';
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
+ return `${Math.floor(seconds / 86400)}d ago`;
+}
+
+export default function OverviewTab({ agent, onStart, onPause, onResume, onStop, onTrigger }) {
+ const statusColor = STATUS_COLORS[agent.status] || 'text-gray-400';
+ const statusBg = STATUS_BG[agent.status] || 'bg-gray-400/10';
+
+ return (
+ <div className="space-y-6">
+ {/* Status + Actions */}
+ <div className="bg-port-card border border-port-border rounded-xl p-5">
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-3">
+ <span className={`inline-flex items-center gap-1 text-sm px-3 py-1 rounded-full font-medium ${statusColor} ${statusBg}`}>
+ {agent.status}
+ </span>
+ <span className={`text-sm ${PRIORITY_COLORS[agent.priority]}`}>{agent.priority} priority</span>
+ <span className="text-sm text-gray-500">{AUTONOMY_LABELS[agent.autonomyLevel] || agent.autonomyLevel}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ {agent.status === 'draft' && (
+ <button onClick={() => onStart(agent.id)} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-port-success bg-port-success/10 hover:bg-port-success/20 rounded-lg transition-colors">
+ <Play size={14} /> Activate
+ </button>
+ )}
+ {agent.status === 'active' && (
+ <>
+ <button onClick={() => onTrigger(agent.id)} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-port-accent bg-port-accent/10 hover:bg-port-accent/20 rounded-lg transition-colors">
+ <Zap size={14} /> Trigger Run
+ </button>
+ <button onClick={() => onPause(agent.id)} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-port-warning bg-port-warning/10 hover:bg-port-warning/20 rounded-lg transition-colors">
+ <Pause size={14} /> Pause
+ </button>
+ </>
+ )}
+ {agent.status === 'paused' && (
+ <button onClick={() => onResume(agent.id)} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-port-success bg-port-success/10 hover:bg-port-success/20 rounded-lg transition-colors">
+ <Play size={14} /> Resume
+ </button>
+ )}
+ {(agent.status === 'active' || agent.status === 'paused') && (
+ <button onClick={() => onStop(agent.id)} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-400 hover:bg-port-border/50 rounded-lg transition-colors">
+ <Square size={14} /> Stop
+ </button>
+ )}
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
+ <div>
+ <div className="text-xs text-gray-500 mb-1">Total Runs</div>
+ <div className="text-lg font-bold text-white">{agent.runCount || 0}</div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 mb-1">Last Run</div>
+ <div className="text-sm text-white">{timeAgo(agent.lastRunAt)}</div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 mb-1">Schedule</div>
+ <div className="text-sm text-white">{SCHEDULE_LABELS[agent.schedule?.mode] || 'Continuous'}</div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 mb-1">Created</div>
+ <div className="text-sm text-white">{timeAgo(agent.createdAt)}</div>
+ </div>
+ </div>
+
+ {agent.backoff && (
+ <div className="mt-4 flex items-center gap-2 text-sm text-port-warning bg-port-warning/10 rounded-lg px-3 py-2">
+ <AlertTriangle size={14} />
+ <span>Backoff active: {Math.round(agent.backoff.currentDelayMs / 60000)}min delay ({agent.backoff.consecutiveIdles} consecutive idle runs)</span>
+ </div>
+ )}
+ </div>
+
+ {/* Persona */}
+ {agent.persona && (
+ <div className="bg-port-card border border-port-border rounded-xl p-5">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">Persona</h3>
+ <p className="text-sm text-gray-300 whitespace-pre-wrap">{agent.persona}</p>
+ </div>
+ )}
+
+ {/* Goals */}
+ <div className="bg-port-card border border-port-border rounded-xl p-5">
+ <div className="flex items-center gap-2 mb-3">
+ <Target size={16} className="text-port-accent" />
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Goals</h3>
+ </div>
+ {agent.goals?.length > 0 ? (
+ <ul className="space-y-2">
+ {agent.goals.map((goal, i) => (
+ <li key={i} className="flex items-start gap-2 text-sm text-gray-300">
+ <span className="text-port-accent mt-0.5">-</span>
+ <span>{goal}</span>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-sm text-gray-600">No goals defined</p>
+ )}
+ </div>
+
+ {/* Feature Scope + Git */}
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div className="bg-port-card border border-port-border rounded-xl p-5">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">Feature Scope</h3>
+ <div className="space-y-2 text-sm">
+ {agent.featureScope?.directories?.length > 0 && (
+ <div>
+ <span className="text-gray-500">Directories: </span>
+ <span className="text-gray-300">{agent.featureScope.directories.join(', ')}</span>
+ </div>
+ )}
+ {agent.featureScope?.filePatterns?.length > 0 && (
+ <div>
+ <span className="text-gray-500">Patterns: </span>
+ <span className="text-gray-300">{agent.featureScope.filePatterns.join(', ')}</span>
+ </div>
+ )}
+ {agent.featureScope?.excludePatterns?.length > 0 && (
+ <div>
+ <span className="text-gray-500">Exclude: </span>
+ <span className="text-gray-300">{agent.featureScope.excludePatterns.join(', ')}</span>
+ </div>
+ )}
+ {!agent.featureScope?.directories?.length && !agent.featureScope?.filePatterns?.length && (
+ <p className="text-gray-600">No scope restrictions (full repo)</p>
+ )}
+ </div>
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-xl p-5">
+ <div className="flex items-center gap-2 mb-3">
+ <GitBranch size={16} className="text-port-accent" />
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Git</h3>
+ </div>
+ <div className="space-y-2 text-sm">
+ <div>
+ <span className="text-gray-500">Branch: </span>
+ <span className="text-gray-300 font-mono">{agent.git?.branchName}</span>
+ </div>
+ <div>
+ <span className="text-gray-500">Base: </span>
+ <span className="text-gray-300 font-mono">{agent.git?.baseBranch || 'main'}</span>
+ </div>
+ <div>
+ <span className="text-gray-500">Auto merge base: </span>
+ <span className="text-gray-300">{agent.git?.autoMergeBase !== false ? 'yes' : 'no'}</span>
+ </div>
+ <div>
+ <span className="text-gray-500">Auto PR: </span>
+ <span className="text-gray-300">{agent.git?.autoPR !== false ? 'yes' : 'no'}</span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Recent Runs */}
+ {agent.recentRuns?.length > 0 && (
+ <div className="bg-port-card border border-port-border rounded-xl p-5">
+ <div className="flex items-center gap-2 mb-3">
+ <Clock size={16} className="text-port-accent" />
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Recent Runs</h3>
+ </div>
+ <div className="space-y-2">
+ {agent.recentRuns.map((run, i) => (
+ <div key={i} className="flex items-center gap-3 text-sm py-1.5 border-b border-port-border last:border-0">
+ <span className={`text-xs px-2 py-0.5 rounded ${
+ run.status === 'working' ? 'bg-port-success/10 text-port-success' :
+ run.status === 'idle-no-work' ? 'bg-port-warning/10 text-port-warning' :
+ 'bg-port-error/10 text-port-error'
+ }`}>
+ {run.status}
+ </span>
+ <span className="text-gray-400 flex-1 truncate">{run.summary || 'No summary'}</span>
+ <span className="text-gray-600 shrink-0">{timeAgo(run.completedAt)}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/feature-agents/RunsTab.jsx b/client/src/components/feature-agents/RunsTab.jsx
new file mode 100644
index 0000000000..44bc1f5e19
--- /dev/null
+++ b/client/src/components/feature-agents/RunsTab.jsx
@@ -0,0 +1,96 @@
+import { useState, useEffect } from 'react';
+import { Play, ChevronDown, ChevronRight } from 'lucide-react';
+import * as api from '../../services/api';
+import BrailleSpinner from '../BrailleSpinner';
+
+function timeAgo(dateStr) {
+ if (!dateStr) return 'unknown';
+ const seconds = Math.floor((Date.now() - new Date(dateStr).getTime()) / 1000);
+ if (seconds < 60) return 'just now';
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
+ return `${Math.floor(seconds / 86400)}d ago`;
+}
+
+export default function RunsTab({ agent }) {
+ const [runs, setRuns] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [expanded, setExpanded] = useState({});
+
+ useEffect(() => {
+ api.getFeatureAgentRuns(agent.id, 50).then(data => {
+ setRuns(data || []);
+ setLoading(false);
+ }).catch(() => setLoading(false));
+ }, [agent.id]);
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-32">
+ <BrailleSpinner text="Loading runs" />
+ </div>
+ );
+ }
+
+ if (runs.length === 0) {
+ return (
+ <div className="text-center py-16">
+ <Play size={48} className="mx-auto text-gray-600 mb-4" />
+ <h3 className="text-lg font-medium text-gray-400 mb-2">No Runs Yet</h3>
+ <p className="text-sm text-gray-600">Activate the agent or trigger a manual run to see history here.</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-2">
+ {runs.map((run, i) => (
+ <div key={run.id || i} className="bg-port-card border border-port-border rounded-lg">
+ <button
+ onClick={() => setExpanded(prev => ({ ...prev, [i]: !prev[i] }))}
+ className="w-full flex items-center gap-3 p-3 text-left hover:bg-port-border/30 rounded-lg transition-colors"
+ >
+ {expanded[i] ? <ChevronDown size={14} className="text-gray-500 shrink-0" /> : <ChevronRight size={14} className="text-gray-500 shrink-0" />}
+ <span className={`text-xs px-2 py-0.5 rounded shrink-0 ${
+ run.status === 'working' ? 'bg-port-success/10 text-port-success' :
+ run.status === 'idle-no-work' ? 'bg-port-warning/10 text-port-warning' :
+ run.status === 'error' ? 'bg-port-error/10 text-port-error' :
+ 'bg-gray-500/10 text-gray-400'
+ }`}>
+ {run.status || 'unknown'}
+ </span>
+ <span className="text-sm text-gray-300 flex-1 truncate">{run.summary || 'No summary'}</span>
+ <span className="text-xs text-gray-600 shrink-0">{timeAgo(run.completedAt)}</span>
+ </button>
+
+ {expanded[i] && (
+ <div className="px-4 pb-3 space-y-2 border-t border-port-border mt-1 pt-2">
+ {run.filesChanged?.length > 0 && (
+ <div>
+ <span className="text-xs text-gray-500">Files changed:</span>
+ <div className="mt-1 space-y-0.5">
+ {run.filesChanged.map((f, j) => (
+ <div key={j} className="text-xs font-mono text-gray-400">{f}</div>
+ ))}
+ </div>
+ </div>
+ )}
+ {run.learnings && (
+ <div>
+ <span className="text-xs text-gray-500">Learnings:</span>
+ <p className="text-xs text-gray-400 mt-1">{run.learnings}</p>
+ </div>
+ )}
+ {run.playwrightResults && (
+ <div>
+ <span className="text-xs text-gray-500">Playwright results:</span>
+ <p className="text-xs text-gray-400 mt-1">{JSON.stringify(run.playwrightResults)}</p>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/client/src/components/feature-agents/constants.js b/client/src/components/feature-agents/constants.js
new file mode 100644
index 0000000000..b2e19b908e
--- /dev/null
+++ b/client/src/components/feature-agents/constants.js
@@ -0,0 +1,47 @@
+import { LayoutDashboard, Settings, Play, GitBranch, Terminal } from 'lucide-react';
+
+export const TABS = [
+ { id: 'overview', label: 'Overview', icon: LayoutDashboard },
+ { id: 'config', label: 'Config', icon: Settings },
+ { id: 'runs', label: 'Runs', icon: Play },
+ { id: 'output', label: 'Output', icon: Terminal },
+ { id: 'git', label: 'Git', icon: GitBranch }
+];
+
+export const VALID_TAB_IDS = new Set(TABS.map(t => t.id));
+
+export const STATUS_COLORS = {
+ draft: 'text-gray-400',
+ active: 'text-port-success',
+ paused: 'text-port-warning',
+ completed: 'text-port-accent',
+ error: 'text-port-error'
+};
+
+export const STATUS_BG = {
+ draft: 'bg-gray-400/10',
+ active: 'bg-port-success/10',
+ paused: 'bg-port-warning/10',
+ completed: 'bg-port-accent/10',
+ error: 'bg-port-error/10'
+};
+
+export const PRIORITY_COLORS = {
+ LOW: 'text-gray-400',
+ MEDIUM: 'text-port-accent',
+ HIGH: 'text-port-warning',
+ CRITICAL: 'text-port-error'
+};
+
+export const SCHEDULE_LABELS = {
+ continuous: 'Continuous',
+ cron: 'Cron',
+ interval: 'Interval'
+};
+
+export const AUTONOMY_LABELS = {
+ standby: 'Standby',
+ assistant: 'Assistant',
+ manager: 'Manager',
+ yolo: 'YOLO'
+};
diff --git a/client/src/pages/FeatureAgentDetail.jsx b/client/src/pages/FeatureAgentDetail.jsx
new file mode 100644
index 0000000000..b9187cff4e
--- /dev/null
+++ b/client/src/pages/FeatureAgentDetail.jsx
@@ -0,0 +1,142 @@
+import { useState, useEffect, useCallback } from 'react';
+import { useParams, useNavigate, Link } from 'react-router-dom';
+import { Wand2, ArrowLeft } from 'lucide-react';
+import toast from 'react-hot-toast';
+import * as api from '../services/api';
+import socket from '../services/socket';
+import { TABS, VALID_TAB_IDS } from '../components/feature-agents/constants';
+import OverviewTab from '../components/feature-agents/OverviewTab';
+import ConfigTab from '../components/feature-agents/ConfigTab';
+import RunsTab from '../components/feature-agents/RunsTab';
+import OutputTab from '../components/feature-agents/OutputTab';
+import GitTab from '../components/feature-agents/GitTab';
+import BrailleSpinner from '../components/BrailleSpinner';
+
+export default function FeatureAgentDetail() {
+ const { id, tab } = useParams();
+ const navigate = useNavigate();
+ const isCreate = !id;
+ const activeTab = VALID_TAB_IDS.has(tab) ? tab : 'overview';
+
+ const [agent, setAgent] = useState(null);
+ const [loading, setLoading] = useState(!isCreate);
+ const [apps, setApps] = useState([]);
+
+ useEffect(() => {
+ api.getApps().then(data => setApps((data || []).filter(a => !a.archived))).catch(() => {});
+ }, []);
+
+ const fetchAgent = useCallback(() => {
+ if (isCreate) return;
+ api.getFeatureAgent(id).then(data => {
+ setAgent(data);
+ setLoading(false);
+ }).catch(() => setLoading(false));
+ }, [id, isCreate]);
+
+ useEffect(() => {
+ fetchAgent();
+ const handler = (data) => { if (data.id === id) fetchAgent(); };
+ socket.on('cos:feature-agent:status', handler);
+ socket.on('cos:feature-agent:run-complete', handler);
+ return () => {
+ socket.off('cos:feature-agent:status', handler);
+ socket.off('cos:feature-agent:run-complete', handler);
+ };
+ }, [fetchAgent, id]);
+
+ const handleStart = useCallback((agentId) => {
+ api.startFeatureAgent(agentId).then(data => { setAgent(prev => ({ ...prev, ...data })); toast.success('Activated'); }).catch(() => {});
+ }, []);
+ const handlePause = useCallback((agentId) => {
+ api.pauseFeatureAgent(agentId).then(data => { setAgent(prev => ({ ...prev, ...data })); toast.success('Paused'); }).catch(() => {});
+ }, []);
+ const handleResume = useCallback((agentId) => {
+ api.resumeFeatureAgent(agentId).then(data => { setAgent(prev => ({ ...prev, ...data })); toast.success('Resumed'); }).catch(() => {});
+ }, []);
+ const handleStop = useCallback((agentId) => {
+ api.stopFeatureAgent(agentId).then(data => { setAgent(prev => ({ ...prev, ...data })); toast.success('Stopped'); }).catch(() => {});
+ }, []);
+ const handleTrigger = useCallback((agentId) => {
+ api.triggerFeatureAgent(agentId).then(() => toast.success('Run triggered')).catch(() => {});
+ }, []);
+
+ const handleSave = useCallback((saved) => {
+ if (isCreate) {
+ navigate(`/feature-agents/${saved.id}/overview`);
+ } else {
+ setAgent(prev => ({ ...prev, ...saved }));
+ }
+ }, [isCreate, navigate]);
+
+ if (loading) {
+ return (
+ <div className="flex flex-col h-full items-center justify-center">
+ <BrailleSpinner text="Loading agent" />
+ </div>
+ );
+ }
+
+ if (!isCreate && !agent) {
+ return (
+ <div className="flex flex-col h-full items-center justify-center">
+ <p className="text-gray-400">Feature agent not found</p>
+ <Link to="/feature-agents" className="text-port-accent text-sm mt-2 hover:underline">Back to list</Link>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col h-full">
+ {/* Header */}
+ <div className="shrink-0 px-6 pt-6 pb-4 border-b border-port-border">
+ <div className="flex items-center gap-3 mb-3">
+ <Link to="/feature-agents" className="p-1.5 text-gray-400 hover:text-white hover:bg-port-border/50 rounded-lg transition-colors">
+ <ArrowLeft size={18} />
+ </Link>
+ <Wand2 size={22} className="text-port-accent" />
+ <div>
+ <h1 className="text-lg font-bold text-white">
+ {isCreate ? 'Create Feature Agent' : agent.name}
+ </h1>
+ {!isCreate && (
+ <p className="text-xs text-gray-500">{agent.id} &middot; {agent.appId}</p>
+ )}
+ </div>
+ </div>
+
+ {!isCreate && (
+ <div className="flex gap-1 overflow-x-auto">
+ {TABS.map(({ id: tabId, label, icon: Icon }) => (
+ <button
+ key={tabId}
+ onClick={() => navigate(`/feature-agents/${id}/${tabId}`)}
+ className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${
+ activeTab === tabId
+ ? 'bg-port-accent/10 text-port-accent'
+ : 'text-gray-400 hover:text-white hover:bg-port-border/50'
+ }`}
+ >
+ <Icon size={16} />
+ {label}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Content */}
+ <div className="flex-1 overflow-auto p-6">
+ {(isCreate || activeTab === 'config') && (
+ <ConfigTab agent={agent} isCreate={isCreate} apps={apps} onSave={handleSave} />
+ )}
+ {!isCreate && activeTab === 'overview' && (
+ <OverviewTab agent={agent} onStart={handleStart} onPause={handlePause} onResume={handleResume} onStop={handleStop} onTrigger={handleTrigger} />
+ )}
+ {!isCreate && activeTab === 'runs' && <RunsTab agent={agent} />}
+ {!isCreate && activeTab === 'output' && <OutputTab agent={agent} />}
+ {!isCreate && activeTab === 'git' && <GitTab agent={agent} />}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/FeatureAgents.jsx b/client/src/pages/FeatureAgents.jsx
new file mode 100644
index 0000000000..ed3ee5525f
--- /dev/null
+++ b/client/src/pages/FeatureAgents.jsx
@@ -0,0 +1,145 @@
+import { useState, useEffect, useCallback } from 'react';
+import { Link } from 'react-router-dom';
+import { Wand2, Plus, RefreshCw } from 'lucide-react';
+import toast from 'react-hot-toast';
+import * as api from '../services/api';
+import socket from '../services/socket';
+import FeatureAgentCard from '../components/feature-agents/FeatureAgentCard';
+import BrailleSpinner from '../components/BrailleSpinner';
+
+export default function FeatureAgents() {
+ const [agents, setAgents] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ const fetchAgents = useCallback(() => {
+ api.getFeatureAgents().then(data => {
+ setAgents(data || []);
+ setLoading(false);
+ }).catch(() => setLoading(false));
+ }, []);
+
+ useEffect(() => {
+ fetchAgents();
+ const handler = () => fetchAgents();
+ socket.on('cos:feature-agent:status', handler);
+ socket.on('cos:feature-agent:run-complete', handler);
+ return () => {
+ socket.off('cos:feature-agent:status', handler);
+ socket.off('cos:feature-agent:run-complete', handler);
+ };
+ }, [fetchAgents]);
+
+ const handleStart = useCallback((id) => {
+ api.startFeatureAgent(id).then(agent => {
+ setAgents(prev => prev.map(a => a.id === id ? { ...a, ...agent } : a));
+ toast.success('Feature agent activated');
+ }).catch(() => {});
+ }, []);
+
+ const handlePause = useCallback((id) => {
+ api.pauseFeatureAgent(id).then(agent => {
+ setAgents(prev => prev.map(a => a.id === id ? { ...a, ...agent } : a));
+ toast.success('Feature agent paused');
+ }).catch(() => {});
+ }, []);
+
+ const handleResume = useCallback((id) => {
+ api.resumeFeatureAgent(id).then(agent => {
+ setAgents(prev => prev.map(a => a.id === id ? { ...a, ...agent } : a));
+ toast.success('Feature agent resumed');
+ }).catch(() => {});
+ }, []);
+
+ const handleStop = useCallback((id) => {
+ api.stopFeatureAgent(id).then(agent => {
+ setAgents(prev => prev.map(a => a.id === id ? { ...a, ...agent } : a));
+ toast.success('Feature agent stopped');
+ }).catch(() => {});
+ }, []);
+
+ const handleTrigger = useCallback((id) => {
+ api.triggerFeatureAgent(id).then(() => {
+ toast.success('Run triggered');
+ }).catch(() => {});
+ }, []);
+
+ const handleDelete = useCallback((id) => {
+ api.deleteFeatureAgent(id).then(() => {
+ setAgents(prev => prev.filter(a => a.id !== id));
+ toast.success('Feature agent deleted');
+ }).catch(() => {});
+ }, []);
+
+ const activeCount = agents.filter(a => a.status === 'active').length;
+ const totalRuns = agents.reduce((sum, a) => sum + (a.runCount || 0), 0);
+
+ return (
+ <div className="flex flex-col h-full">
+ <div className="shrink-0 px-6 pt-6 pb-4 border-b border-port-border">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <Wand2 size={24} className="text-port-accent" />
+ <div>
+ <h1 className="text-xl font-bold text-white">Feature Agents</h1>
+ <p className="text-sm text-gray-500">
+ {agents.length} agent{agents.length !== 1 ? 's' : ''} &middot; {activeCount} active &middot; {totalRuns} total runs
+ </p>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={fetchAgents}
+ className="p-2 text-gray-400 hover:text-white hover:bg-port-border/50 rounded-lg transition-colors"
+ title="Refresh"
+ >
+ <RefreshCw size={16} />
+ </button>
+ <Link
+ to="/feature-agents/create"
+ className="flex items-center gap-2 px-3 py-2 bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 transition-colors"
+ >
+ <Plus size={16} /> New Agent
+ </Link>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex-1 overflow-auto p-6">
+ {loading ? (
+ <div className="flex items-center justify-center h-32">
+ <BrailleSpinner text="Loading agents" />
+ </div>
+ ) : agents.length === 0 ? (
+ <div className="text-center py-16">
+ <Wand2 size={48} className="mx-auto text-gray-600 mb-4" />
+ <h3 className="text-lg font-medium text-gray-400 mb-2">No Feature Agents</h3>
+ <p className="text-sm text-gray-600 mb-4">
+ Create a feature agent to have a persistent AI developer iterate on a specific feature.
+ </p>
+ <Link
+ to="/feature-agents/create"
+ className="inline-flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 transition-colors"
+ >
+ <Plus size={16} /> Create Feature Agent
+ </Link>
+ </div>
+ ) : (
+ <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4">
+ {agents.map(agent => (
+ <FeatureAgentCard
+ key={agent.id}
+ agent={agent}
+ onStart={handleStart}
+ onPause={handlePause}
+ onResume={handleResume}
+ onStop={handleStop}
+ onTrigger={handleTrigger}
+ onDelete={handleDelete}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index a3446d2345..9a954eb59d 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1378,6 +1378,26 @@ export const addGoalMilestone = (goalId, data) => request(`/digital-twin/identit
export const completeGoalMilestone = (goalId, milestoneId) =>
request(`/digital-twin/identity/goals/${goalId}/milestones/${milestoneId}/complete`, { method: 'PUT' });
+// Feature Agents
+export const getFeatureAgents = () => request('/feature-agents');
+export const getFeatureAgent = (id) => request(`/feature-agents/${id}`);
+export const createFeatureAgent = (data) => request('/feature-agents', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const updateFeatureAgent = (id, data) => request(`/feature-agents/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data)
+});
+export const deleteFeatureAgent = (id) => request(`/feature-agents/${id}`, { method: 'DELETE' });
+export const startFeatureAgent = (id) => request(`/feature-agents/${id}/start`, { method: 'POST' });
+export const pauseFeatureAgent = (id) => request(`/feature-agents/${id}/pause`, { method: 'POST' });
+export const resumeFeatureAgent = (id) => request(`/feature-agents/${id}/resume`, { method: 'POST' });
+export const triggerFeatureAgent = (id) => request(`/feature-agents/${id}/trigger`, { method: 'POST' });
+export const stopFeatureAgent = (id) => request(`/feature-agents/${id}/stop`, { method: 'POST' });
+export const getFeatureAgentRuns = (id, limit) => request(`/feature-agents/${id}/runs${limit ? `?limit=${limit}` : ''}`);
+export const getFeatureAgentOutput = (id) => request(`/feature-agents/${id}/output`);
+
// MeatSpace - Health Tracker
export const getMeatspaceOverview = () => request('/meatspace');
export const getMeatspaceConfig = () => request('/meatspace/config');
diff --git a/data/prompts/skills/feature-agent.md b/data/prompts/skills/feature-agent.md
new file mode 100644
index 0000000000..bffd9bb71d
--- /dev/null
+++ b/data/prompts/skills/feature-agent.md
@@ -0,0 +1,42 @@
+# Feature Agent Skill Template
+
+## Routing
+**Use when**: Task metadata contains `featureAgentRun: true`
+**Don't use when**: Standard tasks without feature agent context
+
+## Guidelines
+
+You are a **Feature Agent** — a persistent AI developer persona that owns and iterates on a specific feature. You work in a dedicated git worktree on a long-lived branch.
+
+### Workflow
+1. Check `git status` and `git log --oneline -10` to understand current state
+2. Review your goals and previous run summaries from the briefing
+3. Identify the highest-impact work within your feature scope
+4. Make targeted, incremental changes
+5. Run tests if available
+6. Commit with clear messages: `feat(<feature>): description`
+7. If goals are met and autoPR is enabled, create/update a PR via `gh pr create` or `gh pr edit`
+
+### Idle Detection
+If nothing actionable remains:
+- All goals are met
+- No new base branch changes to integrate
+- No failing tests to fix
+Report `Status: idle-no-work` in your summary. This triggers backoff to avoid wasting resources.
+
+### Self-Review Checklist
+Before committing:
+- [ ] Changes are within feature scope directories
+- [ ] No unrelated files modified
+- [ ] Tests pass (if applicable)
+- [ ] No hardcoded values that should be configurable
+- [ ] Commit message is descriptive
+
+### Structured Summary (REQUIRED)
+Always end with:
+```
+Status: [working|idle-no-work|error]
+Files changed: [list]
+Summary: [what was done]
+Learnings: [discoveries for next run]
+```
diff --git a/server/index.js b/server/index.js
index fc3c732256..b217ee9129 100644
--- a/server/index.js
+++ b/server/index.js
@@ -28,6 +28,7 @@ import automationSchedulesRoutes from './routes/automationSchedules.js';
import agentActivityRoutes from './routes/agentActivity.js';
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';
@@ -216,6 +217,7 @@ 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);
app.use('/api/notifications', notificationsRoutes);
app.use('/api/standardize', standardizeRoutes);
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 9e71199b8e..a33cf2ad11 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -446,6 +446,57 @@ export const restoreRequestSchema = z.object({
dryRun: z.boolean().optional().default(true)
});
+// =============================================================================
+// FEATURE AGENT SCHEMAS
+// =============================================================================
+
+export const featureAgentStatusSchema = z.enum(['draft', 'active', 'paused', 'completed', 'error']);
+export const featureAgentScheduleModeSchema = z.enum(['continuous', 'cron', 'interval']);
+export const featureAgentAutonomySchema = z.enum(['standby', 'assistant', 'manager', 'yolo']);
+export const featureAgentPrioritySchema = z.enum(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']);
+
+export const featureAgentSchema = z.object({
+ name: z.string().min(1).max(200),
+ description: z.string().min(1).max(2000),
+ persona: z.string().max(5000).optional().default(''),
+ appId: z.string().min(1),
+ featureScope: z.object({
+ directories: z.array(z.string()).default([]),
+ filePatterns: z.array(z.string()).default([]),
+ excludePatterns: z.array(z.string()).default([])
+ }).default({}),
+ git: z.object({
+ branchName: z.string().min(1),
+ baseBranch: z.string().default('main'),
+ autoMergeBase: z.boolean().default(true),
+ autoPR: z.boolean().default(true),
+ prTemplate: z.string().max(5000).optional().default('')
+ }),
+ schedule: z.object({
+ mode: featureAgentScheduleModeSchema.default('continuous'),
+ cronExpression: z.string().optional(),
+ intervalMs: z.number().int().min(30000).optional(),
+ pauseBetweenRunsMs: z.number().int().min(0).default(60000)
+ }).default({}),
+ playwright: z.object({
+ testUrls: z.array(z.string()).default([]),
+ baseUrl: z.string().optional(),
+ startCommand: z.string().optional(),
+ viewport: z.object({
+ width: z.number().int().min(320).max(3840).default(1280),
+ height: z.number().int().min(240).max(2160).default(720)
+ }).default({})
+ }).default({}),
+ goals: z.array(z.string()).default([]),
+ constraints: z.array(z.string()).default([]),
+ providerId: z.string().optional().nullable(),
+ model: z.string().optional().nullable(),
+ autonomyLevel: featureAgentAutonomySchema.default('assistant'),
+ priority: featureAgentPrioritySchema.default('MEDIUM')
+});
+
+export const featureAgentUpdateSchema = featureAgentSchema.partial();
+
/**
* Validate data against a schema
* Returns { success: true, data } or { success: false, errors }
diff --git a/server/routes/featureAgents.js b/server/routes/featureAgents.js
new file mode 100644
index 0000000000..60f3ed9c88
--- /dev/null
+++ b/server/routes/featureAgents.js
@@ -0,0 +1,101 @@
+/**
+ * Feature Agents API Routes
+ */
+
+import { Router } from 'express';
+import * as featureAgents from '../services/featureAgents.js';
+import { validateRequest } from '../lib/validation.js';
+import { featureAgentSchema, featureAgentUpdateSchema } from '../lib/validation.js';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+
+const router = Router();
+
+// GET / - List all feature agents
+router.get('/', asyncHandler(async (req, res) => {
+ const agents = await featureAgents.getAllFeatureAgents();
+ res.json(agents);
+}));
+
+// GET /:id - Get single feature agent with recent runs
+router.get('/:id', asyncHandler(async (req, res) => {
+ const agent = await featureAgents.getFeatureAgent(req.params.id);
+ if (!agent) throw new ServerError('Feature agent not found', { status: 404, code: 'NOT_FOUND' });
+ const runs = await featureAgents.getFeatureAgentRuns(req.params.id, 5);
+ res.json({ ...agent, recentRuns: runs });
+}));
+
+// POST / - Create feature agent
+router.post('/', asyncHandler(async (req, res) => {
+ const data = validateRequest(featureAgentSchema, req.body);
+ const agent = await featureAgents.createFeatureAgent(data);
+ res.status(201).json(agent);
+}));
+
+// PUT /:id - Update feature agent
+router.put('/:id', asyncHandler(async (req, res) => {
+ const data = validateRequest(featureAgentUpdateSchema, req.body);
+ const agent = await featureAgents.updateFeatureAgent(req.params.id, data);
+ if (!agent) throw new ServerError('Feature agent not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(agent);
+}));
+
+// DELETE /:id - Delete feature agent
+router.delete('/:id', asyncHandler(async (req, res) => {
+ const deleted = await featureAgents.deleteFeatureAgent(req.params.id);
+ if (!deleted) throw new ServerError('Feature agent not found', { status: 404, code: 'NOT_FOUND' });
+ res.status(204).end();
+}));
+
+// POST /:id/start - Activate (creates worktree on first start)
+router.post('/:id/start', asyncHandler(async (req, res) => {
+ const agent = await featureAgents.activateFeatureAgent(req.params.id);
+ if (!agent) throw new ServerError('Feature agent not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(agent);
+}));
+
+// POST /:id/pause - Pause scheduling
+router.post('/:id/pause', asyncHandler(async (req, res) => {
+ const agent = await featureAgents.pauseFeatureAgent(req.params.id);
+ if (!agent) throw new ServerError('Feature agent not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(agent);
+}));
+
+// POST /:id/resume - Resume scheduling
+router.post('/:id/resume', asyncHandler(async (req, res) => {
+ const agent = await featureAgents.resumeFeatureAgent(req.params.id);
+ if (!agent) throw new ServerError('Feature agent not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(agent);
+}));
+
+// POST /:id/trigger - Force immediate run
+router.post('/:id/trigger', asyncHandler(async (req, res) => {
+ const agent = await featureAgents.triggerFeatureAgent(req.params.id);
+ if (!agent) throw new ServerError('Feature agent not found', { status: 404, code: 'NOT_FOUND' });
+ res.json({ triggered: true, agent });
+}));
+
+// POST /:id/stop - Deactivate fully
+router.post('/:id/stop', asyncHandler(async (req, res) => {
+ const agent = await featureAgents.stopFeatureAgent(req.params.id);
+ if (!agent) throw new ServerError('Feature agent not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(agent);
+}));
+
+// GET /:id/runs - Run history
+router.get('/:id/runs', asyncHandler(async (req, res) => {
+ const limit = parseInt(req.query.limit) || 20;
+ const runs = await featureAgents.getFeatureAgentRuns(req.params.id, limit);
+ res.json(runs);
+}));
+
+// GET /:id/output - Live output
+router.get('/:id/output', asyncHandler(async (req, res) => {
+ const output = await featureAgents.getFeatureAgentOutput(req.params.id);
+ if (!output) {
+ res.json({ agentId: null, output: '' });
+ return;
+ }
+ res.json(output);
+}));
+
+export default router;
diff --git a/server/services/cos.js b/server/services/cos.js
index 61ddff5ca6..860a35372b 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1087,6 +1087,23 @@ export async function evaluateTasks() {
}
}
+ // Priority 3.6: Feature Agents (after autonomous jobs)
+ if (tasksToSpawn.length < availableSlots) {
+ const { getDueFeatureAgents, generateTaskFromFeatureAgent } = await import('./featureAgents.js');
+ const dueAgents = await getDueFeatureAgents().catch(err => {
+ emitLog('debug', `Feature agents check failed: ${err.message}`);
+ return [];
+ });
+ for (const fa of dueAgents) {
+ if (tasksToSpawn.length >= availableSlots) break;
+ const task = generateTaskFromFeatureAgent(fa);
+ if (!canSpawnTask(task)) continue;
+ tasksToSpawn.push(task);
+ trackSpawn(task);
+ emitLog('info', `Feature agent due: ${fa.name}`, { featureAgentId: fa.id });
+ }
+ }
+
// Priority 4: Only generate direct idle task if:
// 1. Nothing to spawn
// 2. No pending user tasks (even on cooldown)
diff --git a/server/services/featureAgents.js b/server/services/featureAgents.js
new file mode 100644
index 0000000000..c0e3849935
--- /dev/null
+++ b/server/services/featureAgents.js
@@ -0,0 +1,511 @@
+/**
+ * Feature Agents Service
+ *
+ * Manages persistent AI developer personas that own and iterate on
+ * specific features of managed apps. Each agent works in a dedicated
+ * git worktree/branch and runs on a schedule.
+ */
+
+import { writeFile, readFile, rename, mkdir, readdir } from 'fs/promises';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { existsSync } from 'fs';
+import { v4 as uuidv4 } from 'uuid';
+import { cosEvents, emitLog } from './cosEvents.js';
+import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { createMutex } from '../lib/asyncMutex.js';
+import { getAppById } from './apps.js';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const DATA_DIR = PATHS.cos;
+const FA_FILE = join(DATA_DIR, 'feature-agents.json');
+const FA_DIR = join(DATA_DIR, 'feature-agents');
+const withLock = createMutex();
+
+// Event name prefix
+const EVT = 'feature-agent';
+
+// Backoff constants
+const MIN_BACKOFF_MS = 60 * 60 * 1000; // 1 hour
+const MAX_BACKOFF_MS = 24 * 60 * 60 * 1000; // 24 hours
+
+/**
+ * Read the feature agents data file
+ */
+async function readData() {
+ const data = await readJSONFile(FA_FILE, { version: 1, lastUpdated: new Date().toISOString(), agents: [] });
+ return data;
+}
+
+/**
+ * Write the feature agents data file (atomic temp+rename)
+ */
+async function writeData(data) {
+ await ensureDir(DATA_DIR);
+ data.lastUpdated = new Date().toISOString();
+ const tmpFile = FA_FILE + '.tmp';
+ await writeFile(tmpFile, JSON.stringify(data, null, 2));
+ await rename(tmpFile, FA_FILE);
+}
+
+/**
+ * Get all feature agents
+ */
+export async function getAllFeatureAgents() {
+ const data = await readData();
+ return data.agents;
+}
+
+/**
+ * Get a single feature agent by ID
+ */
+export async function getFeatureAgent(id) {
+ const data = await readData();
+ return data.agents.find(a => a.id === id) || null;
+}
+
+/**
+ * Create a new feature agent
+ */
+export async function createFeatureAgent(input) {
+ return withLock(async () => {
+ const data = await readData();
+ const id = `fa-${uuidv4().slice(0, 8)}`;
+ const now = new Date().toISOString();
+
+ const agent = {
+ id,
+ ...input,
+ status: 'draft',
+ lastRunAt: null,
+ runCount: 0,
+ currentAgentId: null,
+ backoff: null,
+ createdAt: now,
+ updatedAt: now
+ };
+
+ data.agents.push(agent);
+ await writeData(data);
+ console.log(`🤖 Feature agent created: ${agent.name} (${id})`);
+ cosEvents.emit(`${EVT}:status`, { id, status: 'draft', name: agent.name });
+ return agent;
+ });
+}
+
+/**
+ * Update a feature agent's config
+ */
+export async function updateFeatureAgent(id, updates) {
+ return withLock(async () => {
+ const data = await readData();
+ const idx = data.agents.findIndex(a => a.id === id);
+ if (idx === -1) return null;
+
+ // Deep merge for nested objects
+ const existing = data.agents[idx];
+ const merged = { ...existing };
+
+ for (const [key, value] of Object.entries(updates)) {
+ if (value && typeof value === 'object' && !Array.isArray(value) && existing[key] && typeof existing[key] === 'object') {
+ merged[key] = { ...existing[key], ...value };
+ } else {
+ merged[key] = value;
+ }
+ }
+
+ merged.updatedAt = new Date().toISOString();
+ data.agents[idx] = merged;
+ await writeData(data);
+ console.log(`🤖 Feature agent updated: ${merged.name} (${id})`);
+ return merged;
+ });
+}
+
+/**
+ * Delete a feature agent and clean up resources
+ */
+export async function deleteFeatureAgent(id) {
+ return withLock(async () => {
+ const data = await readData();
+ const idx = data.agents.findIndex(a => a.id === id);
+ if (idx === -1) return false;
+
+ const agent = data.agents[idx];
+ data.agents.splice(idx, 1);
+ await writeData(data);
+
+ // Clean up worktree directory if it exists
+ const worktreeDir = join(FA_DIR, id, 'worktree');
+ if (existsSync(worktreeDir)) {
+ const app = await getAppById(agent.appId).catch(() => null);
+ if (app?.repoPath) {
+ const { removePersistentWorktree } = await import('./worktreeManager.js');
+ await removePersistentWorktree(id, app.repoPath, agent.git.branchName).catch(err => {
+ console.log(`⚠️ Feature agent worktree cleanup failed: ${err.message}`);
+ });
+ }
+ }
+
+ console.log(`🤖 Feature agent deleted: ${agent.name} (${id})`);
+ cosEvents.emit(`${EVT}:status`, { id, status: 'deleted', name: agent.name });
+ return true;
+ });
+}
+
+/**
+ * Activate a feature agent (creates worktree on first activation)
+ */
+export async function activateFeatureAgent(id) {
+ return withLock(async () => {
+ const data = await readData();
+ const idx = data.agents.findIndex(a => a.id === id);
+ if (idx === -1) return null;
+
+ const agent = data.agents[idx];
+ if (agent.status === 'active') return agent;
+
+ // Create persistent worktree on first activation
+ const worktreeDir = join(FA_DIR, id, 'worktree');
+ if (!existsSync(worktreeDir)) {
+ const app = await getAppById(agent.appId).catch(() => null);
+ if (!app?.repoPath) {
+ throw new Error(`App ${agent.appId} not found or missing repoPath`);
+ }
+
+ const { createPersistentWorktree } = await import('./worktreeManager.js');
+ await createPersistentWorktree(id, app.repoPath, agent.git.branchName, agent.git.baseBranch);
+ console.log(`🌳 Feature agent worktree created: ${agent.git.branchName}`);
+ }
+
+ agent.status = 'active';
+ agent.updatedAt = new Date().toISOString();
+ data.agents[idx] = agent;
+ await writeData(data);
+
+ console.log(`🤖 Feature agent activated: ${agent.name} (${id})`);
+ cosEvents.emit(`${EVT}:status`, { id, status: 'active', name: agent.name });
+ return agent;
+ });
+}
+
+/**
+ * Pause a feature agent
+ */
+export async function pauseFeatureAgent(id) {
+ return withLock(async () => {
+ const data = await readData();
+ const idx = data.agents.findIndex(a => a.id === id);
+ if (idx === -1) return null;
+
+ data.agents[idx].status = 'paused';
+ data.agents[idx].updatedAt = new Date().toISOString();
+ await writeData(data);
+
+ console.log(`🤖 Feature agent paused: ${data.agents[idx].name} (${id})`);
+ cosEvents.emit(`${EVT}:status`, { id, status: 'paused', name: data.agents[idx].name });
+ return data.agents[idx];
+ });
+}
+
+/**
+ * Resume a paused feature agent
+ */
+export async function resumeFeatureAgent(id) {
+ return withLock(async () => {
+ const data = await readData();
+ const idx = data.agents.findIndex(a => a.id === id);
+ if (idx === -1) return null;
+
+ if (data.agents[idx].status !== 'paused') return data.agents[idx];
+
+ data.agents[idx].status = 'active';
+ data.agents[idx].backoff = null; // Reset backoff on resume
+ data.agents[idx].updatedAt = new Date().toISOString();
+ await writeData(data);
+
+ console.log(`🤖 Feature agent resumed: ${data.agents[idx].name} (${id})`);
+ cosEvents.emit(`${EVT}:status`, { id, status: 'active', name: data.agents[idx].name });
+ return data.agents[idx];
+ });
+}
+
+/**
+ * Stop a feature agent fully
+ */
+export async function stopFeatureAgent(id) {
+ return withLock(async () => {
+ const data = await readData();
+ const idx = data.agents.findIndex(a => a.id === id);
+ if (idx === -1) return null;
+
+ data.agents[idx].status = 'draft';
+ data.agents[idx].currentAgentId = null;
+ data.agents[idx].backoff = null;
+ data.agents[idx].updatedAt = new Date().toISOString();
+ await writeData(data);
+
+ console.log(`🤖 Feature agent stopped: ${data.agents[idx].name} (${id})`);
+ cosEvents.emit(`${EVT}:status`, { id, status: 'draft', name: data.agents[idx].name });
+ return data.agents[idx];
+ });
+}
+
+/**
+ * Force-trigger an immediate run for a feature agent
+ */
+export async function triggerFeatureAgent(id) {
+ const agent = await getFeatureAgent(id);
+ if (!agent) return null;
+
+ // Temporarily mark as active if in draft/paused for this run
+ if (agent.status === 'draft' || agent.status === 'paused') {
+ await activateFeatureAgent(id);
+ }
+
+ return agent;
+}
+
+/**
+ * Get feature agents that are due for their next run based on schedule
+ */
+export async function getDueFeatureAgents() {
+ const data = await readData();
+ const now = Date.now();
+ const due = [];
+
+ for (const agent of data.agents) {
+ if (agent.status !== 'active') continue;
+ if (agent.currentAgentId) continue; // Already running
+
+ // Check backoff
+ if (agent.backoff?.currentDelayMs) {
+ const nextAllowed = new Date(agent.backoff.lastIdleAt).getTime() + agent.backoff.currentDelayMs;
+ if (now < nextAllowed) continue;
+ }
+
+ const lastRun = agent.lastRunAt ? new Date(agent.lastRunAt).getTime() : 0;
+ const mode = agent.schedule?.mode || 'continuous';
+
+ if (mode === 'continuous') {
+ const pause = agent.schedule?.pauseBetweenRunsMs || 60000;
+ if (now - lastRun >= pause) {
+ due.push(agent);
+ }
+ } else if (mode === 'interval') {
+ const interval = agent.schedule?.intervalMs || 3600000;
+ if (now - lastRun >= interval) {
+ due.push(agent);
+ }
+ } else if (mode === 'cron') {
+ // Simple cron check - for now just use interval as fallback
+ // Full cron parsing can be added later
+ const interval = agent.schedule?.intervalMs || 3600000;
+ if (now - lastRun >= interval) {
+ due.push(agent);
+ }
+ }
+ }
+
+ return due;
+}
+
+/**
+ * Generate a CoS task from a feature agent
+ */
+export function generateTaskFromFeatureAgent(agent) {
+ return {
+ id: `fa-run-${agent.id}-${Date.now()}`,
+ description: `[Feature Agent] ${agent.name}: ${agent.description}`,
+ priority: agent.priority || 'MEDIUM',
+ status: 'pending',
+ taskType: 'internal',
+ approvalRequired: false,
+ metadata: {
+ featureAgentId: agent.id,
+ featureAgentRun: true,
+ app: agent.appId,
+ provider: agent.providerId || undefined,
+ model: agent.model || undefined
+ }
+ };
+}
+
+/**
+ * Record run completion and update agent state
+ */
+export async function recordRunCompletion(id, runData) {
+ return withLock(async () => {
+ const data = await readData();
+ const idx = data.agents.findIndex(a => a.id === id);
+ if (idx === -1) return null;
+
+ const agent = data.agents[idx];
+ agent.lastRunAt = new Date().toISOString();
+ agent.runCount = (agent.runCount || 0) + 1;
+ agent.currentAgentId = null;
+ agent.updatedAt = new Date().toISOString();
+
+ // Handle idle detection for backoff
+ if (runData.status === 'idle-no-work') {
+ const consecutiveIdles = (agent.backoff?.consecutiveIdles || 0) + 1;
+ const currentDelayMs = Math.min(
+ MIN_BACKOFF_MS * Math.pow(2, consecutiveIdles - 1),
+ MAX_BACKOFF_MS
+ );
+ agent.backoff = {
+ currentDelayMs,
+ consecutiveIdles,
+ lastIdleAt: new Date().toISOString()
+ };
+ console.log(`😴 Feature agent ${agent.name} idle (backoff: ${Math.round(currentDelayMs / 60000)}min)`);
+ } else {
+ // Reset backoff on productive work
+ agent.backoff = null;
+ }
+
+ data.agents[idx] = agent;
+ await writeData(data);
+
+ // Save run history
+ const runDir = join(FA_DIR, id, 'runs');
+ await ensureDir(runDir);
+ const runId = `run-${Date.now()}`;
+ await writeFile(
+ join(runDir, `${runId}.json`),
+ JSON.stringify({ id: runId, ...runData, completedAt: new Date().toISOString() }, null, 2)
+ );
+
+ cosEvents.emit(`${EVT}:run-complete`, { id, runId, name: agent.name, status: runData.status });
+ return agent;
+ });
+}
+
+/**
+ * Get run history for a feature agent
+ */
+export async function getFeatureAgentRuns(id, limit = 20) {
+ const runDir = join(FA_DIR, id, 'runs');
+ if (!existsSync(runDir)) return [];
+
+ const files = await readdir(runDir);
+ const runFiles = files
+ .filter(f => f.endsWith('.json'))
+ .sort((a, b) => b.localeCompare(a)) // newest first
+ .slice(0, limit);
+
+ const runs = [];
+ for (const file of runFiles) {
+ const run = await readJSONFile(join(runDir, file), null);
+ if (run) runs.push(run);
+ }
+
+ return runs;
+}
+
+/**
+ * Get live output for a currently running feature agent
+ */
+export async function getFeatureAgentOutput(id) {
+ const agent = await getFeatureAgent(id);
+ if (!agent?.currentAgentId) return null;
+
+ const outputFile = join(PATHS.cosAgents, agent.currentAgentId, 'output.txt');
+ if (!existsSync(outputFile)) return null;
+
+ const content = await readFile(outputFile, 'utf-8').catch(() => '');
+ return { agentId: agent.currentAgentId, output: content };
+}
+
+/**
+ * Build the full prompt for a feature agent run
+ */
+export async function buildFeatureAgentPrompt(agent) {
+ const app = await getAppById(agent.appId).catch(() => null);
+ const recentRuns = await getFeatureAgentRuns(agent.id, 3);
+
+ const runSummaries = recentRuns.length > 0
+ ? recentRuns.map(r => `- ${r.completedAt}: ${r.status} - ${r.summary || 'No summary'}`).join('\n')
+ : 'No previous runs.';
+
+ const worktreeDir = join(FA_DIR, agent.id, 'worktree');
+
+ // Load skill template if exists
+ const skillPath = join(dirname(__dirname), '../data/prompts/skills/feature-agent.md');
+ const skillTemplate = existsSync(skillPath)
+ ? await readFile(skillPath, 'utf-8').catch(() => '')
+ : '';
+
+ return `# Feature Agent Briefing
+
+${agent.persona ? `## Persona\n${agent.persona}\n` : ''}
+
+## Identity
+- **Name**: ${agent.name}
+- **Feature**: ${agent.description}
+- **App**: ${app?.name || agent.appId} (${app?.repoPath || 'unknown path'})
+
+## Feature Scope
+- **Directories**: ${agent.featureScope?.directories?.join(', ') || 'all'}
+- **File patterns**: ${agent.featureScope?.filePatterns?.join(', ') || 'all'}
+- **Exclude**: ${agent.featureScope?.excludePatterns?.join(', ') || 'none'}
+
+## Goals
+${agent.goals?.length ? agent.goals.map(g => `- ${g}`).join('\n') : '- No specific goals defined'}
+
+## Constraints
+${agent.constraints?.length ? agent.constraints.map(c => `- ${c}`).join('\n') : '- No specific constraints'}
+
+## Git Context
+- **Branch**: \`${agent.git.branchName}\`
+- **Base branch**: \`${agent.git.baseBranch}\`
+- **Worktree**: \`${worktreeDir}\`
+- **Auto PR**: ${agent.git.autoPR ? 'yes' : 'no'}
+
+**Important**: You are working in a persistent worktree on branch \`${agent.git.branchName}\`. Commit your changes to this branch. ${agent.git.autoPR ? 'When you have completed meaningful work, create or update a PR using \`gh pr create\` or \`gh pr edit\`.' : ''}
+
+## Previous Runs
+${runSummaries}
+
+${agent.playwright?.testUrls?.length ? `## Playwright Validation
+Test your changes by visiting these URLs:
+${agent.playwright.testUrls.map(u => `- ${u}`).join('\n')}
+${agent.playwright.baseUrl ? `Base URL: ${agent.playwright.baseUrl}` : ''}
+${agent.playwright.viewport ? `Viewport: ${agent.playwright.viewport.width}x${agent.playwright.viewport.height}` : ''}
+` : ''}
+
+${skillTemplate ? `## Skill Guidelines\n${skillTemplate}\n` : ''}
+
+## Instructions
+1. Review the current state of your feature branch
+2. Identify what needs to be done based on your goals
+3. Make targeted changes within your feature scope
+4. Test changes when possible (run tests, check Playwright URLs)
+5. Commit with clear messages prefixed with the feature name
+6. If nothing actionable remains, report idle status
+
+## Structured Summary (REQUIRED at end)
+Always end your work with this format:
+\`\`\`
+Status: [working|idle-no-work|error]
+Files changed: [list of files]
+Summary: [what was done]
+Learnings: [anything discovered for next run]
+\`\`\`
+`;
+}
+
+/**
+ * Mark a feature agent as having a running CoS agent
+ */
+export async function setCurrentAgent(id, agentId) {
+ return withLock(async () => {
+ const data = await readData();
+ const idx = data.agents.findIndex(a => a.id === id);
+ if (idx === -1) return;
+ data.agents[idx].currentAgentId = agentId;
+ data.agents[idx].updatedAt = new Date().toISOString();
+ await writeData(data);
+ });
+}
diff --git a/server/services/socket.js b/server/services/socket.js
index ff0856c36f..4cc012085b 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -538,6 +538,11 @@ function setupCosEventForwarding() {
cosEvents.on('evaluation', (data) => broadcastToCos('cos:evaluation', data));
cosEvents.on('task:ready', (data) => broadcastToCos('cos:task:ready', data));
+ // Feature agent events
+ cosEvents.on('feature-agent:status', (data) => broadcastToCos('cos:feature-agent:status', data));
+ cosEvents.on('feature-agent:output', (data) => broadcastToCos('cos:feature-agent:output', data));
+ cosEvents.on('feature-agent:run-complete', (data) => broadcastToCos('cos:feature-agent:run-complete', data));
+
// Watcher events
cosEvents.on('watcher:started', (data) => broadcastToCos('cos:watcher:started', data));
cosEvents.on('watcher:stopped', (data) => broadcastToCos('cos:watcher:stopped', data));
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index aa4a341e01..4f901e57c1 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -158,6 +158,77 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
return { merged, removed: true };
}
+/**
+ * Create a persistent worktree for a feature agent.
+ * Unlike regular worktrees, these persist across runs.
+ */
+export async function createPersistentWorktree(featureAgentId, sourceWorkspace, branchName, baseBranch = 'main') {
+ const FA_WORKTREES = join(WORKTREES_DIR, '..', 'feature-agents', featureAgentId, 'worktree');
+
+ await mkdir(join(WORKTREES_DIR, '..', 'feature-agents', featureAgentId), { recursive: true });
+
+ await execGit(['fetch', 'origin'], sourceWorkspace).catch(err => {
+ console.log(`⚠️ Persistent worktree fetch failed: ${err.message}`);
+ });
+
+ const baseRef = await execGit(['rev-parse', `origin/${baseBranch}`], sourceWorkspace)
+ .then(() => `origin/${baseBranch}`)
+ .catch(() => baseBranch);
+
+ // Check if branch already exists
+ const branchExists = (await execGit(['branch', '--list', branchName], sourceWorkspace)).trim();
+
+ if (branchExists) {
+ // Branch exists - create worktree from existing branch
+ await execGit(['worktree', 'add', FA_WORKTREES, branchName], sourceWorkspace);
+ } else {
+ // New branch - create from base
+ await execGit(['worktree', 'add', '-b', branchName, FA_WORKTREES, baseRef], sourceWorkspace);
+ }
+
+ console.log(`🌳 Created persistent worktree for feature agent ${featureAgentId} at ${FA_WORKTREES} (branch: ${branchName})`);
+ return { worktreePath: FA_WORKTREES, branchName, baseBranch };
+}
+
+/**
+ * Remove a persistent feature agent worktree
+ */
+export async function removePersistentWorktree(featureAgentId, sourceWorkspace, branchName) {
+ const worktreePath = join(WORKTREES_DIR, '..', 'feature-agents', featureAgentId, 'worktree');
+
+ if (!existsSync(worktreePath)) return { removed: false };
+
+ await execGit(['worktree', 'remove', worktreePath, '--force'], sourceWorkspace).catch(async () => {
+ await rm(worktreePath, { recursive: true, force: true });
+ await execGit(['worktree', 'prune'], sourceWorkspace).catch(() => {});
+ });
+
+ console.log(`🌳 Removed persistent worktree for feature agent ${featureAgentId}`);
+ return { removed: true };
+}
+
+/**
+ * Merge base branch into a persistent feature agent worktree before a run
+ */
+export async function mergeBaseIntoFeatureWorktree(featureAgentId, sourceWorkspace, branchName, baseBranch = 'main') {
+ const worktreePath = join(WORKTREES_DIR, '..', 'feature-agents', featureAgentId, 'worktree');
+ if (!existsSync(worktreePath)) return { merged: false, reason: 'worktree-missing' };
+
+ await execGit(['fetch', 'origin'], worktreePath).catch(() => {});
+ const result = await execGit(['merge', `origin/${baseBranch}`, '--no-edit'], worktreePath)
+ .then(() => ({ merged: true }))
+ .catch(err => {
+ // Abort failed merge
+ execGit(['merge', '--abort'], worktreePath).catch(() => {});
+ return { merged: false, reason: err.message };
+ });
+
+ if (result.merged) {
+ console.log(`🌳 Merged origin/${baseBranch} into feature agent ${featureAgentId}`);
+ }
+ return result;
+}
+
/**
* List all active worktrees for the repository
*/