feat(ai-psychosis): add readRecentEndRecords for cross-session reads

This commit is contained in:
Kjell Tore Guttormsen 2026-05-01 21:23:57 +02:00
commit f0f3bc3294
2 changed files with 108 additions and 3 deletions

View file

@ -195,6 +195,37 @@ export function sessionsToday() {
}
}
// Tail-first scan: return the N most recent end records (records with
// duration_min defined) in chronological order. Cost is bounded by N, not
// by total file size — a 50K-record sessions.jsonl is read once but only
// the last few hundred lines are JSON-parsed before N is satisfied.
export function readRecentEndRecords(n) {
if (!Number.isFinite(n) || n <= 0) return [];
if (!existsSync(SESSIONS_LOG)) return [];
let lines;
try {
lines = readFileSync(SESSIONS_LOG, 'utf8').split('\n');
} catch {
return [];
}
const collected = [];
for (let i = lines.length - 1; i >= 0 && collected.length < n; i--) {
const line = lines[i];
if (!line) continue;
try {
const rec = JSON.parse(line);
if (rec.duration_min !== undefined) {
collected.push(rec);
}
} catch { /* skip malformed */ }
}
// Reverse so caller receives oldest-first (chronological order).
return collected.reverse();
}
// --- State file management ---
export function sessionStateFile(sid) {