292 lines
11 KiB
TypeScript
292 lines
11 KiB
TypeScript
/**
|
|
* 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'
|
|
import type { RawMemoryRecord, RawMemorySearchHit, RawMemorySessionSummary, RawMemoryStatus } from './types.ts'
|
|
|
|
export interface RawMemoryStoreOptions {
|
|
root: string
|
|
maxBytesPerSession: number
|
|
/** Upper bound for one search scan; protects the host from a huge archive. */
|
|
maxScanBytes?: number
|
|
}
|
|
|
|
export interface RawMemorySearchOptions {
|
|
k?: number
|
|
sessionId?: string
|
|
role?: 'user' | 'assistant'
|
|
}
|
|
|
|
export interface RawMemoryReadOptions {
|
|
seq?: number
|
|
offset?: number
|
|
limit?: number
|
|
}
|
|
|
|
function sizeOf(path: string): Promise<number> {
|
|
return stat(path).then((info) => info.size).catch(() => 0)
|
|
}
|
|
|
|
function snippetFor(text: string, terms: string[]): string {
|
|
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: unknown): value is RawMemoryRecord {
|
|
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
|
|
const record = value as Record<string, unknown>
|
|
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 {
|
|
private readonly options: RawMemoryStoreOptions & { maxScanBytes: number }
|
|
private readonly queues = new Map<string, Promise<void>>()
|
|
private readonly sizes = new Map<string, number>()
|
|
|
|
constructor(options: RawMemoryStoreOptions) {
|
|
this.options = { ...options, maxScanBytes: options.maxScanBytes ?? 128 * 1024 * 1024 }
|
|
}
|
|
|
|
get dir(): string {
|
|
return this.options.root
|
|
}
|
|
|
|
private safeSessionName(sessionId: string): string {
|
|
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}`
|
|
}
|
|
|
|
private fileFor(sessionId: string): string {
|
|
return join(this.options.root, `${this.safeSessionName(sessionId)}.jsonl`)
|
|
}
|
|
|
|
private rotatedFor(file: string): string {
|
|
return file.replace(/\.jsonl$/, '.1.jsonl')
|
|
}
|
|
|
|
private async listFiles(): Promise<string[]> {
|
|
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 []
|
|
}
|
|
}
|
|
|
|
private async readRecords(file: string): Promise<RawMemoryRecord[]> {
|
|
let text: string
|
|
try {
|
|
text = await readFile(file, 'utf8')
|
|
} catch {
|
|
return []
|
|
}
|
|
const records: RawMemoryRecord[] = []
|
|
for (const line of text.split(/\r?\n/)) {
|
|
if (line.trim() === '') continue
|
|
try {
|
|
const value: unknown = 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: RawMemoryRecord): Promise<void> {
|
|
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: string, options: RawMemorySearchOptions = {}): Promise<{
|
|
matches: RawMemorySearchHit[]
|
|
total: number
|
|
truncated: boolean
|
|
sessionsScanned: number
|
|
}> {
|
|
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: RawMemorySearchHit[] = []
|
|
const seenSessions = new Set<string>()
|
|
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: string, options: RawMemoryReadOptions = {}): Promise<{
|
|
sessionId: string
|
|
total: number
|
|
items: RawMemoryRecord[]
|
|
}> {
|
|
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: boolean, retentionDays: number): Promise<RawMemoryStatus> {
|
|
const files = await this.listFiles()
|
|
let records = 0
|
|
let bytes = 0
|
|
const sessions = new Set<string>()
|
|
let oldest: number | undefined
|
|
let newest: number | undefined
|
|
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): Promise<RawMemorySessionSummary[]> {
|
|
const files = await this.listFiles()
|
|
const sessions = new Map<string, RawMemorySessionSummary>()
|
|
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: number): Promise<number> {
|
|
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
|
|
}
|
|
}
|
|
|
|
|