dsh-brain/lib/raw-memory/store.js

268 lines
11 KiB
JavaScript

/**
* Append-only original-record store.
*
* One JSONL file per session, under a separate directory from Mnemon's
* mnemon.db. The raw layer deliberately does not join Mnemon's identity /
* merge tables: those walk every non-oplog row and would become slower with
* every captured message. Rotation keeps one session bounded; retention is
* enforced by the entry's maintenance timer.
*/
import { createHash } from 'node:crypto';
import { appendFile, mkdir, readdir, readFile, rename, rm, stat } from 'node:fs/promises';
import { join } from 'node:path';
function sizeOf(path) {
return stat(path).then((info) => info.size).catch(() => 0);
}
function snippetFor(text, terms) {
const lower = text.toLowerCase();
let first = -1;
for (const term of terms) {
const found = lower.indexOf(term);
if (found >= 0 && (first < 0 || found < first))
first = found;
}
const start = first <= 80 ? 0 : first - 80;
const end = Math.min(text.length, start + 500);
return `${start > 0 ? '…' : ''}${text.slice(start, end)}${end < text.length ? '…' : ''}`;
}
function isRecord(value) {
if (value === null || typeof value !== 'object' || Array.isArray(value))
return false;
const record = value;
return record.v === 1
&& typeof record.sessionId === 'string'
&& typeof record.text === 'string'
&& (record.role === 'user' || record.role === 'assistant')
&& typeof record.createdAt === 'number';
}
export class RawMemoryStore {
options;
queues = new Map();
sizes = new Map();
constructor(options) {
this.options = { ...options, maxScanBytes: options.maxScanBytes ?? 128 * 1024 * 1024 };
}
get dir() {
return this.options.root;
}
safeSessionName(sessionId) {
const readable = sessionId.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 80) || 'session';
const hash = createHash('sha256').update(sessionId).digest('hex').slice(0, 8);
return `${readable}-${hash}`;
}
fileFor(sessionId) {
return join(this.options.root, `${this.safeSessionName(sessionId)}.jsonl`);
}
rotatedFor(file) {
return file.replace(/\.jsonl$/, '.1.jsonl');
}
async listFiles() {
try {
const entries = await readdir(this.options.root, { withFileTypes: true });
return entries
.filter((entry) => entry.isFile() && entry.name.endsWith('.jsonl'))
.map((entry) => join(this.options.root, entry.name))
.sort();
}
catch {
return [];
}
}
async readRecords(file) {
let text;
try {
text = await readFile(file, 'utf8');
}
catch {
return [];
}
const records = [];
for (const line of text.split(/\r?\n/)) {
if (line.trim() === '')
continue;
try {
const value = JSON.parse(line);
if (isRecord(value))
records.push(value);
}
catch {
// A torn final line must not make the rest of the file unreadable.
}
}
return records;
}
/** Append one message, serialized per session so concurrent turns cannot interleave. */
async append(record) {
const file = this.fileFor(record.sessionId);
const line = `${JSON.stringify(record)}\n`;
const incoming = Buffer.byteLength(line, 'utf8');
const previous = this.queues.get(file) ?? Promise.resolve();
const next = previous.then(async () => {
await mkdir(this.options.root, { recursive: true });
let size = this.sizes.get(file);
if (size === undefined)
size = await sizeOf(file);
if (size > 0 && size + incoming > this.options.maxBytesPerSession) {
const rotated = this.rotatedFor(file);
await rm(rotated, { force: true }).catch(() => undefined);
await rename(file, rotated).catch(() => undefined);
size = 0;
}
await appendFile(file, line, { encoding: 'utf8', mode: 0o600 });
this.sizes.set(file, size + incoming);
}).finally(() => {
if (this.queues.get(file) === next)
this.queues.delete(file);
});
this.queues.set(file, next);
await next;
}
/** Keyword search over original text, newest / best match first. */
async search(query, options = {}) {
const normalized = query.trim().toLowerCase();
const terms = normalized.split(/\s+/).filter((term) => term !== '');
if (terms.length === 0)
return { matches: [], total: 0, truncated: false, sessionsScanned: 0 };
// Boundary responsibility: callers (raw tools and routes) validate and clamp k.
const k = options.k ?? 10;
const files = await this.listFiles();
const matches = [];
const seenSessions = new Set();
let total = 0;
let scannedBytes = 0;
let truncated = false;
for (const file of files) {
// The scan cap is always set by the constructor; hitting it is reported
// explicitly through `truncated`, never silently.
if (scannedBytes >= this.options.maxScanBytes) {
truncated = true;
break;
}
scannedBytes += await sizeOf(file);
for (const record of await this.readRecords(file)) {
seenSessions.add(record.sessionId);
if (options.sessionId !== undefined && record.sessionId !== options.sessionId)
continue;
if (options.role !== undefined && record.role !== options.role)
continue;
const haystack = `${record.text.toLowerCase()}\n${record.sessionId.toLowerCase()}`;
let score = 0;
for (const term of terms)
if (haystack.includes(term))
score += 1;
if (score === 0)
continue;
if (haystack.includes(normalized))
score += 2;
total += 1;
matches.push({
sessionId: record.sessionId,
...(record.seq === undefined ? {} : { seq: record.seq }),
...(record.turn === undefined ? {} : { turn: record.turn }),
role: record.role,
...(record.time === undefined ? {} : { time: record.time }),
createdAt: record.createdAt,
...(record.messageId === undefined ? {} : { messageId: record.messageId }),
snippet: snippetFor(record.text, terms),
score,
});
}
}
matches.sort((left, right) => right.score - left.score || right.createdAt - left.createdAt);
return { matches: matches.slice(0, k), total, truncated, sessionsScanned: seenSessions.size };
}
/** Read one session, either by exact event seq or by record offset. */
async readSession(sessionId, options = {}) {
const file = this.fileFor(sessionId);
const records = [...await this.readRecords(this.rotatedFor(file)), ...await this.readRecords(file)];
let selected = records;
if (options.seq !== undefined) {
selected = records.filter((record) => record.seq === options.seq);
}
else {
// Boundary responsibility: callers (raw tools and routes) validate and clamp offset/limit.
const offset = options.offset ?? 0;
const limit = options.limit ?? 50;
selected = records.slice(offset, offset + limit);
}
return { sessionId, total: records.length, items: selected };
}
/** Aggregate counts for the status tool. */
async status(enabled, retentionDays) {
const files = await this.listFiles();
let records = 0;
let bytes = 0;
const sessions = new Set();
let oldest;
let newest;
for (const file of files) {
bytes += await sizeOf(file);
for (const record of await this.readRecords(file)) {
records += 1;
sessions.add(record.sessionId);
if (oldest === undefined || record.createdAt < oldest)
oldest = record.createdAt;
if (newest === undefined || record.createdAt > newest)
newest = record.createdAt;
}
}
return {
enabled,
dir: this.options.root,
sessions: sessions.size,
records,
bytes,
...(oldest === undefined ? {} : { oldestAt: new Date(oldest).toISOString() }),
...(newest === undefined ? {} : { newestAt: new Date(newest).toISOString() }),
retentionDays,
maxBytesPerSession: this.options.maxBytesPerSession,
};
}
/** Session rows for the Brain panel's session browser, newest first. */
async listSessions(limit = 30) {
const files = await this.listFiles();
const sessions = new Map();
for (const file of files) {
const bytes = await sizeOf(file);
const records = await this.readRecords(file);
if (records.length === 0)
continue;
const sessionId = records[0].sessionId;
const summary = sessions.get(sessionId) ?? { sessionId, records: 0, bytes: 0 };
summary.records += records.length;
summary.bytes += bytes;
for (const record of records) {
const stamp = record.time ?? record.createdAt;
if (summary.firstAt === undefined || stamp < summary.firstAt)
summary.firstAt = stamp;
if (summary.lastAt === undefined || stamp > summary.lastAt)
summary.lastAt = stamp;
summary.latestSnippet = record.text.slice(0, 160);
}
sessions.set(sessionId, summary);
}
return [...sessions.values()]
.sort((left, right) => (right.lastAt ?? 0) - (left.lastAt ?? 0))
.slice(0, Math.max(1, Math.min(200, Math.trunc(limit))));
}
/** Delete session files whose last write is older than the retention window. */
async prune(retentionDays) {
const cutoff = Date.now() - retentionDays * 24 * 60 * 60 * 1000;
let removed = 0;
for (const file of await this.listFiles()) {
try {
const info = await stat(file);
if (info.mtimeMs < cutoff) {
await rm(file, { force: true });
removed += 1;
this.sizes.delete(file);
}
}
catch {
// A file removed concurrently is already in the desired state.
}
}
return removed;
}
}