feat(diagnostics): JSONL debug logs under .dsh/brain/logs with redaction and rotation

This commit is contained in:
newbie 2026-11-25 12:28:53 +08:00
parent 3d7b59b4c9
commit bdea045635
23 changed files with 605 additions and 12 deletions

View File

@ -28,6 +28,8 @@ export const DEFAULT_SETTINGS = {
autoProfileEnabled: true,
/** Default result count for local memory search. */
localMemoryK: 5,
/** Diagnostic JSONL logs under .dsh/brain/logs; defaults on, inherits enabled. */
diagnosticsEnabled: true,
};
const MIN_TIMEOUT_MS = 1000;
const MAX_TIMEOUT_MS = 60_000;
@ -134,6 +136,8 @@ export function settingsFromConfig(raw) {
result.autoSummaryEnabled = source.autoSummaryEnabled;
if (typeof source.autoProfileEnabled === 'boolean')
result.autoProfileEnabled = source.autoProfileEnabled;
if (typeof source.diagnosticsEnabled === 'boolean')
result.diagnosticsEnabled = source.diagnosticsEnabled;
const localMemoryK = boundedInt(source.localMemoryK, 1, 100);
if (localMemoryK !== undefined)
result.localMemoryK = localMemoryK;

153
lib/diagnostics.js Normal file
View File

@ -0,0 +1,153 @@
/**
* Diagnostic JSONL logging for dsh-brain.
*
* Layout: <root>/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 <project>/.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');
}
}

View File

@ -13,6 +13,7 @@ export function apply(ctx, config) {
const logger = ctx.logger('dsh-brain');
const kernel = brainKernel(config, logger);
kernel.activate('cloudsync');
kernel.logEvent('boot.entry', { bundle: 'cloudsync' });
ctx.effect(() => () => kernel.deactivate('cloudsync'), 'dsh-brain-cloudsync: activation');
// The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a
// third-party bundle cannot rely on; bind the listener through a local shape.

View File

@ -6,5 +6,6 @@ export const inject = [];
export function apply(ctx, config) {
const kernel = brainKernel(config, ctx.logger('dsh-brain'));
kernel.activate('mcp');
kernel.logEvent('boot.entry', { bundle: 'mcp' });
ctx.effect(() => () => kernel.deactivate('mcp'), 'dsh-brain-mcp: activation');
}

View File

@ -10,6 +10,7 @@ export function apply(ctx, config) {
const logger = ctx.logger('dsh-brain');
const kernel = brainKernel(config, logger);
kernel.activate('memory');
kernel.logEvent('boot.entry', { bundle: 'memory' });
ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation');
ctx.inject(['tools'], (toolsCtx) => {
const tools = toolsCtx.tools;

View File

@ -9,6 +9,7 @@ export function apply(ctx, config) {
const logger = ctx.logger('dsh-brain');
const kernel = brainKernel(config, logger);
kernel.activate('settings-ui');
kernel.logEvent('boot.entry', { bundle: 'settings-ui' });
ctx.effect(() => () => kernel.deactivate('settings-ui'), 'dsh-brain-settings-ui: activation');
const webServer = ctx.webServer;
if (webServer === undefined) {

View File

@ -10,6 +10,7 @@ export function apply(ctx, config) {
const logger = ctx.logger('dsh-brain');
const kernel = brainKernel(config, logger);
kernel.activate('skills');
kernel.logEvent('boot.entry', { bundle: 'skills' });
ctx.effect(() => () => kernel.deactivate('skills'), 'dsh-brain-skills: activation');
ctx.inject(['tools'], (toolsCtx) => {
const tools = toolsCtx.tools;

View File

@ -1,5 +1,10 @@
/** Largest request body we accept (a settings patch is tiny). */
export const MAX_BODY_BYTES = 64 * 1024;
/** Optional diagnostics hook for failed route responses (set by the kernel). */
let routeErrorHook;
export function setRouteErrorHook(hook) {
routeErrorHook = hook;
}
/** Collect a request body as UTF-8 text. */
export async function readBody(req, maxBytes = MAX_BODY_BYTES) {
const chunks = [];
@ -33,6 +38,12 @@ export function json(res, status, body) {
}
/** Emit a plain-text error (page route) or JSON error (API routes). */
export function fail(res, status, message, asHtml = false) {
try {
routeErrorHook?.('route.error', { status, error: message, html: asHtml });
}
catch {
/* diagnostics must never change the response */
}
const text = asHtml
? `<!doctype html><meta charset="utf-8"><title>云端记忆</title><body style="font:14px system-ui;padding:32px">${message}</body>`
: JSON.stringify({ ok: false, error: message });

View File

@ -20,7 +20,9 @@
*/
import { join, resolve } from 'node:path';
import { CloudClient } from "./api.js";
import { DepartmentManager, LocalMemoryManager, LocalMemoryRemote } from "./local-memory/index.js";
import { BrainLogger } from "./diagnostics.js";
import { setRouteErrorHook } from "./http.js";
import { DepartmentManager, LocalMemoryManager, LocalMemoryRemote, globalBrainRoot, projectBrainRoot } from "./local-memory/index.js";
import { VERSION } from "./version.js";
import { createCloudMemoryRemoteFactory } from "./cloudsync.js";
import { ClientRegistry } from "./clients.js";
@ -55,6 +57,7 @@ export class BrainKernel {
active = new Set();
settingsOf;
store;
diagnostics;
client;
memoryRemoteFactory;
localMemory;
@ -73,6 +76,16 @@ export class BrainKernel {
this.store = store;
const settings = () => store.settings();
this.settingsOf = settings;
this.diagnostics = new BrainLogger({
globalRoot: globalBrainRoot,
projectRootOf: (workspace) => projectBrainRoot(workspace),
enabled: () => {
const effective = settings();
return effective.diagnosticsEnabled !== false && effective.enabled !== false;
},
});
setRouteErrorHook((event, detail) => this.diagnostics.log({ event, level: 'warn', detail }));
this.diagnostics.prune();
// One client per instance; the settings closures keep it live across edits.
const client = new CloudClient({
baseUrl: () => settings().baseUrl,
@ -90,6 +103,7 @@ export class BrainKernel {
// lazily on the first memory tool call and needs no token or account.
this.localMemory = new LocalMemoryManager({
cwd: () => process.cwd(),
logger: this.diagnostics,
settings: () => ({
localMemoryEnabled: settings().localMemoryEnabled,
cloudMemoryEnabled: settings().cloudMemoryEnabled,
@ -208,11 +222,24 @@ export class BrainKernel {
if (effective.summaryEnabled && store.summaryToken() === '') {
logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged');
}
this.diagnostics.log({
event: 'boot.kernel',
detail: {
version: VERSION,
localMemoryEnabled: effective.localMemoryEnabled !== false,
cloudMemoryEnabled: effective.cloudMemoryEnabled === true,
autoSummaryEnabled: effective.autoSummaryEnabled !== false,
},
});
}
/** Current settings snapshot (live: re-read on every call). */
settings() {
return this.settingsOf();
}
/** Emit one diagnostic event through the shared logger (entries and route wiring). */
logEvent(event, detail, scope, workspace) {
this.diagnostics.log({ event, detail, scope, workspace });
}
/** Mark a bundle's entry as applied; feeds `routeDeps()` gating. */
activate(bundle) {
this.active.add(bundle);
@ -308,4 +335,5 @@ export function brainKernel(config, logger) {
/** Test hook: drop the singleton so the next call rebuilds it. */
export function resetBrainKernel() {
instance = undefined;
setRouteErrorHook(undefined);
}

View File

@ -83,12 +83,17 @@ export class LocalMemoryManager {
workspaces = new Map();
fixedGlobalRoot;
fixedProjectRoot;
loggerOf;
constructor(options = {}) {
this.cwdOf = options.cwd ?? (() => process.cwd());
this.defaultWorkspaceOf = options.workspace;
this.settingsOf = options.settings ?? (() => ({}));
this.fixedGlobalRoot = options.globalRoot;
this.fixedProjectRoot = options.projectRoot;
this.loggerOf = options.logger === undefined ? undefined : { log: (event) => { try {
options.logger.log(event);
}
catch { /* diagnostics must never break memory operations */ } } };
}
/** Bind one operation to a workspace; AsyncLocalStorage keeps concurrent sessions isolated. */
withWorkspace(workspace, job) { return this.workspaceContext.run(workspace, job); }
@ -163,6 +168,7 @@ export class LocalMemoryManager {
if (!(await stat(initPath).catch(() => undefined)))
await atomicWrite(initPath, JSON.stringify({ version: 1, globalReady: true, createdAt: new Date().toISOString() }, null, 2) + '\n');
await this.repairProjectionsIfDirty();
this.loggerOf?.log({ event: 'memory.ensure', detail: { scope: 'global', root: this.globalRoot } });
return meta;
});
}
@ -194,6 +200,7 @@ export class LocalMemoryManager {
});
const state = { root, store, documents };
this.workspaces.set(root, state);
this.loggerOf?.log({ event: 'memory.ensure', scope: 'project', workspace: base, detail: { scope: 'project', root } });
return store;
});
}
@ -207,14 +214,19 @@ export class LocalMemoryManager {
}
/** Add one memory and regenerate the compact projections. */
async remember(input) {
const startedAt = Date.now();
const workspace = this.workspacePath();
const scope = input.scope ?? 'project';
const store = await this.storeFor(scope, workspace);
await this.markProjectionDirty();
const result = await store.add({ ...input, projectId: input.projectId ?? (scope === 'project' ? projectIdFor(this.projectRootFor(workspace)) : undefined) });
if (result.duplicate)
if (result.duplicate) {
this.loggerOf?.log({ event: 'memory.remember', scope: scope === 'global' ? 'global' : 'project', workspace, sessionId: input.sessionId, detail: { recordId: result.record.id, duplicate: true, category: input.category, durationMs: Date.now() - startedAt } });
return result;
return { ...result, ...(await this.tryRegenerateProjections()) };
}
const outcome = { ...result, ...(await this.tryRegenerateProjections()) };
this.loggerOf?.log({ event: 'memory.remember', scope: scope === 'global' ? 'global' : 'project', workspace, sessionId: input.sessionId, detail: { recordId: outcome.record.id, duplicate: false, category: input.category, durationMs: Date.now() - startedAt } });
return outcome;
}
async add(input) { return this.remember(input); }
async read(id, workspace) {
@ -240,9 +252,15 @@ export class LocalMemoryManager {
.sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt));
}
async searchHits(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) {
const startedAt = Date.now();
const hits = await this.collectHits(query, workspace, projectId);
const limit = Math.max(1, Math.min(100, Math.trunc(k)));
return hits.slice(0, limit);
const result = hits.slice(0, limit);
const sources = {};
for (const hit of result)
sources[hit.record.scope] = (sources[hit.record.scope] ?? 0) + 1;
this.loggerOf?.log({ event: 'memory.search', scope: 'project', workspace, detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } });
return result;
}
async search(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) {
return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record);
@ -271,11 +289,13 @@ export class LocalMemoryManager {
if (globalRecord !== undefined) {
const removed = await this.globalStore.forget(id, expectedRevision);
await this.tryRegenerateProjections();
this.loggerOf?.log({ event: 'memory.forget', scope: 'global', detail: { recordId: id, revision: removed.revision } });
return removed;
}
const store = await this.ensureProject(workspace);
const removed = await store.forget(id, expectedRevision);
await this.tryRegenerateProjections();
this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace, detail: { recordId: id, revision: removed.revision } });
return removed;
}
async projects(workspace) {
@ -336,6 +356,7 @@ export class LocalMemoryManager {
await atomicWrite(join(this.globalRoot, 'runtime', 'USER.md'), render('USER', user));
await atomicWrite(join(this.globalRoot, 'runtime', 'MEMORY.md'), render('MEMORY', rules));
await this.clearProjectionDirty(marker);
this.loggerOf?.log({ event: 'memory.projection', detail: { root: this.globalRoot } });
}
catch (error) {
await this.markProjectionDirty(error);
@ -396,8 +417,10 @@ export class LocalMemoryManager {
await atomicWrite(checkpointPath, JSON.stringify(checkpoints, null, 2) + '\n');
if (stored > 0) {
const repair = await this.tryRegenerateProjections();
this.loggerOf?.log({ event: 'memory.summary', sessionId: input.sessionId, detail: { turns: input.turns.length, stored, duplicates, skipped: false } });
return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false, ...repair };
}
this.loggerOf?.log({ event: 'memory.summary', sessionId: input.sessionId, detail: { turns: input.turns.length, stored, duplicates, skipped: false } });
return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false };
});
}
@ -426,6 +449,7 @@ export class LocalMemoryManager {
continue;
await cp(join(this.globalRoot, entry.name), join(path, entry.name), { recursive: true, force: false });
}
this.loggerOf?.log({ event: 'memory.backup', detail: { path } });
return { path };
}
/** Report legacy .mnemon locations without deleting anything. */

View File

@ -117,6 +117,8 @@ function parseState(raw) {
state.autoSummaryEnabled = source.autoSummaryEnabled;
if (typeof source.autoProfileEnabled === 'boolean')
state.autoProfileEnabled = source.autoProfileEnabled;
if (typeof source.diagnosticsEnabled === 'boolean')
state.diagnosticsEnabled = source.diagnosticsEnabled;
const localMemoryK = clampInt(source.localMemoryK, 1, 100);
if (localMemoryK !== undefined)
state.localMemoryK = localMemoryK;
@ -241,6 +243,8 @@ export class SettingsStore {
resolved.autoProfileEnabled = this.state.autoProfileEnabled;
if (this.state.localMemoryK !== undefined)
resolved.localMemoryK = this.state.localMemoryK;
if (this.state.diagnosticsEnabled !== undefined)
resolved.diagnosticsEnabled = this.state.diagnosticsEnabled;
// The split gates inherit `enabled` unless the config or the sidecar set
// them explicitly, so an old configuration keeps its exact behaviour.
if (this.state.activityEnabled === undefined && this.configExplicit.activityEnabled === undefined) {
@ -399,7 +403,7 @@ export class SettingsStore {
return { ok: false, error: 'skillsDir too long' };
next.skillsDir = skillsDir;
}
for (const key of ['localMemoryEnabled', 'cloudMemoryEnabled', 'autoMemorySpaces', 'autoSummaryEnabled', 'autoProfileEnabled']) {
for (const key of ['localMemoryEnabled', 'cloudMemoryEnabled', 'autoMemorySpaces', 'autoSummaryEnabled', 'autoProfileEnabled', 'diagnosticsEnabled']) {
if (patch[key] !== undefined) {
if (typeof patch[key] !== 'boolean')
return { ok: false, error: key + ' must be a boolean' };

View File

@ -29,6 +29,8 @@ export const DEFAULT_SETTINGS: Settings = {
autoProfileEnabled: true,
/** Default result count for local memory search. */
localMemoryK: 5,
/** Diagnostic JSONL logs under .dsh/brain/logs; defaults on, inherits enabled. */
diagnosticsEnabled: true,
}
/** Effective, fully-resolved settings. */
@ -67,6 +69,8 @@ export interface Settings {
autoProfileEnabled: boolean
/** Default local memory result count. */
localMemoryK: number
/** Diagnostic JSONL logging switch. */
diagnosticsEnabled: boolean
}
/** Raw row config as it comes out of the cordis loader. */
@ -157,6 +161,7 @@ export function settingsFromConfig(raw: unknown): Partial<Settings> {
if (typeof source.autoMemorySpaces === 'boolean') result.autoMemorySpaces = source.autoMemorySpaces
if (typeof source.autoSummaryEnabled === 'boolean') result.autoSummaryEnabled = source.autoSummaryEnabled
if (typeof source.autoProfileEnabled === 'boolean') result.autoProfileEnabled = source.autoProfileEnabled
if (typeof source.diagnosticsEnabled === 'boolean') result.diagnosticsEnabled = source.diagnosticsEnabled
const localMemoryK = boundedInt(source.localMemoryK, 1, 100)
if (localMemoryK !== undefined) result.localMemoryK = localMemoryK
return result

170
src/diagnostics.ts Normal file
View File

@ -0,0 +1,170 @@
/**
* Diagnostic JSONL logging for dsh-brain.
*
* Layout: <root>/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 <project>/.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<string, unknown>
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) + '…' : 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<string, unknown> = {}
for (const [key, item] of Object.entries(value as Record<string, unknown>)) record[key] = sanitizeValue(item)
return record
}
return undefined
}
function sanitizeDetail(detail: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
if (detail === undefined) return undefined
const result: Record<string, unknown> = {}
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<Pick<BrainLoggerOptions, 'globalRoot' | 'projectRootOf' | 'enabled'>> & { maxBytes: number; retentionDays: number; now: () => Date }
private queue: Promise<void> = 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<string, unknown> = {
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(): Promise<void> {
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<void> {
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<void> {
const roots = new Set<string>([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
if (typeof console !== 'undefined') console.warn('[dsh-brain] diagnostic log write failed; continuing without logs')
}
}

View File

@ -29,6 +29,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
const logger = ctx.logger('dsh-brain')
const kernel = brainKernel(config, logger)
kernel.activate('cloudsync')
kernel.logEvent('boot.entry', { bundle: 'cloudsync' })
ctx.effect(() => () => kernel.deactivate('cloudsync'), 'dsh-brain-cloudsync: activation')
// The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a

View File

@ -20,5 +20,6 @@ export const inject: string[] = []
export function apply(ctx: CloudMemoryContext, config: unknown): void {
const kernel = brainKernel(config, ctx.logger('dsh-brain'))
kernel.activate('mcp')
kernel.logEvent('boot.entry', { bundle: 'mcp' })
ctx.effect(() => () => kernel.deactivate('mcp'), 'dsh-brain-mcp: activation')
}

View File

@ -24,6 +24,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
const logger = ctx.logger('dsh-brain')
const kernel = brainKernel(config, logger)
kernel.activate('memory')
kernel.logEvent('boot.entry', { bundle: 'memory' })
ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation')
ctx.inject(['tools'], (toolsCtx) => {

View File

@ -21,6 +21,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
const logger = ctx.logger('dsh-brain')
const kernel = brainKernel(config, logger)
kernel.activate('settings-ui')
kernel.logEvent('boot.entry', { bundle: 'settings-ui' })
ctx.effect(() => () => kernel.deactivate('settings-ui'), 'dsh-brain-settings-ui: activation')
const webServer = ctx.webServer

View File

@ -23,6 +23,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
const logger = ctx.logger('dsh-brain')
const kernel = brainKernel(config, logger)
kernel.activate('skills')
kernel.logEvent('boot.entry', { bundle: 'skills' })
ctx.effect(() => () => kernel.deactivate('skills'), 'dsh-brain-skills: activation')
ctx.inject(['tools'], (toolsCtx) => {

View File

@ -7,6 +7,13 @@ import type { IncomingMessage, ServerResponse } from 'node:http'
/** Largest request body we accept (a settings patch is tiny). */
export const MAX_BODY_BYTES = 64 * 1024
/** Optional diagnostics hook for failed route responses (set by the kernel). */
let routeErrorHook: ((event: string, detail: Record<string, unknown>) => void) | undefined
export function setRouteErrorHook(hook: ((event: string, detail: Record<string, unknown>) => void) | undefined): void {
routeErrorHook = hook
}
/** Collect a request body as UTF-8 text. */
export async function readBody(req: IncomingMessage, maxBytes = MAX_BODY_BYTES): Promise<string> {
const chunks: Buffer[] = []
@ -41,6 +48,11 @@ export function json(res: ServerResponse, status: number, body: unknown): void {
/** Emit a plain-text error (page route) or JSON error (API routes). */
export function fail(res: ServerResponse, status: number, message: string, asHtml = false): void {
try {
routeErrorHook?.('route.error', { status, error: message, html: asHtml })
} catch {
/* diagnostics must never change the response */
}
const text = asHtml
? `<!doctype html><meta charset="utf-8"><title>云端记忆</title><body style="font:14px system-ui;padding:32px">${message}</body>`
: JSON.stringify({ ok: false, error: message })

View File

@ -20,7 +20,9 @@
*/
import { join, resolve } from 'node:path'
import { CloudClient } from './api.ts'
import { DepartmentManager, LocalMemoryManager, LocalMemoryRemote } from './local-memory/index.ts'
import { BrainLogger } from './diagnostics.ts'
import { setRouteErrorHook } from './http.ts'
import { DepartmentManager, LocalMemoryManager, LocalMemoryRemote, globalBrainRoot, projectBrainRoot } from './local-memory/index.ts'
import { VERSION } from './version.ts'
import { createCloudMemoryRemoteFactory } from './cloudsync.ts'
import type { DepartmentToolDeps } from './memory/departments-tools.ts'
@ -69,6 +71,7 @@ export class BrainKernel {
private readonly settingsOf: () => ReturnType<SettingsStore['settings']>
readonly store: SettingsStore
readonly diagnostics: BrainLogger
readonly client: CloudClient
readonly memoryRemoteFactory: ReturnType<typeof createCloudMemoryRemoteFactory>
readonly localMemory: LocalMemoryManager
@ -89,6 +92,17 @@ export class BrainKernel {
const settings = () => store.settings()
this.settingsOf = settings
this.diagnostics = new BrainLogger({
globalRoot: globalBrainRoot,
projectRootOf: (workspace?: string) => projectBrainRoot(workspace),
enabled: () => {
const effective = settings()
return effective.diagnosticsEnabled !== false && effective.enabled !== false
},
})
setRouteErrorHook((event, detail) => this.diagnostics.log({ event, level: 'warn', detail }))
this.diagnostics.prune()
// One client per instance; the settings closures keep it live across edits.
const client = new CloudClient({
baseUrl: () => settings().baseUrl,
@ -108,6 +122,7 @@ export class BrainKernel {
// lazily on the first memory tool call and needs no token or account.
this.localMemory = new LocalMemoryManager({
cwd: () => process.cwd(),
logger: this.diagnostics,
settings: () => ({
localMemoryEnabled: settings().localMemoryEnabled,
cloudMemoryEnabled: settings().cloudMemoryEnabled,
@ -233,6 +248,15 @@ export class BrainKernel {
if (effective.summaryEnabled && store.summaryToken() === '') {
logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged')
}
this.diagnostics.log({
event: 'boot.kernel',
detail: {
version: VERSION,
localMemoryEnabled: effective.localMemoryEnabled !== false,
cloudMemoryEnabled: effective.cloudMemoryEnabled === true,
autoSummaryEnabled: effective.autoSummaryEnabled !== false,
},
})
}
/** Current settings snapshot (live: re-read on every call). */
@ -240,6 +264,11 @@ export class BrainKernel {
return this.settingsOf()
}
/** Emit one diagnostic event through the shared logger (entries and route wiring). */
logEvent(event: string, detail?: Record<string, unknown>, scope?: 'global' | 'project', workspace?: string): void {
this.diagnostics.log({ event, detail, scope, workspace })
}
/** Mark a bundle's entry as applied; feeds `routeDeps()` gating. */
activate(bundle: BrainBundle): void {
this.active.add(bundle)
@ -340,4 +369,5 @@ export function brainKernel(config: unknown, logger: KernelLogger): BrainKernel
/** Test hook: drop the singleton so the next call rebuilds it. */
export function resetBrainKernel(): void {
instance = undefined
setRouteErrorHook(undefined)
}

View File

@ -7,6 +7,7 @@ import { dirname, join, resolve } from 'node:path'
import { dshHome } from '../store.ts'
import { JsonDocumentStore, JsonMemoryStore, containsSecret, localMemoryHash, withFileLock } from './storage.ts'
import type { LocalDocument, LocalMemoryAddInput, LocalMemoryRecord, LocalMemoryScope, LocalMemorySettings, LocalSpaceMeta } from './types.ts'
import type { BrainLogger, BrainLogEvent } from '../diagnostics.ts'
export function globalBrainRoot(): string { return resolve(dshHome(), 'brain') }
/** Resolve a user-supplied workspace to its project base, accepting both the project root and its .dsh/brain path. */
@ -70,6 +71,8 @@ export interface LocalMemoryManagerOptions {
globalRoot?: string
/** Optional explicit project root; defaults to <cwd>/.dsh/brain. */
projectRoot?: string
/** Optional diagnostic logger; absent means a byte-equivalent no-op. */
logger?: BrainLogger
}
export interface LocalTurn { turnId?: string; user?: string; assistant?: string }
interface WorkspaceStores { root: string; store: JsonMemoryStore; documents: JsonDocumentStore }
@ -83,12 +86,14 @@ export class LocalMemoryManager {
private readonly workspaces = new Map<string, WorkspaceStores>()
private readonly fixedGlobalRoot: string | undefined
private readonly fixedProjectRoot: string | undefined
private readonly loggerOf: Pick<BrainLogger, 'log'> | undefined
constructor(options: LocalMemoryManagerOptions = {}) {
this.cwdOf = options.cwd ?? (() => process.cwd())
this.defaultWorkspaceOf = options.workspace
this.settingsOf = options.settings ?? (() => ({}))
this.fixedGlobalRoot = options.globalRoot
this.fixedProjectRoot = options.projectRoot
this.loggerOf = options.logger === undefined ? undefined : { log: (event: BrainLogEvent) => { try { options.logger!.log(event) } catch { /* diagnostics must never break memory operations */ } } }
}
/** Bind one operation to a workspace; AsyncLocalStorage keeps concurrent sessions isolated. */
withWorkspace<T>(workspace: string | undefined, job: () => Promise<T>): Promise<T> { return this.workspaceContext.run(workspace, job) }
@ -141,6 +146,7 @@ export class LocalMemoryManager {
const initPath = join(this.globalRoot, 'state', 'init.json')
if (!(await stat(initPath).catch(() => undefined))) await atomicWrite(initPath, JSON.stringify({ version: 1, globalReady: true, createdAt: new Date().toISOString() }, null, 2) + '\n')
await this.repairProjectionsIfDirty()
this.loggerOf?.log({ event: 'memory.ensure', detail: { scope: 'global', root: this.globalRoot } })
return meta
})
}
@ -170,6 +176,7 @@ export class LocalMemoryManager {
})
const state = { root, store, documents }
this.workspaces.set(root, state)
this.loggerOf?.log({ event: 'memory.ensure', scope: 'project', workspace: base, detail: { scope: 'project', root } })
return store
})
}
@ -183,13 +190,19 @@ export class LocalMemoryManager {
}
/** Add one memory and regenerate the compact projections. */
async remember(input: LocalMemoryAddInput): Promise<{ record: LocalMemoryRecord; duplicate: boolean; projectionPending?: boolean; projectionError?: string }> {
const startedAt = Date.now()
const workspace = this.workspacePath()
const scope = input.scope ?? 'project'
const store = await this.storeFor(scope, workspace)
await this.markProjectionDirty()
const result = await store.add({ ...input, projectId: input.projectId ?? (scope === 'project' ? projectIdFor(this.projectRootFor(workspace)) : undefined) })
if (result.duplicate) return result
return { ...result, ...(await this.tryRegenerateProjections()) }
if (result.duplicate) {
this.loggerOf?.log({ event: 'memory.remember', scope: scope === 'global' ? 'global' : 'project', workspace, sessionId: input.sessionId, detail: { recordId: result.record.id, duplicate: true, category: input.category, durationMs: Date.now() - startedAt } })
return result
}
const outcome = { ...result, ...(await this.tryRegenerateProjections()) }
this.loggerOf?.log({ event: 'memory.remember', scope: scope === 'global' ? 'global' : 'project', workspace, sessionId: input.sessionId, detail: { recordId: outcome.record.id, duplicate: false, category: input.category, durationMs: Date.now() - startedAt } })
return outcome
}
async add(input: LocalMemoryAddInput): Promise<{ record: LocalMemoryRecord; duplicate: boolean; projectionPending?: boolean; projectionError?: string }> { return this.remember(input) }
async read(id: string, workspace?: string): Promise<LocalMemoryRecord | undefined> {
@ -211,9 +224,14 @@ export class LocalMemoryManager {
.sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt))
}
async searchHits(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string): Promise<{ record: LocalMemoryRecord; score: number }[]> {
const startedAt = Date.now()
const hits = await this.collectHits(query, workspace, projectId)
const limit = Math.max(1, Math.min(100, Math.trunc(k)))
return hits.slice(0, limit)
const result = hits.slice(0, limit)
const sources: Record<string, number> = {}
for (const hit of result) sources[hit.record.scope] = (sources[hit.record.scope] ?? 0) + 1
this.loggerOf?.log({ event: 'memory.search', scope: 'project', workspace, detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } })
return result
}
async search(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string): Promise<LocalMemoryRecord[]> {
return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record)
@ -236,10 +254,16 @@ export class LocalMemoryManager {
async forget(id: string, expectedRevision?: number, workspace?: string): Promise<LocalMemoryRecord> {
const globalRecord = await this.globalStore.read(id)
await this.markProjectionDirty()
if (globalRecord !== undefined) { const removed = await this.globalStore.forget(id, expectedRevision); await this.tryRegenerateProjections(); return removed }
if (globalRecord !== undefined) {
const removed = await this.globalStore.forget(id, expectedRevision)
await this.tryRegenerateProjections()
this.loggerOf?.log({ event: 'memory.forget', scope: 'global', detail: { recordId: id, revision: removed.revision } })
return removed
}
const store = await this.ensureProject(workspace)
const removed = await store.forget(id, expectedRevision)
await this.tryRegenerateProjections()
this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace, detail: { recordId: id, revision: removed.revision } })
return removed
}
async projects(workspace?: string): Promise<{ id: string; name: string }[]> {
@ -291,6 +315,7 @@ export class LocalMemoryManager {
await atomicWrite(join(this.globalRoot, 'runtime', 'USER.md'), render('USER', user))
await atomicWrite(join(this.globalRoot, 'runtime', 'MEMORY.md'), render('MEMORY', rules))
await this.clearProjectionDirty(marker)
this.loggerOf?.log({ event: 'memory.projection', detail: { root: this.globalRoot } })
} catch (error) {
await this.markProjectionDirty(error)
throw error
@ -335,7 +360,8 @@ export class LocalMemoryManager {
const lastValue = lastCandidate === undefined ? lastTurn : lastTurn === undefined ? lastCandidate : (Number.isFinite(Number(lastCandidate)) && Number.isFinite(Number(lastTurn)) ? (Number(lastCandidate) >= Number(lastTurn) ? lastCandidate : lastTurn) : lastTurn)
checkpoints[input.sessionId] = { ...(lastValue === undefined ? {} : { lastTurn: lastValue }), count: nextCount, processed: [...processedNext].slice(-1000) }
await atomicWrite(checkpointPath, JSON.stringify(checkpoints, null, 2) + '\n')
if (stored > 0) { const repair = await this.tryRegenerateProjections(); return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false, ...repair } }
if (stored > 0) { const repair = await this.tryRegenerateProjections(); this.loggerOf?.log({ event: 'memory.summary', sessionId: input.sessionId, detail: { turns: input.turns.length, stored, duplicates, skipped: false } }); return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false, ...repair } }
this.loggerOf?.log({ event: 'memory.summary', sessionId: input.sessionId, detail: { turns: input.turns.length, stored, duplicates, skipped: false } })
return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false }
})
}
@ -356,6 +382,7 @@ export class LocalMemoryManager {
if (entry.name === 'backups') continue
await cp(join(this.globalRoot, entry.name), join(path, entry.name), { recursive: true, force: false })
}
this.loggerOf?.log({ event: 'memory.backup', detail: { path } })
return { path }
}
/** Report legacy .mnemon locations without deleting anything. */

View File

@ -39,6 +39,7 @@ export interface PersistedState {
autoSummaryEnabled?: boolean
autoProfileEnabled?: boolean
localMemoryK?: number
diagnosticsEnabled?: boolean
/** Token labels the user cleared — set so an env fallback cannot resurrect them. */
clearedTokens?: string[]
}
@ -156,6 +157,7 @@ function parseState(raw: string): PersistedState {
if (typeof source.autoMemorySpaces === 'boolean') state.autoMemorySpaces = source.autoMemorySpaces
if (typeof source.autoSummaryEnabled === 'boolean') state.autoSummaryEnabled = source.autoSummaryEnabled
if (typeof source.autoProfileEnabled === 'boolean') state.autoProfileEnabled = source.autoProfileEnabled
if (typeof source.diagnosticsEnabled === 'boolean') state.diagnosticsEnabled = source.diagnosticsEnabled
const localMemoryK = clampInt(source.localMemoryK, 1, 100)
if (localMemoryK !== undefined) state.localMemoryK = localMemoryK
const baseUrl = normalizeBaseUrl(source.baseUrl)
@ -255,6 +257,7 @@ export class SettingsStore {
if (this.state.autoSummaryEnabled !== undefined) resolved.autoSummaryEnabled = this.state.autoSummaryEnabled
if (this.state.autoProfileEnabled !== undefined) resolved.autoProfileEnabled = this.state.autoProfileEnabled
if (this.state.localMemoryK !== undefined) resolved.localMemoryK = this.state.localMemoryK
if (this.state.diagnosticsEnabled !== undefined) resolved.diagnosticsEnabled = this.state.diagnosticsEnabled
// The split gates inherit `enabled` unless the config or the sidecar set
// them explicitly, so an old configuration keeps its exact behaviour.
if (this.state.activityEnabled === undefined && this.configExplicit.activityEnabled === undefined) {
@ -400,7 +403,7 @@ export class SettingsStore {
if (skillsDir.length > 512) return { ok: false, error: 'skillsDir too long' }
next.skillsDir = skillsDir
}
for (const key of ['localMemoryEnabled', 'cloudMemoryEnabled', 'autoMemorySpaces', 'autoSummaryEnabled', 'autoProfileEnabled'] as const) {
for (const key of ['localMemoryEnabled', 'cloudMemoryEnabled', 'autoMemorySpaces', 'autoSummaryEnabled', 'autoProfileEnabled', 'diagnosticsEnabled'] as const) {
if (patch[key] !== undefined) {
if (typeof patch[key] !== 'boolean') return { ok: false, error: key + ' must be a boolean' }
next[key] = patch[key]

112
verify-diagnostics.mjs Normal file
View File

@ -0,0 +1,112 @@
// U5 diagnostics verification: JSONL layout, redaction, truncation, rotation,
// retention, switches and failure isolation.
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const home = mkdtempSync(join(tmpdir(), 'brain-diagnostics-'))
process.env.DSH_HOME = join(home, '.dsh')
const projectA = join(home, 'project-a')
const projectB = join(home, 'project-b')
const projectC = join(home, 'project-c')
mkdirSync(projectA, { recursive: true })
mkdirSync(projectB, { recursive: true })
mkdirSync(projectC, { recursive: true })
const results = []
function check(name, ok, detail = '') {
results.push({ name, ok })
console.log((ok ? 'PASS ' : 'FAIL ') + name + (detail === '' ? '' : ' :: ' + detail))
}
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
function readLogs(root) {
const directory = join(root, 'logs')
if (!existsSync(directory)) return { text: '', entries: [], files: [] }
const files = readdirSync(directory).filter((name) => name.endsWith('.log')).sort()
const text = files.map((name) => readFileSync(join(directory, name), 'utf8')).join('')
const entries = []
for (const line of text.split('\n')) {
if (line.trim() === '') continue
entries.push(JSON.parse(line))
}
return { text, entries, files }
}
const { BrainLogger } = await import('./lib/diagnostics.js')
const { LocalMemoryManager, globalBrainRoot, projectBrainRoot } = await import('./lib/local-memory/index.js')
const settings = () => ({ localMemoryEnabled: true, cloudMemoryEnabled: false, autoMemorySpaces: true, autoSummaryEnabled: false, autoProfileEnabled: false, localMemoryK: 5, diagnosticsEnabled: true, enabled: true })
// ── 1. memory operations land in project/global JSONL ────────────────────
const logger = new BrainLogger({ globalRoot: () => globalBrainRoot(), projectRootOf: (workspace) => projectBrainRoot(workspace ?? projectA), enabled: () => true })
const memory = new LocalMemoryManager({ cwd: () => projectA, settings, logger })
const record = await memory.remember({ content: '项目 A 使用 pnpm 管理依赖', category: 'fact', scope: 'project' })
await memory.search('pnpm')
await memory.forget(record.record.id)
await memory.remember({ content: '全局 TypeScript 经验', category: 'fact', scope: 'global' })
await logger.flush()
const projectLogs = readLogs(projectBrainRoot(projectA))
const globalLogs = readLogs(globalBrainRoot())
check('project operations write a project JSONL file', projectLogs.files.length > 0)
const projectEvents = projectLogs.entries.map((entry) => entry.event)
for (const event of ['memory.ensure', 'memory.remember', 'memory.search', 'memory.forget']) {
check('project log contains ' + event, projectEvents.includes(event), JSON.stringify(projectEvents))
}
check('global operations write a global JSONL file', globalLogs.entries.some((entry) => entry.event === 'memory.remember' && entry.scope === 'global'))
check('every log line is valid JSON with ts/level/event/scope', projectLogs.entries.length > 0 && projectLogs.entries.every((entry) => typeof entry.ts === 'string' && ['info', 'warn', 'error'].includes(entry.level) && typeof entry.event === 'string' && ['global', 'project'].includes(entry.scope)))
const rememberEntry = projectLogs.entries.find((entry) => entry.event === 'memory.remember')
check('memory.remember carries structured detail only', rememberEntry !== undefined && typeof rememberEntry.detail?.recordId === 'string' && typeof rememberEntry.detail?.durationMs === 'number' && rememberEntry.detail?.content === undefined)
// ── 2/3. secret redaction and content truncation ─────────────────────────
logger.log({ event: 'test.secret', detail: { note: 'api_key: sk-abcdef1234567890' } })
logger.log({ event: 'test.long', detail: { content: 'x'.repeat(700) } })
await logger.flush()
const afterSpecial = readLogs(globalBrainRoot()).text
check('secret-like detail is redacted', !afterSpecial.includes('sk-abcdef1234567890') && afterSpecial.includes('[redacted]'))
check('long detail is truncated at 120 chars', !afterSpecial.includes('x'.repeat(121)))
// ── 4. rotation and retention ────────────────────────────────────────────
const rotationRoot = join(home, 'rotation')
const rotationLogger = new BrainLogger({ globalRoot: () => rotationRoot, projectRootOf: () => rotationRoot, enabled: () => true, maxBytes: 200 })
for (let index = 0; index < 12; index += 1) rotationLogger.log({ event: 'test.rotate', detail: { index, pad: 'y'.repeat(48) } })
await rotationLogger.flush()
const rotationFiles = readdirSync(join(rotationRoot, 'logs'))
check('single-day size cap rotates to .1.log', rotationFiles.some((name) => /\.1\.log$/.test(name)), JSON.stringify(rotationFiles))
const oldLog = join(globalBrainRoot(), 'logs', 'brain-2019-01-01.log')
writeFileSync(oldLog, '{"old":true}\n')
logger.prune()
await delay(300)
check('14-day retention removes old log files', !existsSync(oldLog))
// ── 5. disabled switch and throwing logger ──────────────────────────────
const disabledRoot = join(home, 'disabled')
const disabledLogger = new BrainLogger({ globalRoot: () => disabledRoot, projectRootOf: () => disabledRoot, enabled: () => false })
disabledLogger.log({ event: 'test.disabled', detail: { value: 1 } })
await disabledLogger.flush()
check('disabled logger writes no files', !existsSync(join(disabledRoot, 'logs')) || readdirSync(join(disabledRoot, 'logs')).length === 0)
const throwingLogger = { log() { throw new Error('logger boom') } }
const memoryThrowing = new LocalMemoryManager({ cwd: () => projectB, settings, logger: throwingLogger })
const survived = await memoryThrowing.remember({ content: '日志抛错不影响写入', category: 'fact', scope: 'project' })
check('throwing logger does not break memory operations', survived.record.id !== undefined)
// ── 6. unwritable logs directory is silent ──────────────────────────────
mkdirSync(join(projectC, '.dsh', 'brain'), { recursive: true })
writeFileSync(join(projectC, '.dsh', 'brain', 'logs'), 'blocked')
const blockedLogger = new BrainLogger({ globalRoot: () => join(home, 'blocked-global'), projectRootOf: () => projectBrainRoot(projectC), enabled: () => true })
const memoryBlocked = new LocalMemoryManager({ cwd: () => projectC, settings, logger: blockedLogger })
let blockedThrew = false
try {
const result = await memoryBlocked.remember({ content: '日志目录不可写也要成功', category: 'fact', scope: 'project' })
check('unwritable log directory still saves memory', result.record.id !== undefined)
} catch {
blockedThrew = true
}
if (blockedThrew) check('unwritable log directory still saves memory', false, 'remember threw')
await blockedLogger.flush()
console.log('\n' + (results.every((result) => result.ok) ? 'ALL ' + results.length + ' CHECKS PASSED' : results.filter((result) => !result.ok).length + ' FAILED'))
rmSync(home, { recursive: true, force: true })
process.exit(results.every((result) => result.ok) ? 0 : 1)