/** * 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.ts' export type BrainLogLevel = 'info' | 'warn' | 'error' export interface BrainLogEvent { level?: BrainLogLevel event: string scope?: 'global' | 'project' workspace?: string sessionId?: string detail?: Record err?: string } export interface BrainLoggerOptions { globalRoot: () => string projectRootOf: (workspace?: string) => string enabled: () => boolean /** Rollover size cap; tests inject a small number. Default 5 MB. */ maxBytes?: number /** Retention window in days. Default 14. */ retentionDays?: number now?: () => Date } 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: number): string { return value < 10 ? '0' + String(value) : String(value) } function dateStamp(date: Date): string { 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: unknown): unknown { if (typeof value === 'string') { if (containsSecret(value)) return '[redacted]' return value.length > MAX_FIELD_CHARS ? value.slice(0, MAX_FIELD_CHARS - 1) + '…' : 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: Record = {} for (const [key, item] of Object.entries(value as Record)) record[key] = sanitizeValue(item) return record } return undefined } function sanitizeDetail(detail: Record | undefined): Record | undefined { if (detail === undefined) return undefined const result: Record = {} for (const [key, value] of Object.entries(detail)) { const sanitized = sanitizeValue(value) if (sanitized !== undefined) result[key] = sanitized } return result } export class BrainLogger { private readonly opts: Required> & { maxBytes: number; retentionDays: number; now: () => Date } private queue: Promise = Promise.resolve() private warned = false constructor(options: BrainLoggerOptions) { 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: BrainLogEvent): void { try { if (!this.opts.enabled()) return const now = this.opts.now() const scope = event.scope ?? (event.workspace === undefined ? 'global' : 'project') const record: 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 - 1) + '…' : 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(): Promise { await this.queue.catch(() => {}) } /** Start-of-boot retention sweep; fire-and-forget and never throws. */ prune(): void { void this.pruneAsync().catch(() => {}) } private directoryFor(scope: 'global' | 'project', workspace?: string): string { return scope === 'project' ? join(this.opts.projectRootOf(workspace), 'logs') : join(this.opts.globalRoot(), 'logs') } private async appendLine(directory: string, stamp: string, line: string): Promise { 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' }) } private async pruneAsync(): Promise { 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(() => [] as string[]) 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(() => {}) } } } private warnOnce(): void { if (this.warned) return this.warned = true console.warn('[dsh-brain] diagnostic log write failed; continuing without logs') } }