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!: date-bucketed agent archive with scalability audit fixes

Adam Eivy624382ad360d
diff --git a/.changelog/v1.0.x.md b/.changelog/v1.0.x.md
new file mode 100644
index 0000000000..0705e2d6d6
--- /dev/null
+++ b/.changelog/v1.0.x.md
@@ -0,0 +1,64 @@
+# Release v1.0.x - Changelog
+
+Released: YYYY-MM-DD
+
+## Overview
+
+Major milestone: date-bucketed agent archive with on-demand loading, plus a comprehensive scalability audit that fixed unbounded memory growth, disk waste, and I/O hot paths across the entire system.
+
+## Features
+
+### Date-bucketed agent archive
+- Completed agents now stored in `data/cos/agents/YYYY-MM-DD/agent-{id}/` directories instead of a flat structure
+- Lightweight `index.json` maps agentId to date string for O(1) lookups (~50KB vs 16MB full cache)
+- Automatic one-time migration on first startup moves all existing flat agent dirs into date buckets
+- Migration is idempotent — re-running on an already-migrated system is a no-op
+
+### On-demand agent loading in UI
+- `/api/cos/agents` now returns only running agents (fast, small payload)
+- New `/api/cos/agents/history` endpoint returns available date buckets with counts
+- New `/api/cos/agents/history/:date` endpoint returns completed agents for a specific date
+- AgentsTab auto-loads the most recent date on mount, with "Load older agents" button for previous dates
+- Search filters across all loaded agents client-side
+
+## Improvements
+
+### Scalability audit fixes
+
+**Memory**
+- In-memory state caching for `state.json` — reads from disk once, then serves from memory (eliminates ~1,440 daily disk reads)
+- Capped `liveOutputs` per agent to 500 lines (was unbounded, caused browser memory leaks)
+- Bounded `agentGateway` response cache to 1,000 entries with automatic eviction (was unbounded)
+- Added periodic cache cleanup every 5 minutes in agentGateway (was only on-demand via getStats)
+- Notifications capped at 500 entries (was unbounded)
+
+**Disk**
+- Corrupted state.json backups now auto-cleaned to keep only 3 most recent (was accumulating indefinitely — removed 756 old backups totaling ~1.5GB)
+- Agent archives pruned to 90 days on startup (was unbounded growth at ~25-50MB/month)
+- Run data directories pruned to 30 days on startup (was unbounded)
+- Task learning data auto-prunes stale task types (< 2 completions, > 30 days old)
+
+**Performance**
+- Productivity tracking now uses incremental updates on task completion instead of rescanning all agents (was O(N) full scan on every completion)
+- Weekly digest loads only relevant date buckets instead of all agents
+- `getAgentsByDate()` batches file reads in chunks of 50 (was firing hundreds of concurrent reads)
+- Event scheduler history uses push+splice instead of unshift+pop (faster for large arrays)
+
+### Agent feedback on archived agents
+- Feedback submission now works for agents that have been archived from state.json to disk
+- Previously, feedback only worked for agents still in state — now uses index to locate disk metadata
+
+### Zombie cleanup date bucketing
+- Zombie agents detected during cleanup are now properly moved to date buckets (not left in flat dirs)
+
+## Bug Fixes
+
+- Fixed crash in `getStatus()` — was calling deleted `loadCompletedAgentCache()` function after refactor
+
+## Migration Notes
+
+- On first startup after upgrade, the server will automatically migrate all ~2,000+ agent directories into date-bucketed structure
+- Migration logs progress: `Migrated N agents into date buckets (M unique dates)`
+- No manual action required — migration is fully automatic and idempotent
+- The `index.json` file is created during migration and kept in sync during normal operations
+- Agent archives older than 90 days are automatically pruned on startup
diff --git a/client/package-lock.json b/client/package-lock.json
index 79a2216efc..3e3a93c145 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "portos-client",
- "version": "0.9.3",
+ "version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos-client",
- "version": "0.9.3",
+ "version": "1.0.0",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
diff --git a/client/package.json b/client/package.json
index 86110cef7f..f88e35083b 100644
--- a/client/package.json
+++ b/client/package.json
@@ -1,6 +1,6 @@
{
"name": "portos-client",
- "version": "0.23.1",
+ "version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index aac2bf6936..0998977d02 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -1,23 +1,59 @@
-import { useState, useEffect, useMemo } from 'react';
-import { Trash2, Search, X } from 'lucide-react';
+import { useState, useEffect, useMemo, useCallback } from 'react';
+import { Trash2, Search, X, ChevronDown } from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../../services/api';
import AgentCard from './AgentCard';
import ResumeAgentModal from './ResumeAgentModal';
-const PAGE_SIZE = 50;
-
export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, apps }) {
const [resumingAgent, setResumingAgent] = useState(null);
const [durations, setDurations] = useState(null);
const [searchQuery, setSearchQuery] = useState('');
- const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
+
+ // Date-based lazy loading for completed agents
+ const [dateBuckets, setDateBuckets] = useState([]); // [{ date, count }, ...]
+ const [loadedAgents, setLoadedAgents] = useState([]); // agents loaded so far
+ const [loadedDates, setLoadedDates] = useState(new Set()); // dates already fetched
+ const [loadingMore, setLoadingMore] = useState(false);
// Fetch duration estimates for progress indicators
useEffect(() => {
api.getCosLearningDurations().then(setDurations).catch(() => {});
}, []);
+ // Fetch date buckets on mount and auto-load the most recent date
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ const result = await api.getCosAgentDates().catch(() => ({ dates: [] }));
+ if (cancelled) return;
+ const dates = result.dates || [];
+ setDateBuckets(dates);
+
+ // Auto-load the most recent date
+ if (dates.length > 0) {
+ const firstDate = dates[0].date;
+ const agents = await api.getCosAgentsByDate(firstDate).catch(() => []);
+ if (cancelled) return;
+ setLoadedAgents(agents);
+ setLoadedDates(new Set([firstDate]));
+ }
+ })();
+ return () => { cancelled = true; };
+ }, []);
+
+ const handleLoadMore = useCallback(async () => {
+ // Find next unloaded date
+ const nextDate = dateBuckets.find(d => !loadedDates.has(d.date));
+ if (!nextDate) return;
+
+ setLoadingMore(true);
+ const agents = await api.getCosAgentsByDate(nextDate.date).catch(() => []);
+ setLoadedAgents(prev => [...prev, ...agents]);
+ setLoadedDates(prev => new Set([...prev, nextDate.date]));
+ setLoadingMore(false);
+ }, [dateBuckets, loadedDates]);
+
const handleKill = async (agentId) => {
await api.killCosAgent(agentId).catch(err => toast.error(err.message));
toast.success('Agent force killed');
@@ -26,6 +62,12 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
const handleDelete = async (agentId) => {
await api.deleteCosAgent(agentId).catch(err => toast.error(err.message));
+ setLoadedAgents(prev => prev.filter(a => a.id !== agentId));
+ setDateBuckets(prev => prev.map(d => {
+ const agent = loadedAgents.find(a => a.id === agentId);
+ if (agent?.completedAt?.startsWith(d.date)) return { ...d, count: Math.max(0, d.count - 1) };
+ return d;
+ }).filter(d => d.count > 0));
toast.success('Agent removed');
onRefresh();
};
@@ -53,32 +95,57 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
const handleClearCompleted = async () => {
await api.clearCompletedCosAgents().catch(err => toast.error(err.message));
+ setLoadedAgents([]);
+ setLoadedDates(new Set());
+ setDateBuckets([]);
toast.success('Cleared completed agents');
onRefresh();
};
+ // Running agents come from props (real-time via parent socket updates)
const runningAgents = agents.filter(a => a.status === 'running');
- // Sort completed agents by completion time (most recent first)
- const completedAgents = agents
- .filter(a => a.status === 'completed')
- .sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));
+ // Completed agents still in state (recently completed, not yet archived)
+ const recentCompleted = agents.filter(a => a.status === 'completed');
+ // Merge recent completed (from state) with loaded (from disk), deduplicate
+ const allCompleted = useMemo(() => {
+ const seen = new Set();
+ const merged = [];
+ // Recent state-based agents first (freshest data)
+ for (const a of recentCompleted) {
+ if (!seen.has(a.id)) { seen.add(a.id); merged.push(a); }
+ }
+ // Then disk-loaded agents
+ for (const a of loadedAgents) {
+ if (!seen.has(a.id)) { seen.add(a.id); merged.push(a); }
+ }
+ return merged.sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));
+ }, [recentCompleted, loadedAgents]);
- const filteredCompletedAgents = useMemo(() => {
+ const totalCount = useMemo(() => {
+ const indexTotal = dateBuckets.reduce((sum, d) => sum + d.count, 0);
+ // Add any recent completed agents from state that may not yet be indexed
+ const stateOnlyCount = recentCompleted.filter(a =>
+ !loadedAgents.some(la => la.id === a.id)
+ ).length;
+ return indexTotal + stateOnlyCount;
+ }, [dateBuckets, recentCompleted, loadedAgents]);
+
+ const filteredCompleted = useMemo(() => {
const q = searchQuery.trim().toLowerCase();
- if (!q) return completedAgents;
- return completedAgents.filter(a => {
+ if (!q) return allCompleted;
+ return allCompleted.filter(a => {
const description = (a.metadata?.taskDescription || '').toLowerCase();
const model = (a.metadata?.model || '').toLowerCase();
const id = (a.id || '').toLowerCase();
const error = (a.result?.error || '').toLowerCase();
return description.includes(q) || model.includes(q) || id.includes(q) || error.includes(q);
});
- }, [completedAgents, searchQuery]);
+ }, [allCompleted, searchQuery]);
- // Reset visible count when search changes
- useEffect(() => {
- setVisibleCount(PAGE_SIZE);
- }, [searchQuery]);
+ const hasMoreDates = dateBuckets.some(d => !loadedDates.has(d.date));
+ const remainingCount = dateBuckets
+ .filter(d => !loadedDates.has(d.date))
+ .reduce((sum, d) => sum + d.count, 0);
return (
<div className="space-y-6">
@@ -112,13 +179,13 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
</div>
{/* Completed Agents */}
- {completedAgents.length > 0 && (
+ {(totalCount > 0 || recentCompleted.length > 0) && (
<div>
<div className="flex items-center justify-between mb-3">
<h3 className="text-lg font-semibold text-white">
Completed Agents
<span className="text-sm text-gray-500 font-normal ml-2">
- ({completedAgents.length} total)
+ ({totalCount} total)
</span>
</h3>
<button
@@ -138,7 +205,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
- placeholder="Search completed agents..."
+ placeholder="Search loaded agents..."
className="w-full bg-port-card border border-port-border rounded-lg pl-9 pr-4 py-2 min-h-[40px] text-white text-sm placeholder-gray-500 focus:border-port-accent outline-none"
/>
</div>
@@ -154,24 +221,37 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
</div>
{searchQuery && (
<div className="text-xs text-gray-500 mb-2">
- {filteredCompletedAgents.length} of {completedAgents.length} agents match
+ {filteredCompleted.length} of {allCompleted.length} loaded agents match
</div>
)}
<div className="space-y-2">
- {filteredCompletedAgents.slice(0, visibleCount).map(agent => (
+ {filteredCompleted.map(agent => (
<AgentCard key={agent.id} agent={agent} completed onDelete={handleDelete} onResume={handleResumeClick} onFeedbackChange={onRefresh} />
))}
- {filteredCompletedAgents.length > visibleCount && (
+ {!searchQuery && hasMoreDates && (
<button
- onClick={() => setVisibleCount(prev => prev + PAGE_SIZE)}
- className="w-full py-2 text-sm text-port-accent hover:text-white bg-port-card border border-port-border rounded-lg transition-colors"
+ onClick={handleLoadMore}
+ disabled={loadingMore}
+ className="w-full py-2 text-sm text-port-accent hover:text-white bg-port-card border border-port-border rounded-lg transition-colors flex items-center justify-center gap-1 disabled:opacity-50"
>
- Show more ({filteredCompletedAgents.length - visibleCount} remaining)
+ {loadingMore ? (
+ 'Loading...'
+ ) : (
+ <>
+ <ChevronDown size={14} />
+ Load older agents ({remainingCount} remaining)
+ </>
+ )}
</button>
)}
- {searchQuery && filteredCompletedAgents.length === 0 && (
+ {searchQuery && filteredCompleted.length === 0 && (
<div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">
- No completed agents match "{searchQuery}"
+ No loaded agents match "{searchQuery}"
+ {hasMoreDates && (
+ <div className="mt-2 text-xs">
+ {remainingCount} agents in older dates not yet loaded
+ </div>
+ )}
</div>
)}
</div>
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index d7e64cc7e7..69c4f6be11 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -189,13 +189,11 @@ export default function ChiefOfStaff() {
socket.on('cos:agent:output', (data) => {
if (data?.agentId && data?.line) {
- setLiveOutputs(prev => ({
- ...prev,
- [data.agentId]: [
- ...(prev[data.agentId] || []),
- { line: data.line, timestamp: Date.now() }
- ]
- }));
+ setLiveOutputs(prev => {
+ const existing = prev[data.agentId] || [];
+ const updated = [...existing, { line: data.line, timestamp: Date.now() }];
+ return { ...prev, [data.agentId]: updated.length > 500 ? updated.slice(-500) : updated };
+ });
}
});
diff --git a/client/src/services/api.js b/client/src/services/api.js
index a9703c0c00..0abe2d72fa 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -553,6 +553,8 @@ export const forceCosEvaluate = () => request('/cos/evaluate', { method: 'POST'
export const getCosHealth = () => request('/cos/health');
export const forceHealthCheck = () => request('/cos/health/check', { method: 'POST' });
export const getCosAgents = () => request('/cos/agents');
+export const getCosAgentDates = () => request('/cos/agents/history');
+export const getCosAgentsByDate = (date) => request(`/cos/agents/history/${date}`);
export const getCosAgent = (id) => request(`/cos/agents/${id}`);
export const terminateCosAgent = (id) => request(`/cos/agents/${id}/terminate`, { method: 'POST' });
export const killCosAgent = (id) => request(`/cos/agents/${id}/kill`, { method: 'POST' });
diff --git a/package-lock.json b/package-lock.json
index a9a083454d..285463939d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "portos",
- "version": "0.27.0",
+ "version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos",
- "version": "0.27.0",
+ "version": "1.0.0",
"license": "MIT",
"workspaces": [
"packages/*",
@@ -29,7 +29,7 @@
},
"client": {
"name": "portos-client",
- "version": "0.23.2",
+ "version": "1.0.0",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
@@ -9242,7 +9242,7 @@
},
"server": {
"name": "portos-server",
- "version": "0.23.1",
+ "version": "1.0.0",
"dependencies": {
"axios": "^1.7.9",
"cors": "^2.8.5",
diff --git a/package.json b/package.json
index db9a336a37..5f67bd060f 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "portos",
- "version": "0.27.0",
+ "version": "1.0.0",
"private": true,
"description": "Local dev machine App OS portal",
"author": "Adam Eivy (@antic|@atomantic)",
diff --git a/server/package-lock.json b/server/package-lock.json
index 1d1941dd04..b4b700b8a3 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "portos-server",
- "version": "0.18.8",
+ "version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos-server",
- "version": "0.18.8",
+ "version": "1.0.0",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/server/package.json b/server/package.json
index 5167fb9079..a52ba0cb2d 100644
--- a/server/package.json
+++ b/server/package.json
@@ -1,6 +1,6 @@
{
"name": "portos-server",
- "version": "0.23.1",
+ "version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
diff --git a/server/routes/cos.js b/server/routes/cos.js
index 9af0833580..f94aab0faa 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -208,14 +208,29 @@ router.post('/health/check', asyncHandler(async (req, res) => {
res.json(result);
}));
-// GET /api/cos/agents - Get all agents (auto-cleans zombies)
+// GET /api/cos/agents - Get running agents (auto-cleans zombies)
router.get('/agents', asyncHandler(async (req, res) => {
- // Cleanup zombie agents before returning list
await cos.cleanupZombieAgents();
const agents = await cos.getAgents();
res.json(agents);
}));
+// GET /api/cos/agents/history - Get available date buckets with counts
+router.get('/agents/history', asyncHandler(async (req, res) => {
+ const dates = await cos.getAgentDates();
+ res.json({ dates });
+}));
+
+// GET /api/cos/agents/history/:date - Get completed agents for a date
+router.get('/agents/history/:date', asyncHandler(async (req, res) => {
+ const { date } = req.params;
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
+ throw new ServerError('Invalid date format (expected YYYY-MM-DD)', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const agents = await cos.getAgentsByDate(date);
+ res.json(agents);
+}));
+
// GET /api/cos/agents/:id - Get agent by ID
router.get('/agents/:id', asyncHandler(async (req, res) => {
const agent = await cos.getAgent(req.params.id);
diff --git a/server/services/agentGateway.js b/server/services/agentGateway.js
index 8fb251ed68..866ef20f29 100644
--- a/server/services/agentGateway.js
+++ b/server/services/agentGateway.js
@@ -10,9 +10,10 @@ import { cosEvents } from './cosEvents.js'
// Request deduplication cache
const pendingRequests = new Map()
-// Response cache with TTL
+// Response cache with TTL and size cap
const responseCache = new Map()
const CACHE_TTL_MS = 10 * 60 * 1000 // 10 minutes
+const MAX_CACHE_SIZE = 1000
// Request history for analytics
const requestHistory = []
@@ -50,6 +51,9 @@ function cleanExpiredCache() {
}
}
+// Run cache cleanup every 5 minutes
+setInterval(cleanExpiredCache, 5 * 60 * 1000)
+
/**
* Route a request through the gateway
* Handles deduplication and caching
@@ -97,8 +101,13 @@ async function routeRequest(type, params, handler, options = {}) {
try {
result = await handler(params)
- // Cache successful response
+ // Cache successful response (evict oldest if at capacity)
if (cacheable && result) {
+ if (responseCache.size >= MAX_CACHE_SIZE) {
+ // Evict oldest entry (first key in insertion order)
+ const oldest = responseCache.keys().next().value
+ responseCache.delete(oldest)
+ }
responseCache.set(cacheKey, {
response: result,
expiresAt: now + ttlMs,
diff --git a/server/services/cos.js b/server/services/cos.js
index afd0c78dfa..636f7bcf7f 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -68,86 +68,191 @@ export function emitLog(level, message, data = {}, prefix = '') {
// In-memory daemon state
let daemonRunning = false;
-// In-memory cache of completed agents loaded from disk metadata files
-// Keyed by agentId, lazy-loaded on first getAgents() call
-let completedAgentCache = null;
-
-// Load completed agent metadata from disk into the cache.
-// Reads all data/cos/agents/{id}/metadata.json files.
-// Handles legacy formats (agentId instead of id, missing status) and
-// reconstructs minimal metadata for directories with no metadata.json.
-// Only called once (lazy init), then kept in sync via completeAgent/deleteAgent.
-async function loadCompletedAgentCache() {
- if (completedAgentCache) return completedAgentCache;
+// Lightweight index mapping agentId → YYYY-MM-DD date bucket (~50KB vs 16MB full cache)
+// Lazy-loaded from data/cos/agents/index.json on first access
+let agentIndex = null;
+const INDEX_FILE = join(AGENTS_DIR, 'index.json');
+
+// Load agent index from disk (lazy init)
+async function loadAgentIndex() {
+ if (agentIndex) return agentIndex;
+
+ if (!existsSync(AGENTS_DIR)) {
+ await mkdir(AGENTS_DIR, { recursive: true });
+ }
+
+ if (existsSync(INDEX_FILE)) {
+ const content = await readFile(INDEX_FILE, 'utf-8').catch(() => '{}');
+ const parsed = safeJSONParse(content, {});
+ agentIndex = new Map(Object.entries(parsed));
+ console.log(`📂 Loaded agent index: ${agentIndex.size} entries`);
+ } else {
+ // No index yet — run migration from flat dirs to date buckets
+ agentIndex = await migrateAgentsToDateBuckets();
+ }
+
+ return agentIndex;
+}
+
+// Persist agent index to disk
+async function saveAgentIndex() {
+ if (!agentIndex) return;
+ const obj = Object.fromEntries(agentIndex);
+ await writeFile(INDEX_FILE, JSON.stringify(obj)).catch(err => {
+ console.error(`❌ Failed to save agent index: ${err.message}`);
+ });
+}
+
+// Resolve the correct directory for an agent (running = flat, completed = date bucket)
+function getAgentDir(agentId, dateString) {
+ if (dateString) return join(AGENTS_DIR, dateString, agentId);
+ // Check index for date bucket
+ const date = agentIndex?.get(agentId);
+ if (date) return join(AGENTS_DIR, date, agentId);
+ // Fallback to flat dir (running agents or pre-migration)
+ return join(AGENTS_DIR, agentId);
+}
+
+// Migrate flat agent-* directories into YYYY-MM-DD date buckets
+// Runs once when index.json doesn't exist. Idempotent — no-op if already migrated.
+async function migrateAgentsToDateBuckets() {
+ const index = new Map();
if (!existsSync(AGENTS_DIR)) {
- completedAgentCache = new Map();
- return completedAgentCache;
+ await mkdir(AGENTS_DIR, { recursive: true });
+ await writeFile(INDEX_FILE, '{}');
+ console.log('📂 Created empty agent index (no agents to migrate)');
+ return index;
}
- // Build into a local Map — only assign to module-level cache on success
- // so a failed load can be retried on the next call
- const cache = new Map();
const entries = await readdir(AGENTS_DIR, { withFileTypes: true });
- let recovered = 0;
+
+ // Also scan existing date-bucket dirs to include them in the index
+ const dateDirPattern = /^\d{4}-\d{2}-\d{2}$/;
+ for (const entry of entries) {
+ if (!entry.isDirectory() || !dateDirPattern.test(entry.name)) continue;
+ const dateStr = entry.name;
+ const dateDir = join(AGENTS_DIR, dateStr);
+ const agentDirs = await readdir(dateDir, { withFileTypes: true }).catch(() => []);
+ for (const agentEntry of agentDirs) {
+ if (agentEntry.isDirectory() && agentEntry.name.startsWith('agent-')) {
+ index.set(agentEntry.name, dateStr);
+ }
+ }
+ }
+
+ // Find flat agent-* dirs that need migration
+ const flatAgentDirs = entries.filter(e => e.isDirectory() && e.name.startsWith('agent-'));
+
+ if (flatAgentDirs.length === 0) {
+ await writeFile(INDEX_FILE, JSON.stringify(Object.fromEntries(index)));
+ console.log(`📂 Agent index built: ${index.size} entries (no flat dirs to migrate)`);
+ return index;
+ }
+
+ console.log(`📦 Migrating ${flatAgentDirs.length} agents into date buckets...`);
+ let migrated = 0;
let skipped = 0;
- const metadataReads = entries
- .filter(e => e.isDirectory() && e.name.startsWith('agent-'))
- .map(async (entry) => {
- const agentId = entry.name;
- const agentDir = join(AGENTS_DIR, agentId);
- const metaPath = join(agentDir, 'metadata.json');
- if (existsSync(metaPath)) {
- const content = await readFile(metaPath, 'utf-8').catch(() => null);
- if (!content) { skipped++; return; }
- let raw;
- try { raw = JSON.parse(content); } catch { skipped++; return; }
-
- // Normalize legacy format: agentId → id, missing status → completed
- const id = raw.id || raw.agentId || agentId;
- const status = raw.status || 'completed';
- if (status !== 'running') {
- const { output, ...rest } = raw;
- cache.set(id, { ...rest, id, status });
+ for (const entry of flatAgentDirs) {
+ const agentId = entry.name;
+ const agentDir = join(AGENTS_DIR, agentId);
+ const metaPath = join(agentDir, 'metadata.json');
+
+ let dateStr = null;
+
+ // Try to get date from metadata
+ if (existsSync(metaPath)) {
+ const content = await readFile(metaPath, 'utf-8').catch(() => null);
+ if (content) {
+ const raw = safeJSONParse(content, null);
+ if (raw?.completedAt) {
+ dateStr = raw.completedAt.slice(0, 10); // YYYY-MM-DD
}
- return;
}
+ }
- // No metadata.json — reconstruct from directory contents
- const promptPath = join(agentDir, 'prompt.txt');
- const outputPath = join(agentDir, 'output.txt');
- const hasPrompt = existsSync(promptPath);
- const hasOutput = existsSync(outputPath);
-
- // Use file modification time as best-guess completedAt
+ // Fallback: directory mtime
+ if (!dateStr) {
const dirStat = await stat(agentDir).catch(() => null);
- const completedAt = dirStat?.mtime?.toISOString() ?? new Date().toISOString();
+ if (dirStat?.mtime) {
+ dateStr = dirStat.mtime.toISOString().slice(0, 10);
+ }
+ }
- const reconstructed = {
- id: agentId,
- status: 'completed',
- completedAt,
- result: { success: hasOutput, recovered: true },
- metadata: { description: hasPrompt ? 'Recovered from disk (no metadata)' : 'Recovered (prompt-only)' }
- };
+ if (!dateStr) {
+ console.log(`⚠️ Cannot determine date for ${agentId}, skipping`);
+ skipped++;
+ continue;
+ }
+
+ // Move into date bucket
+ const bucketDir = join(AGENTS_DIR, dateStr);
+ await mkdir(bucketDir, { recursive: true });
+ const targetDir = join(bucketDir, agentId);
+
+ // If target already exists (partial previous migration), skip
+ if (existsSync(targetDir)) {
+ index.set(agentId, dateStr);
+ migrated++;
+ continue;
+ }
- // Persist the reconstructed metadata so future loads are fast
- await writeFile(metaPath, JSON.stringify(reconstructed, null, 2)).catch(() => {});
- cache.set(agentId, reconstructed);
- recovered++;
+ await rename(agentDir, targetDir).catch(async (err) => {
+ // rename can fail across filesystems — fall back to copy+delete
+ console.log(`⚠️ Rename failed for ${agentId}, using copy: ${err.message}`);
+ await mkdir(targetDir, { recursive: true });
+ const files = await readdir(agentDir);
+ for (const file of files) {
+ const content = await readFile(join(agentDir, file));
+ await writeFile(join(targetDir, file), content);
+ }
+ await rm(agentDir, { recursive: true });
});
- // Use allSettled so individual file errors don't abort the entire load
- await Promise.allSettled(metadataReads);
+ index.set(agentId, dateStr);
+ migrated++;
+ }
+
+ // Persist index
+ await writeFile(INDEX_FILE, JSON.stringify(Object.fromEntries(index)));
+ const uniqueDates = new Set(index.values()).size;
+ const parts = [`📦 Migrated ${migrated} agents into date buckets (${uniqueDates} unique dates)`];
+ if (skipped > 0) parts.push(`skipped ${skipped} undatable`);
+ console.log(parts.join(', '));
+
+ return index;
+}
+
+// Prune agent archive date buckets older than retentionDays (default 90).
+// Removes directories + their index entries. Runs after migration on startup.
+async function pruneOldAgentArchives(retentionDays = 90) {
+ const idx = await loadAgentIndex();
+ if (!idx || idx.size === 0) return;
+
+ const cutoff = new Date();
+ cutoff.setDate(cutoff.getDate() - retentionDays);
+ const cutoffStr = cutoff.toISOString().slice(0, 10);
+
+ const dateDirPattern = /^\d{4}-\d{2}-\d{2}$/;
+ const entries = await readdir(AGENTS_DIR, { withFileTypes: true }).catch(() => []);
+ const oldDates = entries
+ .filter(e => e.isDirectory() && dateDirPattern.test(e.name) && e.name < cutoffStr)
+ .map(e => e.name);
+
+ if (oldDates.length === 0) return;
+
+ let pruned = 0;
+ for (const dateStr of oldDates) {
+ await rm(join(AGENTS_DIR, dateStr), { recursive: true }).catch(() => {});
+ // Remove index entries for this date
+ for (const [agentId, date] of idx.entries()) {
+ if (date === dateStr) { idx.delete(agentId); pruned++; }
+ }
+ }
- // Only assign to module-level cache after successful build
- completedAgentCache = cache;
- const parts = [`📂 Loaded ${cache.size} completed agents from disk`];
- if (recovered > 0) parts.push(`recovered ${recovered} missing metadata`);
- if (skipped > 0) parts.push(`skipped ${skipped} unreadable`);
- console.log(parts.length > 1 ? `${parts[0]} (${parts.slice(1).join(', ')})` : parts[0]);
- return completedAgentCache;
+ await saveAgentIndex();
+ console.log(`🗑️ Pruned ${pruned} archived agents older than ${retentionDays} days (${oldDates.length} date buckets)`);
}
// Mutex lock for state operations to prevent race conditions
@@ -243,44 +348,69 @@ function isValidJSON(str) {
return true;
}
+// In-memory state cache — avoids re-reading state.json from disk on every call.
+// All mutations go through withStateLock, so the cache stays consistent.
+let stateCache = null;
+
/**
- * Load CoS state
+ * Load CoS state — returns cached copy if available, reads disk only on first call
*/
async function loadState() {
+ if (stateCache) return stateCache;
+
await ensureDirectories();
if (!existsSync(STATE_FILE)) {
- return { ...DEFAULT_STATE };
+ stateCache = { ...DEFAULT_STATE };
+ return stateCache;
}
const content = await readFile(STATE_FILE, 'utf-8');
if (!isValidJSON(content)) {
console.log(`⚠️ Corrupted or empty state file at ${STATE_FILE}, returning default state`);
- // Backup the corrupted file for debugging
const backupPath = `${STATE_FILE}.corrupted.${Date.now()}`;
await writeFile(backupPath, content).catch(() => {});
console.log(`📝 Backed up corrupted state to ${backupPath}`);
- return { ...DEFAULT_STATE };
+ // Cleanup old corrupted backups (keep only 3 most recent)
+ const cosDir = dirname(STATE_FILE);
+ const files = await readdir(cosDir).catch(() => []);
+ const corrupted = files
+ .filter(f => f.startsWith('state.json.corrupted.'))
+ .sort()
+ .reverse();
+ for (const old of corrupted.slice(3)) {
+ await rm(join(cosDir, old)).catch(() => {});
+ }
+ if (corrupted.length > 3) {
+ console.log(`🗑️ Cleaned up ${corrupted.length - 3} old corrupted state backups`);
+ }
+ stateCache = { ...DEFAULT_STATE };
+ return stateCache;
}
const state = safeJSONParse(content, null, { logError: true, context: 'CoS state' });
- if (!state) return { ...DEFAULT_STATE };
+ if (!state) {
+ stateCache = { ...DEFAULT_STATE };
+ return stateCache;
+ }
// Merge with defaults to ensure all fields exist
- return {
+ stateCache = {
...DEFAULT_STATE,
...state,
config: { ...DEFAULT_CONFIG, ...state.config },
stats: { ...DEFAULT_STATE.stats, ...state.stats }
};
+ return stateCache;
}
/**
- * Save CoS state
+ * Save CoS state — writes to disk and updates in-memory cache
*/
async function saveState(state) {
await ensureDirectories();
+ stateCache = state;
const tmpFile = `${STATE_FILE}.tmp`;
await writeFile(tmpFile, JSON.stringify(state, null, 2));
await rename(tmpFile, STATE_FILE);
@@ -292,18 +422,15 @@ async function saveState(state) {
export async function getStatus() {
const state = await loadState();
const provider = await getActiveProvider();
- const cache = await loadCompletedAgentCache();
+ const idx = await loadAgentIndex();
// Count active agents from state
const activeAgents = Object.values(state.agents).filter(a => a.status === 'running').length;
- // Derive tasksCompleted from actual completed agents on disk + state,
+ // Derive tasksCompleted from index (all completed agents on disk) + state,
// since state.stats.tasksCompleted can drift after state resets
- const completedIds = new Set(cache.keys());
- for (const [id, agent] of Object.entries(state.agents)) {
- if (agent.status === 'completed') completedIds.add(id);
- }
- const tasksCompleted = Math.max(state.stats.tasksCompleted, completedIds.size);
+ const stateCompleted = Object.values(state.agents).filter(a => a.status === 'completed').length;
+ const tasksCompleted = Math.max(state.stats.tasksCompleted, idx.size + stateCompleted);
return {
running: daemonRunning,
@@ -375,6 +502,9 @@ export async function start() {
emitLog('info', `📦 Startup: archived ${archived} stale agent(s) from state`);
}
+ // Prune agent archives older than 90 days
+ await pruneOldAgentArchives(90).catch(() => {});
+
// Health check + orphan cleanup (15 min)
scheduleEvent({
id: 'cos-health-check',
@@ -2439,22 +2569,39 @@ export async function completeAgent(agentId, result = {}) {
cosEvents.emit('agent:completed', state.agents[agentId]);
cosEvents.emit('agent:updated', state.agents[agentId]);
- // Save agent data to file for history
- const agentDir = join(AGENTS_DIR, agentId);
- if (!existsSync(agentDir)) {
- await mkdir(agentDir, { recursive: true });
- }
- await writeFile(
- join(agentDir, 'metadata.json'),
- JSON.stringify(state.agents[agentId], null, 2)
- );
+ // Determine date bucket from completedAt
+ const dateStr = state.agents[agentId].completedAt.slice(0, 10);
+ const bucketDir = join(AGENTS_DIR, dateStr);
+ await mkdir(bucketDir, { recursive: true });
- // Update in-memory cache so completed agents survive state resets
- if (completedAgentCache) {
- const { output, ...agentWithoutOutput } = state.agents[agentId];
- completedAgentCache.set(agentId, agentWithoutOutput);
+ // Write metadata to flat dir first (may already have output.txt/prompt.txt there)
+ const flatDir = join(AGENTS_DIR, agentId);
+ if (!existsSync(flatDir)) {
+ await mkdir(flatDir, { recursive: true });
+ }
+ const { output: _output, ...agentWithoutOutput } = state.agents[agentId];
+ await writeFile(join(flatDir, 'metadata.json'), JSON.stringify(agentWithoutOutput, null, 2));
+
+ // Move entire agent dir into date bucket (atomic on same filesystem)
+ const targetDir = join(bucketDir, agentId);
+ if (!existsSync(targetDir)) {
+ await rename(flatDir, targetDir).catch(async () => {
+ // Fallback for cross-filesystem: copy files then remove
+ await mkdir(targetDir, { recursive: true });
+ const files = await readdir(flatDir);
+ for (const file of files) {
+ const content = await readFile(join(flatDir, file));
+ await writeFile(join(targetDir, file), content);
+ }
+ await rm(flatDir, { recursive: true });
+ });
}
+ // Update index
+ const idx = await loadAgentIndex();
+ idx.set(agentId, dateStr);
+ await saveAgentIndex();
+
return state.agents[agentId];
});
}
@@ -2492,22 +2639,56 @@ export async function appendAgentOutput(agentId, line) {
}
/**
- * Get all agents — merges in-memory state (running agents) with
- * persisted completed agents from disk metadata files.
+ * Get running agents from state (completed agents loaded on-demand via getAgentsByDate)
*/
export async function getAgents() {
const state = await loadState();
- const cache = await loadCompletedAgentCache();
+ return Object.values(state.agents);
+}
- // Start with all agents from state (running + any completed still in state)
- const merged = { ...Object.fromEntries([...cache.entries()]) };
+/**
+ * Get available agent date buckets with counts, sorted descending
+ */
+export async function getAgentDates() {
+ const idx = await loadAgentIndex();
+ const dateCounts = {};
+ for (const date of idx.values()) {
+ dateCounts[date] = (dateCounts[date] || 0) + 1;
+ }
+ return Object.entries(dateCounts)
+ .map(([date, count]) => ({ date, count }))
+ .sort((a, b) => b.date.localeCompare(a.date));
+}
- // State agents override cache (they have fresher data for running agents)
- for (const [id, agent] of Object.entries(state.agents)) {
- merged[id] = agent;
+/**
+ * Get completed agents for a specific date bucket
+ */
+export async function getAgentsByDate(date) {
+ const dateDir = join(AGENTS_DIR, date);
+ if (!existsSync(dateDir)) return [];
+
+ const entries = await readdir(dateDir, { withFileTypes: true });
+ const agentDirs = entries.filter(e => e.isDirectory() && e.name.startsWith('agent-'));
+ const agents = [];
+
+ // Batch reads in chunks of 50 to avoid fd exhaustion on large date buckets
+ const BATCH_SIZE = 50;
+ for (let i = 0; i < agentDirs.length; i += BATCH_SIZE) {
+ const batch = agentDirs.slice(i, i + BATCH_SIZE);
+ const reads = batch.map(async (entry) => {
+ const metaPath = join(dateDir, entry.name, 'metadata.json');
+ const content = await readFile(metaPath, 'utf-8').catch(() => null);
+ if (!content) return;
+ const raw = safeJSONParse(content, null);
+ if (!raw) return;
+ const id = raw.id || raw.agentId || entry.name;
+ const { output, ...rest } = raw;
+ agents.push({ ...rest, id, status: raw.status || 'completed' });
+ });
+ await Promise.allSettled(reads);
}
- return Object.values(merged);
+ return agents.sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));
}
/**
@@ -2517,19 +2698,30 @@ export async function getAgent(agentId) {
const state = await loadState();
let agent = state.agents[agentId];
- // Fall back to disk metadata if not in state
+ // Fall back to disk metadata via index if not in state
if (!agent) {
- const cache = await loadCompletedAgentCache();
- agent = cache.get(agentId) ?? null;
+ const idx = await loadAgentIndex();
+ const dateStr = idx.get(agentId);
+ if (dateStr) {
+ const metaPath = join(AGENTS_DIR, dateStr, agentId, 'metadata.json');
+ const content = await readFile(metaPath, 'utf-8').catch(() => null);
+ if (content) {
+ const raw = safeJSONParse(content, null);
+ if (raw) {
+ const { output, ...rest } = raw;
+ agent = { ...rest, id: raw.id || raw.agentId || agentId, status: raw.status || 'completed' };
+ }
+ }
+ }
}
if (!agent) return null;
// For completed agents, read full output from file
if (agent.status === 'completed') {
- const outputFile = join(AGENTS_DIR, agentId, 'output.txt');
+ const agentDir = getAgentDir(agentId);
+ const outputFile = join(agentDir, 'output.txt');
if (existsSync(outputFile)) {
const fullOutput = await readFile(outputFile, 'utf-8');
- // Convert string to output array format
const lines = fullOutput.split('\n').filter(line => line.trim());
return {
...agent,
@@ -2635,16 +2827,38 @@ export async function cleanupZombieAgents() {
if (cleaned.length > 0) {
await saveState(state);
- // Persist zombie-cleaned agents to disk and update cache so they survive state resets
+ // Persist zombie-cleaned agents to date-bucketed dirs and update index
+ const idx = await loadAgentIndex();
for (const agentId of cleaned) {
- const agentDir = join(AGENTS_DIR, agentId);
- await mkdir(agentDir, { recursive: true });
- const { output, ...agentWithoutOutput } = state.agents[agentId];
- await writeFile(join(agentDir, 'metadata.json'), JSON.stringify(agentWithoutOutput, null, 2)).catch(() => {});
- if (completedAgentCache) {
- completedAgentCache.set(agentId, agentWithoutOutput);
+ const agent = state.agents[agentId];
+ const dateStr = agent.completedAt.slice(0, 10);
+ const bucketDir = join(AGENTS_DIR, dateStr);
+ await mkdir(bucketDir, { recursive: true });
+
+ const flatDir = join(AGENTS_DIR, agentId);
+ const { output, ...agentWithoutOutput } = agent;
+
+ // Ensure metadata is written before move
+ if (!existsSync(flatDir)) await mkdir(flatDir, { recursive: true });
+ await writeFile(join(flatDir, 'metadata.json'), JSON.stringify(agentWithoutOutput, null, 2)).catch(() => {});
+
+ // Move to date bucket
+ const targetDir = join(bucketDir, agentId);
+ if (!existsSync(targetDir)) {
+ await rename(flatDir, targetDir).catch(async () => {
+ await mkdir(targetDir, { recursive: true });
+ const files = await readdir(flatDir);
+ for (const file of files) {
+ const content = await readFile(join(flatDir, file));
+ await writeFile(join(targetDir, file), content);
+ }
+ await rm(flatDir, { recursive: true });
+ });
}
+
+ idx.set(agentId, dateStr);
}
+ await saveAgentIndex();
console.log(`🧹 Cleaned up ${cleaned.length} zombie agents: ${cleaned.join(', ')}`);
cosEvents.emit('agents:changed', { action: 'zombie-cleanup', cleaned });
@@ -2660,27 +2874,27 @@ export async function cleanupZombieAgents() {
export async function deleteAgent(agentId) {
return withStateLock(async () => {
const state = await loadState();
+ const idx = await loadAgentIndex();
- // Check state, cache, and disk (ensure cache is initialized)
const inState = !!state.agents[agentId];
- const cache = await loadCompletedAgentCache();
- const inCache = cache.has(agentId);
- if (!inState && !inCache) {
+ const inIndex = idx.has(agentId);
+ if (!inState && !inIndex) {
return { error: 'Agent not found' };
}
delete state.agents[agentId];
await saveState(state);
- // Remove from cache
- completedAgentCache?.delete(agentId);
-
- // Remove metadata files from disk
- const agentDir = join(AGENTS_DIR, agentId);
+ // Remove from disk (date-bucketed or flat)
+ const agentDir = getAgentDir(agentId);
if (existsSync(agentDir)) {
await rm(agentDir, { recursive: true }).catch(() => {});
}
+ // Remove from index
+ idx.delete(agentId);
+ await saveAgentIndex();
+
cosEvents.emit('agents:changed', { action: 'deleted', agentId });
return { success: true, agentId };
});
@@ -2694,29 +2908,58 @@ export async function deleteAgent(agentId) {
export async function submitAgentFeedback(agentId, feedback) {
return withStateLock(async () => {
const state = await loadState();
-
- if (!state.agents[agentId]) {
- return { error: 'Agent not found' };
- }
-
- const agent = state.agents[agentId];
- if (agent.status !== 'completed') {
- return { error: 'Can only submit feedback for completed agents' };
- }
-
- // Store feedback on the agent
- state.agents[agentId].feedback = {
+ const feedbackData = {
rating: feedback.rating,
comment: feedback.comment || null,
submittedAt: new Date().toISOString()
};
- await saveState(state);
+ // Try state first (recently completed agents still in state)
+ if (state.agents[agentId]) {
+ const agent = state.agents[agentId];
+ if (agent.status !== 'completed') {
+ return { error: 'Can only submit feedback for completed agents' };
+ }
+ state.agents[agentId].feedback = feedbackData;
+ await saveState(state);
- emitLog('info', `Feedback received for agent ${agentId}: ${feedback.rating}`, { agentId, rating: feedback.rating });
- cosEvents.emit('agent:feedback', { agentId, feedback: state.agents[agentId].feedback });
+ // Also update on-disk metadata
+ const agentDir = getAgentDir(agentId);
+ const metaPath = join(agentDir, 'metadata.json');
+ if (existsSync(metaPath)) {
+ const content = await readFile(metaPath, 'utf-8').catch(() => null);
+ if (content) {
+ const raw = safeJSONParse(content, null);
+ if (raw) {
+ raw.feedback = feedbackData;
+ await writeFile(metaPath, JSON.stringify(raw, null, 2)).catch(() => {});
+ }
+ }
+ }
+
+ emitLog('info', `Feedback received for agent ${agentId}: ${feedback.rating}`, { agentId, rating: feedback.rating });
+ cosEvents.emit('agent:feedback', { agentId, feedback: feedbackData });
+ return { success: true, agent: state.agents[agentId] };
+ }
+
+ // Agent not in state — look up from disk via index
+ const idx = await loadAgentIndex();
+ const dateStr = idx.get(agentId);
+ if (!dateStr) return { error: 'Agent not found' };
+
+ const metaPath = join(AGENTS_DIR, dateStr, agentId, 'metadata.json');
+ const content = await readFile(metaPath, 'utf-8').catch(() => null);
+ if (!content) return { error: 'Agent not found' };
+
+ const raw = safeJSONParse(content, null);
+ if (!raw) return { error: 'Agent not found' };
- return { success: true, agent: state.agents[agentId] };
+ raw.feedback = feedbackData;
+ await writeFile(metaPath, JSON.stringify(raw, null, 2));
+
+ emitLog('info', `Feedback received for agent ${agentId}: ${feedback.rating}`, { agentId, rating: feedback.rating });
+ cosEvents.emit('agent:feedback', { agentId, feedback: feedbackData });
+ return { success: true, agent: { ...raw, id: agentId } };
});
}
@@ -3063,25 +3306,37 @@ export async function archiveStaleAgents() {
if (staleIds.length === 0) return { archived: 0 };
+ const idx = await loadAgentIndex();
+
for (const id of staleIds) {
- // Ensure agent is persisted to disk before removing from state
- const agentDir = join(AGENTS_DIR, id);
- if (!existsSync(join(agentDir, 'metadata.json'))) {
- await mkdir(agentDir, { recursive: true });
- const { output, ...agentWithoutOutput } = state.agents[id];
- await writeFile(join(agentDir, 'metadata.json'), JSON.stringify(agentWithoutOutput, null, 2)).catch(() => {});
- }
+ // Ensure agent is persisted to date-bucketed disk before removing from state
+ if (!idx.has(id)) {
+ const agent = state.agents[id];
+ const dateStr = agent.completedAt.slice(0, 10);
+ const bucketDir = join(AGENTS_DIR, dateStr);
+ await mkdir(bucketDir, { recursive: true });
+
+ const { output, ...agentWithoutOutput } = agent;
+ const flatDir = join(AGENTS_DIR, id);
+ const targetDir = join(bucketDir, id);
+
+ if (existsSync(flatDir) && !existsSync(targetDir)) {
+ // Write metadata then move
+ await writeFile(join(flatDir, 'metadata.json'), JSON.stringify(agentWithoutOutput, null, 2)).catch(() => {});
+ await rename(flatDir, targetDir).catch(() => {});
+ } else if (!existsSync(targetDir)) {
+ await mkdir(targetDir, { recursive: true });
+ await writeFile(join(targetDir, 'metadata.json'), JSON.stringify(agentWithoutOutput, null, 2)).catch(() => {});
+ }
- // Ensure agent is in cache before removing from state
- if (completedAgentCache) {
- const { output, ...agentWithoutOutput } = state.agents[id];
- completedAgentCache.set(id, agentWithoutOutput);
+ idx.set(id, dateStr);
}
delete state.agents[id];
}
await saveState(state);
+ await saveAgentIndex();
console.log(`📦 Archived ${staleIds.length} stale agents from state.json (retained on disk)`);
cosEvents.emit('agents:changed', { action: 'auto-archive', archived: staleIds.length });
return { archived: staleIds.length };
@@ -3094,34 +3349,34 @@ export async function archiveStaleAgents() {
export async function clearCompletedAgents() {
return withStateLock(async () => {
const state = await loadState();
- const cache = await loadCompletedAgentCache();
+ const idx = await loadAgentIndex();
- // Collect IDs from both state and cache
+ // Remove completed agents from state
const stateCompleted = Object.keys(state.agents).filter(
id => state.agents[id].status === 'completed'
);
- const cacheCompleted = [...cache.keys()];
- const allCompleted = [...new Set([...stateCompleted, ...cacheCompleted])];
-
- // Remove from state
for (const id of stateCompleted) {
delete state.agents[id];
}
await saveState(state);
- // Clear cache
- cache.clear();
+ // Collect all unique dates from index, then remove date bucket dirs
+ const dates = new Set(idx.values());
+ const totalCleared = idx.size + stateCompleted.filter(id => !idx.has(id)).length;
- // Remove metadata files from disk
- const removals = allCompleted.map(id => {
- const agentDir = join(AGENTS_DIR, id);
- return existsSync(agentDir)
- ? rm(agentDir, { recursive: true }).catch(() => {})
+ const removals = [...dates].map(date => {
+ const dateDir = join(AGENTS_DIR, date);
+ return existsSync(dateDir)
+ ? rm(dateDir, { recursive: true }).catch(() => {})
: Promise.resolve();
});
await Promise.all(removals);
- return { cleared: allCompleted.length };
+ // Clear index
+ idx.clear();
+ await saveAgentIndex();
+
+ return { cleared: totalCleared };
});
}
diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.js
index 123bf3f3b6..66837ae273 100644
--- a/server/services/eventScheduler.js
+++ b/server/services/eventScheduler.js
@@ -296,8 +296,8 @@ async function runEvent(event) {
console.error(`⚠️ Event ${event.id} failed: ${err.message}`)
}
- // Record in history
- eventHistory.unshift({
+ // Record in history (push + truncate is faster than unshift + pop for large arrays)
+ eventHistory.push({
eventId: event.id,
type: event.type,
runAt: startTime,
@@ -306,8 +306,8 @@ async function runEvent(event) {
error
})
- while (eventHistory.length > MAX_HISTORY) {
- eventHistory.pop()
+ if (eventHistory.length > MAX_HISTORY) {
+ eventHistory.splice(0, eventHistory.length - MAX_HISTORY)
}
// Emit completion
@@ -454,7 +454,8 @@ function getEvent(id) {
* @returns {Array} - Event history
*/
function getHistory(options = {}) {
- let history = [...eventHistory]
+ // History is stored oldest-first; reverse for newest-first output
+ let history = [...eventHistory].reverse()
if (options.eventId) {
history = history.filter(h => h.eventId === options.eventId)
@@ -474,7 +475,7 @@ function getHistory(options = {}) {
*/
function getStats() {
const events = Array.from(scheduledEvents.values())
- const recent = eventHistory.slice(0, 100)
+ const recent = eventHistory.slice(-100).reverse()
return {
totalEvents: events.length,
diff --git a/server/services/notifications.js b/server/services/notifications.js
index dc49d6420f..d387141ad2 100644
--- a/server/services/notifications.js
+++ b/server/services/notifications.js
@@ -144,6 +144,12 @@ export async function addNotification(notification) {
};
data.notifications.push(newNotification);
+
+ // Keep only the most recent 500 notifications
+ if (data.notifications.length > 500) {
+ data.notifications = data.notifications.slice(-500);
+ }
+
await saveNotifications(data);
console.log(`🔔 Notification added: ${newNotification.type} - ${newNotification.title}`);
diff --git a/server/services/productivity.js b/server/services/productivity.js
index 6a4b7fa87d..c8ace0e279 100644
--- a/server/services/productivity.js
+++ b/server/services/productivity.js
@@ -395,12 +395,84 @@ export async function getProductivityInsights() {
}
/**
- * Update productivity data on task completion
+ * Update productivity data incrementally on task completion.
+ * Only processes the single newly completed agent instead of rescanning all agents.
*/
export async function onTaskCompleted(agent) {
- // Debounce recalculation - just trigger it
- // A full recalculation ensures accurate streak counting
- await recalculateProductivity();
+ if (!agent?.completedAt) return;
+
+ const data = await loadProductivity();
+ const completedAt = new Date(agent.completedAt);
+ const dateStr = getDateString(completedAt);
+ const weekId = getWeekId(completedAt);
+ const hour = completedAt.getHours();
+ const dayOfWeek = completedAt.getDay();
+ const success = agent.result?.success === true;
+ const duration = agent.result?.duration || 0;
+
+ // Update hourly patterns
+ if (!data.hourlyPatterns[hour]) {
+ data.hourlyPatterns[hour] = { tasks: 0, successes: 0, failures: 0, totalDuration: 0 };
+ }
+ data.hourlyPatterns[hour].tasks++;
+ if (success) data.hourlyPatterns[hour].successes++;
+ else data.hourlyPatterns[hour].failures++;
+ data.hourlyPatterns[hour].totalDuration += duration;
+ data.hourlyPatterns[hour].avgDuration = Math.round(data.hourlyPatterns[hour].totalDuration / data.hourlyPatterns[hour].tasks);
+ data.hourlyPatterns[hour].successRate = Math.round((data.hourlyPatterns[hour].successes / data.hourlyPatterns[hour].tasks) * 100);
+
+ // Update daily patterns (by day of week)
+ if (!data.dailyPatterns[dayOfWeek]) {
+ data.dailyPatterns[dayOfWeek] = { tasks: 0, successes: 0, failures: 0, totalDuration: 0 };
+ }
+ data.dailyPatterns[dayOfWeek].tasks++;
+ if (success) data.dailyPatterns[dayOfWeek].successes++;
+ else data.dailyPatterns[dayOfWeek].failures++;
+ data.dailyPatterns[dayOfWeek].totalDuration += duration;
+ data.dailyPatterns[dayOfWeek].avgDuration = Math.round(data.dailyPatterns[dayOfWeek].totalDuration / data.dailyPatterns[dayOfWeek].tasks);
+ data.dailyPatterns[dayOfWeek].successRate = Math.round((data.dailyPatterns[dayOfWeek].successes / data.dailyPatterns[dayOfWeek].tasks) * 100);
+
+ // Update daily history
+ if (!data.dailyHistory[dateStr]) {
+ data.dailyHistory[dateStr] = { tasks: 0, successes: 0, failures: 0 };
+ }
+ data.dailyHistory[dateStr].tasks++;
+ if (success) data.dailyHistory[dateStr].successes++;
+ else data.dailyHistory[dateStr].failures++;
+ data.dailyHistory[dateStr].successRate = Math.round((data.dailyHistory[dateStr].successes / data.dailyHistory[dateStr].tasks) * 100);
+
+ // Update streaks
+ const today = getDateString();
+ if (data.streaks.lastActiveDate !== today) {
+ if (isConsecutiveDay(data.streaks.lastActiveDate, today)) {
+ data.streaks.currentDaily++;
+ } else if (data.streaks.lastActiveDate !== today) {
+ data.streaks.currentDaily = 1;
+ }
+ data.streaks.longestDaily = Math.max(data.streaks.longestDaily, data.streaks.currentDaily);
+ data.streaks.lastActiveDate = today;
+ }
+
+ const thisWeek = getWeekId();
+ if (data.streaks.lastActiveWeek !== thisWeek) {
+ if (isConsecutiveWeek(data.streaks.lastActiveWeek, thisWeek)) {
+ data.streaks.currentWeekly++;
+ } else {
+ data.streaks.currentWeekly = 1;
+ }
+ data.streaks.longestWeekly = Math.max(data.streaks.longestWeekly, data.streaks.currentWeekly);
+ data.streaks.lastActiveWeek = thisWeek;
+ }
+
+ // Prune dailyHistory older than 90 days
+ const cutoff = new Date();
+ cutoff.setDate(cutoff.getDate() - 90);
+ const cutoffStr = getDateString(cutoff);
+ for (const date of Object.keys(data.dailyHistory)) {
+ if (date < cutoffStr) delete data.dailyHistory[date];
+ }
+
+ await saveProductivity(data);
cosEvents.emit('productivity:updated');
}
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 7de9c894a3..d2cc82485b 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -9,7 +9,7 @@
import { spawn, execSync } from 'child_process';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
-import { writeFile, mkdir, readFile } from 'fs/promises';
+import { writeFile, mkdir, readFile, readdir, rm, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { homedir } from 'os';
import { v4 as uuidv4 } from 'uuid';
@@ -1056,6 +1056,23 @@ export async function initSpawner() {
console.error(`⚠️ Failed to initialize provider status: ${err.message}`);
});
+ // Prune old run data (keep 30 days)
+ if (existsSync(RUNS_DIR)) {
+ const cutoff = Date.now() - 30 * 24 * 60 * 60 * 1000;
+ const entries = await readdir(RUNS_DIR, { withFileTypes: true }).catch(() => []);
+ let pruned = 0;
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ const runDir = join(RUNS_DIR, entry.name);
+ const dirStat = await stat(runDir).catch(() => null);
+ if (dirStat && dirStat.mtime.getTime() < cutoff) {
+ await rm(runDir, { recursive: true }).catch(() => {});
+ pruned++;
+ }
+ }
+ if (pruned > 0) console.log(`🗑️ Pruned ${pruned} old run directories (>30 days)`);
+ }
+
// Check if CoS Runner is available
useRunner = await isRunnerAvailable();
diff --git a/server/services/taskLearning.js b/server/services/taskLearning.js
index 74aa99c75e..e87cf59526 100644
--- a/server/services/taskLearning.js
+++ b/server/services/taskLearning.js
@@ -64,6 +64,17 @@ async function loadLearningData() {
*/
async function saveLearningData(data) {
data.lastUpdated = new Date().toISOString();
+
+ // Prune task types with fewer than 2 completions and last seen > 30 days ago
+ const cutoff = Date.now() - 30 * 24 * 60 * 60 * 1000;
+ if (data.byTaskType) {
+ for (const [type, stats] of Object.entries(data.byTaskType)) {
+ if ((stats.completed || 0) < 2 && stats.lastSeen && new Date(stats.lastSeen).getTime() < cutoff) {
+ delete data.byTaskType[type];
+ }
+ }
+ }
+
await writeFile(LEARNING_FILE, JSON.stringify(data, null, 2));
}
diff --git a/server/services/weeklyDigest.js b/server/services/weeklyDigest.js
index 97b3f4b596..44b1ad8230 100644
--- a/server/services/weeklyDigest.js
+++ b/server/services/weeklyDigest.js
@@ -10,7 +10,7 @@ import { writeFile, mkdir, readdir } from 'fs/promises';
import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
-import { cosEvents, emitLog, getAgents } from './cos.js';
+import { cosEvents, emitLog, getAgents, getAgentDates, getAgentsByDate } from './cos.js';
import { readJSONFile, formatDuration } from '../lib/fileUtils.js';
const __filename = fileURLToPath(import.meta.url);
@@ -100,11 +100,17 @@ export async function generateWeeklyDigest(weekId = null) {
emitLog('info', `Generating weekly digest for ${targetWeekId}`, { weekId: targetWeekId }, '📊 WeeklyDigest');
- // Get all agents
- const agents = await getAgents();
-
- // Filter agents completed this week
- const weekAgents = agents.filter(a => {
+ // Load only agents from dates in this week (not all agents)
+ const dates = await getAgentDates();
+ const weekDates = dates
+ .map(d => d.date)
+ .filter(d => getWeekId(new Date(d + 'T12:00:00')) === targetWeekId);
+ const dateAgents = await Promise.all(weekDates.map(d => getAgentsByDate(d)));
+ // Also include running agents from state that completed this week
+ const stateAgents = await getAgents();
+ const allAgents = [...dateAgents.flat(), ...stateAgents];
+
+ const weekAgents = allAgents.filter(a => {
if (!a.completedAt) return false;
const completedWeek = getWeekId(new Date(a.completedAt));
return completedWeek === targetWeekId;