import { readFile, readdir, stat } from 'node:fs/promises'; import { join } from 'node:path'; import { acquireFileLock, atomicWriteFile } from './fileStore.js'; export interface EpisodeTimeEntry { name: string; ino: number; size: number; mtimeMs: number; oldest: number; newest: number; count: number; } /** Rebuildable metadata only. JSONL remains the source of truth. Stat every * candidate; only changed files need parsing (the reader can reuse its tail cache). * Merge only this query's metadata under a short lock; other queries' entries * survive. Only confirmed absent source files are pruned. */ export async function indexEpisodeTimes< T extends { ino: number; size: number; mtimeMs: number; episodes: Array<{ createdAt: number }>; }, >( root: string, names: string[], load: (path: string) => Promise, signal?: AbortSignal, ) { const path = join(root, 'time-index-v1.json'); let prior: Record = {}; try { const parsed = JSON.parse(await readFile(path, 'utf8')); if ( parsed.version === 1 && parsed.entries && typeof parsed.entries === 'object' ) prior = parsed.entries; } catch { /* Missing/corrupt cache is rebuilt. */ } const entries: EpisodeTimeEntry[] = []; const loaded = new Map(); const failed: string[] = []; for (const name of names) { signal?.throwIfAborted(); try { const current = await stat(join(root, name)); const old = prior[name]; if ( old?.name === name && old.ino === current.ino && old.size === current.size && old.mtimeMs === current.mtimeMs && [old.oldest, old.newest, old.count].every(Number.isFinite) ) { entries.push(old); continue; } const file = await load(join(root, name)); let oldest = Number.MAX_SAFE_INTEGER; let newest = 0; for (const episode of file.episodes) { oldest = Math.min(oldest, episode.createdAt); newest = Math.max(newest, episode.createdAt); } entries.push({ name, ino: file.ino, size: file.size, mtimeMs: file.mtimeMs, oldest, newest, count: file.episodes.length, }); // Avoid retaining all source text while rebuilding a large directory. loaded.clear(); loaded.set(name, file); } catch (error) { signal?.throwIfAborted(); failed.push(name); } } try { const release = await acquireFileLock(path, signal); try { signal?.throwIfAborted(); // Re-read after locking: another workspace may have updated the index // while we were parsing. Never replace its entries with our old snapshot. const latest = await readFile(path, 'utf8').then(JSON.parse).catch(() => null); const next: Record = latest?.version === 1 && latest.entries && typeof latest.entries === 'object' && !Array.isArray(latest.entries) ? { ...latest.entries } : {}; for (const entry of entries) next[entry.name] = entry; const present = new Set(await readdir(root)); for (const name of Object.keys(next)) if (!present.has(name)) delete next[name]; signal?.throwIfAborted(); if (JSON.stringify(latest?.entries) !== JSON.stringify(next)) { await atomicWriteFile(path, JSON.stringify({ version: 1, entries: next })); } } finally { await release(); } } catch { signal?.throwIfAborted(); // Optional cache failure never makes readable source history unavailable. } return { entries, loaded, failed }; }