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: add Brain second-brain management system

Adam Eivy1958c70bd303
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 539d4e8288..97eb919c99 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -7,6 +7,7 @@ import CreateApp from './pages/CreateApp';
import Templates from './pages/Templates';
import PromptManager from './pages/PromptManager';
import ChiefOfStaff from './pages/ChiefOfStaff';
+import Brain from './pages/Brain';
import Media from './pages/Media';
// Lazy load heavier pages for code splitting
@@ -46,6 +47,8 @@ export default function App() {
<Route path="prompts" element={<PromptManager />} />
<Route path="cos" element={<Navigate to="/cos/tasks" replace />} />
<Route path="cos/:tab" element={<ChiefOfStaff />} />
+ <Route path="brain" element={<Navigate to="/brain/inbox" replace />} />
+ <Route path="brain/:tab" element={<Brain />} />
<Route path="apps/create" element={<CreateApp />} />
<Route path="templates" element={<Templates />} />
<Route path="media" element={<Media />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index ab6dce66dd..ee8e27ca92 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -20,7 +20,8 @@ import {
ExternalLink,
Crown,
Play,
- Camera
+ Camera,
+ Brain
} from 'lucide-react';
import packageJson from '../../package.json';
import Logo from './Logo';
@@ -42,6 +43,7 @@ const navItems = [
{ to: '/media', label: 'Media', icon: Camera, single: true },
{ href: '//:5560', label: 'Autofixer', icon: Wrench, external: true, dynamicHost: true },
{ to: '/cos', label: 'Chief of Staff', icon: Crown, single: true, showBadge: true },
+ { to: '/brain', label: 'Brain', icon: Brain, single: true },
{
label: 'Dev Tools',
icon: Terminal,
@@ -385,8 +387,8 @@ export default function Layout() {
</header>
{/* Main content */}
- <main id="main-content" className={`flex-1 overflow-auto ${location.pathname.startsWith('/cos') ? '' : 'p-4 md:p-6'}`}>
- {location.pathname.startsWith('/cos') ? (
+ <main id="main-content" className={`flex-1 overflow-auto ${location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') ? '' : 'p-4 md:p-6'}`}>
+ {location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') ? (
<Outlet />
) : (
<div className="max-w-7xl mx-auto">
diff --git a/client/src/components/brain/constants.js b/client/src/components/brain/constants.js
new file mode 100644
index 0000000000..fd283be304
--- /dev/null
+++ b/client/src/components/brain/constants.js
@@ -0,0 +1,102 @@
+import { MessageSquare, Database, Calendar, Shield, Users, FolderKanban, Lightbulb, ClipboardList } from 'lucide-react';
+
+// Main navigation tabs
+export const TABS = [
+ { id: 'inbox', label: 'Inbox', icon: MessageSquare },
+ { id: 'memory', label: 'Memory', icon: Database },
+ { id: 'digest', label: 'Digest', icon: Calendar },
+ { id: 'trust', label: 'Trust', icon: Shield }
+];
+
+// Memory sub-tabs for entity types
+export const MEMORY_TABS = [
+ { id: 'people', label: 'People', icon: Users },
+ { id: 'projects', label: 'Projects', icon: FolderKanban },
+ { id: 'ideas', label: 'Ideas', icon: Lightbulb },
+ { id: 'admin', label: 'Admin', icon: ClipboardList }
+];
+
+// Destination display info
+export const DESTINATIONS = {
+ people: {
+ label: 'People',
+ icon: Users,
+ color: 'bg-purple-500/20 text-purple-400 border-purple-500/30'
+ },
+ projects: {
+ label: 'Projects',
+ icon: FolderKanban,
+ color: 'bg-blue-500/20 text-blue-400 border-blue-500/30'
+ },
+ ideas: {
+ label: 'Ideas',
+ icon: Lightbulb,
+ color: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30'
+ },
+ admin: {
+ label: 'Admin',
+ icon: ClipboardList,
+ color: 'bg-green-500/20 text-green-400 border-green-500/30'
+ },
+ unknown: {
+ label: 'Unknown',
+ icon: MessageSquare,
+ color: 'bg-gray-500/20 text-gray-400 border-gray-500/30'
+ }
+};
+
+// Inbox status colors
+export const STATUS_COLORS = {
+ filed: 'bg-port-success/20 text-port-success border-port-success/30',
+ needs_review: 'bg-port-warning/20 text-port-warning border-port-warning/30',
+ corrected: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
+ error: 'bg-port-error/20 text-port-error border-port-error/30'
+};
+
+// Project status colors
+export const PROJECT_STATUS_COLORS = {
+ active: 'bg-green-500/20 text-green-400 border-green-500/30',
+ waiting: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
+ blocked: 'bg-red-500/20 text-red-400 border-red-500/30',
+ someday: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
+ done: 'bg-gray-500/20 text-gray-400 border-gray-500/30'
+};
+
+// Admin status colors
+export const ADMIN_STATUS_COLORS = {
+ open: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
+ waiting: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
+ done: 'bg-green-500/20 text-green-400 border-green-500/30'
+};
+
+// Confidence thresholds for display
+export const CONFIDENCE_COLORS = {
+ high: 'text-green-400', // >= 0.8
+ medium: 'text-yellow-400', // >= 0.6
+ low: 'text-red-400' // < 0.6
+};
+
+export function getConfidenceColor(confidence) {
+ if (confidence >= 0.8) return CONFIDENCE_COLORS.high;
+ if (confidence >= 0.6) return CONFIDENCE_COLORS.medium;
+ return CONFIDENCE_COLORS.low;
+}
+
+// Format relative time
+export function formatRelativeTime(dateString) {
+ if (!dateString) return 'Never';
+
+ const date = new Date(dateString);
+ const now = new Date();
+ const diffMs = now - date;
+ const diffMins = Math.floor(diffMs / 60000);
+ const diffHours = Math.floor(diffMs / 3600000);
+ const diffDays = Math.floor(diffMs / 86400000);
+
+ if (diffMins < 1) return 'Just now';
+ if (diffMins < 60) return `${diffMins}m ago`;
+ if (diffHours < 24) return `${diffHours}h ago`;
+ if (diffDays < 7) return `${diffDays}d ago`;
+
+ return date.toLocaleDateString();
+}
diff --git a/client/src/components/brain/index.js b/client/src/components/brain/index.js
new file mode 100644
index 0000000000..8f424d3a43
--- /dev/null
+++ b/client/src/components/brain/index.js
@@ -0,0 +1,8 @@
+// Constants
+export * from './constants';
+
+// Tab Components
+export { default as InboxTab } from './tabs/InboxTab';
+export { default as MemoryTab } from './tabs/MemoryTab';
+export { default as DigestTab } from './tabs/DigestTab';
+export { default as TrustTab } from './tabs/TrustTab';
diff --git a/client/src/components/brain/tabs/DigestTab.jsx b/client/src/components/brain/tabs/DigestTab.jsx
new file mode 100644
index 0000000000..8ae09e00fa
--- /dev/null
+++ b/client/src/components/brain/tabs/DigestTab.jsx
@@ -0,0 +1,299 @@
+import { useState, useEffect, useCallback } from 'react';
+import * as api from '../../../services/api';
+import {
+ RefreshCw,
+ Play,
+ Calendar,
+ ChevronDown,
+ ChevronRight,
+ AlertCircle,
+ CheckCircle,
+ Clock
+} from 'lucide-react';
+import toast from 'react-hot-toast';
+
+import { formatRelativeTime } from '../constants';
+
+export default function DigestTab({ onRefresh }) {
+ const [latestDigest, setLatestDigest] = useState(null);
+ const [latestReview, setLatestReview] = useState(null);
+ const [digestHistory, setDigestHistory] = useState([]);
+ const [reviewHistory, setReviewHistory] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [runningDigest, setRunningDigest] = useState(false);
+ const [runningReview, setRunningReview] = useState(false);
+ const [showDigestHistory, setShowDigestHistory] = useState(false);
+ const [showReviewHistory, setShowReviewHistory] = useState(false);
+
+ const fetchData = useCallback(async () => {
+ const [digest, review, digests, reviews] = await Promise.all([
+ api.getBrainLatestDigest().catch(() => null),
+ api.getBrainLatestReview().catch(() => null),
+ api.getBrainDigests().catch(() => []),
+ api.getBrainReviews().catch(() => [])
+ ]);
+
+ setLatestDigest(digest);
+ setLatestReview(review);
+ setDigestHistory(digests.slice(1)); // Exclude latest
+ setReviewHistory(reviews.slice(1)); // Exclude latest
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ fetchData();
+ }, [fetchData]);
+
+ const handleRunDigest = async () => {
+ setRunningDigest(true);
+ const result = await api.runBrainDigest().catch(err => {
+ toast.error(err.message || 'Failed to generate digest');
+ return null;
+ });
+ setRunningDigest(false);
+
+ if (result) {
+ toast.success('Daily digest generated');
+ fetchData();
+ onRefresh?.();
+ }
+ };
+
+ const handleRunReview = async () => {
+ setRunningReview(true);
+ const result = await api.runBrainReview().catch(err => {
+ toast.error(err.message || 'Failed to generate review');
+ return null;
+ });
+ setRunningReview(false);
+
+ if (result) {
+ toast.success('Weekly review generated');
+ fetchData();
+ onRefresh?.();
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-8 max-w-3xl mx-auto">
+ {/* Daily Digest Section */}
+ <section>
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-2">
+ <Calendar className="w-5 h-5 text-port-accent" />
+ <h2 className="text-lg font-semibold text-white">Daily Digest</h2>
+ </div>
+ <button
+ onClick={handleRunDigest}
+ disabled={runningDigest}
+ className="flex items-center gap-2 px-3 py-1.5 bg-port-accent/20 text-port-accent rounded-lg text-sm hover:bg-port-accent/30 disabled:opacity-50"
+ >
+ {runningDigest ? (
+ <RefreshCw size={14} className="animate-spin" />
+ ) : (
+ <Play size={14} />
+ )}
+ Generate Now
+ </button>
+ </div>
+
+ {latestDigest ? (
+ <div className="p-4 bg-port-card border border-port-border rounded-lg">
+ <div className="flex items-center justify-between mb-3">
+ <span className="text-sm text-gray-500">
+ Generated {formatRelativeTime(latestDigest.generatedAt)}
+ </span>
+ </div>
+
+ <p className="text-white mb-4">{latestDigest.digestText}</p>
+
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-3 mb-4">
+ {/* Top Actions */}
+ <div className="p-3 bg-port-bg rounded-lg">
+ <h4 className="text-xs font-medium text-port-accent mb-2 flex items-center gap-1">
+ <CheckCircle size={12} />
+ Top Actions
+ </h4>
+ <ul className="space-y-1">
+ {latestDigest.topActions?.map((action, i) => (
+ <li key={i} className="text-sm text-gray-300">• {action}</li>
+ ))}
+ </ul>
+ </div>
+
+ {/* Stuck Thing */}
+ <div className="p-3 bg-port-bg rounded-lg">
+ <h4 className="text-xs font-medium text-port-warning mb-2 flex items-center gap-1">
+ <AlertCircle size={12} />
+ Stuck
+ </h4>
+ <p className="text-sm text-gray-300">{latestDigest.stuckThing || 'Nothing stuck'}</p>
+ </div>
+
+ {/* Small Win */}
+ <div className="p-3 bg-port-bg rounded-lg">
+ <h4 className="text-xs font-medium text-port-success mb-2 flex items-center gap-1">
+ <CheckCircle size={12} />
+ Small Win
+ </h4>
+ <p className="text-sm text-gray-300">{latestDigest.smallWin || 'Keep going!'}</p>
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="p-8 bg-port-card border border-port-border rounded-lg text-center">
+ <Calendar className="w-12 h-12 text-gray-500 mx-auto mb-3" />
+ <p className="text-gray-500">No daily digest yet.</p>
+ <p className="text-gray-600 text-sm mt-1">Click "Generate Now" to create your first digest.</p>
+ </div>
+ )}
+
+ {/* Digest History */}
+ {digestHistory.length > 0 && (
+ <div className="mt-3">
+ <button
+ onClick={() => setShowDigestHistory(!showDigestHistory)}
+ className="flex items-center gap-2 text-sm text-gray-400 hover:text-white"
+ >
+ {showDigestHistory ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
+ Previous digests ({digestHistory.length})
+ </button>
+
+ {showDigestHistory && (
+ <div className="mt-2 space-y-2">
+ {digestHistory.map(digest => (
+ <div key={digest.id} className="p-3 bg-port-card/50 border border-port-border rounded-lg">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs text-gray-500">
+ {formatRelativeTime(digest.generatedAt)}
+ </span>
+ </div>
+ <p className="text-sm text-gray-300">{digest.digestText}</p>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </section>
+
+ {/* Weekly Review Section */}
+ <section>
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-2">
+ <Clock className="w-5 h-5 text-purple-400" />
+ <h2 className="text-lg font-semibold text-white">Weekly Review</h2>
+ </div>
+ <button
+ onClick={handleRunReview}
+ disabled={runningReview}
+ className="flex items-center gap-2 px-3 py-1.5 bg-purple-500/20 text-purple-400 rounded-lg text-sm hover:bg-purple-500/30 disabled:opacity-50"
+ >
+ {runningReview ? (
+ <RefreshCw size={14} className="animate-spin" />
+ ) : (
+ <Play size={14} />
+ )}
+ Generate Now
+ </button>
+ </div>
+
+ {latestReview ? (
+ <div className="p-4 bg-port-card border border-port-border rounded-lg">
+ <div className="flex items-center justify-between mb-3">
+ <span className="text-sm text-gray-500">
+ Generated {formatRelativeTime(latestReview.generatedAt)}
+ </span>
+ </div>
+
+ <p className="text-white mb-4">{latestReview.reviewText}</p>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-4">
+ {/* What Happened */}
+ <div className="p-3 bg-port-bg rounded-lg">
+ <h4 className="text-xs font-medium text-blue-400 mb-2">What Happened</h4>
+ <ul className="space-y-1">
+ {latestReview.whatHappened?.map((item, i) => (
+ <li key={i} className="text-sm text-gray-300">• {item}</li>
+ ))}
+ </ul>
+ </div>
+
+ {/* Suggested Actions */}
+ <div className="p-3 bg-port-bg rounded-lg">
+ <h4 className="text-xs font-medium text-port-accent mb-2">Actions Next Week</h4>
+ <ul className="space-y-1">
+ {latestReview.suggestedActionsNextWeek?.map((action, i) => (
+ <li key={i} className="text-sm text-gray-300">• {action}</li>
+ ))}
+ </ul>
+ </div>
+ </div>
+
+ {/* Open Loops */}
+ {latestReview.biggestOpenLoops?.length > 0 && (
+ <div className="p-3 bg-port-warning/10 border border-port-warning/30 rounded-lg mb-4">
+ <h4 className="text-xs font-medium text-port-warning mb-2">Biggest Open Loops</h4>
+ <ul className="space-y-1">
+ {latestReview.biggestOpenLoops.map((loop, i) => (
+ <li key={i} className="text-sm text-gray-300">• {loop}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {/* Recurring Theme */}
+ {latestReview.recurringTheme && (
+ <div className="p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg">
+ <h4 className="text-xs font-medium text-purple-400 mb-1">Pattern Noticed</h4>
+ <p className="text-sm text-gray-300">{latestReview.recurringTheme}</p>
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="p-8 bg-port-card border border-port-border rounded-lg text-center">
+ <Clock className="w-12 h-12 text-gray-500 mx-auto mb-3" />
+ <p className="text-gray-500">No weekly review yet.</p>
+ <p className="text-gray-600 text-sm mt-1">Click "Generate Now" to create your first review.</p>
+ </div>
+ )}
+
+ {/* Review History */}
+ {reviewHistory.length > 0 && (
+ <div className="mt-3">
+ <button
+ onClick={() => setShowReviewHistory(!showReviewHistory)}
+ className="flex items-center gap-2 text-sm text-gray-400 hover:text-white"
+ >
+ {showReviewHistory ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
+ Previous reviews ({reviewHistory.length})
+ </button>
+
+ {showReviewHistory && (
+ <div className="mt-2 space-y-2">
+ {reviewHistory.map(review => (
+ <div key={review.id} className="p-3 bg-port-card/50 border border-port-border rounded-lg">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs text-gray-500">
+ {formatRelativeTime(review.generatedAt)}
+ </span>
+ </div>
+ <p className="text-sm text-gray-300">{review.reviewText}</p>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </section>
+ </div>
+ );
+}
diff --git a/client/src/components/brain/tabs/InboxTab.jsx b/client/src/components/brain/tabs/InboxTab.jsx
new file mode 100644
index 0000000000..4dc4fcf94b
--- /dev/null
+++ b/client/src/components/brain/tabs/InboxTab.jsx
@@ -0,0 +1,366 @@
+import { useState, useEffect, useCallback, useRef } from 'react';
+import * as api from '../../../services/api';
+import {
+ Send,
+ RefreshCw,
+ AlertCircle,
+ CheckCircle,
+ Edit2,
+ ChevronDown,
+ ChevronRight,
+ ExternalLink
+} from 'lucide-react';
+import toast from 'react-hot-toast';
+
+import {
+ DESTINATIONS,
+ STATUS_COLORS,
+ getConfidenceColor,
+ formatRelativeTime
+} from '../constants';
+
+export default function InboxTab({ onRefresh, settings }) {
+ const [inputText, setInputText] = useState('');
+ const [sending, setSending] = useState(false);
+ const [entries, setEntries] = useState([]);
+ const [counts, setCounts] = useState({});
+ const [loading, setLoading] = useState(true);
+ const [showNeedsReview, setShowNeedsReview] = useState(true);
+ const [showFiled, setShowFiled] = useState(true);
+ const [fixingId, setFixingId] = useState(null);
+ const [fixDestination, setFixDestination] = useState('');
+ const inputRef = useRef(null);
+
+ const fetchInbox = useCallback(async () => {
+ const data = await api.getBrainInbox().catch(() => ({ entries: [], counts: {} }));
+ setEntries(data.entries || []);
+ setCounts(data.counts || {});
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ fetchInbox();
+ }, [fetchInbox]);
+
+ const handleSubmit = async (e) => {
+ e.preventDefault();
+ if (!inputText.trim() || sending) return;
+
+ setSending(true);
+ const result = await api.captureBrainThought(inputText.trim()).catch(err => {
+ toast.error(err.message || 'Failed to capture thought');
+ return null;
+ });
+ setSending(false);
+
+ if (result) {
+ toast.success(result.message || 'Thought captured');
+ setInputText('');
+ fetchInbox();
+ onRefresh?.();
+ }
+ };
+
+ const handleResolve = async (entryId, destination) => {
+ const result = await api.resolveBrainReview(entryId, destination).catch(err => {
+ toast.error(err.message || 'Failed to resolve');
+ return null;
+ });
+
+ if (result) {
+ toast.success(`Filed to ${destination}`);
+ fetchInbox();
+ onRefresh?.();
+ }
+ };
+
+ const handleRetry = async (entryId) => {
+ const result = await api.retryBrainClassification(entryId).catch(err => {
+ toast.error(err.message || 'Failed to retry');
+ return null;
+ });
+
+ if (result) {
+ toast.success(result.message || 'Reclassified');
+ fetchInbox();
+ onRefresh?.();
+ }
+ };
+
+ const handleFix = async (entryId) => {
+ if (!fixDestination) {
+ toast.error('Select a destination');
+ return;
+ }
+
+ const result = await api.fixBrainClassification(entryId, fixDestination).catch(err => {
+ toast.error(err.message || 'Failed to fix');
+ return null;
+ });
+
+ if (result) {
+ toast.success(`Moved to ${fixDestination}`);
+ setFixingId(null);
+ setFixDestination('');
+ fetchInbox();
+ onRefresh?.();
+ }
+ };
+
+ const needsReviewEntries = entries.filter(e => e.status === 'needs_review');
+ const filedEntries = entries.filter(e => e.status === 'filed' || e.status === 'corrected');
+ const errorEntries = entries.filter(e => e.status === 'error');
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col h-full max-w-3xl mx-auto">
+ {/* Capture input */}
+ <form onSubmit={handleSubmit} className="mb-6">
+ <div className="flex gap-2">
+ <input
+ ref={inputRef}
+ type="text"
+ value={inputText}
+ onChange={(e) => setInputText(e.target.value)}
+ placeholder="One thought at a time..."
+ className="flex-1 px-4 py-3 bg-port-card border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
+ disabled={sending}
+ />
+ <button
+ type="submit"
+ disabled={sending || !inputText.trim()}
+ className="px-4 py-3 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
+ >
+ {sending ? (
+ <RefreshCw className="w-5 h-5 animate-spin" />
+ ) : (
+ <Send className="w-5 h-5" />
+ )}
+ </button>
+ </div>
+ <p className="mt-2 text-xs text-gray-500">
+ Capture a thought. AI will classify and route it automatically.
+ {settings?.confidenceThreshold && (
+ <span> Confidence threshold: {Math.round(settings.confidenceThreshold * 100)}%</span>
+ )}
+ </p>
+ </form>
+
+ {/* Needs Review section */}
+ {needsReviewEntries.length > 0 && (
+ <div className="mb-4">
+ <button
+ onClick={() => setShowNeedsReview(!showNeedsReview)}
+ className="flex items-center gap-2 text-port-warning font-medium mb-2"
+ >
+ {showNeedsReview ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
+ <AlertCircle size={16} />
+ Needs Review ({needsReviewEntries.length})
+ </button>
+
+ {showNeedsReview && (
+ <div className="space-y-2">
+ {needsReviewEntries.map(entry => (
+ <div
+ key={entry.id}
+ className="p-3 bg-port-card border border-port-warning/30 rounded-lg"
+ >
+ <div className="flex items-start justify-between gap-2 mb-2">
+ <p className="text-white flex-1">{entry.capturedText}</p>
+ <span className="text-xs text-gray-500 whitespace-nowrap">
+ {formatRelativeTime(entry.capturedAt)}
+ </span>
+ </div>
+
+ {entry.classification?.reasons && (
+ <p className="text-xs text-gray-500 mb-2">
+ {entry.classification.reasons.join(' • ')}
+ </p>
+ )}
+
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-xs text-gray-500">Route to:</span>
+ {['people', 'projects', 'ideas', 'admin'].map(dest => {
+ const destInfo = DESTINATIONS[dest];
+ const Icon = destInfo.icon;
+ return (
+ <button
+ key={dest}
+ onClick={() => handleResolve(entry.id, dest)}
+ className={`flex items-center gap-1 px-2 py-1 text-xs rounded border ${destInfo.color} hover:opacity-80 transition-opacity`}
+ >
+ <Icon size={12} />
+ {destInfo.label}
+ </button>
+ );
+ })}
+ <button
+ onClick={() => handleRetry(entry.id)}
+ className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"
+ >
+ <RefreshCw size={12} />
+ Retry AI
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Error entries */}
+ {errorEntries.length > 0 && (
+ <div className="mb-4">
+ <div className="text-port-error font-medium mb-2 flex items-center gap-2">
+ <AlertCircle size={16} />
+ Errors ({errorEntries.length})
+ </div>
+ <div className="space-y-2">
+ {errorEntries.map(entry => (
+ <div
+ key={entry.id}
+ className="p-3 bg-port-card border border-port-error/30 rounded-lg"
+ >
+ <p className="text-white mb-1">{entry.capturedText}</p>
+ <p className="text-xs text-port-error">{entry.error?.message || 'Unknown error'}</p>
+ <button
+ onClick={() => handleRetry(entry.id)}
+ className="mt-2 flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"
+ >
+ <RefreshCw size={12} />
+ Retry
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Filed entries */}
+ <div>
+ <button
+ onClick={() => setShowFiled(!showFiled)}
+ className="flex items-center gap-2 text-port-success font-medium mb-2"
+ >
+ {showFiled ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
+ <CheckCircle size={16} />
+ Filed ({filedEntries.length})
+ </button>
+
+ {showFiled && (
+ <div className="space-y-2">
+ {filedEntries.map(entry => {
+ const destInfo = DESTINATIONS[entry.classification?.destination || 'unknown'];
+ const DestIcon = destInfo.icon;
+ const confidence = entry.classification?.confidence || 0;
+ const isCorrected = entry.status === 'corrected';
+
+ return (
+ <div
+ key={entry.id}
+ className={`p-3 bg-port-card border rounded-lg ${
+ isCorrected ? 'border-blue-500/30' : 'border-port-border'
+ }`}
+ >
+ <div className="flex items-start justify-between gap-2 mb-2">
+ <div className="flex-1">
+ <p className="text-white">{entry.capturedText}</p>
+ {entry.classification?.title && (
+ <p className="text-sm text-gray-400 mt-1">
+ → {entry.classification.title}
+ </p>
+ )}
+ </div>
+ <span className="text-xs text-gray-500 whitespace-nowrap">
+ {formatRelativeTime(entry.capturedAt)}
+ </span>
+ </div>
+
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className={`flex items-center gap-1 px-2 py-1 text-xs rounded border ${destInfo.color}`}>
+ <DestIcon size={12} />
+ {destInfo.label}
+ </span>
+
+ <span className={`text-xs ${getConfidenceColor(confidence)}`}>
+ {Math.round(confidence * 100)}%
+ </span>
+
+ {isCorrected && (
+ <span className="text-xs text-blue-400">
+ (corrected from {entry.correction?.previousDestination})
+ </span>
+ )}
+
+ {entry.filed?.destinationId && (
+ <button
+ onClick={() => {
+ // Navigate to the record in memory tab
+ window.location.href = `/brain/memory?type=${entry.filed.destination}&id=${entry.filed.destinationId}`;
+ }}
+ className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"
+ >
+ <ExternalLink size={12} />
+ View
+ </button>
+ )}
+
+ {/* Fix button */}
+ {fixingId === entry.id ? (
+ <div className="flex items-center gap-2">
+ <select
+ value={fixDestination}
+ onChange={(e) => setFixDestination(e.target.value)}
+ className="px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-white"
+ >
+ <option value="">Select...</option>
+ {['people', 'projects', 'ideas', 'admin']
+ .filter(d => d !== entry.filed?.destination)
+ .map(d => (
+ <option key={d} value={d}>{DESTINATIONS[d].label}</option>
+ ))}
+ </select>
+ <button
+ onClick={() => handleFix(entry.id)}
+ className="px-2 py-1 text-xs rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30"
+ >
+ Move
+ </button>
+ <button
+ onClick={() => { setFixingId(null); setFixDestination(''); }}
+ className="px-2 py-1 text-xs text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ </div>
+ ) : (
+ <button
+ onClick={() => setFixingId(entry.id)}
+ className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"
+ >
+ <Edit2 size={12} />
+ Fix
+ </button>
+ )}
+ </div>
+ </div>
+ );
+ })}
+
+ {filedEntries.length === 0 && (
+ <p className="text-gray-500 text-sm">No filed entries yet. Start capturing thoughts above.</p>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsx
new file mode 100644
index 0000000000..596ae4fc8a
--- /dev/null
+++ b/client/src/components/brain/tabs/MemoryTab.jsx
@@ -0,0 +1,519 @@
+import { useState, useEffect, useCallback } from 'react';
+import * as api from '../../../services/api';
+import {
+ RefreshCw,
+ Plus,
+ Edit2,
+ Trash2,
+ X,
+ Save,
+ ChevronDown,
+ ChevronRight
+} from 'lucide-react';
+import toast from 'react-hot-toast';
+
+import {
+ MEMORY_TABS,
+ DESTINATIONS,
+ PROJECT_STATUS_COLORS,
+ ADMIN_STATUS_COLORS,
+ formatRelativeTime
+} from '../constants';
+
+export default function MemoryTab({ onRefresh }) {
+ const [activeType, setActiveType] = useState('people');
+ const [records, setRecords] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [editingId, setEditingId] = useState(null);
+ const [editForm, setEditForm] = useState({});
+ const [showAdd, setShowAdd] = useState(false);
+ const [addForm, setAddForm] = useState({});
+ const [statusFilter, setStatusFilter] = useState('');
+
+ const fetchRecords = useCallback(async () => {
+ setLoading(true);
+ let data = [];
+
+ const filters = statusFilter ? { status: statusFilter } : undefined;
+
+ switch (activeType) {
+ case 'people':
+ data = await api.getBrainPeople().catch(() => []);
+ break;
+ case 'projects':
+ data = await api.getBrainProjects(filters).catch(() => []);
+ break;
+ case 'ideas':
+ data = await api.getBrainIdeas().catch(() => []);
+ break;
+ case 'admin':
+ data = await api.getBrainAdmin(filters).catch(() => []);
+ break;
+ }
+
+ // Filter out archived records
+ data = data.filter(r => !r.archived);
+ setRecords(data);
+ setLoading(false);
+ }, [activeType, statusFilter]);
+
+ useEffect(() => {
+ fetchRecords();
+ }, [fetchRecords]);
+
+ const handleSave = async () => {
+ let result;
+ switch (activeType) {
+ case 'people':
+ result = await api.updateBrainPerson(editingId, editForm).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ case 'projects':
+ result = await api.updateBrainProject(editingId, editForm).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ case 'ideas':
+ result = await api.updateBrainIdea(editingId, editForm).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ case 'admin':
+ result = await api.updateBrainAdminItem(editingId, editForm).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ }
+
+ if (result) {
+ toast.success('Saved');
+ setEditingId(null);
+ setEditForm({});
+ fetchRecords();
+ onRefresh?.();
+ }
+ };
+
+ const handleAdd = async () => {
+ let result;
+ switch (activeType) {
+ case 'people':
+ result = await api.createBrainPerson(addForm).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ case 'projects':
+ result = await api.createBrainProject({ ...addForm, status: addForm.status || 'active' }).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ case 'ideas':
+ result = await api.createBrainIdea(addForm).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ case 'admin':
+ result = await api.createBrainAdminItem({ ...addForm, status: addForm.status || 'open' }).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ }
+
+ if (result) {
+ toast.success('Created');
+ setShowAdd(false);
+ setAddForm({});
+ fetchRecords();
+ onRefresh?.();
+ }
+ };
+
+ const handleDelete = async (id) => {
+ let result;
+ switch (activeType) {
+ case 'people':
+ result = await api.deleteBrainPerson(id).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ case 'projects':
+ result = await api.deleteBrainProject(id).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ case 'ideas':
+ result = await api.deleteBrainIdea(id).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ case 'admin':
+ result = await api.deleteBrainAdminItem(id).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ break;
+ }
+
+ if (result !== null) {
+ toast.success('Deleted');
+ fetchRecords();
+ onRefresh?.();
+ }
+ };
+
+ const startEdit = (record) => {
+ setEditingId(record.id);
+ setEditForm({ ...record });
+ };
+
+ const renderForm = (form, setForm, isEdit = false) => {
+ switch (activeType) {
+ case 'people':
+ return (
+ <div className="space-y-3">
+ <input
+ type="text"
+ placeholder="Name"
+ value={form.name || ''}
+ onChange={(e) => setForm({ ...form, name: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ <textarea
+ placeholder="Context (who they are, how you know them)"
+ value={form.context || ''}
+ onChange={(e) => setForm({ ...form, context: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ rows={2}
+ />
+ <input
+ type="text"
+ placeholder="Follow-ups (comma separated)"
+ value={(form.followUps || []).join(', ')}
+ onChange={(e) => setForm({ ...form, followUps: e.target.value.split(',').map(s => s.trim()).filter(Boolean) })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ </div>
+ );
+
+ case 'projects':
+ return (
+ <div className="space-y-3">
+ <input
+ type="text"
+ placeholder="Project name"
+ value={form.name || ''}
+ onChange={(e) => setForm({ ...form, name: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ <select
+ value={form.status || 'active'}
+ onChange={(e) => setForm({ ...form, status: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ >
+ <option value="active">Active</option>
+ <option value="waiting">Waiting</option>
+ <option value="blocked">Blocked</option>
+ <option value="someday">Someday</option>
+ <option value="done">Done</option>
+ </select>
+ <input
+ type="text"
+ placeholder="Next action (concrete, actionable step)"
+ value={form.nextAction || ''}
+ onChange={(e) => setForm({ ...form, nextAction: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ <textarea
+ placeholder="Notes"
+ value={form.notes || ''}
+ onChange={(e) => setForm({ ...form, notes: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ rows={2}
+ />
+ </div>
+ );
+
+ case 'ideas':
+ return (
+ <div className="space-y-3">
+ <input
+ type="text"
+ placeholder="Title"
+ value={form.title || ''}
+ onChange={(e) => setForm({ ...form, title: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ <input
+ type="text"
+ placeholder="One-liner (core insight)"
+ value={form.oneLiner || ''}
+ onChange={(e) => setForm({ ...form, oneLiner: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ <textarea
+ placeholder="Notes"
+ value={form.notes || ''}
+ onChange={(e) => setForm({ ...form, notes: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ rows={2}
+ />
+ </div>
+ );
+
+ case 'admin':
+ return (
+ <div className="space-y-3">
+ <input
+ type="text"
+ placeholder="Title"
+ value={form.title || ''}
+ onChange={(e) => setForm({ ...form, title: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ <select
+ value={form.status || 'open'}
+ onChange={(e) => setForm({ ...form, status: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ >
+ <option value="open">Open</option>
+ <option value="waiting">Waiting</option>
+ <option value="done">Done</option>
+ </select>
+ <input
+ type="date"
+ placeholder="Due date"
+ value={form.dueDate ? form.dueDate.split('T')[0] : ''}
+ onChange={(e) => setForm({ ...form, dueDate: e.target.value ? new Date(e.target.value).toISOString() : null })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ <input
+ type="text"
+ placeholder="Next action"
+ value={form.nextAction || ''}
+ onChange={(e) => setForm({ ...form, nextAction: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ </div>
+ );
+ }
+ };
+
+ const renderRecord = (record) => {
+ if (editingId === record.id) {
+ return (
+ <div key={record.id} className="p-4 bg-port-card border border-port-accent/50 rounded-lg">
+ {renderForm(editForm, setEditForm, true)}
+ <div className="flex items-center gap-2 mt-3">
+ <button
+ onClick={handleSave}
+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 text-port-accent rounded hover:bg-port-accent/30"
+ >
+ <Save size={14} />
+ Save
+ </button>
+ <button
+ onClick={() => { setEditingId(null); setEditForm({}); }}
+ className="px-3 py-1.5 text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div key={record.id} className="p-4 bg-port-card border border-port-border rounded-lg hover:border-port-border/80 transition-colors">
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex-1">
+ {activeType === 'people' && (
+ <>
+ <h3 className="font-medium text-white">{record.name}</h3>
+ {record.context && <p className="text-sm text-gray-400 mt-1">{record.context}</p>}
+ {record.followUps?.length > 0 && (
+ <div className="mt-2">
+ <span className="text-xs text-gray-500">Follow-ups:</span>
+ <ul className="list-disc list-inside text-sm text-gray-400">
+ {record.followUps.map((f, i) => <li key={i}>{f}</li>)}
+ </ul>
+ </div>
+ )}
+ </>
+ )}
+
+ {activeType === 'projects' && (
+ <>
+ <div className="flex items-center gap-2">
+ <h3 className="font-medium text-white">{record.name}</h3>
+ <span className={`px-2 py-0.5 text-xs rounded border ${PROJECT_STATUS_COLORS[record.status]}`}>
+ {record.status}
+ </span>
+ </div>
+ <p className="text-sm text-port-accent mt-1">Next: {record.nextAction}</p>
+ {record.notes && <p className="text-sm text-gray-400 mt-1">{record.notes}</p>}
+ </>
+ )}
+
+ {activeType === 'ideas' && (
+ <>
+ <h3 className="font-medium text-white">{record.title}</h3>
+ <p className="text-sm text-yellow-400 mt-1">{record.oneLiner}</p>
+ {record.notes && <p className="text-sm text-gray-400 mt-1">{record.notes}</p>}
+ </>
+ )}
+
+ {activeType === 'admin' && (
+ <>
+ <div className="flex items-center gap-2">
+ <h3 className="font-medium text-white">{record.title}</h3>
+ <span className={`px-2 py-0.5 text-xs rounded border ${ADMIN_STATUS_COLORS[record.status]}`}>
+ {record.status}
+ </span>
+ </div>
+ {record.dueDate && (
+ <p className="text-sm text-port-warning mt-1">
+ Due: {new Date(record.dueDate).toLocaleDateString()}
+ </p>
+ )}
+ {record.nextAction && <p className="text-sm text-gray-400 mt-1">Next: {record.nextAction}</p>}
+ </>
+ )}
+
+ <p className="text-xs text-gray-500 mt-2">
+ Updated {formatRelativeTime(record.updatedAt)}
+ </p>
+ </div>
+
+ <div className="flex items-center gap-1">
+ <button
+ onClick={() => startEdit(record)}
+ className="p-1.5 text-gray-400 hover:text-white rounded hover:bg-port-border/50"
+ title="Edit"
+ >
+ <Edit2 size={14} />
+ </button>
+ <button
+ onClick={() => handleDelete(record.id)}
+ className="p-1.5 text-gray-400 hover:text-port-error rounded hover:bg-port-error/20"
+ title="Delete"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div className="space-y-4">
+ {/* Type tabs */}
+ <div className="flex items-center gap-2 flex-wrap">
+ {MEMORY_TABS.map((tab) => {
+ const Icon = tab.icon;
+ const isActive = activeType === tab.id;
+ const destInfo = DESTINATIONS[tab.id];
+ return (
+ <button
+ key={tab.id}
+ onClick={() => { setActiveType(tab.id); setStatusFilter(''); }}
+ className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${
+ isActive
+ ? `${destInfo.color}`
+ : 'bg-port-card text-gray-400 hover:text-white'
+ }`}
+ >
+ <Icon size={16} />
+ {tab.label}
+ </button>
+ );
+ })}
+
+ {/* Add button */}
+ <button
+ onClick={() => { setShowAdd(true); setAddForm({}); }}
+ className="flex items-center gap-1 px-3 py-2 bg-port-accent/20 text-port-accent rounded-lg text-sm hover:bg-port-accent/30"
+ >
+ <Plus size={16} />
+ Add
+ </button>
+
+ {/* Status filter for projects/admin */}
+ {(activeType === 'projects' || activeType === 'admin') && (
+ <select
+ value={statusFilter}
+ onChange={(e) => setStatusFilter(e.target.value)}
+ className="px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-white"
+ >
+ <option value="">All statuses</option>
+ {activeType === 'projects' ? (
+ <>
+ <option value="active">Active</option>
+ <option value="waiting">Waiting</option>
+ <option value="blocked">Blocked</option>
+ <option value="someday">Someday</option>
+ <option value="done">Done</option>
+ </>
+ ) : (
+ <>
+ <option value="open">Open</option>
+ <option value="waiting">Waiting</option>
+ <option value="done">Done</option>
+ </>
+ )}
+ </select>
+ )}
+ </div>
+
+ {/* Add form */}
+ {showAdd && (
+ <div className="p-4 bg-port-card border border-port-accent/50 rounded-lg">
+ <h3 className="font-medium text-white mb-3">Add {DESTINATIONS[activeType].label}</h3>
+ {renderForm(addForm, setAddForm)}
+ <div className="flex items-center gap-2 mt-3">
+ <button
+ onClick={handleAdd}
+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 text-port-accent rounded hover:bg-port-accent/30"
+ >
+ <Plus size={14} />
+ Create
+ </button>
+ <button
+ onClick={() => { setShowAdd(false); setAddForm({}); }}
+ className="px-3 py-1.5 text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Records list */}
+ {loading ? (
+ <div className="flex items-center justify-center h-32">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ ) : records.length === 0 ? (
+ <p className="text-gray-500 text-center py-8">
+ No {DESTINATIONS[activeType].label.toLowerCase()} yet. Add one or capture thoughts in the Inbox.
+ </p>
+ ) : (
+ <div className="space-y-2">
+ {records.map(record => renderRecord(record))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/brain/tabs/TrustTab.jsx b/client/src/components/brain/tabs/TrustTab.jsx
new file mode 100644
index 0000000000..125544a03d
--- /dev/null
+++ b/client/src/components/brain/tabs/TrustTab.jsx
@@ -0,0 +1,300 @@
+import { useState, useEffect, useCallback } from 'react';
+import * as api from '../../../services/api';
+import {
+ RefreshCw,
+ Shield,
+ ChevronDown,
+ ChevronRight,
+ Eye,
+ Settings
+} from 'lucide-react';
+import toast from 'react-hot-toast';
+
+import {
+ DESTINATIONS,
+ STATUS_COLORS,
+ getConfidenceColor,
+ formatRelativeTime
+} from '../constants';
+
+export default function TrustTab({ onRefresh }) {
+ const [entries, setEntries] = useState([]);
+ const [counts, setCounts] = useState({});
+ const [settings, setSettings] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [statusFilter, setStatusFilter] = useState('');
+ const [expandedId, setExpandedId] = useState(null);
+ const [editingSettings, setEditingSettings] = useState(false);
+ const [settingsForm, setSettingsForm] = useState({});
+
+ const fetchData = useCallback(async () => {
+ const [inboxData, settingsData] = await Promise.all([
+ api.getBrainInbox({ status: statusFilter || undefined, limit: 100 }).catch(() => ({ entries: [], counts: {} })),
+ api.getBrainSettings().catch(() => null)
+ ]);
+
+ setEntries(inboxData.entries || []);
+ setCounts(inboxData.counts || {});
+ setSettings(settingsData);
+ setSettingsForm(settingsData || {});
+ setLoading(false);
+ }, [statusFilter]);
+
+ useEffect(() => {
+ fetchData();
+ }, [fetchData]);
+
+ const handleSaveSettings = async () => {
+ const result = await api.updateBrainSettings({
+ confidenceThreshold: parseFloat(settingsForm.confidenceThreshold),
+ dailyDigestTime: settingsForm.dailyDigestTime,
+ weeklyReviewTime: settingsForm.weeklyReviewTime,
+ weeklyReviewDay: settingsForm.weeklyReviewDay
+ }).catch(err => {
+ toast.error(err.message || 'Failed to save settings');
+ return null;
+ });
+
+ if (result) {
+ toast.success('Settings saved');
+ setEditingSettings(false);
+ setSettings(result);
+ onRefresh?.();
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* Header with stats */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <Shield className="w-6 h-6 text-port-accent" />
+ <div>
+ <h2 className="text-lg font-semibold text-white">Trust Panel</h2>
+ <p className="text-sm text-gray-500">Audit trail and system settings</p>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-4 text-sm">
+ <span className="text-gray-500">Total: {counts.total || 0}</span>
+ <span className="text-port-success">Filed: {counts.filed || 0}</span>
+ <span className="text-port-warning">Review: {counts.needs_review || 0}</span>
+ <span className="text-blue-400">Corrected: {counts.corrected || 0}</span>
+ <span className="text-port-error">Errors: {counts.error || 0}</span>
+ </div>
+ </div>
+
+ {/* Settings Section */}
+ <div className="p-4 bg-port-card border border-port-border rounded-lg">
+ <div className="flex items-center justify-between mb-4">
+ <h3 className="font-medium text-white flex items-center gap-2">
+ <Settings size={16} />
+ Settings
+ </h3>
+ {!editingSettings && (
+ <button
+ onClick={() => setEditingSettings(true)}
+ className="text-sm text-port-accent hover:underline"
+ >
+ Edit
+ </button>
+ )}
+ </div>
+
+ {editingSettings ? (
+ <div className="space-y-4">
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Confidence Threshold</label>
+ <input
+ type="number"
+ min="0"
+ max="1"
+ step="0.05"
+ value={settingsForm.confidenceThreshold || 0.6}
+ onChange={(e) => setSettingsForm({ ...settingsForm, confidenceThreshold: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ <p className="text-xs text-gray-500 mt-1">
+ Items below this threshold go to "needs review" (0-1)
+ </p>
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Daily Digest Time</label>
+ <input
+ type="time"
+ value={settingsForm.dailyDigestTime || '09:00'}
+ onChange={(e) => setSettingsForm({ ...settingsForm, dailyDigestTime: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Weekly Review Day</label>
+ <select
+ value={settingsForm.weeklyReviewDay || 'sunday'}
+ onChange={(e) => setSettingsForm({ ...settingsForm, weeklyReviewDay: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ >
+ <option value="sunday">Sunday</option>
+ <option value="monday">Monday</option>
+ <option value="tuesday">Tuesday</option>
+ <option value="wednesday">Wednesday</option>
+ <option value="thursday">Thursday</option>
+ <option value="friday">Friday</option>
+ <option value="saturday">Saturday</option>
+ </select>
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Weekly Review Time</label>
+ <input
+ type="time"
+ value={settingsForm.weeklyReviewTime || '16:00'}
+ onChange={(e) => setSettingsForm({ ...settingsForm, weeklyReviewTime: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ </div>
+ </div>
+
+ <div className="flex items-center gap-2">
+ <button
+ onClick={handleSaveSettings}
+ className="px-3 py-1.5 bg-port-accent/20 text-port-accent rounded hover:bg-port-accent/30"
+ >
+ Save
+ </button>
+ <button
+ onClick={() => { setEditingSettings(false); setSettingsForm(settings || {}); }}
+ className="px-3 py-1.5 text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
+ <div>
+ <span className="text-gray-500">Confidence Threshold:</span>
+ <span className="text-white ml-2">{Math.round((settings?.confidenceThreshold || 0.6) * 100)}%</span>
+ </div>
+ <div>
+ <span className="text-gray-500">Daily Digest:</span>
+ <span className="text-white ml-2">{settings?.dailyDigestTime || '09:00'}</span>
+ </div>
+ <div>
+ <span className="text-gray-500">Weekly Review:</span>
+ <span className="text-white ml-2">{settings?.weeklyReviewDay || 'Sunday'} {settings?.weeklyReviewTime || '16:00'}</span>
+ </div>
+ <div>
+ <span className="text-gray-500">Provider:</span>
+ <span className="text-white ml-2">{settings?.defaultProvider || 'lmstudio'}</span>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Filters */}
+ <div className="flex items-center gap-4">
+ <span className="text-sm text-gray-500">Filter by status:</span>
+ <select
+ value={statusFilter}
+ onChange={(e) => setStatusFilter(e.target.value)}
+ className="px-3 py-1.5 bg-port-card border border-port-border rounded text-sm text-white"
+ >
+ <option value="">All</option>
+ <option value="filed">Filed</option>
+ <option value="needs_review">Needs Review</option>
+ <option value="corrected">Corrected</option>
+ <option value="error">Error</option>
+ </select>
+
+ <button
+ onClick={fetchData}
+ className="flex items-center gap-1 px-3 py-1.5 text-sm text-gray-400 hover:text-white"
+ >
+ <RefreshCw size={14} />
+ Refresh
+ </button>
+ </div>
+
+ {/* Audit Log */}
+ <div className="space-y-2">
+ {entries.length === 0 ? (
+ <p className="text-gray-500 text-center py-8">No entries found.</p>
+ ) : (
+ entries.map(entry => {
+ const isExpanded = expandedId === entry.id;
+ const destInfo = DESTINATIONS[entry.classification?.destination || 'unknown'];
+ const DestIcon = destInfo.icon;
+ const confidence = entry.classification?.confidence || 0;
+
+ return (
+ <div
+ key={entry.id}
+ className="p-3 bg-port-card border border-port-border rounded-lg"
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex-1 min-w-0">
+ <p className="text-white truncate">{entry.capturedText}</p>
+ <div className="flex items-center gap-2 mt-1 flex-wrap">
+ <span className={`px-2 py-0.5 text-xs rounded border ${STATUS_COLORS[entry.status]}`}>
+ {entry.status}
+ </span>
+ <span className={`flex items-center gap-1 px-2 py-0.5 text-xs rounded border ${destInfo.color}`}>
+ <DestIcon size={10} />
+ {destInfo.label}
+ </span>
+ <span className={`text-xs ${getConfidenceColor(confidence)}`}>
+ {Math.round(confidence * 100)}%
+ </span>
+ <span className="text-xs text-gray-500">
+ {formatRelativeTime(entry.capturedAt)}
+ </span>
+ </div>
+ </div>
+
+ <button
+ onClick={() => setExpandedId(isExpanded ? null : entry.id)}
+ className="p-1.5 text-gray-400 hover:text-white rounded hover:bg-port-border/50"
+ title="View details"
+ >
+ {isExpanded ? <ChevronDown size={16} /> : <Eye size={16} />}
+ </button>
+ </div>
+
+ {isExpanded && (
+ <div className="mt-3 p-3 bg-port-bg rounded-lg">
+ <h4 className="text-xs font-medium text-gray-400 mb-2">Full Classification Data</h4>
+ <pre className="text-xs text-gray-300 overflow-x-auto whitespace-pre-wrap">
+ {JSON.stringify({
+ id: entry.id,
+ capturedAt: entry.capturedAt,
+ source: entry.source,
+ status: entry.status,
+ classification: entry.classification,
+ filed: entry.filed,
+ correction: entry.correction,
+ error: entry.error,
+ ai: entry.ai
+ }, null, 2)}
+ </pre>
+ </div>
+ )}
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsx
index 985ddff7a9..043dcbbf6a 100644
--- a/client/src/components/cos/tabs/ScheduleTab.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.jsx
@@ -94,7 +94,6 @@ function TaskTypeRow({ taskType, config, onUpdate, onTrigger, onReset, category,
const selectedProvider = providers?.find(p => p.id === (selectedProviderId || ''));
const availableModels = selectedProvider?.models || [];
- const hasCustomPrompt = config.prompt && config.prompt.trim() !== '';
const status = config.status || {};
const isEligible = status.shouldRun;
@@ -249,15 +248,13 @@ function TaskTypeRow({ taskType, config, onUpdate, onTrigger, onReset, category,
<div>
<div className="flex items-center justify-between mb-2">
- <label className="text-sm text-gray-400">
- Task Prompt {hasCustomPrompt && <span className="text-port-accent">(custom)</span>}
- </label>
+ <label className="text-sm text-gray-400">Task Prompt</label>
{!editingPrompt && (
<button
onClick={() => setEditingPrompt(true)}
className="text-xs text-port-accent hover:text-port-accent/80"
>
- {hasCustomPrompt ? 'Edit' : 'Customize'}
+ Edit
</button>
)}
</div>
@@ -269,7 +266,7 @@ function TaskTypeRow({ taskType, config, onUpdate, onTrigger, onReset, category,
disabled={updating}
rows={12}
className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm font-mono"
- placeholder="Enter custom prompt (leave empty to use default)"
+ placeholder="Enter task prompt"
/>
<div className="flex gap-2">
<button
@@ -286,30 +283,18 @@ function TaskTypeRow({ taskType, config, onUpdate, onTrigger, onReset, category,
>
Cancel
</button>
- {hasCustomPrompt && (
- <button
- onClick={() => {
- setPromptValue('');
- handleSavePrompt();
- }}
- disabled={updating}
- className="px-3 py-1.5 text-sm bg-port-error/20 hover:bg-port-error/30 text-port-error rounded transition-colors"
- >
- Reset to Default
- </button>
- )}
</div>
<p className="text-xs text-gray-500">
- Leave empty to use the default prompt. For app improvement tasks, use <code className="bg-port-border px-1 rounded">{'{appName}'}</code> and <code className="bg-port-border px-1 rounded">{'{repoPath}'}</code> as placeholders.
+ For app improvement tasks, use <code className="bg-port-border px-1 rounded">{'{appName}'}</code> and <code className="bg-port-border px-1 rounded">{'{repoPath}'}</code> as placeholders.
</p>
</div>
) : (
- <div className="bg-port-bg border border-port-border rounded px-3 py-2 text-xs text-gray-400 font-mono max-h-32 overflow-y-auto">
- {hasCustomPrompt ? (
- <pre className="whitespace-pre-wrap">{promptValue}</pre>
- ) : (
- <span className="italic">Using default prompt (click Customize to edit)</span>
- )}
+ <div
+ className="bg-port-bg border border-port-border rounded px-3 py-2 text-xs text-gray-400 font-mono max-h-32 overflow-y-auto cursor-pointer hover:border-port-accent/50"
+ onClick={() => setEditingPrompt(true)}
+ title="Click to edit prompt"
+ >
+ <pre className="whitespace-pre-wrap">{promptValue || 'No prompt configured'}</pre>
</div>
)}
</div>
diff --git a/client/src/pages/Brain.jsx b/client/src/pages/Brain.jsx
new file mode 100644
index 0000000000..a92b1004e6
--- /dev/null
+++ b/client/src/pages/Brain.jsx
@@ -0,0 +1,134 @@
+import { useState, useEffect, useCallback } from 'react';
+import { useParams, useNavigate } from 'react-router-dom';
+import * as api from '../services/api';
+import { Brain as BrainIcon, RefreshCw } from 'lucide-react';
+import toast from 'react-hot-toast';
+
+import {
+ TABS,
+ formatRelativeTime
+} from '../components/brain/constants';
+
+import InboxTab from '../components/brain/tabs/InboxTab';
+import MemoryTab from '../components/brain/tabs/MemoryTab';
+import DigestTab from '../components/brain/tabs/DigestTab';
+import TrustTab from '../components/brain/tabs/TrustTab';
+
+export default function Brain() {
+ const { tab } = useParams();
+ const navigate = useNavigate();
+ const activeTab = tab || 'inbox';
+
+ const [summary, setSummary] = useState(null);
+ const [settings, setSettings] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ const fetchData = useCallback(async () => {
+ const [summaryData, settingsData] = await Promise.all([
+ api.getBrainSummary().catch(() => null),
+ api.getBrainSettings().catch(() => null)
+ ]);
+ setSummary(summaryData);
+ setSettings(settingsData);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ fetchData();
+ const interval = setInterval(fetchData, 30000);
+ return () => clearInterval(interval);
+ }, [fetchData]);
+
+ const handleTabChange = (tabId) => {
+ navigate(`/brain/${tabId}`);
+ };
+
+ const renderTabContent = () => {
+ switch (activeTab) {
+ case 'inbox':
+ return <InboxTab onRefresh={fetchData} settings={settings} />;
+ case 'memory':
+ return <MemoryTab onRefresh={fetchData} />;
+ case 'digest':
+ return <DigestTab onRefresh={fetchData} />;
+ case 'trust':
+ return <TrustTab onRefresh={fetchData} />;
+ default:
+ return <InboxTab onRefresh={fetchData} settings={settings} />;
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-full">
+ <RefreshCw className="w-8 h-8 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col h-full">
+ {/* Header */}
+ <div className="flex items-center justify-between p-4 border-b border-port-border">
+ <div className="flex items-center gap-3">
+ <BrainIcon className="w-8 h-8 text-port-accent" />
+ <div>
+ <h1 className="text-xl font-bold text-white">Brain</h1>
+ <p className="text-sm text-gray-500">Second brain for capturing and organizing thoughts</p>
+ </div>
+ </div>
+
+ {/* Quick stats */}
+ {summary && (
+ <div className="flex items-center gap-4 text-sm">
+ {summary.needsReview > 0 && (
+ <span className="px-2 py-1 rounded bg-port-warning/20 text-port-warning">
+ {summary.needsReview} needs review
+ </span>
+ )}
+ <span className="text-gray-500">
+ {summary.counts?.projects || 0} projects
+ </span>
+ <span className="text-gray-500">
+ {summary.counts?.people || 0} people
+ </span>
+ {summary.lastDailyDigest && (
+ <span className="text-gray-500">
+ Last digest: {formatRelativeTime(summary.lastDailyDigest)}
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Tab navigation */}
+ <div className="flex border-b border-port-border">
+ {TABS.map((tabItem) => {
+ const Icon = tabItem.icon;
+ const isActive = activeTab === tabItem.id;
+ return (
+ <button
+ key={tabItem.id}
+ onClick={() => handleTabChange(tabItem.id)}
+ className={`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors ${
+ isActive
+ ? 'text-port-accent border-b-2 border-port-accent bg-port-accent/5'
+ : 'text-gray-400 hover:text-white hover:bg-port-card'
+ }`}
+ role="tab"
+ aria-selected={isActive}
+ >
+ <Icon size={16} aria-hidden="true" />
+ {tabItem.label}
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Tab content */}
+ <div className="flex-1 overflow-auto p-4">
+ {renderTabContent()}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 220f70fb35..f3a1b9257a 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -414,3 +414,111 @@ export const createGitBackup = (repoPath) => request('/standardize/backup', {
method: 'POST',
body: JSON.stringify({ repoPath })
});
+
+// Brain - Second Brain Feature
+export const getBrainSummary = () => request('/brain/summary');
+export const getBrainSettings = () => request('/brain/settings');
+export const updateBrainSettings = (settings) => request('/brain/settings', {
+ method: 'PUT',
+ body: JSON.stringify(settings)
+});
+
+// Brain - Capture & Inbox
+export const captureBrainThought = (text, providerOverride, modelOverride) => request('/brain/capture', {
+ method: 'POST',
+ body: JSON.stringify({ text, providerOverride, modelOverride })
+});
+export const getBrainInbox = (options = {}) => {
+ const params = new URLSearchParams();
+ if (options.status) params.set('status', options.status);
+ if (options.limit) params.set('limit', options.limit);
+ if (options.offset) params.set('offset', options.offset);
+ return request(`/brain/inbox?${params}`);
+};
+export const getBrainInboxEntry = (id) => request(`/brain/inbox/${id}`);
+export const resolveBrainReview = (inboxLogId, destination, editedExtracted) => request('/brain/review/resolve', {
+ method: 'POST',
+ body: JSON.stringify({ inboxLogId, destination, editedExtracted })
+});
+export const fixBrainClassification = (inboxLogId, newDestination, updatedFields, note) => request('/brain/fix', {
+ method: 'POST',
+ body: JSON.stringify({ inboxLogId, newDestination, updatedFields, note })
+});
+export const retryBrainClassification = (id, providerOverride, modelOverride) => request(`/brain/inbox/${id}/retry`, {
+ method: 'POST',
+ body: JSON.stringify({ providerOverride, modelOverride })
+});
+
+// Brain - People
+export const getBrainPeople = () => request('/brain/people');
+export const getBrainPerson = (id) => request(`/brain/people/${id}`);
+export const createBrainPerson = (data) => request('/brain/people', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const updateBrainPerson = (id, data) => request(`/brain/people/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data)
+});
+export const deleteBrainPerson = (id) => request(`/brain/people/${id}`, { method: 'DELETE' });
+
+// Brain - Projects
+export const getBrainProjects = (filters) => {
+ const params = new URLSearchParams();
+ if (filters?.status) params.set('status', filters.status);
+ return request(`/brain/projects?${params}`);
+};
+export const getBrainProject = (id) => request(`/brain/projects/${id}`);
+export const createBrainProject = (data) => request('/brain/projects', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const updateBrainProject = (id, data) => request(`/brain/projects/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data)
+});
+export const deleteBrainProject = (id) => request(`/brain/projects/${id}`, { method: 'DELETE' });
+
+// Brain - Ideas
+export const getBrainIdeas = () => request('/brain/ideas');
+export const getBrainIdea = (id) => request(`/brain/ideas/${id}`);
+export const createBrainIdea = (data) => request('/brain/ideas', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const updateBrainIdea = (id, data) => request(`/brain/ideas/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data)
+});
+export const deleteBrainIdea = (id) => request(`/brain/ideas/${id}`, { method: 'DELETE' });
+
+// Brain - Admin
+export const getBrainAdmin = (filters) => {
+ const params = new URLSearchParams();
+ if (filters?.status) params.set('status', filters.status);
+ return request(`/brain/admin?${params}`);
+};
+export const getBrainAdminItem = (id) => request(`/brain/admin/${id}`);
+export const createBrainAdminItem = (data) => request('/brain/admin', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const updateBrainAdminItem = (id, data) => request(`/brain/admin/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data)
+});
+export const deleteBrainAdminItem = (id) => request(`/brain/admin/${id}`, { method: 'DELETE' });
+
+// Brain - Digests & Reviews
+export const getBrainLatestDigest = () => request('/brain/digest/latest');
+export const getBrainDigests = (limit = 10) => request(`/brain/digests?limit=${limit}`);
+export const runBrainDigest = (providerOverride, modelOverride) => request('/brain/digest/run', {
+ method: 'POST',
+ body: JSON.stringify({ providerOverride, modelOverride })
+});
+export const getBrainLatestReview = () => request('/brain/review/latest');
+export const getBrainReviews = (limit = 10) => request(`/brain/reviews?limit=${limit}`);
+export const runBrainReview = (providerOverride, modelOverride) => request('/brain/review/run', {
+ method: 'POST',
+ body: JSON.stringify({ providerOverride, modelOverride })
+});
diff --git a/data.sample/brain/admin.json b/data.sample/brain/admin.json
new file mode 100644
index 0000000000..b6111a83f1
--- /dev/null
+++ b/data.sample/brain/admin.json
@@ -0,0 +1,31 @@
+{
+ "records": {
+ "ad1a2b3c-d4e5-4f6a-7b8c-9d0e1f2a3b4c": {
+ "title": "Renew car registration",
+ "status": "open",
+ "dueDate": "2024-01-31T23:59:59.000Z",
+ "nextAction": "Go to DMV website and complete renewal",
+ "notes": "Registration expires end of January. Can do online.",
+ "createdAt": "2024-01-02T09:00:00.000Z",
+ "updatedAt": "2024-01-02T09:00:00.000Z"
+ },
+ "ad2b3c4d-e5f6-4a7b-8c9d-0e1f2a3b4c5d": {
+ "title": "Schedule annual physical",
+ "status": "waiting",
+ "dueDate": "2024-02-15T23:59:59.000Z",
+ "nextAction": "Waiting for callback from doctor's office",
+ "notes": "Called and left message. They said they'd call back to schedule.",
+ "createdAt": "2024-01-05T10:00:00.000Z",
+ "updatedAt": "2024-01-08T09:00:00.000Z"
+ },
+ "ad3c4d5e-f6a7-4b8c-9d0e-1f2a3b4c5d6e": {
+ "title": "File Q4 expenses",
+ "status": "done",
+ "dueDate": "2024-01-10T23:59:59.000Z",
+ "nextAction": null,
+ "notes": "Submitted all Q4 expense reports. Approved and reimbursement processed.",
+ "createdAt": "2024-01-03T09:00:00.000Z",
+ "updatedAt": "2024-01-09T11:00:00.000Z"
+ }
+ }
+}
diff --git a/data.sample/brain/digests.jsonl b/data.sample/brain/digests.jsonl
new file mode 100644
index 0000000000..487579ae77
--- /dev/null
+++ b/data.sample/brain/digests.jsonl
@@ -0,0 +1,2 @@
+{"id":"dg1a2b3c-d4e5-4f6a-7b8c-9d0e1f2a3b4c","generatedAt":"2024-01-09T09:00:00.000Z","digestText":"Today: Focus on Brain classifier implementation. You have 2 items needing review in your inbox - clear those first. Sarah is waiting on API timeline follow-up. Car registration due in 22 days. Standing desk arriving next week - plan your office rearrangement.","topActions":["Clear 2 inbox items needing review","Follow up with Sarah on API timeline","Start Brain classifier prompt template"],"stuckThing":"Blog post series blocked on design team images","smallWin":"Q1 planning doc got approved","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-daily-digest"}}
+{"id":"dg2b3c4d-e5f6-4a7b-8c9d-0e1f2a3b4c5d","generatedAt":"2024-01-08T09:00:00.000Z","digestText":"Start of the week. Brain feature is your main active project - good momentum. 1 person follow-up due (Jake for bathroom quote). Admin: car registration and physical scheduling both need attention this month. Your idea backlog is growing - consider time-boxing idea capture.","topActions":["Continue Brain implementation","Contact Jake for bathroom quote","Schedule annual physical"],"stuckThing":"Blog post still waiting on images","smallWin":"Home office desk ordered","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-daily-digest"}}
diff --git a/data.sample/brain/ideas.json b/data.sample/brain/ideas.json
new file mode 100644
index 0000000000..b027311b30
--- /dev/null
+++ b/data.sample/brain/ideas.json
@@ -0,0 +1,28 @@
+{
+ "records": {
+ "i1a2b3c4-d5e6-4f7a-8b9c-0d1e2f3a4b5c": {
+ "title": "Voice-first capture mode",
+ "oneLiner": "Add voice transcription to Brain so thoughts can be captured hands-free via Whisper",
+ "notes": "Could use OpenAI Whisper API or local whisper.cpp. Would be great for capturing ideas while walking or driving.",
+ "tags": ["brain", "feature", "voice"],
+ "createdAt": "2024-01-07T08:00:00.000Z",
+ "updatedAt": "2024-01-07T08:00:00.000Z"
+ },
+ "i2b3c4d5-e6f7-4a8b-9c0d-1e2f3a4b5c6d": {
+ "title": "Weekly email digest",
+ "oneLiner": "Send the weekly review as an email so it reaches me even when I'm not using PortOS",
+ "notes": "Could integrate with SendGrid or use local SMTP. Include quick action links.",
+ "tags": ["brain", "email"],
+ "createdAt": "2024-01-06T14:00:00.000Z",
+ "updatedAt": "2024-01-06T14:00:00.000Z"
+ },
+ "i3c4d5e6-f7a8-4b9c-0d1e-2f3a4b5c6d7e": {
+ "title": "Spaced repetition for people",
+ "oneLiner": "Surface people you haven't contacted in a while using spaced repetition algorithm",
+ "notes": "Like Anki but for relationships. Remind me to reach out to people before the connection goes cold.",
+ "tags": ["brain", "people", "relationships"],
+ "createdAt": "2024-01-04T11:00:00.000Z",
+ "updatedAt": "2024-01-04T11:00:00.000Z"
+ }
+ }
+}
diff --git a/data.sample/brain/inbox_log.jsonl b/data.sample/brain/inbox_log.jsonl
new file mode 100644
index 0000000000..2612a4cbca
--- /dev/null
+++ b/data.sample/brain/inbox_log.jsonl
@@ -0,0 +1,10 @@
+{"id":"il1a2b3c-d4e5-4f6a-7b8c-9d0e1f2a3b4c","capturedText":"Need to follow up with Sarah about the API redesign timeline","capturedAt":"2024-01-09T10:30:00.000Z","source":"brain_ui","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-classifier"},"classification":{"destination":"people","confidence":0.85,"title":"Sarah API follow-up","extracted":{"name":"Sarah Chen","context":"","followUps":["Follow up about API redesign timeline"],"tags":[]},"reasons":["Mentions specific person by name","Contains action item for that person"]},"status":"filed","filed":{"destination":"people","destinationId":"a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"}}
+{"id":"il2b3c4d-e5f6-4a7b-8c9d-0e1f2a3b4c5d","capturedText":"Start working on the classifier prompt template for Brain","capturedAt":"2024-01-09T09:00:00.000Z","source":"brain_ui","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-classifier"},"classification":{"destination":"projects","confidence":0.92,"title":"Brain classifier work","extracted":{"name":"PortOS Brain Feature","status":"active","nextAction":"Implement the classifier prompt template","tags":["brain","ai"]},"reasons":["Clear project task","Actionable next step"]},"status":"filed","filed":{"destination":"projects","destinationId":"p1a2b3c4-d5e6-4f7a-8b9c-0d1e2f3a4b5c"}}
+{"id":"il3c4d5e-f6a7-4b8c-9d0e-1f2a3b4c5d6e","capturedText":"What if Brain could surface people I haven't talked to in a while using spaced repetition?","capturedAt":"2024-01-08T14:00:00.000Z","source":"brain_ui","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-classifier"},"classification":{"destination":"ideas","confidence":0.88,"title":"Spaced repetition for people","extracted":{"title":"Spaced repetition for people","oneLiner":"Surface people you haven't contacted in a while using spaced repetition algorithm","tags":["brain","people"]},"reasons":["Starts with 'What if'","Novel concept","Not actionable yet"]},"status":"filed","filed":{"destination":"ideas","destinationId":"i3c4d5e6-f7a8-4b9c-0d1e-2f3a4b5c6d7e"}}
+{"id":"il4d5e6f-a7b8-4c9d-0e1f-2a3b4c5d6e7f","capturedText":"Car registration due end of January - need to renew online","capturedAt":"2024-01-07T11:00:00.000Z","source":"brain_ui","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-classifier"},"classification":{"destination":"admin","confidence":0.95,"title":"Car registration renewal","extracted":{"title":"Renew car registration","status":"open","dueDate":"2024-01-31T23:59:59.000Z","nextAction":"Go to DMV website and complete renewal"},"reasons":["Administrative task","Has clear deadline","One-time action"]},"status":"filed","filed":{"destination":"admin","destinationId":"ad1a2b3c-d4e5-4f6a-7b8c-9d0e1f2a3b4c"}}
+{"id":"il5e6f7a-b8c9-4d0e-1f2a-3b4c5d6e7f8a","capturedText":"something about that thing we discussed","capturedAt":"2024-01-06T16:00:00.000Z","source":"brain_ui","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-classifier"},"classification":{"destination":"unknown","confidence":0.35,"title":"Unclear reference","extracted":{},"reasons":["Too vague","No clear subject","Cannot determine category"]},"status":"needs_review"}
+{"id":"il6f7a8b-c9d0-4e1f-2a3b-4c5d6e7f8a9b","capturedText":"Maybe use voice transcription for Brain input - Whisper could work","capturedAt":"2024-01-05T08:30:00.000Z","source":"brain_ui","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-classifier"},"classification":{"destination":"ideas","confidence":0.82,"title":"Voice input for Brain","extracted":{"title":"Voice-first capture mode","oneLiner":"Add voice transcription to Brain so thoughts can be captured hands-free via Whisper","tags":["brain","voice"]},"reasons":["Explores potential feature","Not immediately actionable","Speculative"]},"status":"filed","filed":{"destination":"ideas","destinationId":"i1a2b3c4-d5e6-4f7a-8b9c-0d1e2f3a4b5c"}}
+{"id":"il7a8b9c-d0e1-4f2a-3b4c-5d6e7f8a9b0c","capturedText":"Jake the contractor - ask him for bathroom renovation quote","capturedAt":"2024-01-04T10:00:00.000Z","source":"brain_ui","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-classifier"},"classification":{"destination":"people","confidence":0.78,"title":"Jake bathroom quote","extracted":{"name":"Jake Reynolds","context":"Contractor","followUps":["Get quote for bathroom work"],"tags":["contractor"]},"reasons":["References specific person","Action item related to person"]},"status":"filed","filed":{"destination":"people","destinationId":"d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a"}}
+{"id":"il8b9c0d-e1f2-4a3b-4c5d-6e7f8a9b0c1d","capturedText":"ordered standing desk today - should arrive jan 15","capturedAt":"2024-01-03T14:00:00.000Z","source":"brain_ui","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-classifier"},"classification":{"destination":"projects","confidence":0.75,"title":"Standing desk order","extracted":{"name":"Home Office Setup","status":"waiting","nextAction":"Wait for standing desk delivery (ETA Jan 15)","tags":["home"]},"reasons":["Part of ongoing project","Has timeline","Waiting state"]},"status":"filed","filed":{"destination":"projects","destinationId":"p2b3c4d5-e6f7-4a8b-9c0d-1e2f3a4b5c6d"}}
+{"id":"il9c0d1e-f2a3-4b4c-5d6e-7f8a9b0c1d2e","capturedText":"quarterly catch up with Lisa - she gives great career advice","capturedAt":"2024-01-02T09:00:00.000Z","source":"brain_ui","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-classifier"},"classification":{"destination":"people","confidence":0.88,"title":"Lisa quarterly catchup","extracted":{"name":"Lisa Park","context":"Mentor, career advice","followUps":["Schedule quarterly catch-up"],"tags":["mentor"]},"reasons":["References specific person","Recurring action"]},"status":"filed","filed":{"destination":"people","destinationId":"e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b"}}
+{"id":"ila0d1e2-f3a4-4b5c-6d7e-8f9a0b1c2d3e","capturedText":"review that thing from last week meeting","capturedAt":"2024-01-01T15:00:00.000Z","source":"brain_ui","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-classifier"},"classification":{"destination":"unknown","confidence":0.28,"title":"Unclear meeting reference","extracted":{},"reasons":["No specific subject","Cannot identify what 'that thing' refers to","Needs clarification"]},"status":"needs_review"}
diff --git a/data.sample/brain/meta.json b/data.sample/brain/meta.json
new file mode 100644
index 0000000000..f9445b7874
--- /dev/null
+++ b/data.sample/brain/meta.json
@@ -0,0 +1,11 @@
+{
+ "version": 1,
+ "confidenceThreshold": 0.6,
+ "dailyDigestTime": "09:00",
+ "weeklyReviewTime": "16:00",
+ "weeklyReviewDay": "sunday",
+ "defaultProvider": "lmstudio",
+ "defaultModel": "gptoss-20b",
+ "lastDailyDigest": null,
+ "lastWeeklyReview": null
+}
diff --git a/data.sample/brain/people.json b/data.sample/brain/people.json
new file mode 100644
index 0000000000..5019e25507
--- /dev/null
+++ b/data.sample/brain/people.json
@@ -0,0 +1,49 @@
+{
+ "records": {
+ "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d": {
+ "name": "Sarah Chen",
+ "context": "Product manager at Acme Corp. Met at tech conference in Austin. Works on developer tools.",
+ "followUps": ["Ask about the API redesign project", "Follow up on coffee meeting"],
+ "lastTouched": "2024-01-05T10:30:00.000Z",
+ "tags": ["work", "product"],
+ "createdAt": "2024-01-01T09:00:00.000Z",
+ "updatedAt": "2024-01-05T10:30:00.000Z"
+ },
+ "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e": {
+ "name": "Marcus Johnson",
+ "context": "Old college friend. Now runs a startup in the AI space. Good for advice on fundraising.",
+ "followUps": ["Congratulate on Series A"],
+ "lastTouched": "2024-01-02T14:00:00.000Z",
+ "tags": ["friend", "startup"],
+ "createdAt": "2024-01-01T09:00:00.000Z",
+ "updatedAt": "2024-01-02T14:00:00.000Z"
+ },
+ "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f": {
+ "name": "Dr. Emily Foster",
+ "context": "Dentist. Annual checkups. Office on Main Street.",
+ "followUps": [],
+ "lastTouched": "2023-12-15T09:00:00.000Z",
+ "tags": ["health"],
+ "createdAt": "2023-12-15T09:00:00.000Z",
+ "updatedAt": "2023-12-15T09:00:00.000Z"
+ },
+ "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a": {
+ "name": "Jake Reynolds",
+ "context": "Contractor who did the kitchen renovation. Reliable, fair pricing.",
+ "followUps": ["Get quote for bathroom work"],
+ "lastTouched": "2024-01-03T11:00:00.000Z",
+ "tags": ["home", "contractor"],
+ "createdAt": "2023-11-01T09:00:00.000Z",
+ "updatedAt": "2024-01-03T11:00:00.000Z"
+ },
+ "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b": {
+ "name": "Lisa Park",
+ "context": "Mentor from previous job. VP of Engineering at TechGiant. Great career advice.",
+ "followUps": ["Schedule quarterly catch-up", "Ask about engineering leadership books"],
+ "lastTouched": "2023-12-20T16:00:00.000Z",
+ "tags": ["mentor", "career"],
+ "createdAt": "2023-06-01T09:00:00.000Z",
+ "updatedAt": "2023-12-20T16:00:00.000Z"
+ }
+ }
+}
diff --git a/data.sample/brain/projects.json b/data.sample/brain/projects.json
new file mode 100644
index 0000000000..becb8835db
--- /dev/null
+++ b/data.sample/brain/projects.json
@@ -0,0 +1,49 @@
+{
+ "records": {
+ "p1a2b3c4-d5e6-4f7a-8b9c-0d1e2f3a4b5c": {
+ "name": "PortOS Brain Feature",
+ "status": "active",
+ "nextAction": "Implement the AI classifier prompt template",
+ "notes": "Building a second-brain capture system for PortOS. Core workflow: capture -> classify -> store -> surface.",
+ "tags": ["portos", "feature", "ai"],
+ "createdAt": "2024-01-08T09:00:00.000Z",
+ "updatedAt": "2024-01-09T14:00:00.000Z"
+ },
+ "p2b3c4d5-e6f7-4a8b-9c0d-1e2f3a4b5c6d": {
+ "name": "Home Office Setup",
+ "status": "waiting",
+ "nextAction": "Wait for standing desk delivery (ETA Jan 15)",
+ "notes": "Upgrading home office. Ordered standing desk, need to get monitor arm next.",
+ "tags": ["home", "setup"],
+ "createdAt": "2024-01-02T10:00:00.000Z",
+ "updatedAt": "2024-01-06T11:00:00.000Z"
+ },
+ "p3c4d5e6-f7a8-4b9c-0d1e-2f3a4b5c6d7e": {
+ "name": "Learn Rust",
+ "status": "someday",
+ "nextAction": "Buy the Rust Programming Language book",
+ "notes": "Want to learn Rust for systems programming. Low priority for now.",
+ "tags": ["learning", "programming"],
+ "createdAt": "2023-11-15T09:00:00.000Z",
+ "updatedAt": "2023-11-15T09:00:00.000Z"
+ },
+ "p4d5e6f7-a8b9-4c0d-1e2f-3a4b5c6d7e8f": {
+ "name": "Q1 Planning Document",
+ "status": "done",
+ "nextAction": "N/A - Completed",
+ "notes": "Created and shared Q1 planning doc with team. Got approval from leadership.",
+ "tags": ["work", "planning"],
+ "createdAt": "2023-12-01T09:00:00.000Z",
+ "updatedAt": "2024-01-05T16:00:00.000Z"
+ },
+ "p5e6f7a8-b9c0-4d1e-2f3a-4b5c6d7e8f9a": {
+ "name": "Blog Post Series",
+ "status": "blocked",
+ "nextAction": "Wait for design team to provide header images",
+ "notes": "Writing a 3-part series on AI tooling. Part 1 drafted, need images before publishing.",
+ "tags": ["writing", "blog"],
+ "createdAt": "2024-01-03T09:00:00.000Z",
+ "updatedAt": "2024-01-07T10:00:00.000Z"
+ }
+ }
+}
diff --git a/data.sample/brain/reviews.jsonl b/data.sample/brain/reviews.jsonl
new file mode 100644
index 0000000000..9a81ac4fc9
--- /dev/null
+++ b/data.sample/brain/reviews.jsonl
@@ -0,0 +1 @@
+{"id":"rv1a2b3c-d4e5-4f6a-7b8c-9d0e1f2a3b4c","generatedAt":"2024-01-07T16:00:00.000Z","reviewText":"This week you captured 10 thoughts, filed 8 successfully. Brain feature made good progress - you're in the implementation phase now. Relationship maintenance: 3 people have pending follow-ups. Admin is under control with only 2 open items. Your biggest open loop is the blog post blocked on design. Consider: you've had several ideas about Brain enhancements - might be worth a dedicated brainstorm session.","whatHappened":["Started Brain feature implementation","Ordered standing desk for home office","Completed Q1 planning doc","Captured 10 thoughts, 80% auto-filed"],"biggestOpenLoops":["Blog post series waiting on design images","Follow up with Sarah on API timeline","Schedule annual physical"],"suggestedActionsNextWeek":["Complete Brain classifier implementation","Clear the 2 inbox items needing review","Ping design team about blog images"],"recurringTheme":"You're generating good ideas but some inbox items need more context to be useful - try adding a sentence of context when capturing.","ai":{"providerId":"lmstudio","modelId":"gptoss-20b","promptTemplateId":"brain-weekly-review"}}
diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.json
index bfcd2ff03f..77674bf96c 100644
--- a/data.sample/prompts/stage-config.json
+++ b/data.sample/prompts/stage-config.json
@@ -56,6 +56,30 @@
"provider": "lmstudio",
"returnsJson": true,
"variables": []
+ },
+ "brain-classifier": {
+ "name": "Brain Classifier",
+ "description": "Classify captured thoughts into People/Projects/Ideas/Admin",
+ "model": "lmstudio:gptoss-20b",
+ "provider": "lmstudio",
+ "returnsJson": true,
+ "variables": []
+ },
+ "brain-daily-digest": {
+ "name": "Brain Daily Digest",
+ "description": "Generate daily actionable digest",
+ "model": "lmstudio:gptoss-20b",
+ "provider": "lmstudio",
+ "returnsJson": true,
+ "variables": []
+ },
+ "brain-weekly-review": {
+ "name": "Brain Weekly Review",
+ "description": "Generate weekly review and open loops analysis",
+ "model": "lmstudio:gptoss-20b",
+ "provider": "lmstudio",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.sample/prompts/stages/brain-classifier.md b/data.sample/prompts/stages/brain-classifier.md
new file mode 100644
index 0000000000..b56270638c
--- /dev/null
+++ b/data.sample/prompts/stages/brain-classifier.md
@@ -0,0 +1,144 @@
+# Brain Classifier
+
+You are a thought classifier for a "second brain" system. Your job is to analyze captured thoughts and determine the best destination category.
+
+## Input
+
+**Captured Thought**: {{capturedText}}
+**Current Time**: {{now}}
+
+## Categories
+
+1. **people** - Information about a specific person, relationship notes, follow-up reminders about someone
+2. **projects** - Active work with a clear outcome, ongoing initiatives, things with multiple steps
+3. **ideas** - Concepts, possibilities, "what if" thoughts, inspiration, things to explore later
+4. **admin** - One-time tasks, errands, appointments, bureaucratic items with deadlines
+5. **unknown** - Cannot determine category with confidence
+
+## Output Format
+
+Return ONLY valid JSON with this exact structure:
+
+```json
+{
+ "destination": "people|projects|ideas|admin|unknown",
+ "confidence": 0.0-1.0,
+ "title": "Short descriptive title (max 50 chars)",
+ "extracted": {},
+ "reasons": ["reason1", "reason2"]
+}
+```
+
+## Extracted Fields by Destination
+
+### For "people":
+```json
+{
+ "name": "Person's name",
+ "context": "Who they are / how you know them",
+ "followUps": ["Action items related to this person"],
+ "tags": ["optional", "tags"]
+}
+```
+
+### For "projects":
+```json
+{
+ "name": "Project name",
+ "status": "active|waiting|blocked|someday|done",
+ "nextAction": "CONCRETE next step (must be specific and actionable)",
+ "notes": "Additional context",
+ "tags": ["optional", "tags"]
+}
+```
+
+### For "ideas":
+```json
+{
+ "title": "Idea title",
+ "oneLiner": "Core insight in one sentence",
+ "notes": "Additional thoughts",
+ "tags": ["optional", "tags"]
+}
+```
+
+### For "admin":
+```json
+{
+ "title": "Admin task title",
+ "status": "open|waiting|done",
+ "dueDate": "ISO date string or null",
+ "nextAction": "Specific action to take",
+ "notes": "Additional context"
+}
+```
+
+## Confidence Guidelines
+
+- **0.9-1.0**: Extremely clear category, unambiguous
+- **0.8-0.9**: Strong match with clear indicators
+- **0.7-0.8**: Good match but some ambiguity
+- **0.6-0.7**: Reasonable guess, could fit multiple categories
+- **Below 0.6**: Too vague or ambiguous - use "unknown"
+
+## Rules
+
+1. If a thought mentions a specific person by name AND contains an action for that person, prefer "people"
+2. If a thought has multiple steps or an ongoing nature, prefer "projects"
+3. If a thought starts with "What if" or explores a possibility, prefer "ideas"
+4. If a thought is a one-time task with a potential deadline, prefer "admin"
+5. If the thought is too vague (e.g., "that thing", "the stuff"), set destination="unknown" and confidence below 0.6
+6. For projects, the nextAction MUST be concrete and executable. If you can't infer a clear next action, lower confidence.
+7. Keep tags minimal (0-3 tags max). Only add tags if genuinely useful.
+8. Provide 1-3 short reasons explaining your classification decision.
+
+## Examples
+
+Input: "Sarah mentioned she's launching the new API next month - follow up with her"
+Output:
+```json
+{
+ "destination": "people",
+ "confidence": 0.88,
+ "title": "Sarah API launch follow-up",
+ "extracted": {
+ "name": "Sarah",
+ "context": "Working on new API launch",
+ "followUps": ["Follow up about API launch next month"],
+ "tags": ["work"]
+ },
+ "reasons": ["Mentions specific person", "Contains follow-up action", "Person-centric information"]
+}
+```
+
+Input: "Build a CLI tool for managing dotfiles"
+Output:
+```json
+{
+ "destination": "projects",
+ "confidence": 0.85,
+ "title": "Dotfiles CLI tool",
+ "extracted": {
+ "name": "Dotfiles CLI Tool",
+ "status": "active",
+ "nextAction": "Define the core features and commands for the CLI",
+ "notes": "Build a CLI tool for managing dotfiles",
+ "tags": ["dev-tools"]
+ },
+ "reasons": ["Multi-step undertaking", "Has clear deliverable", "Ongoing work nature"]
+}
+```
+
+Input: "something from the meeting yesterday"
+Output:
+```json
+{
+ "destination": "unknown",
+ "confidence": 0.25,
+ "title": "Unclear meeting reference",
+ "extracted": {},
+ "reasons": ["No specific subject identified", "Too vague to categorize", "Needs clarification"]
+}
+```
+
+Now classify the captured thought above. Return ONLY the JSON output, no additional text.
diff --git a/data.sample/prompts/stages/brain-daily-digest.md b/data.sample/prompts/stages/brain-daily-digest.md
new file mode 100644
index 0000000000..1cdfce49b6
--- /dev/null
+++ b/data.sample/prompts/stages/brain-daily-digest.md
@@ -0,0 +1,62 @@
+# Brain Daily Digest
+
+You are generating a daily digest for a "second brain" system. Your job is to create a brief, actionable summary to start the day.
+
+## Current Time
+{{now}}
+
+## Data
+
+### Active Projects
+{{activeProjects}}
+
+### Open Admin Items
+{{openAdmin}}
+
+### People with Follow-ups
+{{peopleFollowUps}}
+
+### Items Needing Review
+{{needsReview}}
+
+## Output Format
+
+Return ONLY valid JSON with this exact structure:
+
+```json
+{
+ "digestText": "Your digest text here (MUST be under 150 words)",
+ "topActions": ["action1", "action2", "action3"],
+ "stuckThing": "One thing that seems stuck or blocked",
+ "smallWin": "One positive thing or recent progress"
+}
+```
+
+## Rules
+
+1. **digestText MUST be under 150 words** - be concise and scannable
+2. **topActions** - exactly 3 items, each starting with a verb (e.g., "Email...", "Complete...", "Review...")
+3. **stuckThing** - identify ONE thing that appears stuck, blocked, or overdue
+4. **smallWin** - find ONE positive thing (completed item, progress made, upcoming milestone)
+
+## Style Guidelines
+
+- Be operational, not motivational. No fluff like "You've got this!"
+- Use specific names and details from the data
+- Prioritize items that are overdue or have upcoming deadlines
+- Mention inbox items needing review if any exist
+- Keep language direct and scannable
+- If data is sparse, acknowledge it honestly and suggest a simple next step
+
+## Example Output
+
+```json
+{
+ "digestText": "Today: 3 active projects, focus on API redesign (blocked on Sarah's input). Car registration due in 5 days - handle today. 2 inbox items need review. Marcus follow-up is overdue by a week. Afternoon: check standing desk delivery status.",
+ "topActions": ["Email Sarah about API timeline", "Complete car registration online", "Clear 2 inbox review items"],
+ "stuckThing": "API redesign blocked waiting on Sarah's input for 3 days",
+ "smallWin": "Q1 planning doc was approved yesterday"
+}
+```
+
+Now generate the daily digest. Return ONLY the JSON output, no additional text.
diff --git a/data.sample/prompts/stages/brain-weekly-review.md b/data.sample/prompts/stages/brain-weekly-review.md
new file mode 100644
index 0000000000..e6fab70b6e
--- /dev/null
+++ b/data.sample/prompts/stages/brain-weekly-review.md
@@ -0,0 +1,67 @@
+# Brain Weekly Review
+
+You are generating a weekly review for a "second brain" system. Your job is to summarize the past week and surface patterns and open loops.
+
+## Current Time
+{{now}}
+
+## Data
+
+### Inbox Log (Last 7 Days)
+{{inboxLogLast7Days}}
+
+### Active Projects
+{{activeProjects}}
+
+## Output Format
+
+Return ONLY valid JSON with this exact structure:
+
+```json
+{
+ "reviewText": "Your review text here (MUST be under 250 words)",
+ "whatHappened": ["bullet1", "bullet2", "bullet3"],
+ "biggestOpenLoops": ["loop1", "loop2", "loop3"],
+ "suggestedActionsNextWeek": ["action1", "action2", "action3"],
+ "recurringTheme": "One sentence describing a pattern you notice"
+}
+```
+
+## Rules
+
+1. **reviewText MUST be under 250 words** - comprehensive but scannable
+2. **whatHappened** - 3-5 bullets summarizing key activities/captures this week
+3. **biggestOpenLoops** - 1-3 things that are stuck, waiting, or need attention
+4. **suggestedActionsNextWeek** - exactly 3 actionable items for the coming week
+5. **recurringTheme** - ONE pattern you notice (e.g., "Many captures about X", "Projects tend to stall at Y stage")
+
+## Analysis Guidelines
+
+- Count total captures and filing success rate
+- Identify projects that haven't moved
+- Notice if certain categories are over/under-represented
+- Flag items in "waiting" status for too long
+- Highlight any items that were corrected (misclassified then fixed)
+- Look for recurring topics or concerns
+
+## Style Guidelines
+
+- Be analytical, not motivational
+- Use specific numbers and names
+- Focus on actionable insights
+- If the week was light on activity, acknowledge it and suggest why
+- Be honest about what's working and what isn't
+
+## Example Output
+
+```json
+{
+ "reviewText": "This week: 12 thoughts captured, 10 filed successfully (83% auto-file rate). Brain feature implementation progressed well - classifier is working. 2 items needed manual review due to vague input. Open loops: blog post blocked on design for 10 days now, Sarah follow-up still pending. Admin is under control with only car registration due. Pattern: your idea captures often lack enough context for good classification. Consider adding a sentence of explanation when capturing ideas.",
+ "whatHappened": ["Implemented Brain classifier", "Captured 12 thoughts (10 auto-filed)", "Completed Q1 planning doc", "Ordered standing desk"],
+ "biggestOpenLoops": ["Blog post series - blocked on design images for 10 days", "Sarah API timeline - no response in 5 days", "Annual physical - still needs scheduling"],
+ "suggestedActionsNextWeek": ["Ping design team about blog images", "Send Sarah a follow-up email", "Complete Brain scheduler implementation"],
+ "recurringTheme": "Idea captures tend to be too brief - adding context would improve auto-classification."
+}
+```
+
+Now generate the weekly review. Return ONLY the JSON output, no additional text.
diff --git a/server/index.js b/server/index.js
index 3459792007..da2d99e6c8 100644
--- a/server/index.js
+++ b/server/index.js
@@ -26,6 +26,7 @@ import scriptsRoutes from './routes/scripts.js';
import memoryRoutes from './routes/memory.js';
import notificationsRoutes from './routes/notifications.js';
import standardizeRoutes from './routes/standardize.js';
+import brainRoutes from './routes/brain.js';
import { initSocket } from './services/socket.js';
import { initScriptRunner } from './services/scriptRunner.js';
import { errorMiddleware, setupProcessErrorHandlers } from './lib/errorHandler.js';
@@ -92,6 +93,7 @@ app.use('/api/cos', cosRoutes);
app.use('/api/memory', memoryRoutes);
app.use('/api/notifications', notificationsRoutes);
app.use('/api/standardize', standardizeRoutes);
+app.use('/api/brain', brainRoutes);
// Initialize script runner
initScriptRunner().catch(err => console.error(`❌ Script runner init failed: ${err.message}`));
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
new file mode 100644
index 0000000000..c73440457a
--- /dev/null
+++ b/server/lib/brainValidation.js
@@ -0,0 +1,280 @@
+import { z } from 'zod';
+
+// Destination enum
+export const destinationEnum = z.enum(['people', 'projects', 'ideas', 'admin', 'unknown']);
+
+// Project status enum
+export const projectStatusEnum = z.enum(['active', 'waiting', 'blocked', 'someday', 'done']);
+
+// Admin status enum
+export const adminStatusEnum = z.enum(['open', 'waiting', 'done']);
+
+// Inbox log status enum
+export const inboxStatusEnum = z.enum(['filed', 'needs_review', 'corrected', 'error']);
+
+// AI configuration schema
+export const aiConfigSchema = z.object({
+ providerId: z.string(),
+ modelId: z.string(),
+ promptTemplateId: z.string(),
+ temperature: z.number().min(0).max(2).optional(),
+ maxTokens: z.number().int().positive().optional()
+});
+
+// Classification result schema
+export const classificationSchema = z.object({
+ destination: destinationEnum,
+ confidence: z.number().min(0).max(1),
+ title: z.string().min(1).max(200),
+ extracted: z.record(z.unknown()),
+ reasons: z.array(z.string()).max(5).optional()
+});
+
+// Filed info schema
+export const filedSchema = z.object({
+ destination: destinationEnum.exclude(['unknown']),
+ destinationId: z.string().uuid()
+});
+
+// Correction schema
+export const correctionSchema = z.object({
+ correctedAt: z.string().datetime(),
+ previousDestination: destinationEnum,
+ newDestination: destinationEnum.exclude(['unknown']),
+ note: z.string().max(500).optional()
+});
+
+// Error schema
+export const errorSchema = z.object({
+ message: z.string(),
+ stack: z.string().optional()
+});
+
+// Inbox Log Record schema
+export const inboxLogRecordSchema = z.object({
+ id: z.string().uuid(),
+ capturedText: z.string().min(1).max(10000),
+ capturedAt: z.string().datetime(),
+ source: z.literal('brain_ui'),
+ ai: aiConfigSchema.optional(),
+ classification: classificationSchema.optional(),
+ status: inboxStatusEnum,
+ filed: filedSchema.optional(),
+ correction: correctionSchema.optional(),
+ error: errorSchema.optional()
+});
+
+// People Record schema
+export const peopleRecordSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string().min(1).max(200),
+ context: z.string().max(2000).optional().default(''),
+ followUps: z.array(z.string().max(500)).optional().default([]),
+ lastTouched: z.string().datetime().optional(),
+ tags: z.array(z.string().max(50)).optional().default([]),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime()
+});
+
+// Project Record schema
+export const projectRecordSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string().min(1).max(200),
+ status: projectStatusEnum,
+ nextAction: z.string().min(1).max(500),
+ notes: z.string().max(5000).optional(),
+ tags: z.array(z.string().max(50)).optional().default([]),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime()
+});
+
+// Idea Record schema
+export const ideaRecordSchema = z.object({
+ id: z.string().uuid(),
+ title: z.string().min(1).max(200),
+ oneLiner: z.string().min(1).max(500),
+ notes: z.string().max(5000).optional(),
+ tags: z.array(z.string().max(50)).optional().default([]),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime()
+});
+
+// Admin Record schema
+export const adminRecordSchema = z.object({
+ id: z.string().uuid(),
+ title: z.string().min(1).max(200),
+ status: adminStatusEnum,
+ dueDate: z.string().datetime().optional(),
+ nextAction: z.string().max(500).optional(),
+ notes: z.string().max(5000).optional(),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime()
+});
+
+// Meta/Settings schema
+export const brainSettingsSchema = z.object({
+ version: z.number().int().positive().default(1),
+ confidenceThreshold: z.number().min(0).max(1).default(0.6),
+ dailyDigestTime: z.string().regex(/^\d{2}:\d{2}$/).default('09:00'),
+ weeklyReviewTime: z.string().regex(/^\d{2}:\d{2}$/).default('16:00'),
+ weeklyReviewDay: z.enum(['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']).default('sunday'),
+ defaultProvider: z.string().default('lmstudio'),
+ defaultModel: z.string().default('gptoss-20b'),
+ lastDailyDigest: z.string().datetime().optional(),
+ lastWeeklyReview: z.string().datetime().optional()
+});
+
+// Digest Record schema
+export const digestRecordSchema = z.object({
+ id: z.string().uuid(),
+ generatedAt: z.string().datetime(),
+ digestText: z.string().max(2000),
+ topActions: z.array(z.string().max(200)).max(3),
+ stuckThing: z.string().max(200),
+ smallWin: z.string().max(200),
+ ai: aiConfigSchema.optional()
+});
+
+// Weekly Review Record schema
+export const reviewRecordSchema = z.object({
+ id: z.string().uuid(),
+ generatedAt: z.string().datetime(),
+ reviewText: z.string().max(3000),
+ whatHappened: z.array(z.string().max(200)).max(5),
+ biggestOpenLoops: z.array(z.string().max(200)).max(3),
+ suggestedActionsNextWeek: z.array(z.string().max(200)).max(3),
+ recurringTheme: z.string().max(500),
+ ai: aiConfigSchema.optional()
+});
+
+// --- Input schemas for API endpoints ---
+
+// Capture input schema
+export const captureInputSchema = z.object({
+ text: z.string().min(1).max(10000),
+ providerOverride: z.string().optional(),
+ modelOverride: z.string().optional()
+});
+
+// Resolve review input schema
+export const resolveReviewInputSchema = z.object({
+ inboxLogId: z.string().uuid(),
+ destination: destinationEnum.exclude(['unknown']),
+ editedExtracted: z.record(z.unknown()).optional()
+});
+
+// Fix classification input schema
+export const fixInputSchema = z.object({
+ inboxLogId: z.string().uuid(),
+ newDestination: destinationEnum.exclude(['unknown']),
+ updatedFields: z.record(z.unknown()).optional(),
+ note: z.string().max(500).optional()
+});
+
+// Create/Update People input schema
+export const peopleInputSchema = z.object({
+ name: z.string().min(1).max(200),
+ context: z.string().max(2000).optional(),
+ followUps: z.array(z.string().max(500)).optional(),
+ lastTouched: z.string().datetime().optional(),
+ tags: z.array(z.string().max(50)).optional()
+});
+
+// Create/Update Project input schema
+export const projectInputSchema = z.object({
+ name: z.string().min(1).max(200),
+ status: projectStatusEnum.optional().default('active'),
+ nextAction: z.string().min(1).max(500),
+ notes: z.string().max(5000).optional(),
+ tags: z.array(z.string().max(50)).optional()
+});
+
+// Create/Update Idea input schema
+export const ideaInputSchema = z.object({
+ title: z.string().min(1).max(200),
+ oneLiner: z.string().min(1).max(500),
+ notes: z.string().max(5000).optional(),
+ tags: z.array(z.string().max(50)).optional()
+});
+
+// Create/Update Admin input schema
+export const adminInputSchema = z.object({
+ title: z.string().min(1).max(200),
+ status: adminStatusEnum.optional().default('open'),
+ dueDate: z.string().datetime().optional(),
+ nextAction: z.string().max(500).optional(),
+ notes: z.string().max(5000).optional()
+});
+
+// Settings update input schema
+export const settingsUpdateInputSchema = brainSettingsSchema.partial().omit({ version: true, lastDailyDigest: true, lastWeeklyReview: true });
+
+// Inbox query schema
+export const inboxQuerySchema = z.object({
+ status: inboxStatusEnum.optional(),
+ limit: z.coerce.number().int().min(1).max(100).optional().default(50),
+ offset: z.coerce.number().int().min(0).optional().default(0)
+});
+
+// --- Extracted field schemas for AI classification ---
+
+// Extracted People fields
+export const extractedPeopleSchema = z.object({
+ name: z.string().min(1).max(200),
+ context: z.string().max(2000).optional().default(''),
+ followUps: z.array(z.string().max(500)).optional().default([]),
+ lastTouched: z.string().datetime().nullable().optional(),
+ tags: z.array(z.string().max(50)).optional().default([])
+});
+
+// Extracted Project fields
+export const extractedProjectSchema = z.object({
+ name: z.string().min(1).max(200),
+ status: projectStatusEnum.optional().default('active'),
+ nextAction: z.string().min(1).max(500),
+ notes: z.string().max(5000).optional().default(''),
+ tags: z.array(z.string().max(50)).optional().default([])
+});
+
+// Extracted Idea fields
+export const extractedIdeaSchema = z.object({
+ title: z.string().min(1).max(200),
+ oneLiner: z.string().min(1).max(500),
+ notes: z.string().max(5000).optional().default(''),
+ tags: z.array(z.string().max(50)).optional().default([])
+});
+
+// Extracted Admin fields
+export const extractedAdminSchema = z.object({
+ title: z.string().min(1).max(200),
+ status: adminStatusEnum.optional().default('open'),
+ dueDate: z.string().datetime().nullable().optional(),
+ nextAction: z.string().max(500).nullable().optional(),
+ notes: z.string().max(5000).optional().default('')
+});
+
+// AI Classifier output schema (what we expect from the AI)
+export const classifierOutputSchema = z.object({
+ destination: destinationEnum,
+ confidence: z.number().min(0).max(1),
+ title: z.string().min(1).max(200),
+ extracted: z.record(z.unknown()),
+ reasons: z.array(z.string()).max(5).optional().default([])
+});
+
+// Daily digest AI output schema
+export const digestOutputSchema = z.object({
+ digestText: z.string(),
+ topActions: z.array(z.string()).max(3),
+ stuckThing: z.string(),
+ smallWin: z.string()
+});
+
+// Weekly review AI output schema
+export const reviewOutputSchema = z.object({
+ reviewText: z.string(),
+ whatHappened: z.array(z.string()).max(5),
+ biggestOpenLoops: z.array(z.string()).max(3),
+ suggestedActionsNextWeek: z.array(z.string()).max(3),
+ recurringTheme: z.string()
+});
diff --git a/server/routes/brain.js b/server/routes/brain.js
new file mode 100644
index 0000000000..a1f9240527
--- /dev/null
+++ b/server/routes/brain.js
@@ -0,0 +1,452 @@
+/**
+ * Brain API Routes
+ *
+ * Handles all HTTP endpoints for the Brain feature:
+ * - Capture and classify thoughts
+ * - CRUD for People, Projects, Ideas, Admin
+ * - Daily digest and weekly review
+ * - Settings management
+ */
+
+import { Router } from 'express';
+import * as brainService from '../services/brain.js';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validate } from '../lib/validation.js';
+import {
+ captureInputSchema,
+ resolveReviewInputSchema,
+ fixInputSchema,
+ inboxQuerySchema,
+ peopleInputSchema,
+ projectInputSchema,
+ ideaInputSchema,
+ adminInputSchema,
+ settingsUpdateInputSchema
+} from '../lib/brainValidation.js';
+
+const router = Router();
+
+// =============================================================================
+// CAPTURE & INBOX
+// =============================================================================
+
+/**
+ * POST /api/brain/capture
+ * Capture a thought, classify it, and store it
+ */
+router.post('/capture', asyncHandler(async (req, res) => {
+ const validation = validate(captureInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { text, providerOverride, modelOverride } = validation.data;
+ const result = await brainService.captureThought(text, providerOverride, modelOverride);
+ res.json(result);
+}));
+
+/**
+ * GET /api/brain/inbox
+ * Get inbox log entries with optional filters
+ */
+router.get('/inbox', asyncHandler(async (req, res) => {
+ const validation = validate(inboxQuerySchema, req.query);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const entries = await brainService.getInboxLog(validation.data);
+ const counts = await brainService.getInboxLogCounts();
+ res.json({ entries, counts });
+}));
+
+/**
+ * GET /api/brain/inbox/:id
+ * Get a single inbox log entry
+ */
+router.get('/inbox/:id', asyncHandler(async (req, res) => {
+ const entry = await brainService.getInboxLogById(req.params.id);
+ if (!entry) {
+ throw new ServerError('Inbox entry not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(entry);
+}));
+
+/**
+ * POST /api/brain/review/resolve
+ * Resolve a needs_review inbox item
+ */
+router.post('/review/resolve', asyncHandler(async (req, res) => {
+ const validation = validate(resolveReviewInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { inboxLogId, destination, editedExtracted } = validation.data;
+ const result = await brainService.resolveReview(inboxLogId, destination, editedExtracted);
+ res.json(result);
+}));
+
+/**
+ * POST /api/brain/fix
+ * Fix/correct a filed inbox item
+ */
+router.post('/fix', asyncHandler(async (req, res) => {
+ const validation = validate(fixInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { inboxLogId, newDestination, updatedFields, note } = validation.data;
+ const result = await brainService.fixClassification(inboxLogId, newDestination, updatedFields, note);
+ res.json(result);
+}));
+
+/**
+ * POST /api/brain/inbox/:id/retry
+ * Retry AI classification for a needs_review item
+ */
+router.post('/inbox/:id/retry', asyncHandler(async (req, res) => {
+ const { providerOverride, modelOverride } = req.body;
+ const result = await brainService.retryClassification(req.params.id, providerOverride, modelOverride);
+ res.json(result);
+}));
+
+// =============================================================================
+// PEOPLE CRUD
+// =============================================================================
+
+router.get('/people', asyncHandler(async (req, res) => {
+ const people = await brainService.getPeople();
+ res.json(people);
+}));
+
+router.get('/people/:id', asyncHandler(async (req, res) => {
+ const person = await brainService.getPersonById(req.params.id);
+ if (!person) {
+ throw new ServerError('Person not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(person);
+}));
+
+router.post('/people', asyncHandler(async (req, res) => {
+ const validation = validate(peopleInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+ const person = await brainService.createPerson(validation.data);
+ res.status(201).json(person);
+}));
+
+router.put('/people/:id', asyncHandler(async (req, res) => {
+ const validation = validate(peopleInputSchema.partial(), req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+ const person = await brainService.updatePerson(req.params.id, validation.data);
+ if (!person) {
+ throw new ServerError('Person not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(person);
+}));
+
+router.delete('/people/:id', asyncHandler(async (req, res) => {
+ const deleted = await brainService.deletePerson(req.params.id);
+ if (!deleted) {
+ throw new ServerError('Person not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.status(204).send();
+}));
+
+// =============================================================================
+// PROJECTS CRUD
+// =============================================================================
+
+router.get('/projects', asyncHandler(async (req, res) => {
+ const { status } = req.query;
+ const filters = status ? { status } : undefined;
+ const projects = await brainService.getProjects(filters);
+ res.json(projects);
+}));
+
+router.get('/projects/:id', asyncHandler(async (req, res) => {
+ const project = await brainService.getProjectById(req.params.id);
+ if (!project) {
+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(project);
+}));
+
+router.post('/projects', asyncHandler(async (req, res) => {
+ const validation = validate(projectInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+ const project = await brainService.createProject(validation.data);
+ res.status(201).json(project);
+}));
+
+router.put('/projects/:id', asyncHandler(async (req, res) => {
+ const validation = validate(projectInputSchema.partial(), req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+ const project = await brainService.updateProject(req.params.id, validation.data);
+ if (!project) {
+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(project);
+}));
+
+router.delete('/projects/:id', asyncHandler(async (req, res) => {
+ const deleted = await brainService.deleteProject(req.params.id);
+ if (!deleted) {
+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.status(204).send();
+}));
+
+// =============================================================================
+// IDEAS CRUD
+// =============================================================================
+
+router.get('/ideas', asyncHandler(async (req, res) => {
+ const ideas = await brainService.getIdeas();
+ res.json(ideas);
+}));
+
+router.get('/ideas/:id', asyncHandler(async (req, res) => {
+ const idea = await brainService.getIdeaById(req.params.id);
+ if (!idea) {
+ throw new ServerError('Idea not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(idea);
+}));
+
+router.post('/ideas', asyncHandler(async (req, res) => {
+ const validation = validate(ideaInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+ const idea = await brainService.createIdea(validation.data);
+ res.status(201).json(idea);
+}));
+
+router.put('/ideas/:id', asyncHandler(async (req, res) => {
+ const validation = validate(ideaInputSchema.partial(), req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+ const idea = await brainService.updateIdea(req.params.id, validation.data);
+ if (!idea) {
+ throw new ServerError('Idea not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(idea);
+}));
+
+router.delete('/ideas/:id', asyncHandler(async (req, res) => {
+ const deleted = await brainService.deleteIdea(req.params.id);
+ if (!deleted) {
+ throw new ServerError('Idea not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.status(204).send();
+}));
+
+// =============================================================================
+// ADMIN CRUD
+// =============================================================================
+
+router.get('/admin', asyncHandler(async (req, res) => {
+ const { status } = req.query;
+ const filters = status ? { status } : undefined;
+ const adminItems = await brainService.getAdminItems(filters);
+ res.json(adminItems);
+}));
+
+router.get('/admin/:id', asyncHandler(async (req, res) => {
+ const item = await brainService.getAdminById(req.params.id);
+ if (!item) {
+ throw new ServerError('Admin item not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(item);
+}));
+
+router.post('/admin', asyncHandler(async (req, res) => {
+ const validation = validate(adminInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+ const item = await brainService.createAdminItem(validation.data);
+ res.status(201).json(item);
+}));
+
+router.put('/admin/:id', asyncHandler(async (req, res) => {
+ const validation = validate(adminInputSchema.partial(), req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+ const item = await brainService.updateAdminItem(req.params.id, validation.data);
+ if (!item) {
+ throw new ServerError('Admin item not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(item);
+}));
+
+router.delete('/admin/:id', asyncHandler(async (req, res) => {
+ const deleted = await brainService.deleteAdminItem(req.params.id);
+ if (!deleted) {
+ throw new ServerError('Admin item not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.status(204).send();
+}));
+
+// =============================================================================
+// DIGEST & REVIEW
+// =============================================================================
+
+/**
+ * GET /api/brain/digest/latest
+ * Get the most recent daily digest
+ */
+router.get('/digest/latest', asyncHandler(async (req, res) => {
+ const digest = await brainService.getLatestDigest();
+ res.json(digest);
+}));
+
+/**
+ * GET /api/brain/digests
+ * Get digest history
+ */
+router.get('/digests', asyncHandler(async (req, res) => {
+ const limit = parseInt(req.query.limit) || 10;
+ const digests = await brainService.getDigests(limit);
+ res.json(digests);
+}));
+
+/**
+ * POST /api/brain/digest/run
+ * Manually trigger daily digest generation
+ */
+router.post('/digest/run', asyncHandler(async (req, res) => {
+ const { providerOverride, modelOverride } = req.body;
+ const digest = await brainService.runDailyDigest(providerOverride, modelOverride);
+ res.json(digest);
+}));
+
+/**
+ * GET /api/brain/review/latest
+ * Get the most recent weekly review
+ */
+router.get('/review/latest', asyncHandler(async (req, res) => {
+ const review = await brainService.getLatestReview();
+ res.json(review);
+}));
+
+/**
+ * GET /api/brain/reviews
+ * Get review history
+ */
+router.get('/reviews', asyncHandler(async (req, res) => {
+ const limit = parseInt(req.query.limit) || 10;
+ const reviews = await brainService.getReviews(limit);
+ res.json(reviews);
+}));
+
+/**
+ * POST /api/brain/review/run
+ * Manually trigger weekly review generation
+ */
+router.post('/review/run', asyncHandler(async (req, res) => {
+ const { providerOverride, modelOverride } = req.body;
+ const review = await brainService.runWeeklyReview(providerOverride, modelOverride);
+ res.json(review);
+}));
+
+// =============================================================================
+// SETTINGS & SUMMARY
+// =============================================================================
+
+/**
+ * GET /api/brain/settings
+ * Get brain settings
+ */
+router.get('/settings', asyncHandler(async (req, res) => {
+ const settings = await brainService.loadMeta();
+ res.json(settings);
+}));
+
+/**
+ * PUT /api/brain/settings
+ * Update brain settings
+ */
+router.put('/settings', asyncHandler(async (req, res) => {
+ const validation = validate(settingsUpdateInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+ const settings = await brainService.updateMeta(validation.data);
+ res.json(settings);
+}));
+
+/**
+ * GET /api/brain/summary
+ * Get brain data summary for dashboard
+ */
+router.get('/summary', asyncHandler(async (req, res) => {
+ const summary = await brainService.getSummary();
+ res.json(summary);
+}));
+
+export default router;
diff --git a/server/routes/brain.test.js b/server/routes/brain.test.js
new file mode 100644
index 0000000000..c8dfd51260
--- /dev/null
+++ b/server/routes/brain.test.js
@@ -0,0 +1,750 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import request from 'supertest';
+import brainRoutes from './brain.js';
+
+// Mock the brain service
+vi.mock('../services/brain.js', () => ({
+ // Capture & Inbox
+ captureThought: vi.fn(),
+ getInboxLog: vi.fn(),
+ getInboxLogById: vi.fn(),
+ getInboxLogCounts: vi.fn(),
+ resolveReview: vi.fn(),
+ fixClassification: vi.fn(),
+ retryClassification: vi.fn(),
+ // People
+ getPeople: vi.fn(),
+ getPersonById: vi.fn(),
+ createPerson: vi.fn(),
+ updatePerson: vi.fn(),
+ deletePerson: vi.fn(),
+ // Projects
+ getProjects: vi.fn(),
+ getProjectById: vi.fn(),
+ createProject: vi.fn(),
+ updateProject: vi.fn(),
+ deleteProject: vi.fn(),
+ // Ideas
+ getIdeas: vi.fn(),
+ getIdeaById: vi.fn(),
+ createIdea: vi.fn(),
+ updateIdea: vi.fn(),
+ deleteIdea: vi.fn(),
+ // Admin
+ getAdminItems: vi.fn(),
+ getAdminById: vi.fn(),
+ createAdminItem: vi.fn(),
+ updateAdminItem: vi.fn(),
+ deleteAdminItem: vi.fn(),
+ // Digest & Review
+ getLatestDigest: vi.fn(),
+ getDigests: vi.fn(),
+ runDailyDigest: vi.fn(),
+ getLatestReview: vi.fn(),
+ getReviews: vi.fn(),
+ runWeeklyReview: vi.fn(),
+ // Settings & Summary
+ loadMeta: vi.fn(),
+ updateMeta: vi.fn(),
+ getSummary: vi.fn()
+}));
+
+// Import mocked module
+import * as brainService from '../services/brain.js';
+
+describe('Brain Routes', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/brain', brainRoutes);
+ vi.clearAllMocks();
+ });
+
+ // ===========================================================================
+ // CAPTURE & INBOX
+ // ===========================================================================
+
+ describe('POST /api/brain/capture', () => {
+ it('should capture a thought and return result', async () => {
+ const mockResult = {
+ inboxLog: {
+ id: 'inbox-001',
+ capturedText: 'Test thought',
+ status: 'filed',
+ classification: {
+ destination: 'ideas',
+ confidence: 0.9,
+ title: 'Test Idea'
+ }
+ },
+ filedRecord: { id: 'idea-001', title: 'Test Idea' },
+ message: 'Filed to ideas: Test Idea'
+ };
+ brainService.captureThought.mockResolvedValue(mockResult);
+
+ const response = await request(app)
+ .post('/api/brain/capture')
+ .send({ text: 'Test thought' });
+
+ expect(response.status).toBe(200);
+ expect(response.body.inboxLog.id).toBe('inbox-001');
+ expect(brainService.captureThought).toHaveBeenCalledWith('Test thought', undefined, undefined);
+ });
+
+ it('should return 400 if text is missing', async () => {
+ const response = await request(app)
+ .post('/api/brain/capture')
+ .send({});
+
+ expect(response.status).toBe(400);
+ });
+
+ it('should pass provider and model overrides', async () => {
+ brainService.captureThought.mockResolvedValue({ inboxLog: { id: 'inbox-002' } });
+
+ await request(app)
+ .post('/api/brain/capture')
+ .send({ text: 'Test', providerOverride: 'openai', modelOverride: 'gpt-4' });
+
+ expect(brainService.captureThought).toHaveBeenCalledWith('Test', 'openai', 'gpt-4');
+ });
+ });
+
+ describe('GET /api/brain/inbox', () => {
+ it('should return inbox entries with counts', async () => {
+ const mockEntries = [
+ { id: 'inbox-001', status: 'filed' },
+ { id: 'inbox-002', status: 'needs_review' }
+ ];
+ const mockCounts = { total: 2, filed: 1, needs_review: 1 };
+ brainService.getInboxLog.mockResolvedValue(mockEntries);
+ brainService.getInboxLogCounts.mockResolvedValue(mockCounts);
+
+ const response = await request(app).get('/api/brain/inbox');
+
+ expect(response.status).toBe(200);
+ expect(response.body.entries).toHaveLength(2);
+ expect(response.body.counts.total).toBe(2);
+ });
+
+ it('should pass filters to service', async () => {
+ brainService.getInboxLog.mockResolvedValue([]);
+ brainService.getInboxLogCounts.mockResolvedValue({});
+
+ await request(app).get('/api/brain/inbox?status=needs_review&limit=50');
+
+ expect(brainService.getInboxLog).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'needs_review', limit: 50 })
+ );
+ });
+ });
+
+ describe('GET /api/brain/inbox/:id', () => {
+ it('should return inbox entry by ID', async () => {
+ brainService.getInboxLogById.mockResolvedValue({ id: 'inbox-001', capturedText: 'Test' });
+
+ const response = await request(app).get('/api/brain/inbox/inbox-001');
+
+ expect(response.status).toBe(200);
+ expect(response.body.id).toBe('inbox-001');
+ });
+
+ it('should return 404 if not found', async () => {
+ brainService.getInboxLogById.mockResolvedValue(null);
+
+ const response = await request(app).get('/api/brain/inbox/inbox-999');
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe('POST /api/brain/review/resolve', () => {
+ it('should resolve a needs_review item', async () => {
+ const testUuid = '550e8400-e29b-41d4-a716-446655440000';
+ brainService.resolveReview.mockResolvedValue({
+ inboxLog: { id: testUuid, status: 'filed' },
+ filedRecord: { id: 'project-001' }
+ });
+
+ const response = await request(app)
+ .post('/api/brain/review/resolve')
+ .send({
+ inboxLogId: testUuid,
+ destination: 'projects',
+ editedExtracted: { name: 'Test Project' }
+ });
+
+ expect(response.status).toBe(200);
+ expect(brainService.resolveReview).toHaveBeenCalledWith(
+ testUuid,
+ 'projects',
+ { name: 'Test Project' }
+ );
+ });
+
+ it('should return 400 if required fields are missing', async () => {
+ const response = await request(app)
+ .post('/api/brain/review/resolve')
+ .send({ inboxLogId: '550e8400-e29b-41d4-a716-446655440000' });
+
+ expect(response.status).toBe(400);
+ });
+ });
+
+ describe('POST /api/brain/fix', () => {
+ it('should fix a filed classification', async () => {
+ const testUuid = '550e8400-e29b-41d4-a716-446655440001';
+ brainService.fixClassification.mockResolvedValue({
+ inboxLog: { id: testUuid, status: 'corrected' },
+ newRecord: { id: 'people-001' }
+ });
+
+ const response = await request(app)
+ .post('/api/brain/fix')
+ .send({
+ inboxLogId: testUuid,
+ newDestination: 'people',
+ updatedFields: { name: 'John Doe' },
+ note: 'Wrong category'
+ });
+
+ expect(response.status).toBe(200);
+ expect(brainService.fixClassification).toHaveBeenCalledWith(
+ testUuid,
+ 'people',
+ { name: 'John Doe' },
+ 'Wrong category'
+ );
+ });
+
+ it('should return 400 if required fields are missing', async () => {
+ const response = await request(app)
+ .post('/api/brain/fix')
+ .send({ inboxLogId: '550e8400-e29b-41d4-a716-446655440001' });
+
+ expect(response.status).toBe(400);
+ });
+ });
+
+ describe('POST /api/brain/inbox/:id/retry', () => {
+ it('should retry classification', async () => {
+ brainService.retryClassification.mockResolvedValue({
+ inboxLog: { id: 'inbox-001', status: 'filed' }
+ });
+
+ const response = await request(app)
+ .post('/api/brain/inbox/inbox-001/retry')
+ .send({});
+
+ expect(response.status).toBe(200);
+ expect(brainService.retryClassification).toHaveBeenCalledWith('inbox-001', undefined, undefined);
+ });
+ });
+
+ // ===========================================================================
+ // PEOPLE CRUD
+ // ===========================================================================
+
+ describe('GET /api/brain/people', () => {
+ it('should return all people', async () => {
+ brainService.getPeople.mockResolvedValue([
+ { id: 'people-001', name: 'John' },
+ { id: 'people-002', name: 'Jane' }
+ ]);
+
+ const response = await request(app).get('/api/brain/people');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toHaveLength(2);
+ });
+ });
+
+ describe('GET /api/brain/people/:id', () => {
+ it('should return person by ID', async () => {
+ brainService.getPersonById.mockResolvedValue({ id: 'people-001', name: 'John' });
+
+ const response = await request(app).get('/api/brain/people/people-001');
+
+ expect(response.status).toBe(200);
+ expect(response.body.name).toBe('John');
+ });
+
+ it('should return 404 if not found', async () => {
+ brainService.getPersonById.mockResolvedValue(null);
+
+ const response = await request(app).get('/api/brain/people/people-999');
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe('POST /api/brain/people', () => {
+ it('should create a person', async () => {
+ brainService.createPerson.mockResolvedValue({
+ id: 'people-001',
+ name: 'John Doe',
+ context: 'Work colleague'
+ });
+
+ const response = await request(app)
+ .post('/api/brain/people')
+ .send({ name: 'John Doe', context: 'Work colleague' });
+
+ expect(response.status).toBe(201);
+ expect(response.body.id).toBe('people-001');
+ });
+
+ it('should return 400 if name is missing', async () => {
+ const response = await request(app)
+ .post('/api/brain/people')
+ .send({ context: 'Test' });
+
+ expect(response.status).toBe(400);
+ });
+ });
+
+ describe('PUT /api/brain/people/:id', () => {
+ it('should update a person', async () => {
+ brainService.updatePerson.mockResolvedValue({ id: 'people-001', name: 'John Updated' });
+
+ const response = await request(app)
+ .put('/api/brain/people/people-001')
+ .send({ name: 'John Updated' });
+
+ expect(response.status).toBe(200);
+ expect(response.body.name).toBe('John Updated');
+ });
+
+ it('should return 404 if not found', async () => {
+ brainService.updatePerson.mockResolvedValue(null);
+
+ const response = await request(app)
+ .put('/api/brain/people/people-999')
+ .send({ name: 'Test' });
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe('DELETE /api/brain/people/:id', () => {
+ it('should delete a person', async () => {
+ brainService.deletePerson.mockResolvedValue(true);
+
+ const response = await request(app).delete('/api/brain/people/people-001');
+
+ expect(response.status).toBe(204);
+ });
+
+ it('should return 404 if not found', async () => {
+ brainService.deletePerson.mockResolvedValue(false);
+
+ const response = await request(app).delete('/api/brain/people/people-999');
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ // ===========================================================================
+ // PROJECTS CRUD
+ // ===========================================================================
+
+ describe('GET /api/brain/projects', () => {
+ it('should return all projects', async () => {
+ brainService.getProjects.mockResolvedValue([
+ { id: 'proj-001', name: 'Project A' }
+ ]);
+
+ const response = await request(app).get('/api/brain/projects');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toHaveLength(1);
+ });
+
+ it('should filter by status', async () => {
+ brainService.getProjects.mockResolvedValue([]);
+
+ await request(app).get('/api/brain/projects?status=active');
+
+ expect(brainService.getProjects).toHaveBeenCalledWith({ status: 'active' });
+ });
+ });
+
+ describe('POST /api/brain/projects', () => {
+ it('should create a project', async () => {
+ brainService.createProject.mockResolvedValue({
+ id: 'proj-001',
+ name: 'New Project',
+ status: 'active'
+ });
+
+ const response = await request(app)
+ .post('/api/brain/projects')
+ .send({ name: 'New Project', status: 'active', nextAction: 'Define scope' });
+
+ expect(response.status).toBe(201);
+ expect(response.body.id).toBe('proj-001');
+ });
+
+ it('should return 400 if name is missing', async () => {
+ const response = await request(app)
+ .post('/api/brain/projects')
+ .send({ status: 'active' });
+
+ expect(response.status).toBe(400);
+ });
+ });
+
+ // ===========================================================================
+ // IDEAS CRUD
+ // ===========================================================================
+
+ describe('GET /api/brain/ideas', () => {
+ it('should return all ideas', async () => {
+ brainService.getIdeas.mockResolvedValue([
+ { id: 'idea-001', title: 'Great Idea' }
+ ]);
+
+ const response = await request(app).get('/api/brain/ideas');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toHaveLength(1);
+ });
+ });
+
+ describe('POST /api/brain/ideas', () => {
+ it('should create an idea', async () => {
+ brainService.createIdea.mockResolvedValue({
+ id: 'idea-001',
+ title: 'New Idea',
+ oneLiner: 'A brief description'
+ });
+
+ const response = await request(app)
+ .post('/api/brain/ideas')
+ .send({ title: 'New Idea', oneLiner: 'A brief description' });
+
+ expect(response.status).toBe(201);
+ expect(response.body.id).toBe('idea-001');
+ });
+
+ it('should return 400 if title is missing', async () => {
+ const response = await request(app)
+ .post('/api/brain/ideas')
+ .send({ oneLiner: 'Test' });
+
+ expect(response.status).toBe(400);
+ });
+ });
+
+ // ===========================================================================
+ // ADMIN CRUD
+ // ===========================================================================
+
+ describe('GET /api/brain/admin', () => {
+ it('should return all admin items', async () => {
+ brainService.getAdminItems.mockResolvedValue([
+ { id: 'admin-001', title: 'Renew license' }
+ ]);
+
+ const response = await request(app).get('/api/brain/admin');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toHaveLength(1);
+ });
+
+ it('should filter by status', async () => {
+ brainService.getAdminItems.mockResolvedValue([]);
+
+ await request(app).get('/api/brain/admin?status=open');
+
+ expect(brainService.getAdminItems).toHaveBeenCalledWith({ status: 'open' });
+ });
+ });
+
+ describe('POST /api/brain/admin', () => {
+ it('should create an admin item', async () => {
+ brainService.createAdminItem.mockResolvedValue({
+ id: 'admin-001',
+ title: 'Renew license',
+ status: 'open'
+ });
+
+ const response = await request(app)
+ .post('/api/brain/admin')
+ .send({ title: 'Renew license', status: 'open' });
+
+ expect(response.status).toBe(201);
+ expect(response.body.id).toBe('admin-001');
+ });
+
+ it('should return 400 if title is missing', async () => {
+ const response = await request(app)
+ .post('/api/brain/admin')
+ .send({ status: 'open' });
+
+ expect(response.status).toBe(400);
+ });
+ });
+
+ // ===========================================================================
+ // DIGEST & REVIEW
+ // ===========================================================================
+
+ describe('GET /api/brain/digest/latest', () => {
+ it('should return latest digest', async () => {
+ brainService.getLatestDigest.mockResolvedValue({
+ id: 'digest-001',
+ digestText: 'Today summary...'
+ });
+
+ const response = await request(app).get('/api/brain/digest/latest');
+
+ expect(response.status).toBe(200);
+ expect(response.body.id).toBe('digest-001');
+ });
+ });
+
+ describe('GET /api/brain/digests', () => {
+ it('should return digest history', async () => {
+ brainService.getDigests.mockResolvedValue([
+ { id: 'digest-001' },
+ { id: 'digest-002' }
+ ]);
+
+ const response = await request(app).get('/api/brain/digests');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toHaveLength(2);
+ });
+
+ it('should pass limit parameter', async () => {
+ brainService.getDigests.mockResolvedValue([]);
+
+ await request(app).get('/api/brain/digests?limit=5');
+
+ expect(brainService.getDigests).toHaveBeenCalledWith(5);
+ });
+ });
+
+ describe('POST /api/brain/digest/run', () => {
+ it('should run daily digest manually', async () => {
+ brainService.runDailyDigest.mockResolvedValue({
+ id: 'digest-001',
+ digestText: 'New digest...'
+ });
+
+ const response = await request(app)
+ .post('/api/brain/digest/run')
+ .send({});
+
+ expect(response.status).toBe(200);
+ expect(brainService.runDailyDigest).toHaveBeenCalled();
+ });
+ });
+
+ describe('GET /api/brain/review/latest', () => {
+ it('should return latest weekly review', async () => {
+ brainService.getLatestReview.mockResolvedValue({
+ id: 'review-001',
+ reviewText: 'Weekly summary...'
+ });
+
+ const response = await request(app).get('/api/brain/review/latest');
+
+ expect(response.status).toBe(200);
+ expect(response.body.id).toBe('review-001');
+ });
+ });
+
+ describe('GET /api/brain/reviews', () => {
+ it('should return review history', async () => {
+ brainService.getReviews.mockResolvedValue([{ id: 'review-001' }]);
+
+ const response = await request(app).get('/api/brain/reviews');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toHaveLength(1);
+ });
+ });
+
+ describe('POST /api/brain/review/run', () => {
+ it('should run weekly review manually', async () => {
+ brainService.runWeeklyReview.mockResolvedValue({
+ id: 'review-001',
+ reviewText: 'New review...'
+ });
+
+ const response = await request(app)
+ .post('/api/brain/review/run')
+ .send({});
+
+ expect(response.status).toBe(200);
+ expect(brainService.runWeeklyReview).toHaveBeenCalled();
+ });
+ });
+
+ // ===========================================================================
+ // SETTINGS & SUMMARY
+ // ===========================================================================
+
+ describe('GET /api/brain/settings', () => {
+ it('should return brain settings', async () => {
+ brainService.loadMeta.mockResolvedValue({
+ confidenceThreshold: 0.6,
+ dailyDigestTime: '09:00',
+ defaultProvider: 'lmstudio'
+ });
+
+ const response = await request(app).get('/api/brain/settings');
+
+ expect(response.status).toBe(200);
+ expect(response.body.confidenceThreshold).toBe(0.6);
+ });
+ });
+
+ describe('PUT /api/brain/settings', () => {
+ it('should update brain settings', async () => {
+ brainService.updateMeta.mockResolvedValue({
+ confidenceThreshold: 0.8,
+ dailyDigestTime: '10:00'
+ });
+
+ const response = await request(app)
+ .put('/api/brain/settings')
+ .send({ confidenceThreshold: 0.8, dailyDigestTime: '10:00' });
+
+ expect(response.status).toBe(200);
+ expect(brainService.updateMeta).toHaveBeenCalledWith(
+ expect.objectContaining({ confidenceThreshold: 0.8 })
+ );
+ });
+ });
+
+ describe('GET /api/brain/summary', () => {
+ it('should return brain summary', async () => {
+ brainService.getSummary.mockResolvedValue({
+ peopleCount: 5,
+ projectsCount: 3,
+ ideasCount: 10,
+ adminCount: 2,
+ needsReviewCount: 1
+ });
+
+ const response = await request(app).get('/api/brain/summary');
+
+ expect(response.status).toBe(200);
+ expect(response.body.peopleCount).toBe(5);
+ });
+ });
+
+ // ===========================================================================
+ // CAPTURE FLOW - ALWAYS CREATES INBOX LOG
+ // ===========================================================================
+
+ describe('Capture Flow - Always Creates Inbox Log', () => {
+ it('should create inbox log even when AI classification fails', async () => {
+ // Simulate AI failure that still creates inbox log in needs_review state
+ brainService.captureThought.mockResolvedValue({
+ inboxLog: {
+ id: 'inbox-001',
+ capturedText: 'Test thought',
+ status: 'needs_review',
+ classification: {
+ destination: 'unknown',
+ confidence: 0
+ }
+ },
+ message: 'Thought captured but AI unavailable. Queued for manual review.'
+ });
+
+ const response = await request(app)
+ .post('/api/brain/capture')
+ .send({ text: 'Test thought' });
+
+ expect(response.status).toBe(200);
+ expect(response.body.inboxLog.id).toBeDefined();
+ expect(response.body.inboxLog.status).toBe('needs_review');
+ });
+ });
+
+ // ===========================================================================
+ // CONFIDENCE THRESHOLD GATING
+ // ===========================================================================
+
+ describe('Confidence Threshold Gating', () => {
+ it('should file directly when confidence is above threshold', async () => {
+ brainService.captureThought.mockResolvedValue({
+ inboxLog: {
+ id: 'inbox-001',
+ status: 'filed',
+ classification: { confidence: 0.9, destination: 'ideas' }
+ },
+ filedRecord: { id: 'idea-001' }
+ });
+
+ const response = await request(app)
+ .post('/api/brain/capture')
+ .send({ text: 'High confidence thought' });
+
+ expect(response.status).toBe(200);
+ expect(response.body.inboxLog.status).toBe('filed');
+ });
+
+ it('should send to needs_review when confidence is below threshold', async () => {
+ brainService.captureThought.mockResolvedValue({
+ inboxLog: {
+ id: 'inbox-002',
+ status: 'needs_review',
+ classification: { confidence: 0.4, destination: 'ideas' }
+ },
+ message: 'Thought captured but needs review. Confidence: 40%'
+ });
+
+ const response = await request(app)
+ .post('/api/brain/capture')
+ .send({ text: 'Low confidence thought' });
+
+ expect(response.status).toBe(200);
+ expect(response.body.inboxLog.status).toBe('needs_review');
+ });
+ });
+
+ // ===========================================================================
+ // FIX/MOVE BEHAVIOR
+ // ===========================================================================
+
+ describe('Fix/Move Behavior Updates Records', () => {
+ it('should update inbox log status to corrected after fix', async () => {
+ const testUuid = '550e8400-e29b-41d4-a716-446655440002';
+ brainService.fixClassification.mockResolvedValue({
+ inboxLog: {
+ id: testUuid,
+ status: 'corrected',
+ correction: {
+ previousDestination: 'ideas',
+ newDestination: 'projects',
+ note: 'Actually a project'
+ }
+ },
+ newRecord: { id: 'proj-001' }
+ });
+
+ const response = await request(app)
+ .post('/api/brain/fix')
+ .send({
+ inboxLogId: testUuid,
+ newDestination: 'projects',
+ updatedFields: { name: 'Test Project' },
+ note: 'Actually a project'
+ });
+
+ expect(response.status).toBe(200);
+ expect(response.body.inboxLog.status).toBe('corrected');
+ expect(response.body.inboxLog.correction.previousDestination).toBe('ideas');
+ expect(response.body.inboxLog.correction.newDestination).toBe('projects');
+ });
+ });
+});
diff --git a/server/services/brain.js b/server/services/brain.js
new file mode 100644
index 0000000000..a8c77e032f
--- /dev/null
+++ b/server/services/brain.js
@@ -0,0 +1,520 @@
+/**
+ * Brain Service
+ *
+ * Core business logic for the Brain feature:
+ * - Capture and classify thoughts
+ * - Route to appropriate databases
+ * - Generate daily digests and weekly reviews
+ * - Handle corrections and fixes
+ */
+
+import * as storage from './brainStorage.js';
+import { getActiveProvider, getProviderById } from './providers.js';
+import { buildPrompt } from './promptService.js';
+import { validate } from '../lib/validation.js';
+import {
+ classifierOutputSchema,
+ digestOutputSchema,
+ reviewOutputSchema,
+ extractedPeopleSchema,
+ extractedProjectSchema,
+ extractedIdeaSchema,
+ extractedAdminSchema
+} from '../lib/brainValidation.js';
+
+// Extracted field validators by destination
+const EXTRACTED_VALIDATORS = {
+ people: extractedPeopleSchema,
+ projects: extractedProjectSchema,
+ ideas: extractedIdeaSchema,
+ admin: extractedAdminSchema
+};
+
+/**
+ * Call AI provider with a prompt
+ */
+async function callAI(promptStageName, variables, providerOverride, modelOverride) {
+ const provider = providerOverride
+ ? await getProviderById(providerOverride)
+ : await getActiveProvider();
+
+ if (!provider || !provider.enabled) {
+ throw new Error('No AI provider available');
+ }
+
+ const prompt = await buildPrompt(promptStageName, variables);
+ const model = modelOverride || provider.defaultModel;
+
+ if (provider.type === 'api') {
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) {
+ headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ }
+
+ const response = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ model,
+ messages: [{ role: 'user', content: prompt }],
+ temperature: 0.1
+ })
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`AI API error: ${response.status} - ${errorText}`);
+ }
+
+ const data = await response.json();
+ return data.choices?.[0]?.message?.content || '';
+ }
+
+ throw new Error(`Unsupported provider type: ${provider.type}`);
+}
+
+/**
+ * Parse JSON from AI response (handles markdown code blocks)
+ */
+function parseJsonResponse(content) {
+ if (!content || typeof content !== 'string') {
+ throw new Error('Empty or invalid AI response');
+ }
+
+ let jsonStr = content.trim();
+
+ // Remove markdown code blocks if present
+ const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
+ if (jsonMatch) {
+ jsonStr = jsonMatch[1].trim();
+ }
+
+ // Find JSON object
+ const objectMatch = jsonStr.match(/\{[\s\S]*\}/);
+ if (objectMatch) {
+ jsonStr = objectMatch[0];
+ }
+
+ return JSON.parse(jsonStr);
+}
+
+/**
+ * Capture a thought and classify it
+ */
+export async function captureThought(text, providerOverride, modelOverride) {
+ const meta = await storage.loadMeta();
+ const provider = providerOverride || meta.defaultProvider;
+ const model = modelOverride || meta.defaultModel;
+
+ // Create initial inbox log entry
+ const inboxEntry = await storage.createInboxLog({
+ capturedText: text,
+ source: 'brain_ui',
+ ai: {
+ providerId: provider,
+ modelId: model,
+ promptTemplateId: 'brain-classifier'
+ },
+ status: 'needs_review'
+ });
+
+ // Attempt AI classification
+ let classification = null;
+ let aiError = null;
+
+ const aiResponse = await callAI(
+ 'brain-classifier',
+ { capturedText: text, now: new Date().toISOString() },
+ providerOverride,
+ modelOverride
+ ).catch(err => {
+ aiError = err;
+ return null;
+ });
+
+ if (aiResponse) {
+ const parsed = parseJsonResponse(aiResponse);
+ const validationResult = classifierOutputSchema.safeParse(parsed);
+
+ if (validationResult.success) {
+ classification = validationResult.data;
+ } else {
+ console.error(`🧠 Classification validation failed: ${JSON.stringify(validationResult.error.errors)}`);
+ aiError = new Error('Invalid classification output from AI');
+ }
+ }
+
+ // If AI failed, return entry as needs_review
+ if (!classification) {
+ const errorMessage = aiError?.message || 'AI classification failed';
+ await storage.updateInboxLog(inboxEntry.id, {
+ classification: {
+ destination: 'unknown',
+ confidence: 0,
+ title: 'Classification failed',
+ extracted: {},
+ reasons: [errorMessage]
+ },
+ status: 'needs_review',
+ error: { message: errorMessage }
+ });
+
+ console.log(`🧠 Capture queued for review (AI unavailable): ${inboxEntry.id}`);
+ return {
+ inboxLog: await storage.getInboxLogById(inboxEntry.id),
+ message: `Thought captured but AI unavailable. Queued for manual review.`
+ };
+ }
+
+ // Check confidence threshold
+ if (classification.confidence < meta.confidenceThreshold || classification.destination === 'unknown') {
+ await storage.updateInboxLog(inboxEntry.id, {
+ classification,
+ status: 'needs_review'
+ });
+
+ console.log(`🧠 Capture needs review (low confidence ${classification.confidence}): ${inboxEntry.id}`);
+ return {
+ inboxLog: await storage.getInboxLogById(inboxEntry.id),
+ message: `Thought captured but needs review. Confidence: ${Math.round(classification.confidence * 100)}%`
+ };
+ }
+
+ // File to appropriate destination
+ const filedRecord = await fileToDestination(classification.destination, classification.extracted, classification.title);
+
+ await storage.updateInboxLog(inboxEntry.id, {
+ classification,
+ status: 'filed',
+ filed: {
+ destination: classification.destination,
+ destinationId: filedRecord.id
+ }
+ });
+
+ console.log(`🧠 Captured and filed to ${classification.destination}: ${filedRecord.id}`);
+ return {
+ inboxLog: await storage.getInboxLogById(inboxEntry.id),
+ filedRecord,
+ message: `Filed to ${classification.destination}: ${classification.title}`
+ };
+}
+
+/**
+ * File extracted data to destination database
+ */
+async function fileToDestination(destination, extracted, title) {
+ const validator = EXTRACTED_VALIDATORS[destination];
+ if (!validator) {
+ throw new Error(`Unknown destination: ${destination}`);
+ }
+
+ // Validate and set defaults
+ const validationResult = validator.safeParse(extracted);
+ const data = validationResult.success ? validationResult.data : extracted;
+
+ switch (destination) {
+ case 'people':
+ return storage.createPerson({
+ name: data.name || title,
+ context: data.context || '',
+ followUps: data.followUps || [],
+ lastTouched: data.lastTouched || null,
+ tags: data.tags || []
+ });
+
+ case 'projects':
+ return storage.createProject({
+ name: data.name || title,
+ status: data.status || 'active',
+ nextAction: data.nextAction || 'Define next action',
+ notes: data.notes || '',
+ tags: data.tags || []
+ });
+
+ case 'ideas':
+ return storage.createIdea({
+ title: data.title || title,
+ oneLiner: data.oneLiner || title,
+ notes: data.notes || '',
+ tags: data.tags || []
+ });
+
+ case 'admin':
+ return storage.createAdminItem({
+ title: data.title || title,
+ status: data.status || 'open',
+ dueDate: data.dueDate || null,
+ nextAction: data.nextAction || null,
+ notes: data.notes || ''
+ });
+
+ default:
+ throw new Error(`Cannot file to destination: ${destination}`);
+ }
+}
+
+/**
+ * Resolve a needs_review inbox item
+ */
+export async function resolveReview(inboxLogId, destination, editedExtracted) {
+ const inboxLog = await storage.getInboxLogById(inboxLogId);
+ if (!inboxLog) {
+ throw new Error('Inbox log entry not found');
+ }
+
+ if (inboxLog.status !== 'needs_review') {
+ throw new Error('Inbox entry is not in needs_review status');
+ }
+
+ // Merge extracted data with edits
+ const extracted = { ...inboxLog.classification?.extracted, ...editedExtracted };
+ const title = inboxLog.classification?.title || 'Untitled';
+
+ // File to destination
+ const filedRecord = await fileToDestination(destination, extracted, title);
+
+ // Update inbox log
+ await storage.updateInboxLog(inboxLogId, {
+ classification: {
+ ...inboxLog.classification,
+ destination,
+ extracted,
+ confidence: 1.0,
+ reasons: [...(inboxLog.classification?.reasons || []), 'Manually resolved']
+ },
+ status: 'filed',
+ filed: {
+ destination,
+ destinationId: filedRecord.id
+ }
+ });
+
+ console.log(`🧠 Resolved review to ${destination}: ${filedRecord.id}`);
+ return {
+ inboxLog: await storage.getInboxLogById(inboxLogId),
+ filedRecord
+ };
+}
+
+/**
+ * Fix/correct a filed inbox item
+ */
+export async function fixClassification(inboxLogId, newDestination, updatedFields, note) {
+ const inboxLog = await storage.getInboxLogById(inboxLogId);
+ if (!inboxLog) {
+ throw new Error('Inbox log entry not found');
+ }
+
+ if (inboxLog.status !== 'filed' && inboxLog.status !== 'corrected') {
+ throw new Error('Can only fix filed or previously corrected entries');
+ }
+
+ const previousDestination = inboxLog.filed?.destination || inboxLog.classification?.destination;
+ const previousId = inboxLog.filed?.destinationId;
+
+ // Create new record in new destination
+ const extracted = { ...inboxLog.classification?.extracted, ...updatedFields };
+ const title = inboxLog.classification?.title || 'Untitled';
+ const newRecord = await fileToDestination(newDestination, extracted, title);
+
+ // Mark old record as archived (soft delete by adding archived flag)
+ if (previousId && previousDestination) {
+ await archiveRecord(previousDestination, previousId);
+ }
+
+ // Update inbox log with correction info
+ await storage.updateInboxLog(inboxLogId, {
+ status: 'corrected',
+ filed: {
+ destination: newDestination,
+ destinationId: newRecord.id
+ },
+ correction: {
+ correctedAt: new Date().toISOString(),
+ previousDestination: previousDestination || 'unknown',
+ newDestination,
+ note
+ }
+ });
+
+ console.log(`🧠 Fixed classification from ${previousDestination} to ${newDestination}`);
+ return {
+ inboxLog: await storage.getInboxLogById(inboxLogId),
+ newRecord
+ };
+}
+
+/**
+ * Archive a record (soft delete)
+ */
+async function archiveRecord(destination, id) {
+ const updateFn = {
+ people: storage.updatePerson,
+ projects: storage.updateProject,
+ ideas: storage.updateIdea,
+ admin: storage.updateAdminItem
+ }[destination];
+
+ if (updateFn) {
+ await updateFn(id, { archived: true });
+ }
+}
+
+/**
+ * Run daily digest
+ */
+export async function runDailyDigest(providerOverride, modelOverride) {
+ const meta = await storage.loadMeta();
+
+ // Gather data for digest
+ const [activeProjects, openAdmin, allPeople, needsReviewLogs] = await Promise.all([
+ storage.getProjects({ status: 'active' }),
+ storage.getAdminItems({ status: 'open' }),
+ storage.getPeople(),
+ storage.getInboxLog({ status: 'needs_review' })
+ ]);
+
+ // Filter people with follow-ups
+ const peopleWithFollowUps = allPeople.filter(p => p.followUps && p.followUps.length > 0);
+
+ const aiResponse = await callAI(
+ 'brain-daily-digest',
+ {
+ activeProjects: JSON.stringify(activeProjects),
+ openAdmin: JSON.stringify(openAdmin),
+ peopleFollowUps: JSON.stringify(peopleWithFollowUps),
+ needsReview: JSON.stringify(needsReviewLogs),
+ now: new Date().toISOString()
+ },
+ providerOverride || meta.defaultProvider,
+ modelOverride || meta.defaultModel
+ );
+
+ const parsed = parseJsonResponse(aiResponse);
+ const validationResult = digestOutputSchema.safeParse(parsed);
+
+ if (!validationResult.success) {
+ throw new Error(`Invalid digest output: ${JSON.stringify(validationResult.error.errors)}`);
+ }
+
+ const digestData = validationResult.data;
+
+ // Enforce word limit
+ const wordCount = digestData.digestText.split(/\s+/).length;
+ if (wordCount > 150) {
+ digestData.digestText = digestData.digestText.split(/\s+/).slice(0, 150).join(' ') + '...';
+ }
+
+ // Store digest
+ const digest = await storage.createDigest({
+ ...digestData,
+ ai: {
+ providerId: providerOverride || meta.defaultProvider,
+ modelId: modelOverride || meta.defaultModel,
+ promptTemplateId: 'brain-daily-digest'
+ }
+ });
+
+ console.log(`🧠 Generated daily digest: ${digest.id}`);
+ return digest;
+}
+
+/**
+ * Run weekly review
+ */
+export async function runWeeklyReview(providerOverride, modelOverride) {
+ const meta = await storage.loadMeta();
+
+ // Get inbox log from last 7 days
+ const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
+ const allInboxLogs = await storage.getInboxLog({ limit: 500 });
+ const recentInboxLogs = allInboxLogs.filter(log => log.capturedAt >= sevenDaysAgo);
+
+ // Get active projects
+ const activeProjects = await storage.getProjects({ status: 'active' });
+
+ const aiResponse = await callAI(
+ 'brain-weekly-review',
+ {
+ inboxLogLast7Days: JSON.stringify(recentInboxLogs),
+ activeProjects: JSON.stringify(activeProjects),
+ now: new Date().toISOString()
+ },
+ providerOverride || meta.defaultProvider,
+ modelOverride || meta.defaultModel
+ );
+
+ const parsed = parseJsonResponse(aiResponse);
+ const validationResult = reviewOutputSchema.safeParse(parsed);
+
+ if (!validationResult.success) {
+ throw new Error(`Invalid review output: ${JSON.stringify(validationResult.error.errors)}`);
+ }
+
+ const reviewData = validationResult.data;
+
+ // Enforce word limit
+ const wordCount = reviewData.reviewText.split(/\s+/).length;
+ if (wordCount > 250) {
+ reviewData.reviewText = reviewData.reviewText.split(/\s+/).slice(0, 250).join(' ') + '...';
+ }
+
+ // Store review
+ const review = await storage.createReview({
+ ...reviewData,
+ ai: {
+ providerId: providerOverride || meta.defaultProvider,
+ modelId: modelOverride || meta.defaultModel,
+ promptTemplateId: 'brain-weekly-review'
+ }
+ });
+
+ console.log(`🧠 Generated weekly review: ${review.id}`);
+ return review;
+}
+
+/**
+ * Retry classification for a needs_review item
+ */
+export async function retryClassification(inboxLogId, providerOverride, modelOverride) {
+ const inboxLog = await storage.getInboxLogById(inboxLogId);
+ if (!inboxLog) {
+ throw new Error('Inbox log entry not found');
+ }
+
+ // Re-run capture logic with the original text
+ return captureThought(inboxLog.capturedText, providerOverride, modelOverride);
+}
+
+// Re-export storage functions for convenience
+export const loadMeta = storage.loadMeta;
+export const updateMeta = storage.updateMeta;
+export const getSummary = storage.getSummary;
+export const getInboxLog = storage.getInboxLog;
+export const getInboxLogById = storage.getInboxLogById;
+export const getInboxLogCounts = storage.getInboxLogCounts;
+export const getPeople = storage.getPeople;
+export const getPersonById = storage.getPersonById;
+export const createPerson = storage.createPerson;
+export const updatePerson = storage.updatePerson;
+export const deletePerson = storage.deletePerson;
+export const getProjects = storage.getProjects;
+export const getProjectById = storage.getProjectById;
+export const createProject = storage.createProject;
+export const updateProject = storage.updateProject;
+export const deleteProject = storage.deleteProject;
+export const getIdeas = storage.getIdeas;
+export const getIdeaById = storage.getIdeaById;
+export const createIdea = storage.createIdea;
+export const updateIdea = storage.updateIdea;
+export const deleteIdea = storage.deleteIdea;
+export const getAdminItems = storage.getAdminItems;
+export const getAdminById = storage.getAdminById;
+export const createAdminItem = storage.createAdminItem;
+export const updateAdminItem = storage.updateAdminItem;
+export const deleteAdminItem = storage.deleteAdminItem;
+export const getDigests = storage.getDigests;
+export const getLatestDigest = storage.getLatestDigest;
+export const getReviews = storage.getReviews;
+export const getLatestReview = storage.getLatestReview;
diff --git a/server/services/brainScheduler.js b/server/services/brainScheduler.js
new file mode 100644
index 0000000000..a4915b85fd
--- /dev/null
+++ b/server/services/brainScheduler.js
@@ -0,0 +1,203 @@
+/**
+ * Brain Scheduler Service
+ *
+ * Manages scheduled jobs for the Brain feature:
+ * - Daily digest generation (default 9:00 AM)
+ * - Weekly review generation (default Sunday 4:00 PM)
+ *
+ * Handles catch-up logic for missed runs (max 1 per type)
+ */
+
+import * as storage from './brainStorage.js';
+import { runDailyDigest, runWeeklyReview } from './brain.js';
+
+let schedulerInterval = null;
+let lastCheckTime = null;
+const CHECK_INTERVAL_MS = 60000; // Check every minute
+
+// Day name to number mapping
+const DAY_MAP = {
+ sunday: 0,
+ monday: 1,
+ tuesday: 2,
+ wednesday: 3,
+ thursday: 4,
+ friday: 5,
+ saturday: 6
+};
+
+/**
+ * Parse time string (HH:MM) to hours and minutes
+ */
+function parseTime(timeStr) {
+ const [hours, minutes] = timeStr.split(':').map(Number);
+ return { hours, minutes };
+}
+
+/**
+ * Check if it's time for daily digest
+ */
+function isDailyDigestTime(settings, now) {
+ const { hours, minutes } = parseTime(settings.dailyDigestTime);
+ return now.getHours() === hours && now.getMinutes() === minutes;
+}
+
+/**
+ * Check if it's time for weekly review
+ */
+function isWeeklyReviewTime(settings, now) {
+ const { hours, minutes } = parseTime(settings.weeklyReviewTime);
+ const targetDay = DAY_MAP[settings.weeklyReviewDay];
+ return now.getDay() === targetDay &&
+ now.getHours() === hours &&
+ now.getMinutes() === minutes;
+}
+
+/**
+ * Check if daily digest was missed (should have run today but didn't)
+ */
+function isDailyDigestMissed(settings, now) {
+ if (!settings.lastDailyDigest) return false;
+
+ const lastRun = new Date(settings.lastDailyDigest);
+ const { hours, minutes } = parseTime(settings.dailyDigestTime);
+
+ // Create target time for today
+ const todayTarget = new Date(now);
+ todayTarget.setHours(hours, minutes, 0, 0);
+
+ // If current time is past today's target and last run was before today
+ if (now > todayTarget) {
+ const lastRunDate = lastRun.toDateString();
+ const todayDate = now.toDateString();
+ return lastRunDate !== todayDate;
+ }
+
+ return false;
+}
+
+/**
+ * Check if weekly review was missed
+ */
+function isWeeklyReviewMissed(settings, now) {
+ if (!settings.lastWeeklyReview) return false;
+
+ const lastRun = new Date(settings.lastWeeklyReview);
+ const daysSinceLastRun = Math.floor((now - lastRun) / (24 * 60 * 60 * 1000));
+
+ // If more than 7 days since last run, we missed one
+ return daysSinceLastRun > 7;
+}
+
+/**
+ * Run the scheduler check
+ */
+async function checkSchedule() {
+ const now = new Date();
+ const settings = await storage.loadMeta();
+
+ // Avoid running multiple times in the same minute
+ const currentMinute = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}-${now.getHours()}-${now.getMinutes()}`;
+ if (lastCheckTime === currentMinute) return;
+ lastCheckTime = currentMinute;
+
+ // Check for daily digest
+ if (isDailyDigestTime(settings, now)) {
+ console.log('🧠 Scheduler: Running daily digest...');
+ runDailyDigest().catch(err => {
+ console.error(`🧠 Scheduler: Daily digest failed: ${err.message}`);
+ });
+ } else if (isDailyDigestMissed(settings, now)) {
+ console.log('🧠 Scheduler: Running missed daily digest (catch-up)...');
+ runDailyDigest().catch(err => {
+ console.error(`🧠 Scheduler: Catch-up daily digest failed: ${err.message}`);
+ });
+ }
+
+ // Check for weekly review
+ if (isWeeklyReviewTime(settings, now)) {
+ console.log('🧠 Scheduler: Running weekly review...');
+ runWeeklyReview().catch(err => {
+ console.error(`🧠 Scheduler: Weekly review failed: ${err.message}`);
+ });
+ } else if (isWeeklyReviewMissed(settings, now)) {
+ console.log('🧠 Scheduler: Running missed weekly review (catch-up)...');
+ runWeeklyReview().catch(err => {
+ console.error(`🧠 Scheduler: Catch-up weekly review failed: ${err.message}`);
+ });
+ }
+}
+
+/**
+ * Start the Brain scheduler
+ */
+export function startBrainScheduler() {
+ if (schedulerInterval) {
+ console.log('🧠 Scheduler: Already running');
+ return;
+ }
+
+ console.log('🧠 Scheduler: Starting Brain scheduler...');
+
+ // Run initial check
+ checkSchedule().catch(err => {
+ console.error(`🧠 Scheduler: Initial check failed: ${err.message}`);
+ });
+
+ // Set up interval
+ schedulerInterval = setInterval(() => {
+ checkSchedule().catch(err => {
+ console.error(`🧠 Scheduler: Check failed: ${err.message}`);
+ });
+ }, CHECK_INTERVAL_MS);
+
+ console.log('🧠 Scheduler: Brain scheduler started');
+}
+
+/**
+ * Stop the Brain scheduler
+ */
+export function stopBrainScheduler() {
+ if (schedulerInterval) {
+ clearInterval(schedulerInterval);
+ schedulerInterval = null;
+ console.log('🧠 Scheduler: Brain scheduler stopped');
+ }
+}
+
+/**
+ * Get scheduler status
+ */
+export async function getSchedulerStatus() {
+ const settings = await storage.loadMeta();
+
+ return {
+ running: schedulerInterval !== null,
+ checkIntervalMs: CHECK_INTERVAL_MS,
+ dailyDigest: {
+ scheduledTime: settings.dailyDigestTime,
+ lastRun: settings.lastDailyDigest
+ },
+ weeklyReview: {
+ scheduledDay: settings.weeklyReviewDay,
+ scheduledTime: settings.weeklyReviewTime,
+ lastRun: settings.lastWeeklyReview
+ }
+ };
+}
+
+/**
+ * Manually trigger the next scheduled digest (for testing)
+ */
+export async function triggerNextDigest() {
+ console.log('🧠 Scheduler: Manually triggering daily digest...');
+ return runDailyDigest();
+}
+
+/**
+ * Manually trigger the next scheduled review (for testing)
+ */
+export async function triggerNextReview() {
+ console.log('🧠 Scheduler: Manually triggering weekly review...');
+ return runWeeklyReview();
+}
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
new file mode 100644
index 0000000000..10f088badd
--- /dev/null
+++ b/server/services/brainStorage.js
@@ -0,0 +1,565 @@
+/**
+ * Brain Storage Service
+ *
+ * Handles file-based persistence for the Brain feature.
+ * - JSON for entity stores (people, projects, ideas, admin)
+ * - JSONL for append-heavy logs (inbox_log, digests, reviews)
+ * - In-memory caching with TTL for performance
+ */
+
+import { readFile, writeFile, appendFile, mkdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { v4 as uuidv4 } from 'uuid';
+import EventEmitter from 'events';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const DATA_DIR = join(__dirname, '../../data/brain');
+
+// File paths
+const FILES = {
+ meta: join(DATA_DIR, 'meta.json'),
+ inboxLog: join(DATA_DIR, 'inbox_log.jsonl'),
+ people: join(DATA_DIR, 'people.json'),
+ projects: join(DATA_DIR, 'projects.json'),
+ ideas: join(DATA_DIR, 'ideas.json'),
+ admin: join(DATA_DIR, 'admin.json'),
+ digests: join(DATA_DIR, 'digests.jsonl'),
+ reviews: join(DATA_DIR, 'reviews.jsonl')
+};
+
+// Event emitter for brain data changes
+export const brainEvents = new EventEmitter();
+
+// In-memory caches
+const caches = {
+ meta: { data: null, timestamp: 0 },
+ people: { data: null, timestamp: 0 },
+ projects: { data: null, timestamp: 0 },
+ ideas: { data: null, timestamp: 0 },
+ admin: { data: null, timestamp: 0 },
+ inboxLog: { data: null, timestamp: 0 },
+ digests: { data: null, timestamp: 0 },
+ reviews: { data: null, timestamp: 0 }
+};
+
+const CACHE_TTL_MS = 2000;
+
+// Default settings
+const DEFAULT_META = {
+ version: 1,
+ confidenceThreshold: 0.6,
+ dailyDigestTime: '09:00',
+ weeklyReviewTime: '16:00',
+ weeklyReviewDay: 'sunday',
+ defaultProvider: 'lmstudio',
+ defaultModel: 'gptoss-20b',
+ lastDailyDigest: null,
+ lastWeeklyReview: null
+};
+
+/**
+ * Ensure brain data directory exists
+ */
+export async function ensureBrainDir() {
+ if (!existsSync(DATA_DIR)) {
+ await mkdir(DATA_DIR, { recursive: true });
+ console.log(`🧠 Created brain data directory: ${DATA_DIR}`);
+ }
+}
+
+/**
+ * Generate a new UUID
+ */
+export function generateId() {
+ return uuidv4();
+}
+
+/**
+ * Get current ISO timestamp
+ */
+export function now() {
+ return new Date().toISOString();
+}
+
+// =============================================================================
+// META / SETTINGS
+// =============================================================================
+
+/**
+ * Load brain settings
+ */
+export async function loadMeta() {
+ const cache = caches.meta;
+ if (cache.data && (Date.now() - cache.timestamp) < CACHE_TTL_MS) {
+ return cache.data;
+ }
+
+ await ensureBrainDir();
+
+ if (!existsSync(FILES.meta)) {
+ cache.data = { ...DEFAULT_META };
+ cache.timestamp = Date.now();
+ return cache.data;
+ }
+
+ const content = await readFile(FILES.meta, 'utf-8');
+ cache.data = { ...DEFAULT_META, ...JSON.parse(content) };
+ cache.timestamp = Date.now();
+ return cache.data;
+}
+
+/**
+ * Save brain settings
+ */
+export async function saveMeta(meta) {
+ await ensureBrainDir();
+ await writeFile(FILES.meta, JSON.stringify(meta, null, 2));
+ caches.meta.data = meta;
+ caches.meta.timestamp = Date.now();
+ brainEvents.emit('meta:changed', meta);
+}
+
+/**
+ * Update brain settings (partial update)
+ */
+export async function updateMeta(updates) {
+ const meta = await loadMeta();
+ const updated = { ...meta, ...updates };
+ await saveMeta(updated);
+ return updated;
+}
+
+// =============================================================================
+// JSON ENTITY STORES (people, projects, ideas, admin)
+// =============================================================================
+
+/**
+ * Load a JSON entity store
+ */
+async function loadJsonStore(type) {
+ const cache = caches[type];
+ if (cache.data && (Date.now() - cache.timestamp) < CACHE_TTL_MS) {
+ return cache.data;
+ }
+
+ await ensureBrainDir();
+ const filePath = FILES[type];
+
+ if (!existsSync(filePath)) {
+ cache.data = { records: {} };
+ cache.timestamp = Date.now();
+ return cache.data;
+ }
+
+ const content = await readFile(filePath, 'utf-8');
+ cache.data = JSON.parse(content);
+ cache.timestamp = Date.now();
+ return cache.data;
+}
+
+/**
+ * Save a JSON entity store
+ */
+async function saveJsonStore(type, data) {
+ await ensureBrainDir();
+ await writeFile(FILES[type], JSON.stringify(data, null, 2));
+ caches[type].data = data;
+ caches[type].timestamp = Date.now();
+ brainEvents.emit(`${type}:changed`, data);
+}
+
+/**
+ * Get all records from a JSON store
+ */
+export async function getAll(type) {
+ const data = await loadJsonStore(type);
+ return Object.entries(data.records).map(([id, record]) => ({ id, ...record }));
+}
+
+/**
+ * Get a record by ID
+ */
+export async function getById(type, id) {
+ const data = await loadJsonStore(type);
+ const record = data.records[id];
+ return record ? { id, ...record } : null;
+}
+
+/**
+ * Create a new record
+ */
+export async function create(type, recordData) {
+ const data = await loadJsonStore(type);
+ const id = generateId();
+ const timestamp = now();
+
+ const record = {
+ ...recordData,
+ createdAt: timestamp,
+ updatedAt: timestamp
+ };
+
+ data.records[id] = record;
+ await saveJsonStore(type, data);
+
+ console.log(`🧠 Created ${type} record: ${id}`);
+ return { id, ...record };
+}
+
+/**
+ * Update a record
+ */
+export async function update(type, id, updates) {
+ const data = await loadJsonStore(type);
+
+ if (!data.records[id]) {
+ return null;
+ }
+
+ const record = {
+ ...data.records[id],
+ ...updates,
+ createdAt: data.records[id].createdAt,
+ updatedAt: now()
+ };
+
+ data.records[id] = record;
+ await saveJsonStore(type, data);
+
+ console.log(`🧠 Updated ${type} record: ${id}`);
+ return { id, ...record };
+}
+
+/**
+ * Delete a record
+ */
+export async function remove(type, id) {
+ const data = await loadJsonStore(type);
+
+ if (!data.records[id]) {
+ return false;
+ }
+
+ delete data.records[id];
+ await saveJsonStore(type, data);
+
+ console.log(`🧠 Deleted ${type} record: ${id}`);
+ return true;
+}
+
+/**
+ * Query records with filters
+ */
+export async function query(type, filters = {}) {
+ const records = await getAll(type);
+
+ return records.filter(record => {
+ for (const [key, value] of Object.entries(filters)) {
+ if (record[key] !== value) return false;
+ }
+ return true;
+ });
+}
+
+// =============================================================================
+// JSONL APPEND LOGS (inbox_log, digests, reviews)
+// =============================================================================
+
+/**
+ * Load all records from a JSONL file
+ */
+async function loadJsonlStore(type) {
+ const cache = caches[type];
+ if (cache.data && (Date.now() - cache.timestamp) < CACHE_TTL_MS) {
+ return cache.data;
+ }
+
+ await ensureBrainDir();
+ const filePath = FILES[type];
+
+ if (!existsSync(filePath)) {
+ cache.data = [];
+ cache.timestamp = Date.now();
+ return cache.data;
+ }
+
+ const content = await readFile(filePath, 'utf-8');
+ const lines = content.trim().split('\n').filter(line => line.trim());
+ cache.data = lines.map(line => JSON.parse(line));
+ cache.timestamp = Date.now();
+ return cache.data;
+}
+
+/**
+ * Append a record to a JSONL file
+ */
+async function appendJsonl(type, record) {
+ await ensureBrainDir();
+ const line = JSON.stringify(record) + '\n';
+ await appendFile(FILES[type], line);
+
+ // Invalidate cache so next read gets fresh data
+ caches[type].data = null;
+ caches[type].timestamp = 0;
+
+ brainEvents.emit(`${type}:added`, record);
+}
+
+/**
+ * Rewrite entire JSONL file (for updates/deletes)
+ */
+async function rewriteJsonl(type, records) {
+ await ensureBrainDir();
+ const content = records.map(r => JSON.stringify(r)).join('\n') + (records.length > 0 ? '\n' : '');
+ await writeFile(FILES[type], content);
+
+ caches[type].data = records;
+ caches[type].timestamp = Date.now();
+
+ brainEvents.emit(`${type}:changed`, records);
+}
+
+// =============================================================================
+// INBOX LOG OPERATIONS
+// =============================================================================
+
+/**
+ * Get all inbox log entries
+ */
+export async function getInboxLog(options = {}) {
+ const { status, limit = 50, offset = 0 } = options;
+ let records = await loadJsonlStore('inboxLog');
+
+ // Sort by capturedAt descending (newest first)
+ records = records.sort((a, b) => new Date(b.capturedAt) - new Date(a.capturedAt));
+
+ // Filter by status if provided
+ if (status) {
+ records = records.filter(r => r.status === status);
+ }
+
+ // Apply pagination
+ return records.slice(offset, offset + limit);
+}
+
+/**
+ * Get inbox log entry by ID
+ */
+export async function getInboxLogById(id) {
+ const records = await loadJsonlStore('inboxLog');
+ return records.find(r => r.id === id) || null;
+}
+
+/**
+ * Create inbox log entry
+ */
+export async function createInboxLog(entry) {
+ const record = {
+ id: generateId(),
+ ...entry,
+ capturedAt: entry.capturedAt || now()
+ };
+
+ await appendJsonl('inboxLog', record);
+ console.log(`🧠 Created inbox log: ${record.id}`);
+ return record;
+}
+
+/**
+ * Update inbox log entry
+ */
+export async function updateInboxLog(id, updates) {
+ const records = await loadJsonlStore('inboxLog');
+ const index = records.findIndex(r => r.id === id);
+
+ if (index === -1) {
+ return null;
+ }
+
+ records[index] = { ...records[index], ...updates };
+ await rewriteJsonl('inboxLog', records);
+
+ console.log(`🧠 Updated inbox log: ${id}`);
+ return records[index];
+}
+
+/**
+ * Get inbox log count by status
+ */
+export async function getInboxLogCounts() {
+ const records = await loadJsonlStore('inboxLog');
+
+ const counts = {
+ total: records.length,
+ filed: 0,
+ needs_review: 0,
+ corrected: 0,
+ error: 0
+ };
+
+ for (const record of records) {
+ if (counts[record.status] !== undefined) {
+ counts[record.status]++;
+ }
+ }
+
+ return counts;
+}
+
+// =============================================================================
+// DIGEST OPERATIONS
+// =============================================================================
+
+/**
+ * Get all digests
+ */
+export async function getDigests(limit = 10) {
+ let records = await loadJsonlStore('digests');
+ records = records.sort((a, b) => new Date(b.generatedAt) - new Date(a.generatedAt));
+ return records.slice(0, limit);
+}
+
+/**
+ * Get latest digest
+ */
+export async function getLatestDigest() {
+ const digests = await getDigests(1);
+ return digests[0] || null;
+}
+
+/**
+ * Create digest entry
+ */
+export async function createDigest(digest) {
+ const record = {
+ id: generateId(),
+ ...digest,
+ generatedAt: now()
+ };
+
+ await appendJsonl('digests', record);
+
+ // Update meta with last digest time
+ await updateMeta({ lastDailyDigest: record.generatedAt });
+
+ console.log(`🧠 Created daily digest: ${record.id}`);
+ return record;
+}
+
+// =============================================================================
+// REVIEW OPERATIONS
+// =============================================================================
+
+/**
+ * Get all reviews
+ */
+export async function getReviews(limit = 10) {
+ let records = await loadJsonlStore('reviews');
+ records = records.sort((a, b) => new Date(b.generatedAt) - new Date(a.generatedAt));
+ return records.slice(0, limit);
+}
+
+/**
+ * Get latest review
+ */
+export async function getLatestReview() {
+ const reviews = await getReviews(1);
+ return reviews[0] || null;
+}
+
+/**
+ * Create review entry
+ */
+export async function createReview(review) {
+ const record = {
+ id: generateId(),
+ ...review,
+ generatedAt: now()
+ };
+
+ await appendJsonl('reviews', record);
+
+ // Update meta with last review time
+ await updateMeta({ lastWeeklyReview: record.generatedAt });
+
+ console.log(`🧠 Created weekly review: ${record.id}`);
+ return record;
+}
+
+// =============================================================================
+// CONVENIENCE EXPORTS FOR ENTITY TYPES
+// =============================================================================
+
+// People
+export const getPeople = (filters) => filters ? query('people', filters) : getAll('people');
+export const getPersonById = (id) => getById('people', id);
+export const createPerson = (data) => create('people', data);
+export const updatePerson = (id, data) => update('people', id, data);
+export const deletePerson = (id) => remove('people', id);
+
+// Projects
+export const getProjects = (filters) => filters ? query('projects', filters) : getAll('projects');
+export const getProjectById = (id) => getById('projects', id);
+export const createProject = (data) => create('projects', data);
+export const updateProject = (id, data) => update('projects', id, data);
+export const deleteProject = (id) => remove('projects', id);
+
+// Ideas
+export const getIdeas = (filters) => filters ? query('ideas', filters) : getAll('ideas');
+export const getIdeaById = (id) => getById('ideas', id);
+export const createIdea = (data) => create('ideas', data);
+export const updateIdea = (id, data) => update('ideas', id, data);
+export const deleteIdea = (id) => remove('ideas', id);
+
+// Admin
+export const getAdminItems = (filters) => filters ? query('admin', filters) : getAll('admin');
+export const getAdminById = (id) => getById('admin', id);
+export const createAdminItem = (data) => create('admin', data);
+export const updateAdminItem = (id, data) => update('admin', id, data);
+export const deleteAdminItem = (id) => remove('admin', id);
+
+// =============================================================================
+// UTILITY FUNCTIONS
+// =============================================================================
+
+/**
+ * Invalidate all caches
+ */
+export function invalidateAllCaches() {
+ for (const key of Object.keys(caches)) {
+ caches[key].data = null;
+ caches[key].timestamp = 0;
+ }
+}
+
+/**
+ * Get brain data summary (for dashboard)
+ */
+export async function getSummary() {
+ const [people, projects, ideas, adminItems, inboxCounts, meta] = await Promise.all([
+ getAll('people'),
+ getAll('projects'),
+ getAll('ideas'),
+ getAll('admin'),
+ getInboxLogCounts(),
+ loadMeta()
+ ]);
+
+ return {
+ counts: {
+ people: people.length,
+ projects: projects.length,
+ ideas: ideas.length,
+ admin: adminItems.length,
+ inbox: inboxCounts
+ },
+ activeProjects: projects.filter(p => p.status === 'active').length,
+ openAdmin: adminItems.filter(a => a.status === 'open').length,
+ needsReview: inboxCounts.needs_review,
+ lastDailyDigest: meta.lastDailyDigest,
+ lastWeeklyReview: meta.lastWeeklyReview
+ };
+}
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 7f1df0f4af..8f7eaace50 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -624,7 +624,7 @@ export async function loadSchedule() {
const loaded = JSON.parse(content);
// Merge with defaults to ensure all task types have settings
- return {
+ const schedule = {
...DEFAULT_SCHEDULE,
...loaded,
selfImprovement: {
@@ -638,6 +638,29 @@ export async function loadSchedule() {
executions: loaded.executions || {},
templates: loaded.templates || []
};
+
+ // Populate prompts from defaults if they don't exist
+ let needsSave = false;
+ for (const [taskType, config] of Object.entries(schedule.selfImprovement)) {
+ if (!config.prompt && DEFAULT_SELF_IMPROVEMENT_PROMPTS[taskType]) {
+ config.prompt = DEFAULT_SELF_IMPROVEMENT_PROMPTS[taskType];
+ needsSave = true;
+ }
+ }
+
+ for (const [taskType, config] of Object.entries(schedule.appImprovement)) {
+ if (!config.prompt && DEFAULT_APP_IMPROVEMENT_PROMPTS[taskType]) {
+ config.prompt = DEFAULT_APP_IMPROVEMENT_PROMPTS[taskType];
+ needsSave = true;
+ }
+ }
+
+ // Save if we populated any prompts
+ if (needsSave) {
+ await saveSchedule(schedule);
+ }
+
+ return schedule;
}
/**
@@ -1196,21 +1219,19 @@ export function getDefaultAppImprovementPrompt(taskType) {
}
/**
- * Get the effective prompt for a self-improvement task type
- * Returns custom prompt if set, otherwise returns default
+ * Get the prompt for a self-improvement task type
*/
export async function getSelfImprovementPrompt(taskType) {
const interval = await getSelfImprovementInterval(taskType);
- return interval.prompt || DEFAULT_SELF_IMPROVEMENT_PROMPTS[taskType] || `[Self-Improvement] ${taskType} analysis`;
+ return interval.prompt || `[Self-Improvement] ${taskType} analysis`;
}
/**
- * Get the effective prompt for an app improvement task type
- * Returns custom prompt if set, otherwise returns default template
+ * Get the prompt for an app improvement task type
*/
export async function getAppImprovementPrompt(taskType) {
const interval = await getAppImprovementInterval(taskType);
- return interval.prompt || DEFAULT_APP_IMPROVEMENT_PROMPTS[taskType] || `[App Improvement] ${taskType} analysis
+ return interval.prompt || `[App Improvement] ${taskType} analysis
Repository: {repoPath}