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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
perf: resolve a date's completed agents through the date-bucket index instead of scanning all agent history (#3501)
[._.]/ Adam Eivy04032f7c7263
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f797591fcf..6b3f202196 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -121,3 +121,5 @@- **[issue-3500] The Chief of Staff's cooldown sweep no longer re-scans its whole blocked backlog once per blocked task.** Tasks that get parked with an orphan-retry cooldown are revived by a pass that walks both task queues — the user queue and the internal one — and each revived task has to be written back to the queue it came from. That queue was being re-derived per task by searching the user queue for the task itself, a linear scan inside a linear loop, so the work grew with the square of the backlog on every scheduler tick. The two queues are now walked separately, which hands each task its origin for free and makes the sweep linear. Behavior is unchanged, including that a task carrying an explicit type still wins over the queue it was found in.- **[issue-3508] The "N missing · Embed" badge on the Brain graph no longer reads your entire Brain off disk to compute a number.** Checking embedding coverage means counting live records and asking which of them have a vector yet — but it was answering that by loading and parsing every person, project, idea, admin item, memory entry and daily log entry in full, across every store, then throwing all of it away except each record's id. On a Brain with a few thousand records that is a few thousand file reads and JSON parses to render two integers. The tally now works from an id index instead: which record ids exist is re-read from the directory listing every time (cheap, and it is the honest source of truth for records added or hard-pruned), while whether a given record is archived or tombstoned — the part that requires opening the file — is resolved once per record and then remembered. Changes that keep a record's id, an archive flip or a delete writing a tombstone over it, drop just that one id from the index so the next count re-reads exactly one file; records arriving from a sync peer, which land deliberately silent so they cannot echo back around the network, ride the same local-only signal the search projection already uses, so an archive performed on another machine is not invisible here. The daily-log walk also loses a cap nobody meant as a policy: it used to ask for the first 10,000 days and would simply have stopped counting after that.++- **[issue-3501] Daily agent reports for past dates read as all-zero, and the dashboard's activity card re-scanned every agent you have ever run.** Both the daily report and the "today" activity card worked out which agents finished on a given date by walking the entire in-memory agent dictionary and string-matching each record's completion timestamp — so the cost grew with your whole agent history rather than with the day being asked about, and once the housekeeping sweep had evicted a day's finished agents out of live state (it keeps roughly a day), asking for that date's report returned zeros even though every one of those runs was still sitting on disk. Both now consult the date-bucket index that already maps each archived agent to its day: the index is a small in-memory id-to-date map, so a date whose agents are all still live costs no disk reads at all, and a date that has been swept out resolves from the archive instead of reporting nothing. Live records still win over their archived copies, since the archive is written at completion time and the live one carries anything recorded since. The "while you were away" card is built on the same lookup now, which also stops it re-reading up to thirty days of archives on every poll for agents it already had in hand.diff --git a/server/services/cosAgentIndex.js b/server/services/cosAgentIndex.jsindex 6aed4300c0..0aa580180b 100644--- a/server/services/cosAgentIndex.js+++ b/server/services/cosAgentIndex.js@@ -269,6 +269,23 @@ export async function getAgentDates() {.sort((a, b) => b.date.localeCompare(a.date));}+// Agent ids grouped by date bucket for the requested dates, read straight from+// the in-memory id→date index (strings only, no disk I/O) in a single pass no+// matter how many dates are asked for. Returns a Map keyed by every requested+// date, with `[]` for dates the index doesn't know.+//+// Callers that already hold live agent records use this to learn WHICH ids a+// date owns before deciding whether the on-disk bucket is worth reading — see+// `collectCompletedAgents` in cosReports.js.+export async function getAgentIdsForDates(dates) {+ const byDate = new Map(dates.map(date => [date, []]));+ const idx = await loadAgentIndex();+ for (const [agentId, bucket] of idx.entries()) {+ byDate.get(bucket)?.push(agentId);+ }+ return byDate;+}+// Get completed agents for a specific date bucketexport async function getAgentsByDate(date) {const dateDir = join(AGENTS_DIR, date);diff --git a/server/services/cosAgentIndex.merge.test.js b/server/services/cosAgentIndex.merge.test.jsindex 50177b592f..8433541c85 100644--- a/server/services/cosAgentIndex.merge.test.js+++ b/server/services/cosAgentIndex.merge.test.js@@ -18,7 +18,7 @@ vi.mock('./cosState.js', () => ({}));vi.mock('./domainUsage.js', () => ({ recordDomainUsage: vi.fn(async () => {}) }));-import { addAgentArchivesToIndex, loadAgentIndex } from './cosAgentIndex.js';+import { addAgentArchivesToIndex, getAgentIdsForDates, loadAgentIndex } from './cosAgentIndex.js';const INDEX_FILE = join(mockCosState.agentsDir, 'index.json');@@ -72,3 +72,34 @@ describe('addAgentArchivesToIndex (#1650)', () => {expect(await addAgentArchivesToIndex([])).toBe(0);});});++describe('getAgentIdsForDates (#3501)', () => {+ beforeEach(async () => {+ await rm(mockCosState.agentsDir, { recursive: true, force: true });+ await mkdir(mockCosState.agentsDir, { recursive: true });+ await writeFile(INDEX_FILE, '{}');+ await addAgentArchivesToIndex([+ { agentId: 'agent-sep1a', date: '2026-09-01' },+ { agentId: 'agent-sep1b', date: '2026-09-01' },+ { agentId: 'agent-sep2', date: '2026-09-02' },+ ]);+ });+ afterEach(async () => {+ await rm(mockCosState.agentsDir, { recursive: true, force: true });+ });++ it('groups ids per requested date and returns an empty list for unknown dates', async () => {+ const byDate = await getAgentIdsForDates(['2026-09-01', '2026-09-02', '2026-09-03']);++ expect([...byDate.get('2026-09-01')].sort()).toEqual(['agent-sep1a', 'agent-sep1b']);+ expect(byDate.get('2026-09-02')).toEqual(['agent-sep2']);+ // Requested but unindexed dates are still keyed — callers can read without a guard.+ expect(byDate.get('2026-09-03')).toEqual([]);+ // Dates outside the request never leak into the result.+ expect(byDate.has('2026-06-20')).toBe(false);+ });++ it('returns an empty map for an empty date list', async () => {+ expect((await getAgentIdsForDates([])).size).toBe(0);+ });+});diff --git a/server/services/cosReports.js b/server/services/cosReports.jsindex 0c5ed872c5..da75997d35 100644--- a/server/services/cosReports.js+++ b/server/services/cosReports.js@@ -9,9 +9,40 @@ import { readFile, readdir } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { loadState, ensureDirectories, REPORTS_DIR, isDaemonRunning } from './cosState.js';-import { getAgentsByDate } from './cosAgentIndex.js';+import { getAgentIdsForDates, getAgentsByDate } from './cosAgentIndex.js';import { formatDuration, safeJSONParse, atomicWrite } from '../lib/fileUtils.js';+// Completed-agent records for a set of UTC date buckets (YYYY-MM-DD), merged+// from live in-memory state and the on-disk date-bucket archive. `accept(agent)`+// filters both sources identically.+//+// `state.agents` stays authoritative for every id it still holds — it carries the+// freshest result/feedback for a run whose archive was written back at completion+// time — so the archive is consulted only for ids the date-bucket INDEX lists and+// state has already evicted. The index is a tiny in-memory id→date map, so a date+// whose agents are all still live costs zero disk reads, while a date already+// swept out of state.json by `archiveStaleAgents` resolves from disk instead of+// reading as empty (issue #3501: reports for past dates came back all-zero, and+// every dashboard refresh linearly rescanned the whole agent history).+async function collectCompletedAgents(dates, state, accept) {+ const liveIds = new Set(Object.keys(state.agents));+ const collected = Object.values(state.agents).filter(a => a.completedAt && accept(a));+ const idsByDate = await getAgentIdsForDates(dates);++ // Iterating the Map (not `dates`) keeps a repeated date from reading its bucket twice.+ for (const [date, ids] of idsByDate) {+ const missing = new Set(ids.filter(id => !liveIds.has(id)));+ if (missing.size === 0) continue;+ for (const agent of await getAgentsByDate(date)) {+ if (!missing.has(agent.id)) continue; // live copy wins, and non-indexed strays stay out+ if (!agent.completedAt || !accept(agent)) continue;+ collected.push(agent);+ }+ }++ return collected;+}+// A completed agent's work duration in ms: prefer the recorded `result.duration`,// else derive from completedAt − startedAt. Clamped to >=0 so a clock-skewed// record (completedAt < startedAt) can't surface a negative duration.@@ -27,11 +58,12 @@ export async function generateReport(date = null) {const reportDate = date || new Date().toISOString().split('T')[0];const state = await loadState();- // Filter agents completed on this date- const completedAgents = Object.values(state.agents).filter(a => {- if (!a.completedAt) return false;- return a.completedAt.startsWith(reportDate);- });+ // Agents completed on this date, from the date bucket (index-gated) + live state+ const completedAgents = await collectCompletedAgents(+ [reportDate],+ state,+ a => a.completedAt.startsWith(reportDate)+ );const report = {date: reportDate,@@ -119,11 +151,12 @@ export async function getTodayActivity() {const state = await loadState();const today = new Date().toISOString().split('T')[0];- // Filter agents completed today- const todayAgents = Object.values(state.agents).filter(a => {- if (!a.completedAt) return false;- return a.completedAt.startsWith(today);- });+ // Agents completed today, from today's date bucket (index-gated) + live state+ const todayAgents = await collectCompletedAgents(+ [today],+ state,+ a => a.completedAt.startsWith(today)+ );const succeeded = todayAgents.filter(a => a.result?.success);const failed = todayAgents.filter(a => !a.result?.success);@@ -251,29 +284,24 @@ export async function getWhileAwayActivity(sinceIso) {return Number.isFinite(t) && t >= sinceMs && t <= now;};- // Live (in-memory) completed agents within the window.- const state = await loadState();- const live = Object.values(state.agents).filter(a => a.status === 'completed' && inWindow(a));-- // Archived agents: read each date bucket the window spans (UTC day strings).- const seen = new Set(live.map(a => a.id));- const archived = [];+ // Every UTC day string the window spans — each is a date bucket to consider.+ const dates = [];const startDay = new Date(sinceMs);const endDay = new Date(now);for (let d = new Date(Date.UTC(startDay.getUTCFullYear(), startDay.getUTCMonth(), startDay.getUTCDate()));d.getTime() <= endDay.getTime();d = new Date(d.getTime() + 86400000)) {- const dateStr = d.toISOString().slice(0, 10);- const agents = await getAgentsByDate(dateStr);- for (const a of agents) {- if (seen.has(a.id)) continue; // live copy wins (fresher result/output)- if (!inWindow(a)) continue;- seen.add(a.id);- archived.push(a);- }+ dates.push(d.toISOString().slice(0, 10));}- const summary = summarizeAwayActivity([...live, ...archived], effectiveSinceIso);+ const state = await loadState();+ const agents = await collectCompletedAgents(+ dates,+ state,+ a => a.status === 'completed' && inWindow(a)+ );++ const summary = summarizeAwayActivity(agents, effectiveSinceIso);return { ...summary, isRunning: isDaemonRunning(), isPaused: state.paused };}diff --git a/server/services/cosReports.test.js b/server/services/cosReports.test.jsindex 888ee1d892..bbfa6df9c5 100644--- a/server/services/cosReports.test.js+++ b/server/services/cosReports.test.js@@ -14,11 +14,23 @@ vi.mock('./cosState.js', () => ({isDaemonRunning: () => mock.daemonRunning}));+// The date-bucket index is derived from the same fixture as the on-disk buckets,+// mirroring the real invariant: every archived agent has an index entry.vi.mock('./cosAgentIndex.js', () => ({- getAgentsByDate: vi.fn(async (date) => mock.agentsByDate[date] || [])+ getAgentsByDate: vi.fn(async (date) => mock.agentsByDate[date] || []),+ getAgentIdsForDates: vi.fn(async (dates) => new Map(+ dates.map(date => [date, (mock.agentsByDate[date] || []).map(a => a.id)])+ ))}));-import { getWhileAwayActivity } from './cosReports.js';+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ atomicWrite: vi.fn(async () => {})+}));++import { getAgentsByDate } from './cosAgentIndex.js';+import { atomicWrite } from '../lib/fileUtils.js';+import { generateReport, getTodayActivity, getWhileAwayActivity } from './cosReports.js';// Build a completed agent record at a fixed completedAt offset (ms before now).const agentAt = (id, { msAgo, success = true, desc = 'did a thing', taskType = 'review', app = null } = {}) => {@@ -157,4 +169,117 @@ describe('getWhileAwayActivity', () => {expect(result.incidents).toHaveLength(8);expect(result.stats.completed).toBe(24);});++ it('skips the archive read entirely when every indexed id is still live (#3501)', async () => {+ const live = agentAt('a1', { msAgo: 30 * 60000 });+ mock.state = stateWith([live]);+ const todayStr = new Date().toISOString().slice(0, 10);+ mock.agentsByDate[todayStr] = [live]; // archived at completion, still in state++ const result = await getWhileAwayActivity(new Date(Date.now() - 3600000).toISOString());++ expect(result.stats.completed).toBe(1);+ expect(getAgentsByDate).not.toHaveBeenCalled();+ });+});++// Completed agent pinned to an explicit UTC date so the assertions can't drift+// across a midnight boundary mid-run.+const agentOnDate = (id, dateStr, { success = true, desc = 'did a thing' } = {}) => ({+ id,+ taskId: `task-${id}`,+ status: 'completed',+ startedAt: `${dateStr}T11:00:00.000Z`,+ completedAt: `${dateStr}T12:00:00.000Z`,+ result: { success, duration: 3600000 },+ metadata: { taskDescription: desc, taskType: 'review' }+});++const todayStr = () => new Date().toISOString().slice(0, 10);++describe('generateReport (#3501 date-bucket sourcing)', () => {+ beforeEach(() => {+ mock.daemonRunning = true;+ mock.agentsByDate = {};+ mock.state = stateWith([]);+ });++ afterEach(() => vi.clearAllMocks());++ it('reports a historical date from the archive after state.json was swept', async () => {+ // archiveStaleAgents evicted these from state.json — before #3501 the report+ // scanned state.agents only and came back all-zero.+ mock.agentsByDate['2026-01-15'] = [+ agentOnDate('old1', '2026-01-15', { success: true }),+ agentOnDate('old2', '2026-01-15', { success: false })+ ];++ const report = await generateReport('2026-01-15');++ expect(report.date).toBe('2026-01-15');+ expect(report.summary).toMatchObject({ tasksCompleted: 1, tasksFailed: 1, totalAgents: 2 });+ expect(report.agents.map(a => a.id).sort()).toEqual(['old1', 'old2']);+ expect(report.agents[0].duration).toBe(3600000);+ expect(atomicWrite).toHaveBeenCalledTimes(1);+ });++ it('prefers the live record over its archived copy', async () => {+ const date = '2026-01-16';+ // Live record carries the authoritative verdict; the archive predates it.+ mock.state = stateWith([agentOnDate('dup', date, { success: true })]);+ mock.agentsByDate[date] = [agentOnDate('dup', date, { success: false })];++ const report = await generateReport(date);++ expect(report.summary).toMatchObject({ tasksCompleted: 1, tasksFailed: 0, totalAgents: 1 });+ expect(getAgentsByDate).not.toHaveBeenCalled();+ });++ it('ignores agents completed on other dates', async () => {+ mock.state = stateWith([agentOnDate('other', '2026-01-17')]);+ mock.agentsByDate['2026-01-18'] = [agentOnDate('wanted', '2026-01-18')];++ const report = await generateReport('2026-01-18');++ expect(report.agents.map(a => a.id)).toEqual(['wanted']);+ });+});++describe('getTodayActivity (#3501 date-bucket sourcing)', () => {+ beforeEach(() => {+ mock.daemonRunning = true;+ mock.agentsByDate = {};+ mock.state = stateWith([]);+ });++ afterEach(() => vi.clearAllMocks());++ it('counts today agents that have been archived out of state.json', async () => {+ const today = todayStr();+ mock.state = stateWith([agentOnDate('live', today, { success: true })]);+ mock.agentsByDate[today] = [+ agentOnDate('live', today, { success: true }),+ agentOnDate('evicted', today, { success: false })+ ];++ const activity = await getTodayActivity();++ expect(activity.stats).toMatchObject({ completed: 2, succeeded: 1, failed: 1, successRate: 50 });+ expect(activity.time.totalDurationMs).toBe(7200000);+ expect(activity.accomplishments.map(a => a.id)).toEqual(['live']);+ });++ it('still counts running agents from live state', async () => {+ const today = todayStr();+ mock.state = stateWith([+ agentOnDate('done', today),+ { id: 'busy', taskId: 'task-busy', status: 'running', startedAt: new Date().toISOString() }+ ]);+ mock.agentsByDate[today] = [agentOnDate('done', today)];++ const activity = await getTodayActivity();++ expect(activity.stats).toMatchObject({ completed: 1, running: 1, successRate: 100 });+ expect(getAgentsByDate).not.toHaveBeenCalled();+ });});