/** * Diagnostic JSONL logging for dsh-brain. * * Layout: /logs/brain-YYYY-MM-DD.log, with numbered rollover files when * one day's file exceeds the size cap. Global events go to $DSH_HOME/brain, * workspace-scoped events to /.dsh/brain. Writes are asynchronous and * must never affect the operation they describe: every failure is swallowed * after one console.warn. */ import { appendFile, mkdir, readdir, rename, stat, unlink } from 'node:fs/promises'; import { join } from 'node:path'; import { containsSecret } from "./local-memory/storage.js"; const MAX_FIELD_CHARS = 120; const MAX_ERR_CHARS = 300; const DEFAULT_MAX_BYTES = 5 * 1024 * 1024; const DEFAULT_RETENTION_DAYS = 14; function pad(value) { return value < 10 ? '0' + String(value) : String(value); } function dateStamp(date) { return String(date.getFullYear()) + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()); } /** Keep only small structured fields; long strings are truncated and secrets redacted. */ function sanitizeValue(value) { if (typeof value === 'string') { if (containsSecret(value)) return '[redacted]'; return value.length > MAX_FIELD_CHARS ? value.slice(0, MAX_FIELD_CHARS) + '…' : value; } if (typeof value === 'number' || typeof value === 'boolean' || value === null) return value; if (Array.isArray(value)) return value.slice(0, 20).map((item) => sanitizeValue(item)); if (typeof value === 'object' && value !== undefined) { const record = {}; for (const [key, item] of Object.entries(value)) record[key] = sanitizeValue(item); return record; } return undefined; } function sanitizeDetail(detail) { if (detail === undefined) return undefined; const result = {}; for (const [key, value] of Object.entries(detail)) { const sanitized = sanitizeValue(value); if (sanitized !== undefined) result[key] = sanitized; } return result; } export class BrainLogger { opts; queue = Promise.resolve(); warned = false; constructor(options) { this.opts = { globalRoot: options.globalRoot, projectRootOf: options.projectRootOf, enabled: options.enabled, maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES, retentionDays: options.retentionDays ?? DEFAULT_RETENTION_DAYS, now: options.now ?? (() => new Date()), }; } /** Synchronous enqueue; asynchronous append. Never throws. */ log(event) { try { if (!this.opts.enabled()) return; const now = this.opts.now(); const scope = event.scope ?? (event.workspace === undefined ? 'global' : 'project'); const record = { ts: now.toISOString(), level: event.level ?? 'info', event: event.event, scope, }; if (event.workspace !== undefined) record.workspace = event.workspace; if (event.sessionId !== undefined) record.sessionId = event.sessionId; const detail = sanitizeDetail(event.detail); if (detail !== undefined && Object.keys(detail).length > 0) record.detail = detail; if (event.err !== undefined) { const err = containsSecret(event.err) ? '[redacted]' : event.err.length > MAX_ERR_CHARS ? event.err.slice(0, MAX_ERR_CHARS) + '…' : event.err; record.err = err; } const line = JSON.stringify(record) + '\n'; const directory = this.directoryFor(scope, event.workspace); this.queue = this.queue.then(() => this.appendLine(directory, dateStamp(now), line)).catch(() => { this.warnOnce(); }); } catch { this.warnOnce(); } } /** Await all queued writes (tests / graceful shutdown). */ async flush() { await this.queue.catch(() => { }); } /** Start-of-boot retention sweep; fire-and-forget and never throws. */ prune() { void this.pruneAsync().catch(() => { }); } directoryFor(scope, workspace) { return scope === 'project' ? join(this.opts.projectRootOf(workspace), 'logs') : join(this.opts.globalRoot(), 'logs'); } async appendLine(directory, stamp, line) { await mkdir(directory, { recursive: true }); let file = join(directory, 'brain-' + stamp + '.log'); try { const info = await stat(file); if (info.size > 0 && info.size + Buffer.byteLength(line) > this.opts.maxBytes) { let index = 1; while (true) { const candidate = join(directory, 'brain-' + stamp + '.' + String(index) + '.log'); const exists = await stat(candidate).catch(() => undefined); if (exists === undefined) { await rename(file, candidate); break; } index += 1; } file = join(directory, 'brain-' + stamp + '.log'); } } catch { /* first write of the day: the file does not exist yet */ } await appendFile(file, line, { encoding: 'utf8' }); } async pruneAsync() { const roots = new Set([this.opts.globalRoot(), this.opts.projectRootOf(undefined)]); const cutoff = this.opts.now().getTime() - this.opts.retentionDays * 24 * 60 * 60 * 1000; for (const root of roots) { const directory = join(root, 'logs'); const entries = await readdir(directory).catch(() => []); for (const name of entries) { const match = /^brain-(\d{4}-\d{2}-\d{2})(?:\.\d+)?\.log$/.exec(name); if (match === null) continue; const stamp = Date.parse(match[1] + 'T00:00:00'); if (Number.isFinite(stamp) && stamp < cutoff) await unlink(join(directory, name)).catch(() => { }); } } } warnOnce() { if (this.warned) return; this.warned = true; if (typeof console !== 'undefined') console.warn('[dsh-brain] diagnostic log write failed; continuing without logs'); } }