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 pending memory approval system and user notifications

Adam Eivyde37b12a3c13
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 459adecda7..494b566a31 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -24,6 +24,8 @@ import {
import packageJson from '../../package.json';
import Logo from './Logo';
import { useErrorNotifications } from '../hooks/useErrorNotifications';
+import { useNotifications } from '../hooks/useNotifications';
+import NotificationDropdown from './NotificationDropdown';
const navItems = [
{ to: '/', label: 'Dashboard', icon: Home, single: true },
@@ -37,7 +39,7 @@ const navItems = [
},
{ to: '/apps', label: 'Apps', icon: Package, single: true },
{ href: '//:5560', label: 'Autofixer', icon: Wrench, external: true, dynamicHost: true },
- { to: '/cos', label: 'Chief of Staff', icon: Crown, single: true },
+ { to: '/cos', label: 'Chief of Staff', icon: Crown, single: true, showBadge: true },
{
label: 'Dev Tools',
icon: Terminal,
@@ -67,6 +69,16 @@ export default function Layout() {
// Subscribe to server error notifications
useErrorNotifications();
+ // Notifications for user task alerts
+ const {
+ notifications,
+ unreadCount,
+ markAsRead,
+ markAllAsRead,
+ removeNotification,
+ clearAll
+ } = useNotifications();
+
useEffect(() => {
localStorage.setItem(SIDEBAR_KEY, String(collapsed));
}, [collapsed]);
@@ -161,11 +173,25 @@ export default function Layout() {
title={collapsed ? item.label : undefined}
>
<div className="flex items-center gap-3">
- <Icon size={20} className="flex-shrink-0" />
+ <div className="relative">
+ <Icon size={20} className="flex-shrink-0" />
+ {/* Badge for collapsed state */}
+ {item.showBadge && unreadCount > 0 && collapsed && (
+ <span className="absolute -top-1.5 -right-1.5 min-w-[14px] h-[14px] flex items-center justify-center text-[9px] font-bold rounded-full bg-yellow-500 text-black px-0.5">
+ {unreadCount > 9 ? '9+' : unreadCount}
+ </span>
+ )}
+ </div>
<span className={`whitespace-nowrap ${collapsed ? 'lg:hidden' : ''}`}>
{item.label}
</span>
</div>
+ {/* Badge for expanded state */}
+ {item.showBadge && unreadCount > 0 && !collapsed && (
+ <span className="min-w-[18px] h-[18px] flex items-center justify-center text-[10px] font-bold rounded-full bg-yellow-500 text-black px-1">
+ {unreadCount > 9 ? '9+' : unreadCount}
+ </span>
+ )}
</NavLink>
);
}
@@ -324,9 +350,28 @@ export default function Layout() {
<Logo size={18} className="text-port-accent" />
<span className="font-bold text-sm text-port-accent">PortOS</span>
</div>
- <div className="w-8" /> {/* Spacer for centering */}
+ <NotificationDropdown
+ notifications={notifications}
+ unreadCount={unreadCount}
+ onMarkAsRead={markAsRead}
+ onMarkAllAsRead={markAllAsRead}
+ onRemove={removeNotification}
+ onClearAll={clearAll}
+ />
</header>
+ {/* Desktop notification dropdown - fixed position top right */}
+ <div className="hidden lg:block fixed top-4 right-4 z-50">
+ <NotificationDropdown
+ notifications={notifications}
+ unreadCount={unreadCount}
+ onMarkAsRead={markAsRead}
+ onMarkAllAsRead={markAllAsRead}
+ onRemove={removeNotification}
+ onClearAll={clearAll}
+ />
+ </div>
+
{/* Main content */}
<main className={`flex-1 overflow-auto ${location.pathname.startsWith('/cos') ? '' : 'p-4 md:p-6'}`}>
{location.pathname.startsWith('/cos') ? (
diff --git a/client/src/components/NotificationDropdown.jsx b/client/src/components/NotificationDropdown.jsx
new file mode 100644
index 0000000000..5c26ca2b98
--- /dev/null
+++ b/client/src/components/NotificationDropdown.jsx
@@ -0,0 +1,206 @@
+import { useState, useRef, useEffect } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { Bell, X, Check, CheckCheck, Trash2, Brain, ListTodo, AlertTriangle, Code } from 'lucide-react';
+
+const NOTIFICATION_TYPE_CONFIG = {
+ memory_approval: {
+ icon: Brain,
+ color: 'text-purple-400',
+ bgColor: 'bg-purple-500/20'
+ },
+ task_approval: {
+ icon: ListTodo,
+ color: 'text-yellow-400',
+ bgColor: 'bg-yellow-500/20'
+ },
+ code_review: {
+ icon: Code,
+ color: 'text-blue-400',
+ bgColor: 'bg-blue-500/20'
+ },
+ health_issue: {
+ icon: AlertTriangle,
+ color: 'text-red-400',
+ bgColor: 'bg-red-500/20'
+ }
+};
+
+const PRIORITY_COLORS = {
+ low: 'border-gray-500/30',
+ medium: 'border-yellow-500/30',
+ high: 'border-orange-500/50',
+ critical: 'border-red-500/50'
+};
+
+function formatTimeAgo(timestamp) {
+ const now = new Date();
+ const date = new Date(timestamp);
+ const seconds = Math.floor((now - date) / 1000);
+
+ if (seconds < 60) return 'just now';
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
+ return `${Math.floor(seconds / 86400)}d ago`;
+}
+
+export default function NotificationDropdown({
+ notifications,
+ unreadCount,
+ onMarkAsRead,
+ onMarkAllAsRead,
+ onRemove,
+ onClearAll
+}) {
+ const [isOpen, setIsOpen] = useState(false);
+ const dropdownRef = useRef(null);
+ const navigate = useNavigate();
+
+ // Close dropdown when clicking outside
+ useEffect(() => {
+ const handleClickOutside = (event) => {
+ if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
+ setIsOpen(false);
+ }
+ };
+
+ document.addEventListener('mousedown', handleClickOutside);
+ return () => document.removeEventListener('mousedown', handleClickOutside);
+ }, []);
+
+ const handleNotificationClick = (notification) => {
+ if (!notification.read) {
+ onMarkAsRead(notification.id);
+ }
+ if (notification.link) {
+ navigate(notification.link);
+ setIsOpen(false);
+ }
+ };
+
+ return (
+ <div className="relative" ref={dropdownRef}>
+ {/* Bell button with badge */}
+ <button
+ onClick={() => setIsOpen(!isOpen)}
+ className="relative p-2 rounded-lg hover:bg-port-card transition-colors"
+ title="Notifications"
+ >
+ <Bell className={`w-5 h-5 ${unreadCount > 0 ? 'text-yellow-400' : 'text-gray-400'}`} />
+ {unreadCount > 0 && (
+ <span className="absolute -top-1 -right-1 min-w-[18px] h-[18px] flex items-center justify-center text-[10px] font-bold rounded-full bg-yellow-500 text-black px-1">
+ {unreadCount > 9 ? '9+' : unreadCount}
+ </span>
+ )}
+ </button>
+
+ {/* Dropdown panel */}
+ {isOpen && (
+ <div className="absolute right-0 mt-2 w-80 bg-port-card border border-port-border rounded-lg shadow-xl z-50 overflow-hidden">
+ {/* Header */}
+ <div className="flex items-center justify-between px-4 py-3 border-b border-port-border">
+ <span className="font-medium text-white">Notifications</span>
+ <div className="flex items-center gap-2">
+ {unreadCount > 0 && (
+ <button
+ onClick={onMarkAllAsRead}
+ className="p-1.5 rounded hover:bg-port-border transition-colors"
+ title="Mark all as read"
+ >
+ <CheckCheck className="w-4 h-4 text-gray-400" />
+ </button>
+ )}
+ {notifications.length > 0 && (
+ <button
+ onClick={onClearAll}
+ className="p-1.5 rounded hover:bg-port-border transition-colors"
+ title="Clear all"
+ >
+ <Trash2 className="w-4 h-4 text-gray-400" />
+ </button>
+ )}
+ </div>
+ </div>
+
+ {/* Notification list */}
+ <div className="max-h-96 overflow-y-auto">
+ {notifications.length === 0 ? (
+ <div className="px-4 py-8 text-center text-gray-500">
+ No notifications
+ </div>
+ ) : (
+ notifications.slice(0, 10).map(notification => {
+ const config = NOTIFICATION_TYPE_CONFIG[notification.type] || NOTIFICATION_TYPE_CONFIG.task_approval;
+ const Icon = config.icon;
+
+ return (
+ <div
+ key={notification.id}
+ className={`
+ px-4 py-3 border-b border-port-border last:border-b-0 cursor-pointer
+ hover:bg-port-border/50 transition-colors
+ ${!notification.read ? 'bg-port-border/30' : ''}
+ border-l-2 ${PRIORITY_COLORS[notification.priority] || PRIORITY_COLORS.medium}
+ `}
+ onClick={() => handleNotificationClick(notification)}
+ >
+ <div className="flex items-start gap-3">
+ <div className={`p-1.5 rounded ${config.bgColor}`}>
+ <Icon className={`w-4 h-4 ${config.color}`} />
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center justify-between">
+ <span className={`text-sm font-medium ${!notification.read ? 'text-white' : 'text-gray-300'}`}>
+ {notification.title}
+ </span>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onRemove(notification.id);
+ }}
+ className="p-1 rounded hover:bg-port-border transition-colors opacity-0 group-hover:opacity-100"
+ >
+ <X className="w-3 h-3 text-gray-500" />
+ </button>
+ </div>
+ {notification.description && (
+ <p className="text-xs text-gray-500 mt-0.5 truncate">
+ {notification.description}
+ </p>
+ )}
+ <div className="flex items-center gap-2 mt-1">
+ <span className="text-[10px] text-gray-600">
+ {formatTimeAgo(notification.timestamp)}
+ </span>
+ {!notification.read && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onMarkAsRead(notification.id);
+ }}
+ className="text-[10px] text-port-accent hover:underline"
+ >
+ Mark read
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+ })
+ )}
+ </div>
+
+ {/* Footer */}
+ {notifications.length > 10 && (
+ <div className="px-4 py-2 border-t border-port-border text-center">
+ <span className="text-xs text-gray-500">
+ +{notifications.length - 10} more notifications
+ </span>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/cos/tabs/MemoryTab.jsx b/client/src/components/cos/tabs/MemoryTab.jsx
index cdfdea5cb3..e6384d3cf6 100644
--- a/client/src/components/cos/tabs/MemoryTab.jsx
+++ b/client/src/components/cos/tabs/MemoryTab.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
-import { RefreshCw, Trash2, X } from 'lucide-react';
+import { RefreshCw, Trash2, X, Check, XCircle } from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../../services/api';
import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';
@@ -8,6 +8,7 @@ import MemoryGraph from './MemoryGraph';
export default function MemoryTab() {
const [memories, setMemories] = useState([]);
+ const [pendingMemories, setPendingMemories] = useState([]);
const [stats, setStats] = useState(null);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
@@ -18,17 +19,31 @@ export default function MemoryTab() {
const fetchData = useCallback(async () => {
setLoading(true);
- const [memoriesRes, statsRes, embRes] = await Promise.all([
+ const [memoriesRes, pendingRes, statsRes, embRes] = await Promise.all([
api.getMemories({ limit: 100, ...filters }).catch(() => ({ memories: [] })),
+ api.getMemories({ status: 'pending_approval', limit: 50 }).catch(() => ({ memories: [] })),
api.getMemoryStats().catch(() => null),
api.getEmbeddingStatus().catch(() => null)
]);
setMemories(memoriesRes.memories || []);
+ setPendingMemories(pendingRes.memories || []);
setStats(statsRes);
setEmbeddingStatus(embRes);
setLoading(false);
}, [filters]);
+ const handleApprove = async (id) => {
+ await api.approveMemory(id);
+ toast.success('Memory approved');
+ fetchData();
+ };
+
+ const handleReject = async (id) => {
+ await api.rejectMemory(id);
+ toast.success('Memory rejected');
+ fetchData();
+ };
+
useEffect(() => {
fetchData();
}, [fetchData]);
@@ -60,6 +75,7 @@ export default function MemoryTab() {
<h3 className="text-lg font-semibold text-white">Memory System</h3>
<p className="text-sm text-gray-500">
{stats?.active || 0} active memories
+ {stats?.pendingApproval > 0 && <span className="text-yellow-400"> * {stats.pendingApproval} pending</span>}
{embeddingStatus?.available ? ' * LM Studio connected' : ' * LM Studio offline'}
</p>
</div>
@@ -136,6 +152,59 @@ export default function MemoryTab() {
</div>
)}
+ {/* Pending Approvals */}
+ {pendingMemories.length > 0 && (
+ <div className="space-y-3">
+ <h3 className="text-lg font-semibold text-yellow-500">Pending Approval ({pendingMemories.length})</h3>
+ {pendingMemories.map(memory => (
+ <div key={memory.id} className="bg-port-card border border-yellow-500/50 rounded-lg p-4">
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-2">
+ <span className={`px-2 py-0.5 text-xs rounded-full border ${MEMORY_TYPE_COLORS[memory.type]}`}>
+ {memory.type}
+ </span>
+ <span className="text-xs text-gray-500">{memory.category}</span>
+ <span className="text-xs text-yellow-400">
+ {((memory.confidence || 0) * 100).toFixed(0)}% confidence
+ </span>
+ </div>
+ <p className="text-white text-sm">{memory.summary || memory.content?.substring(0, 200)}</p>
+ {memory.tags?.length > 0 && (
+ <div className="flex gap-1 mt-2">
+ {memory.tags.map(tag => (
+ <span key={tag} className="px-2 py-0.5 text-xs bg-port-border rounded text-gray-400">
+ {tag}
+ </span>
+ ))}
+ </div>
+ )}
+ <div className="text-xs text-gray-500 mt-2">
+ {new Date(memory.createdAt).toLocaleDateString()}
+ </div>
+ </div>
+ <div className="flex gap-2">
+ <button
+ onClick={() => handleApprove(memory.id)}
+ className="p-2 bg-green-500/20 text-green-400 hover:bg-green-500/30 rounded-lg transition-colors"
+ title="Approve"
+ >
+ <Check size={16} />
+ </button>
+ <button
+ onClick={() => handleReject(memory.id)}
+ className="p-2 bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded-lg transition-colors"
+ title="Reject"
+ >
+ <XCircle size={16} />
+ </button>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
{/* Content */}
{loading ? (
<div className="flex items-center justify-center py-12">
diff --git a/client/src/hooks/useNotifications.js b/client/src/hooks/useNotifications.js
new file mode 100644
index 0000000000..e52983c523
--- /dev/null
+++ b/client/src/hooks/useNotifications.js
@@ -0,0 +1,117 @@
+import { useState, useEffect, useCallback } from 'react';
+import { useSocket } from './useSocket';
+import * as api from '../services/api';
+
+export function useNotifications() {
+ const [notifications, setNotifications] = useState([]);
+ const [unreadCount, setUnreadCount] = useState(0);
+ const [loading, setLoading] = useState(true);
+ const socket = useSocket();
+
+ // Fetch initial notifications
+ useEffect(() => {
+ const fetchNotifications = async () => {
+ setLoading(true);
+ const [notifs, countData] = await Promise.all([
+ api.getNotifications({ limit: 50 }),
+ api.getNotificationCount()
+ ]);
+ setNotifications(notifs);
+ setUnreadCount(countData.count);
+ setLoading(false);
+ };
+
+ fetchNotifications();
+ }, []);
+
+ // Subscribe to socket events
+ useEffect(() => {
+ if (!socket) return;
+
+ socket.emit('notifications:subscribe');
+
+ const handleAdded = (notification) => {
+ setNotifications(prev => [notification, ...prev]);
+ setUnreadCount(prev => prev + 1);
+ };
+
+ const handleRemoved = ({ id }) => {
+ setNotifications(prev => prev.filter(n => n.id !== id));
+ };
+
+ const handleUpdated = (notification) => {
+ setNotifications(prev =>
+ prev.map(n => n.id === notification.id ? notification : n)
+ );
+ };
+
+ const handleCount = (count) => {
+ setUnreadCount(count);
+ };
+
+ const handleCleared = () => {
+ setNotifications([]);
+ setUnreadCount(0);
+ };
+
+ socket.on('notifications:added', handleAdded);
+ socket.on('notifications:removed', handleRemoved);
+ socket.on('notifications:updated', handleUpdated);
+ socket.on('notifications:count', handleCount);
+ socket.on('notifications:cleared', handleCleared);
+
+ return () => {
+ socket.off('notifications:added', handleAdded);
+ socket.off('notifications:removed', handleRemoved);
+ socket.off('notifications:updated', handleUpdated);
+ socket.off('notifications:count', handleCount);
+ socket.off('notifications:cleared', handleCleared);
+ socket.emit('notifications:unsubscribe');
+ };
+ }, [socket]);
+
+ const markAsRead = useCallback(async (id) => {
+ await api.markNotificationRead(id);
+ setNotifications(prev =>
+ prev.map(n => n.id === id ? { ...n, read: true } : n)
+ );
+ setUnreadCount(prev => Math.max(0, prev - 1));
+ }, []);
+
+ const markAllAsRead = useCallback(async () => {
+ await api.markAllNotificationsRead();
+ setNotifications(prev => prev.map(n => ({ ...n, read: true })));
+ setUnreadCount(0);
+ }, []);
+
+ const removeNotification = useCallback(async (id) => {
+ await api.deleteNotification(id);
+ setNotifications(prev => prev.filter(n => n.id !== id));
+ }, []);
+
+ const clearAll = useCallback(async () => {
+ await api.clearNotifications();
+ setNotifications([]);
+ setUnreadCount(0);
+ }, []);
+
+ const refresh = useCallback(async () => {
+ const [notifs, countData] = await Promise.all([
+ api.getNotifications({ limit: 50 }),
+ api.getNotificationCount()
+ ]);
+ setNotifications(notifs);
+ setUnreadCount(countData.count);
+ }, []);
+
+ return {
+ notifications,
+ unreadCount,
+ loading,
+ markAsRead,
+ markAllAsRead,
+ removeNotification,
+ clearAll,
+ refresh
+ };
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index d3407eea43..1066597476 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -343,6 +343,23 @@ export const consolidateMemories = (options = {}) => request('/memory/consolidat
body: JSON.stringify(options)
});
export const getEmbeddingStatus = () => request('/memory/embeddings/status');
+export const approveMemory = (id) => request(`/memory/${id}/approve`, { method: 'POST' });
+export const rejectMemory = (id) => request(`/memory/${id}/reject`, { method: 'POST' });
+
+// Notifications
+export const getNotifications = (options = {}) => {
+ const params = new URLSearchParams();
+ if (options.type) params.set('type', options.type);
+ if (options.unreadOnly) params.set('unreadOnly', 'true');
+ if (options.limit) params.set('limit', options.limit);
+ return request(`/notifications?${params}`);
+};
+export const getNotificationCount = () => request('/notifications/count');
+export const getNotificationCounts = () => request('/notifications/counts');
+export const markNotificationRead = (id) => request(`/notifications/${id}/read`, { method: 'POST' });
+export const markAllNotificationsRead = () => request('/notifications/read-all', { method: 'POST' });
+export const deleteNotification = (id) => request(`/notifications/${id}`, { method: 'DELETE' });
+export const clearNotifications = () => request('/notifications', { method: 'DELETE' });
// PM2 Standardization
export const analyzeStandardization = (repoPath, providerId) => request('/standardize/analyze', {
diff --git a/server/index.js b/server/index.js
index 193a53490b..3459792007 100644
--- a/server/index.js
+++ b/server/index.js
@@ -24,6 +24,7 @@ import agentsRoutes from './routes/agents.js';
import cosRoutes from './routes/cos.js';
import scriptsRoutes from './routes/scripts.js';
import memoryRoutes from './routes/memory.js';
+import notificationsRoutes from './routes/notifications.js';
import standardizeRoutes from './routes/standardize.js';
import { initSocket } from './services/socket.js';
import { initScriptRunner } from './services/scriptRunner.js';
@@ -89,6 +90,7 @@ app.use('/api/agents', agentsRoutes);
app.use('/api/cos/scripts', scriptsRoutes); // Mount before /api/cos to avoid route conflicts
app.use('/api/cos', cosRoutes);
app.use('/api/memory', memoryRoutes);
+app.use('/api/notifications', notificationsRoutes);
app.use('/api/standardize', standardizeRoutes);
// Initialize script runner
diff --git a/server/lib/memoryValidation.js b/server/lib/memoryValidation.js
index 7613ffbff1..ab5331053e 100644
--- a/server/lib/memoryValidation.js
+++ b/server/lib/memoryValidation.js
@@ -11,7 +11,7 @@ export const memoryTypeEnum = z.enum([
]);
// Memory status enum
-export const memoryStatusEnum = z.enum(['active', 'archived', 'expired']);
+export const memoryStatusEnum = z.enum(['active', 'archived', 'expired', 'pending_approval']);
// Memory category enum (extensible, but common ones)
export const memoryCategoryEnum = z.enum([
diff --git a/server/routes/memory.js b/server/routes/memory.js
index e0a83ccc3f..cf748e8966 100644
--- a/server/routes/memory.js
+++ b/server/routes/memory.js
@@ -201,6 +201,24 @@ router.put('/:id', asyncHandler(async (req, res) => {
res.json(updated);
}));
+// POST /api/memory/:id/approve - Approve a pending memory
+router.post('/:id/approve', asyncHandler(async (req, res) => {
+ const result = await memory.approveMemory(req.params.id);
+ if (!result.success) {
+ throw new ServerError(result.error, { status: result.error === 'Memory not found' ? 404 : 400 });
+ }
+ res.json(result);
+}));
+
+// POST /api/memory/:id/reject - Reject a pending memory
+router.post('/:id/reject', asyncHandler(async (req, res) => {
+ const result = await memory.rejectMemory(req.params.id);
+ if (!result.success) {
+ throw new ServerError(result.error, { status: result.error === 'Memory not found' ? 404 : 400 });
+ }
+ res.json(result);
+}));
+
// DELETE /api/memory/:id - Delete a memory
router.delete('/:id', asyncHandler(async (req, res) => {
const hard = req.query.hard === 'true';
diff --git a/server/routes/notifications.js b/server/routes/notifications.js
new file mode 100644
index 0000000000..17990d6091
--- /dev/null
+++ b/server/routes/notifications.js
@@ -0,0 +1,65 @@
+/**
+ * Notifications API Routes
+ */
+
+import { Router } from 'express';
+import * as notifications from '../services/notifications.js';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+
+const router = Router();
+
+// GET /api/notifications - List all notifications
+router.get('/', asyncHandler(async (req, res) => {
+ const options = {
+ type: req.query.type,
+ unreadOnly: req.query.unreadOnly === 'true',
+ limit: req.query.limit ? parseInt(req.query.limit) : undefined
+ };
+
+ const result = await notifications.getNotifications(options);
+ res.json(result);
+}));
+
+// GET /api/notifications/count - Get unread count
+router.get('/count', asyncHandler(async (req, res) => {
+ const count = await notifications.getUnreadCount();
+ res.json({ count });
+}));
+
+// GET /api/notifications/counts - Get counts by type
+router.get('/counts', asyncHandler(async (req, res) => {
+ const counts = await notifications.getCountsByType();
+ res.json(counts);
+}));
+
+// POST /api/notifications/:id/read - Mark as read
+router.post('/:id/read', asyncHandler(async (req, res) => {
+ const result = await notifications.markAsRead(req.params.id);
+ if (!result.success) {
+ throw new ServerError(result.error, { status: 404 });
+ }
+ res.json(result);
+}));
+
+// POST /api/notifications/read-all - Mark all as read
+router.post('/read-all', asyncHandler(async (req, res) => {
+ const result = await notifications.markAllAsRead();
+ res.json(result);
+}));
+
+// DELETE /api/notifications/:id - Remove a notification
+router.delete('/:id', asyncHandler(async (req, res) => {
+ const result = await notifications.removeNotification(req.params.id);
+ if (!result.success) {
+ throw new ServerError(result.error, { status: 404 });
+ }
+ res.json(result);
+}));
+
+// DELETE /api/notifications - Clear all notifications
+router.delete('/', asyncHandler(async (req, res) => {
+ const result = await notifications.clearAll();
+ res.json(result);
+}));
+
+export default router;
diff --git a/server/services/memory.js b/server/services/memory.js
index e791c7867f..ca39d2434c 100644
--- a/server/services/memory.js
+++ b/server/services/memory.js
@@ -12,6 +12,7 @@ import { fileURLToPath } from 'url';
import { v4 as uuidv4 } from 'uuid';
import { cosEvents } from './cos.js';
import { findTopK, findAboveThreshold, clusterBySimilarity, cosineSimilarity } from '../lib/vectorMath.js';
+import * as notifications from './notifications.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -190,7 +191,7 @@ export async function createMemory(data, embedding = null) {
createdAt: now,
updatedAt: now,
expiresAt: data.expiresAt || null,
- status: 'active'
+ status: data.status || 'active'
};
// Save full memory
@@ -365,6 +366,74 @@ export async function deleteMemory(id, hard = false) {
});
}
+/**
+ * Approve a pending memory (changes status from pending_approval to active)
+ */
+export async function approveMemory(id) {
+ return withMemoryLock(async () => {
+ const memory = await loadMemory(id);
+ if (!memory) return { success: false, error: 'Memory not found' };
+ if (memory.status !== 'pending_approval') {
+ return { success: false, error: 'Memory is not pending approval' };
+ }
+
+ memory.status = 'active';
+ memory.updatedAt = new Date().toISOString();
+ await saveMemory(memory);
+
+ // Update index
+ const index = await loadIndex();
+ const idx = index.memories.findIndex(m => m.id === id);
+ if (idx !== -1) {
+ index.memories[idx].status = 'active';
+ await saveIndex(index);
+ }
+
+ console.log(`🧠 Memory approved: ${id}`);
+ cosEvents.emit('memory:approved', { id, memory });
+
+ // Remove associated notification
+ await notifications.removeByMetadata('memoryId', id);
+
+ return { success: true, memory };
+ });
+}
+
+/**
+ * Reject a pending memory (hard deletes it)
+ */
+export async function rejectMemory(id) {
+ return withMemoryLock(async () => {
+ const memory = await loadMemory(id);
+ if (!memory) return { success: false, error: 'Memory not found' };
+ if (memory.status !== 'pending_approval') {
+ return { success: false, error: 'Memory is not pending approval' };
+ }
+
+ // Hard delete - remove files
+ await deleteMemoryFiles(id);
+
+ // Remove from index
+ const index = await loadIndex();
+ index.memories = index.memories.filter(m => m.id !== id);
+ index.count = index.memories.length;
+ await saveIndex(index);
+
+ // Remove embedding
+ const embeddings = await loadEmbeddings();
+ delete embeddings.vectors[id];
+ await saveEmbeddings(embeddings);
+
+ console.log(`🧠 Memory rejected: ${id}`);
+ cosEvents.emit('memory:rejected', { id });
+
+ // Remove associated notification
+ await notifications.removeByMetadata('memoryId', id);
+
+ return { success: true, id };
+ });
+}
+
/**
* Search memories semantically
*/
@@ -737,6 +806,7 @@ export async function getStats() {
active: byStatus.active || 0,
archived: byStatus.archived || 0,
expired: byStatus.expired || 0,
+ pendingApproval: byStatus.pending_approval || 0,
withEmbeddings: Object.keys(embeddings.vectors).length,
byType,
byCategory,
diff --git a/server/services/memoryExtractor.js b/server/services/memoryExtractor.js
index f95c73c163..a6e8ca6950 100644
--- a/server/services/memoryExtractor.js
+++ b/server/services/memoryExtractor.js
@@ -8,6 +8,7 @@
import { createMemory } from './memory.js';
import { generateMemoryEmbedding } from './memoryEmbeddings.js';
import { cosEvents } from './cos.js';
+import * as notifications from './notifications.js';
/**
* Parse structured MEMORY blocks from agent output
@@ -265,18 +266,55 @@ export async function extractAndStoreMemories(agentId, taskId, output, task = nu
created.push(memory);
}
- // Queue medium confidence for approval (just emit event for now)
- if (mediumConfidence.length > 0) {
- console.log(`🧠 ${mediumConfidence.length} memories pending approval`);
+ // Store medium confidence memories as pending_approval
+ const pendingMemories = [];
+ for (const mem of mediumConfidence) {
+ const embedding = await generateMemoryEmbedding(mem);
+ const memory = await createMemory({
+ ...mem,
+ sourceAgentId: agentId,
+ sourceTaskId: taskId,
+ status: 'pending_approval'
+ }, embedding);
+ pendingMemories.push(memory);
+ }
+
+ if (pendingMemories.length > 0) {
+ console.log(`🧠 ${pendingMemories.length} memories pending approval`);
cosEvents.emit('memory:approval-needed', {
agentId,
taskId,
- memories: mediumConfidence.map(m => ({
+ memories: pendingMemories.map(m => ({
+ id: m.id,
type: m.type,
content: m.content.substring(0, 200),
confidence: m.confidence
}))
});
+
+ // Create notification for user
+ for (const mem of pendingMemories) {
+ const alreadyExists = await notifications.exists(
+ notifications.NOTIFICATION_TYPES.MEMORY_APPROVAL,
+ 'memoryId',
+ mem.id
+ );
+ if (!alreadyExists) {
+ await notifications.addNotification({
+ type: notifications.NOTIFICATION_TYPES.MEMORY_APPROVAL,
+ title: `Memory needs approval`,
+ description: mem.summary || mem.content.substring(0, 100),
+ priority: notifications.PRIORITY_LEVELS.MEDIUM,
+ link: '/cos/memory',
+ metadata: {
+ memoryId: mem.id,
+ memoryType: mem.type,
+ agentId,
+ taskId
+ }
+ });
+ }
+ }
}
console.log(`🧠 Extracted ${created.length} memories from agent ${agentId}`);
@@ -284,13 +322,14 @@ export async function extractAndStoreMemories(agentId, taskId, output, task = nu
agentId,
taskId,
count: created.length,
- pendingApproval: mediumConfidence.length
+ pendingApproval: pendingMemories.length
});
return {
created: created.length,
- pendingApproval: mediumConfidence.length,
- memories: created
+ pendingApproval: pendingMemories.length,
+ memories: created,
+ pendingMemories
};
}
diff --git a/server/services/notifications.js b/server/services/notifications.js
new file mode 100644
index 0000000000..dc4290dea9
--- /dev/null
+++ b/server/services/notifications.js
@@ -0,0 +1,281 @@
+/**
+ * Notifications Service
+ *
+ * Manages user task notifications for items requiring attention:
+ * - Memory approvals
+ * - CoS task approvals
+ * - Code reviews
+ * - Health issues
+ */
+
+import { readFile, writeFile, 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');
+const NOTIFICATIONS_FILE = join(DATA_DIR, 'notifications.json');
+
+// Event emitter for notification changes
+export const notificationEvents = new EventEmitter();
+
+// In-memory cache
+let notificationsCache = null;
+
+// Notification types
+export const NOTIFICATION_TYPES = {
+ MEMORY_APPROVAL: 'memory_approval',
+ TASK_APPROVAL: 'task_approval',
+ CODE_REVIEW: 'code_review',
+ HEALTH_ISSUE: 'health_issue'
+};
+
+// Priority levels
+export const PRIORITY_LEVELS = {
+ LOW: 'low',
+ MEDIUM: 'medium',
+ HIGH: 'high',
+ CRITICAL: 'critical'
+};
+
+/**
+ * Ensure data directory exists
+ */
+async function ensureDirectory() {
+ if (!existsSync(DATA_DIR)) {
+ await mkdir(DATA_DIR, { recursive: true });
+ }
+}
+
+/**
+ * Load notifications from file
+ */
+async function loadNotifications() {
+ if (notificationsCache) return notificationsCache;
+
+ await ensureDirectory();
+
+ if (!existsSync(NOTIFICATIONS_FILE)) {
+ notificationsCache = { version: 1, notifications: [] };
+ return notificationsCache;
+ }
+
+ const content = await readFile(NOTIFICATIONS_FILE, 'utf-8');
+ notificationsCache = JSON.parse(content);
+ return notificationsCache;
+}
+
+/**
+ * Save notifications to file
+ */
+async function saveNotifications(data) {
+ await ensureDirectory();
+ notificationsCache = data;
+ await writeFile(NOTIFICATIONS_FILE, JSON.stringify(data, null, 2));
+}
+
+/**
+ * Get all notifications
+ */
+export async function getNotifications(options = {}) {
+ const data = await loadNotifications();
+ let notifications = [...data.notifications];
+
+ // Filter by type
+ if (options.type) {
+ notifications = notifications.filter(n => n.type === options.type);
+ }
+
+ // Filter by read status
+ if (options.unreadOnly) {
+ notifications = notifications.filter(n => !n.read);
+ }
+
+ // Sort by timestamp descending (newest first)
+ notifications.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
+
+ // Limit
+ if (options.limit) {
+ notifications = notifications.slice(0, options.limit);
+ }
+
+ return notifications;
+}
+
+/**
+ * Get unread notification count
+ */
+export async function getUnreadCount() {
+ const data = await loadNotifications();
+ return data.notifications.filter(n => !n.read).length;
+}
+
+/**
+ * Get notification counts by type
+ */
+export async function getCountsByType() {
+ const data = await loadNotifications();
+ const counts = {
+ total: 0,
+ unread: 0,
+ byType: {}
+ };
+
+ for (const n of data.notifications) {
+ counts.total++;
+ if (!n.read) counts.unread++;
+ counts.byType[n.type] = (counts.byType[n.type] || 0) + 1;
+ }
+
+ return counts;
+}
+
+/**
+ * Add a new notification
+ */
+export async function addNotification(notification) {
+ const data = await loadNotifications();
+
+ const newNotification = {
+ id: uuidv4(),
+ type: notification.type,
+ title: notification.title,
+ description: notification.description || '',
+ priority: notification.priority || PRIORITY_LEVELS.MEDIUM,
+ timestamp: new Date().toISOString(),
+ link: notification.link || null,
+ read: false,
+ metadata: notification.metadata || {}
+ };
+
+ data.notifications.push(newNotification);
+ await saveNotifications(data);
+
+ console.log(`🔔 Notification added: ${newNotification.type} - ${newNotification.title}`);
+ notificationEvents.emit('added', newNotification);
+ notificationEvents.emit('count-changed', await getUnreadCount());
+
+ return newNotification;
+}
+
+/**
+ * Remove a notification by ID
+ */
+export async function removeNotification(id) {
+ const data = await loadNotifications();
+ const index = data.notifications.findIndex(n => n.id === id);
+
+ if (index === -1) {
+ return { success: false, error: 'Notification not found' };
+ }
+
+ const removed = data.notifications.splice(index, 1)[0];
+ await saveNotifications(data);
+
+ console.log(`🔔 Notification removed: ${id}`);
+ notificationEvents.emit('removed', { id });
+ notificationEvents.emit('count-changed', await getUnreadCount());
+
+ return { success: true, notification: removed };
+}
+
+/**
+ * Remove notifications by metadata field
+ * Useful for removing notifications when the underlying item is handled
+ */
+export async function removeByMetadata(field, value) {
+ const data = await loadNotifications();
+ const before = data.notifications.length;
+
+ data.notifications = data.notifications.filter(n => n.metadata[field] !== value);
+
+ const removed = before - data.notifications.length;
+ if (removed > 0) {
+ await saveNotifications(data);
+ console.log(`🔔 Removed ${removed} notifications with ${field}=${value}`);
+ notificationEvents.emit('count-changed', await getUnreadCount());
+ }
+
+ return { success: true, removed };
+}
+
+/**
+ * Mark a notification as read
+ */
+export async function markAsRead(id) {
+ const data = await loadNotifications();
+ const notification = data.notifications.find(n => n.id === id);
+
+ if (!notification) {
+ return { success: false, error: 'Notification not found' };
+ }
+
+ if (!notification.read) {
+ notification.read = true;
+ await saveNotifications(data);
+
+ notificationEvents.emit('updated', notification);
+ notificationEvents.emit('count-changed', await getUnreadCount());
+ }
+
+ return { success: true, notification };
+}
+
+/**
+ * Mark all notifications as read
+ */
+export async function markAllAsRead() {
+ const data = await loadNotifications();
+ let updated = 0;
+
+ for (const notification of data.notifications) {
+ if (!notification.read) {
+ notification.read = true;
+ updated++;
+ }
+ }
+
+ if (updated > 0) {
+ await saveNotifications(data);
+ notificationEvents.emit('count-changed', 0);
+ }
+
+ return { success: true, updated };
+}
+
+/**
+ * Clear all notifications
+ */
+export async function clearAll() {
+ const data = await loadNotifications();
+ const count = data.notifications.length;
+
+ data.notifications = [];
+ await saveNotifications(data);
+
+ notificationEvents.emit('cleared');
+ notificationEvents.emit('count-changed', 0);
+
+ return { success: true, cleared: count };
+}
+
+/**
+ * Check if a notification already exists (prevent duplicates)
+ */
+export async function exists(type, metadataField, metadataValue) {
+ const data = await loadNotifications();
+ return data.notifications.some(
+ n => n.type === type && n.metadata[metadataField] === metadataValue
+ );
+}
+
+/**
+ * Invalidate cache (call after external changes)
+ */
+export function invalidateCache() {
+ notificationsCache = null;
+}
diff --git a/server/services/socket.js b/server/services/socket.js
index 63facc2840..bd6d6251a0 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -5,6 +5,7 @@ import { appsEvents } from './apps.js';
import { errorEvents } from '../lib/errorHandler.js';
import { handleErrorRecovery } from './autoFixer.js';
import * as pm2Standardizer from './pm2Standardizer.js';
+import { notificationEvents } from './notifications.js';
// Store active log streams per socket
const activeStreams = new Map();
@@ -12,6 +13,8 @@ const activeStreams = new Map();
const cosSubscribers = new Set();
// Store error subscribers for auto-fix notifications
const errorSubscribers = new Set();
+// Store notification subscribers
+const notificationSubscribers = new Set();
// Store io instance for broadcasting
let ioInstance = null;
@@ -183,6 +186,17 @@ export function initSocket(io) {
socket.emit('errors:unsubscribed');
});
+ // Notification subscriptions
+ socket.on('notifications:subscribe', () => {
+ notificationSubscribers.add(socket);
+ socket.emit('notifications:subscribed');
+ });
+
+ socket.on('notifications:unsubscribe', () => {
+ notificationSubscribers.delete(socket);
+ socket.emit('notifications:unsubscribed');
+ });
+
// Handle error recovery requests (can trigger auto-fix agents)
socket.on('error:recover', async ({ code, context }) => {
console.log(`🔧 Error recovery requested: ${code}`);
@@ -205,6 +219,7 @@ export function initSocket(io) {
cleanupStream(socket.id);
cosSubscribers.delete(socket);
errorSubscribers.delete(socket);
+ notificationSubscribers.delete(socket);
});
});
@@ -219,6 +234,9 @@ export function initSocket(io) {
// Set up apps event forwarding to all clients
setupAppsEventForwarding();
+
+ // Set up notification event forwarding
+ setupNotificationEventForwarding();
}
function cleanupStream(socketId) {
@@ -311,3 +329,19 @@ function setupAppsEventForwarding() {
}
});
}
+
+// Broadcast to notification subscribers only
+function broadcastToNotifications(event, data) {
+ for (const socket of notificationSubscribers) {
+ socket.emit(event, data);
+ }
+}
+
+// Set up notification event forwarding
+function setupNotificationEventForwarding() {
+ notificationEvents.on('added', (data) => broadcastToNotifications('notifications:added', data));
+ notificationEvents.on('removed', (data) => broadcastToNotifications('notifications:removed', data));
+ notificationEvents.on('updated', (data) => broadcastToNotifications('notifications:updated', data));
+ notificationEvents.on('count-changed', (count) => broadcastToNotifications('notifications:count', count));
+ notificationEvents.on('cleared', () => broadcastToNotifications('notifications:cleared', {}));
+}