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: parallelize sequential file/query reads and memoize hot render derivations
[._.]/ Adam Eivy5c61db6adf66
diff --git a/client/src/components/KanbanBoard.jsx b/client/src/components/KanbanBoard.jsxindex 0fe0457a5c..001ee3eec5 100644--- a/client/src/components/KanbanBoard.jsx+++ b/client/src/components/KanbanBoard.jsx@@ -1,11 +1,14 @@-import { useState, useEffect, useCallback, useMemo } from 'react';+import { useState, useEffect, useCallback, useMemo, memo } from 'react';import { DndContext, DragOverlay, useDraggable, useDroppable, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';import { GripVertical, Play } from 'lucide-react';import toast from './ui/Toast';import * as api from '../services/api';import { FALLBACK_COLUMNS, ticketInColumn, bucketTickets } from '../lib/kanbanColumns.js';-function TicketCard({ ticket, isDragOverlay }) {+// Memoized: rendered once per ticket inside a dnd-kit board that re-renders on+// every pointer move during a drag. Props are a stable ticket object + a+// primitive flag, so memo skips re-rendering cards that aren't being dragged.+const TicketCard = memo(function TicketCard({ ticket, isDragOverlay }) {return (<div className={`p-2 bg-port-card border border-port-border rounded-lg transition-colors ${isDragOverlay ? 'shadow-lg shadow-black/50 border-port-accent/50 rotate-2' : ''}`}><div className="flex items-start justify-between gap-1">@@ -28,9 +31,11 @@ function TicketCard({ ticket, isDragOverlay }) {</div></div>);-}+});-function DraggableTicket({ ticket, disabled, appId, canQueue }) {+// Memoized for the same reason as TicketCard: only the card actively being+// dragged changes; the rest keep stable ticket/disabled/appId/canQueue props.+const DraggableTicket = memo(function DraggableTicket({ ticket, disabled, appId, canQueue }) {const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({id: ticket.key,data: { ticket },@@ -93,7 +98,7 @@ function DraggableTicket({ ticket, disabled, appId, canQueue }) {</div></div>);-}+});function DroppableColumn({ column, isOver, disabled, appId }) {const { setNodeRef } = useDroppable({ id: column.id, disabled });diff --git a/client/src/components/messages/InboxTab.jsx b/client/src/components/messages/InboxTab.jsxindex b425d2f516..26c4206b73 100644--- a/client/src/components/messages/InboxTab.jsx+++ b/client/src/components/messages/InboxTab.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback, useRef } from 'react';+import { useState, useEffect, useCallback, useRef, useMemo } from 'react';import { Mail, Search, RefreshCw, ChevronRight, Sparkles, Archive, Trash2, Reply, Eye, Flag, Pin, Loader2 } from 'lucide-react';import { useNavigate, useSearchParams } from 'react-router-dom';import toast from '../ui/Toast';@@ -185,6 +185,18 @@ export default function InboxTab({ accounts }) {}};+ // The active triage tab and its filtered message list are derived from+ // messages + activeTab; memoize so the O(n) filter runs once per change+ // instead of twice on every render (empty-state check + the rendered list).+ const currentTab = useMemo(+ () => TRIAGE_TABS.find(t => t.key === activeTab) || TRIAGE_TABS[0],+ [activeTab]+ );+ const visibleMessages = useMemo(+ () => messages.filter(currentTab.filter),+ [messages, currentTab]+ );+if (selectedMessage) {return (<MessageDetail@@ -307,9 +319,7 @@ export default function InboxTab({ accounts }) {</div>{(() => {- const currentTab = TRIAGE_TABS.find(t => t.key === activeTab) || TRIAGE_TABS[0];- const filtered = messages.filter(currentTab.filter);- if (filtered.length === 0 && !loading) return (+ if (visibleMessages.length === 0 && !loading) return (<div className="text-center py-12 text-gray-500"><Mail size={48} className="mx-auto mb-4 opacity-50" />{messages.length === 0 ? (@@ -326,7 +336,7 @@ export default function InboxTab({ accounts }) {})()}<div className="space-y-1">- {messages.filter((TRIAGE_TABS.find(t => t.key === activeTab) || TRIAGE_TABS[0]).filter).map((msg) => {+ {visibleMessages.map((msg) => {const ev = msg.evaluation;return (<divdiff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsxindex 49635ea4a7..1689733614 100644--- a/client/src/pages/Tribe.jsx+++ b/client/src/pages/Tribe.jsx@@ -557,13 +557,13 @@ function CareQueue({ contacts, onSelect, onLogTouch, onNew }) {// External people are outside the tribe — no care cadence is owed, so they// never appear in the queue (otherwise their null daysRemaining would sort// them to the top alongside genuinely-overdue contacts).- const queue = contacts.filter((contact) => contact.ring !== 'external').sort((a, b) => {+ const queue = useMemo(() => contacts.filter((contact) => contact.ring !== 'external').sort((a, b) => {const aStatus = contactStatus(a);const bStatus = contactStatus(b);const aScore = aStatus.daysRemaining == null ? -999 : aStatus.daysRemaining;const bScore = bStatus.daysRemaining == null ? -999 : bStatus.daysRemaining;return aScore - bScore;- });+ }), [contacts]);if (!queue.length) return <EmptyState onNew={onNew} />;@@ -583,12 +583,12 @@ function CareQueue({ contacts, onSelect, onLogTouch, onNew }) {}function FocusPanel({ contacts }) {- const byEnergy = ENERGY.map((energy) => ({+ const byEnergy = useMemo(() => ENERGY.map((energy) => ({...energy,count: contacts.filter((contact) => contact.energy === energy.id).length,- }));- const support = contacts.filter((contact) => contact.ring === 'support');- const nextMoves = contacts.filter((contact) => contact.nextMove).slice(0, 8);+ })), [contacts]);+ const support = useMemo(() => contacts.filter((contact) => contact.ring === 'support'), [contacts]);+ const nextMoves = useMemo(() => contacts.filter((contact) => contact.nextMove).slice(0, 8), [contacts]);return (<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,360px)]">diff --git a/server/services/calendarSync.js b/server/services/calendarSync.jsindex dcc503e124..3e943ba4ac 100644--- a/server/services/calendarSync.js+++ b/server/services/calendarSync.js@@ -84,15 +84,20 @@ export async function getEvents(options = {}) {const accounts = await listAccounts();const accountMap = new Map(accounts.map(a => [a.id, a]));+ const accountIds = files+ .filter(file => file.endsWith('.json'))+ .map(file => file.replace('.json', ''))+ .filter(id => UUID_RE.test(id));+ // Load each account's cache in parallel rather than serializing one disk read+ // per account before aggregating the combined calendar view.+ const caches = await Promise.all(+ accountIds.map(async id => ({ id, cache: await loadCache(id) }))+ );let allEvents = [];- for (const file of files) {- if (!file.endsWith('.json')) continue;- const fileAccountId = file.replace('.json', '');- if (!UUID_RE.test(fileAccountId)) continue;- const cache = await loadCache(fileAccountId);- let events = cache.events.map(e => ({ ...e, accountId: e.accountId || fileAccountId }));+ for (const { id, cache } of caches) {+ let events = cache.events.map(e => ({ ...e, accountId: e.accountId || id }));events = filterDeclinedAndCancelled(events);- events = filterByEnabledSubcalendars(events, accountMap.get(fileAccountId));+ events = filterByEnabledSubcalendars(events, accountMap.get(id));allEvents.push(...events);}allEvents = filterBySearch(allEvents, search);diff --git a/server/services/dailyReview.js b/server/services/dailyReview.jsindex 0ebd921ba0..18584ce6cd 100644--- a/server/services/dailyReview.js+++ b/server/services/dailyReview.js@@ -131,23 +131,32 @@ export async function getDailyReviewHistory(startDate, endDate) {const { readdir } = await import('fs/promises');const files = await readdir(REVIEW_DIR).catch(() => []);- const reviews = [];- for (const file of files) {- if (!file.endsWith('.json')) continue;- const reviewDate = file.replace('.json', '');- if (startDate && reviewDate < startDate) continue;- if (endDate && reviewDate > endDate) continue;- const data = await readJSONFile(join(REVIEW_DIR, file), null);- if (!data) continue;- const confirmations = Object.values(data.confirmations || {});- reviews.push({- date: reviewDate,- confirmed: confirmations.filter(c => c.happened).length,- skipped: confirmations.filter(c => c.happened === false).length,- total: confirmations.length,- updatedAt: data.updatedAt+ // Filter to the requested date window first (cheap, no I/O), then read the+ // surviving review files in parallel instead of serializing one disk read+ // per day across the whole history.+ const inRange = files+ .filter(file => file.endsWith('.json'))+ .map(file => file.replace('.json', ''))+ .filter(reviewDate => {+ if (startDate && reviewDate < startDate) return false;+ if (endDate && reviewDate > endDate) return false;+ return true;});- }- return reviews.sort((a, b) => b.date.localeCompare(a.date));+ const loaded = await Promise.all(+ inRange.map(async reviewDate => {+ const data = await readJSONFile(join(REVIEW_DIR, `${reviewDate}.json`), null);+ if (!data) return null;+ const confirmations = Object.values(data.confirmations || {});+ return {+ date: reviewDate,+ confirmed: confirmations.filter(c => c.happened).length,+ skipped: confirmations.filter(c => c.happened === false).length,+ total: confirmations.length,+ updatedAt: data.updatedAt+ };+ })+ );++ return loaded.filter(Boolean).sort((a, b) => b.date.localeCompare(a.date));}diff --git a/server/services/digital-twin-analysis.js b/server/services/digital-twin-analysis.jsindex d59a88eb12..7b620df914 100644--- a/server/services/digital-twin-analysis.js+++ b/server/services/digital-twin-analysis.js@@ -66,15 +66,16 @@ export async function validateCompleteness() {const documents = await getDocuments();const enabledDocs = documents.filter(d => d.enabled && d.category !== 'behavioral');- // Load content for all enabled documents- const contents = [];- for (const doc of enabledDocs) {- const filePath = join(DIGITAL_TWIN_DIR, doc.filename);- if (existsSync(filePath)) {+ // Load content for all enabled documents in parallel — the reads are+ // independent and their results are just concatenated for keyword scanning.+ const contents = (await Promise.all(+ enabledDocs.map(async doc => {+ const filePath = join(DIGITAL_TWIN_DIR, doc.filename);+ if (!existsSync(filePath)) return null;const content = await readFile(filePath, 'utf-8');- contents.push({ doc, content: content.toLowerCase() });- }- }+ return { doc, content: content.toLowerCase() };+ })+ )).filter(Boolean);const allContent = contents.map(c => c.content).join('\n');const found = [];diff --git a/server/services/digital-twin-context.js b/server/services/digital-twin-context.jsindex 847b1ce22b..570823a060 100644--- a/server/services/digital-twin-context.js+++ b/server/services/digital-twin-context.js@@ -1,10 +1,25 @@-import { readFile } from 'fs/promises';+import { readFile, stat } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { DIGITAL_TWIN_DIR } from './digital-twin-helpers.js';import { loadMeta } from './digital-twin-meta.js';import { renderTraitBlendDirective } from '../lib/personaTraitBlend.js';+// Twin document markdown is re-read on every agent prompt build+// (getDigitalTwinForPrompt runs per prompt, per twin test). These files rarely+// change, so cache their contents keyed by path + mtime and only re-read when+// the file actually changes on disk. A cheap fs.stat gates the expensive read.+const docContentCache = new Map();++async function readTwinDoc(filePath) {+ const { mtimeMs } = await stat(filePath);+ const cached = docContentCache.get(filePath);+ if (cached && cached.mtimeMs === mtimeMs) return cached.content;+ const content = await readFile(filePath, 'utf-8');+ docContentCache.set(filePath, { mtimeMs, content });+ return content;+}+/*** Resolve the persona to apply for this prompt. `personaId` may be a specific* id, the string 'active' (resolve from settings.activePersonaId), or@@ -69,7 +84,7 @@ export async function getDigitalTwinForPrompt(options = {}) {const filePath = join(DIGITAL_TWIN_DIR, doc.filename);if (!existsSync(filePath)) continue;- const content = await readFile(filePath, 'utf-8');+ const content = await readTwinDoc(filePath);if (tokenCount + content.length > maxChars) {// Truncate if we're over budgetdiff --git a/server/services/digital-twin-export.js b/server/services/digital-twin-export.jsindex b0749cd88b..d0667e2ca1 100644--- a/server/services/digital-twin-export.js+++ b/server/services/digital-twin-export.js@@ -41,15 +41,16 @@ export async function exportDigitalTwin(format, documentIds = null, includeDisab// Sort by prioritydocs.sort((a, b) => a.priority - b.priority);- // Load content for each document- const documentsWithContent = [];- for (const doc of docs) {- const filePath = join(DIGITAL_TWIN_DIR, doc.filename);- if (existsSync(filePath)) {+ // Load content for each document in parallel, preserving priority order —+ // every doc is needed regardless, so there is no reason to serialize the reads.+ const documentsWithContent = (await Promise.all(+ docs.map(async doc => {+ const filePath = join(DIGITAL_TWIN_DIR, doc.filename);+ if (!existsSync(filePath)) return null;const content = await readFile(filePath, 'utf-8');- documentsWithContent.push({ ...doc, content });- }- }+ return { ...doc, content };+ })+ )).filter(Boolean);switch (format) {case 'system_prompt':diff --git a/server/services/featureAgents.js b/server/services/featureAgents.jsindex bcf7a55299..98e32d3fb4 100644--- a/server/services/featureAgents.js+++ b/server/services/featureAgents.js@@ -415,13 +415,14 @@ export async function getFeatureAgentRuns(id, limit = 20) {.sort((a, b) => b.localeCompare(a)) // newest first.slice(0, limit);- const runs = [];- for (const file of runFiles) {- const run = await readJSONFile(join(runDir, file), null);- if (run) runs.push(run);- }-- return runs;+ // Read the (already limit-capped) run files in parallel — these are+ // independent small JSON reads, so a sequential loop needlessly serializes+ // disk latency on the run-history endpoint.+ const loaded = await Promise.all(+ runFiles.map(file => readJSONFile(join(runDir, file), null))+ );++ return loaded.filter(Boolean);}/**diff --git a/server/services/memoryDB.js b/server/services/memoryDB.jsindex 06e23ace63..0e24fed2aa 100644--- a/server/services/memoryDB.js+++ b/server/services/memoryDB.js@@ -936,17 +936,23 @@ export async function consolidateMemories(threshold = 0.9, dryRun = false) {};}- let merged = 0;+ // Collect every duplicate to archive (all but the highest-importance member of+ // each cluster), then archive them in a single set-based UPDATE instead of one+ // round-trip per memory id.+ const archiveIds = [];for (const cluster of duplicateClusters) {// Sort by importance, keep highestcluster.sort((a, b) => (importanceMap.get(b) || 0) - (importanceMap.get(a) || 0));-for (let i = 1; i < cluster.length; i++) {- await query("UPDATE memories SET status = 'archived' WHERE id = $1", [cluster[i]]);- merged++;+ archiveIds.push(cluster[i]);}}+ if (archiveIds.length > 0) {+ await query("UPDATE memories SET status = 'archived' WHERE id = ANY($1)", [archiveIds]);+ }+ const merged = archiveIds.length;+console.log(`🧠 Consolidated ${merged} duplicate memories into ${duplicateClusters.length} clusters`);return { merged, clusters: duplicateClusters.length };}diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex 6bcac2df84..829c00d243 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -47,13 +47,18 @@ export async function getMessages(options = {}) {await ensureDir(CACHE_DIR);const { readdir } = await import('fs/promises');const files = await readdir(CACHE_DIR).catch(() => []);+ const accountIds = files+ .filter(file => file.endsWith('.json'))+ .map(file => file.replace('.json', ''))+ .filter(id => UUID_RE.test(id));+ // Load each account's cache in parallel rather than serializing one disk read+ // per account before we can aggregate the combined inbox.+ const caches = await Promise.all(+ accountIds.map(async id => ({ id, cache: await loadCache(id) }))+ );let allMessages = [];- for (const file of files) {- if (!file.endsWith('.json')) continue;- const fileAccountId = file.replace('.json', '');- if (!UUID_RE.test(fileAccountId)) continue;- const cache = await loadCache(fileAccountId);- allMessages.push(...cache.messages.map(m => ({ ...m, accountId: m.accountId || fileAccountId })));+ for (const { id, cache } of caches) {+ allMessages.push(...cache.messages.map(m => ({ ...m, accountId: m.accountId || id })));}allMessages = filterBySearch(allMessages, search);allMessages.sort((a, b) => safeDate(b.date) - safeDate(a.date));diff --git a/server/services/missions.js b/server/services/missions.jsindex 0128e2f0f0..6272379d23 100644--- a/server/services/missions.js+++ b/server/services/missions.js@@ -26,18 +26,20 @@ async function loadMissions() {await ensureDir(DATA_DIR)const files = await fs.readdir(DATA_DIR).catch(() => [])- const missions = []- for (const file of files) {- if (!file.endsWith('.json')) continue-- const filePath = path.join(DATA_DIR, file)- const content = await tryReadFile(filePath)- if (content) {- const mission = safeJSONParse(content, null, { context: `mission:${file}` })- if (mission) missions.push(mission)- }- }+ // Read every mission file in parallel on cold load rather than serializing+ // one disk read at a time; the result is memoized in missionsCache below.+ const loaded = await Promise.all(+ files+ .filter(file => file.endsWith('.json'))+ .map(async file => {+ const content = await tryReadFile(path.join(DATA_DIR, file))+ if (!content) return null+ return safeJSONParse(content, null, { context: `mission:${file}` })+ })+ )++ const missions = loaded.filter(Boolean)missionsCache = missionsreturn missionsdiff --git a/server/services/obsidian.js b/server/services/obsidian.jsindex ab98d1c101..29b00d446c 100644--- a/server/services/obsidian.js+++ b/server/services/obsidian.js@@ -306,46 +306,57 @@ export async function searchNotes(vaultId, query) {async function searchDir(rootPath, currentPath, query, countRe, results) {const entries = await readdir(currentPath, { withFileTypes: true });+ const subdirs = [];+ const mdFiles = [];for (const entry of entries) {if (entry.name.startsWith('.') || SKIP_DIRS.has(entry.name)) continue;const fullPath = join(currentPath, entry.name);+ if (entry.isDirectory()) subdirs.push(fullPath);+ else if (entry.isFile() && extname(entry.name) === '.md') mdFiles.push({ name: entry.name, fullPath });+ }- if (entry.isDirectory()) {- await searchDir(rootPath, fullPath, query, countRe, results);- } else if (entry.isFile() && extname(entry.name) === '.md') {- const content = await readFile(fullPath, 'utf-8');- const contentLower = content.toLowerCase();- const nameLower = basename(entry.name, '.md').toLowerCase();- const titleMatch = nameLower.includes(query);- const contentMatch = contentLower.includes(query);-- if (titleMatch || contentMatch) {- const relativePath = relative(rootPath, fullPath);- const { tags } = parseNoteMetadata(content);-- const snippets = [];- if (contentMatch) {- const lines = content.split('\n');- for (let i = 0; i < lines.length && snippets.length < 3; i++) {- if (lines[i].toLowerCase().includes(query)) {- snippets.push({ line: i + 1, text: lines[i].trim().slice(0, 200) });- }- }+ // Read every markdown file in this directory concurrently — each match is+ // independent, so serializing the disk reads only added latency to search.+ // Per-file synchronous processing (including the shared countRe) never yields,+ // so there is no interleaving on the regex state.+ const dirResults = await Promise.all(mdFiles.map(async ({ name, fullPath }) => {+ const content = await readFile(fullPath, 'utf-8');+ const contentLower = content.toLowerCase();+ const nameLower = basename(name, '.md').toLowerCase();+ const titleMatch = nameLower.includes(query);+ const contentMatch = contentLower.includes(query);+ if (!titleMatch && !contentMatch) return null;++ const relativePath = relative(rootPath, fullPath);+ const { tags } = parseNoteMetadata(content);++ const snippets = [];+ if (contentMatch) {+ const lines = content.split('\n');+ for (let i = 0; i < lines.length && snippets.length < 3; i++) {+ if (lines[i].toLowerCase().includes(query)) {+ snippets.push({ line: i + 1, text: lines[i].trim().slice(0, 200) });}-- // Reset regex lastIndex before reuse- countRe.lastIndex = 0;- results.push({- path: relativePath,- name: basename(entry.name, '.md'),- folder: dirname(relativePath) === '.' ? '' : dirname(relativePath),- titleMatch,- matchCount: (contentLower.match(countRe) || []).length,- snippets,- tags- });}}++ countRe.lastIndex = 0;+ return {+ path: relativePath,+ name: basename(name, '.md'),+ folder: dirname(relativePath) === '.' ? '' : dirname(relativePath),+ titleMatch,+ matchCount: (contentLower.match(countRe) || []).length,+ snippets,+ tags+ };+ }));+ for (const r of dirResults) if (r) results.push(r);++ // Recurse into subdirectories (kept sequential to bound open file descriptors+ // on deep vaults; the per-directory file reads above are already parallel).+ for (const dir of subdirs) {+ await searchDir(rootPath, dir, query, countRe, results);}}@@ -390,27 +401,37 @@ export async function getVaultGraph(vaultId) {async function collectNotes(rootPath, currentPath, noteMap, nodes) {const entries = await readdir(currentPath, { withFileTypes: true });+ const subdirs = [];+ const mdFiles = [];for (const entry of entries) {if (entry.name.startsWith('.') || SKIP_DIRS.has(entry.name)) continue;const fullPath = join(currentPath, entry.name);+ if (entry.isDirectory()) subdirs.push(fullPath);+ else if (entry.isFile() && extname(entry.name) === '.md') mdFiles.push({ name: entry.name, fullPath });+ }- if (entry.isDirectory()) {- await collectNotes(rootPath, fullPath, noteMap, nodes);- } else if (entry.isFile() && extname(entry.name) === '.md') {- const content = await readFile(fullPath, 'utf-8');- const relativePath = relative(rootPath, fullPath);- const noteName = basename(entry.name, '.md');- const { tags, wikilinks } = parseNoteMetadata(content);+ // Read this directory's markdown files concurrently, then push results in+ // stable directory order — building the note graph no longer serializes disk.+ const parsed = await Promise.all(mdFiles.map(async ({ name, fullPath }) => {+ const content = await readFile(fullPath, 'utf-8');+ const relativePath = relative(rootPath, fullPath);+ const noteName = basename(name, '.md');+ const { tags, wikilinks } = parseNoteMetadata(content);+ return { noteName, relativePath, tags, wikilinks };+ }));+ for (const { noteName, relativePath, tags, wikilinks } of parsed) {+ noteMap.set(noteName, relativePath);+ nodes.push({+ path: relativePath,+ name: noteName,+ folder: dirname(relativePath) === '.' ? '' : dirname(relativePath),+ tags,+ wikilinks+ });+ }- noteMap.set(noteName, relativePath);- nodes.push({- path: relativePath,- name: noteName,- folder: dirname(relativePath) === '.' ? '' : dirname(relativePath),- tags,- wikilinks- });- }+ for (const dir of subdirs) {+ await collectNotes(rootPath, dir, noteMap, nodes);}}diff --git a/server/services/timeCapsule.js b/server/services/timeCapsule.jsindex 2f737e369c..a045be8b55 100644--- a/server/services/timeCapsule.js+++ b/server/services/timeCapsule.js@@ -42,32 +42,34 @@ async function collectTwinData() {const jsonFiles = ['meta.json', 'identity.json', 'goals.json', 'taste-profile.json','feedback.json', 'genome.json', 'longevity.json', 'chronotype.json'];- for (const filename of jsonFiles) {- const filePath = join(DIGITAL_TWIN_DIR, filename);- if (existsSync(filePath)) {- const content = await readFile(filePath, 'utf-8');- files[filename] = JSON.parse(content);- }- }-- // Collect autobiography stories- const storiesPath = join(DIGITAL_TWIN_DIR, 'autobiography', 'stories.json');- if (existsSync(storiesPath)) {- const content = await readFile(storiesPath, 'utf-8');- files['autobiography/stories.json'] = JSON.parse(content);- }+ // Read the fixed JSON set plus the autobiography stories concurrently — they+ // are independent files, so a sequential loop just serialized disk latency on+ // snapshot creation.+ const jsonTargets = [+ ...jsonFiles.map(filename => ({ key: filename, path: join(DIGITAL_TWIN_DIR, filename) })),+ { key: 'autobiography/stories.json', path: join(DIGITAL_TWIN_DIR, 'autobiography', 'stories.json') }+ ];+ await Promise.all(jsonTargets.map(async ({ key, path }) => {+ if (!existsSync(path)) return;+ const content = await readFile(path, 'utf-8');+ files[key] = JSON.parse(content);+ }));- // Collect all markdown documents- const mdFiles = {};+ // Collect all markdown documents in parallel as well.const entries = await readdir(DIGITAL_TWIN_DIR).catch(() => []);- for (const entry of entries) {- if (entry.endsWith('.md')) {- const filePath = join(DIGITAL_TWIN_DIR, entry);- const info = await stat(filePath);- if (info.isFile()) {- mdFiles[entry] = await readFile(filePath, 'utf-8');- }- }+ const mdEntries = await Promise.all(+ entries+ .filter(entry => entry.endsWith('.md'))+ .map(async entry => {+ const filePath = join(DIGITAL_TWIN_DIR, entry);+ const info = await stat(filePath);+ if (!info.isFile()) return null;+ return { entry, content: await readFile(filePath, 'utf-8') };+ })+ );+ const mdFiles = {};+ for (const md of mdEntries) {+ if (md) mdFiles[md.entry] = md.content;}if (Object.keys(mdFiles).length > 0) {files.documents = mdFiles;diff --git a/server/services/weeklyDigest.js b/server/services/weeklyDigest.jsindex afc01f89c4..e70b37fb47 100644--- a/server/services/weeklyDigest.js+++ b/server/services/weeklyDigest.js@@ -377,22 +377,25 @@ export async function listWeeklyDigests() {await ensureDigestDir();const files = await readdir(DIGESTS_DIR);- const digests = [];-- for (const file of files.filter(f => f.endsWith('.json'))) {- const weekId = file.replace('.json', '');- const digest = await loadDigest(weekId);- if (digest) {- digests.push({- weekId: digest.weekId,- weekStart: digest.weekStart,- weekEnd: digest.weekEnd,- totalTasks: digest.summary.totalTasks,- successRate: digest.summary.successRate,- generatedAt: digest.generatedAt- });- }- }++ // Load each week's digest in parallel rather than serializing one disk read+ // per week across the full digest history.+ const loaded = await Promise.all(+ files+ .filter(f => f.endsWith('.json'))+ .map(file => loadDigest(file.replace('.json', '')))+ );++ const digests = loaded+ .filter(Boolean)+ .map(digest => ({+ weekId: digest.weekId,+ weekStart: digest.weekStart,+ weekEnd: digest.weekEnd,+ totalTasks: digest.summary.totalTasks,+ successRate: digest.summary.successRate,+ generatedAt: digest.generatedAt+ }));return digests.sort((a, b) => b.weekId.localeCompare(a.weekId));}