feat(diagnostics): JSONL debug logs under .dsh/brain/logs with redaction and rotation
This commit is contained in:
parent
3d7b59b4c9
commit
bdea045635
|
|
@ -28,6 +28,8 @@ export const DEFAULT_SETTINGS = {
|
||||||
autoProfileEnabled: true,
|
autoProfileEnabled: true,
|
||||||
/** Default result count for local memory search. */
|
/** Default result count for local memory search. */
|
||||||
localMemoryK: 5,
|
localMemoryK: 5,
|
||||||
|
/** Diagnostic JSONL logs under .dsh/brain/logs; defaults on, inherits enabled. */
|
||||||
|
diagnosticsEnabled: true,
|
||||||
};
|
};
|
||||||
const MIN_TIMEOUT_MS = 1000;
|
const MIN_TIMEOUT_MS = 1000;
|
||||||
const MAX_TIMEOUT_MS = 60_000;
|
const MAX_TIMEOUT_MS = 60_000;
|
||||||
|
|
@ -134,6 +136,8 @@ export function settingsFromConfig(raw) {
|
||||||
result.autoSummaryEnabled = source.autoSummaryEnabled;
|
result.autoSummaryEnabled = source.autoSummaryEnabled;
|
||||||
if (typeof source.autoProfileEnabled === 'boolean')
|
if (typeof source.autoProfileEnabled === 'boolean')
|
||||||
result.autoProfileEnabled = source.autoProfileEnabled;
|
result.autoProfileEnabled = source.autoProfileEnabled;
|
||||||
|
if (typeof source.diagnosticsEnabled === 'boolean')
|
||||||
|
result.diagnosticsEnabled = source.diagnosticsEnabled;
|
||||||
const localMemoryK = boundedInt(source.localMemoryK, 1, 100);
|
const localMemoryK = boundedInt(source.localMemoryK, 1, 100);
|
||||||
if (localMemoryK !== undefined)
|
if (localMemoryK !== undefined)
|
||||||
result.localMemoryK = localMemoryK;
|
result.localMemoryK = localMemoryK;
|
||||||
|
|
|
||||||
|
|
@ -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');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -13,6 +13,7 @@ export function apply(ctx, config) {
|
||||||
const logger = ctx.logger('dsh-brain');
|
const logger = ctx.logger('dsh-brain');
|
||||||
const kernel = brainKernel(config, logger);
|
const kernel = brainKernel(config, logger);
|
||||||
kernel.activate('cloudsync');
|
kernel.activate('cloudsync');
|
||||||
|
kernel.logEvent('boot.entry', { bundle: 'cloudsync' });
|
||||||
ctx.effect(() => () => kernel.deactivate('cloudsync'), 'dsh-brain-cloudsync: activation');
|
ctx.effect(() => () => kernel.deactivate('cloudsync'), 'dsh-brain-cloudsync: activation');
|
||||||
// The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a
|
// 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.
|
// third-party bundle cannot rely on; bind the listener through a local shape.
|
||||||
|
|
|
||||||
|
|
@ -6,5 +6,6 @@ export const inject = [];
|
||||||
export function apply(ctx, config) {
|
export function apply(ctx, config) {
|
||||||
const kernel = brainKernel(config, ctx.logger('dsh-brain'));
|
const kernel = brainKernel(config, ctx.logger('dsh-brain'));
|
||||||
kernel.activate('mcp');
|
kernel.activate('mcp');
|
||||||
|
kernel.logEvent('boot.entry', { bundle: 'mcp' });
|
||||||
ctx.effect(() => () => kernel.deactivate('mcp'), 'dsh-brain-mcp: activation');
|
ctx.effect(() => () => kernel.deactivate('mcp'), 'dsh-brain-mcp: activation');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ export function apply(ctx, config) {
|
||||||
const logger = ctx.logger('dsh-brain');
|
const logger = ctx.logger('dsh-brain');
|
||||||
const kernel = brainKernel(config, logger);
|
const kernel = brainKernel(config, logger);
|
||||||
kernel.activate('memory');
|
kernel.activate('memory');
|
||||||
|
kernel.logEvent('boot.entry', { bundle: 'memory' });
|
||||||
ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation');
|
ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation');
|
||||||
ctx.inject(['tools'], (toolsCtx) => {
|
ctx.inject(['tools'], (toolsCtx) => {
|
||||||
const tools = toolsCtx.tools;
|
const tools = toolsCtx.tools;
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ export function apply(ctx, config) {
|
||||||
const logger = ctx.logger('dsh-brain');
|
const logger = ctx.logger('dsh-brain');
|
||||||
const kernel = brainKernel(config, logger);
|
const kernel = brainKernel(config, logger);
|
||||||
kernel.activate('settings-ui');
|
kernel.activate('settings-ui');
|
||||||
|
kernel.logEvent('boot.entry', { bundle: 'settings-ui' });
|
||||||
ctx.effect(() => () => kernel.deactivate('settings-ui'), 'dsh-brain-settings-ui: activation');
|
ctx.effect(() => () => kernel.deactivate('settings-ui'), 'dsh-brain-settings-ui: activation');
|
||||||
const webServer = ctx.webServer;
|
const webServer = ctx.webServer;
|
||||||
if (webServer === undefined) {
|
if (webServer === undefined) {
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ export function apply(ctx, config) {
|
||||||
const logger = ctx.logger('dsh-brain');
|
const logger = ctx.logger('dsh-brain');
|
||||||
const kernel = brainKernel(config, logger);
|
const kernel = brainKernel(config, logger);
|
||||||
kernel.activate('skills');
|
kernel.activate('skills');
|
||||||
|
kernel.logEvent('boot.entry', { bundle: 'skills' });
|
||||||
ctx.effect(() => () => kernel.deactivate('skills'), 'dsh-brain-skills: activation');
|
ctx.effect(() => () => kernel.deactivate('skills'), 'dsh-brain-skills: activation');
|
||||||
ctx.inject(['tools'], (toolsCtx) => {
|
ctx.inject(['tools'], (toolsCtx) => {
|
||||||
const tools = toolsCtx.tools;
|
const tools = toolsCtx.tools;
|
||||||
|
|
|
||||||
11
lib/http.js
11
lib/http.js
|
|
@ -1,5 +1,10 @@
|
||||||
/** Largest request body we accept (a settings patch is tiny). */
|
/** Largest request body we accept (a settings patch is tiny). */
|
||||||
export const MAX_BODY_BYTES = 64 * 1024;
|
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. */
|
/** Collect a request body as UTF-8 text. */
|
||||||
export async function readBody(req, maxBytes = MAX_BODY_BYTES) {
|
export async function readBody(req, maxBytes = MAX_BODY_BYTES) {
|
||||||
const chunks = [];
|
const chunks = [];
|
||||||
|
|
@ -33,6 +38,12 @@ export function json(res, status, body) {
|
||||||
}
|
}
|
||||||
/** Emit a plain-text error (page route) or JSON error (API routes). */
|
/** Emit a plain-text error (page route) or JSON error (API routes). */
|
||||||
export function fail(res, status, message, asHtml = false) {
|
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
|
const text = asHtml
|
||||||
? `<!doctype html><meta charset="utf-8"><title>云端记忆</title><body style="font:14px system-ui;padding:32px">${message}</body>`
|
? `<!doctype html><meta charset="utf-8"><title>云端记忆</title><body style="font:14px system-ui;padding:32px">${message}</body>`
|
||||||
: JSON.stringify({ ok: false, error: message });
|
: JSON.stringify({ ok: false, error: message });
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,9 @@
|
||||||
*/
|
*/
|
||||||
import { join, resolve } from 'node:path';
|
import { join, resolve } from 'node:path';
|
||||||
import { CloudClient } from "./api.js";
|
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 { VERSION } from "./version.js";
|
||||||
import { createCloudMemoryRemoteFactory } from "./cloudsync.js";
|
import { createCloudMemoryRemoteFactory } from "./cloudsync.js";
|
||||||
import { ClientRegistry } from "./clients.js";
|
import { ClientRegistry } from "./clients.js";
|
||||||
|
|
@ -55,6 +57,7 @@ export class BrainKernel {
|
||||||
active = new Set();
|
active = new Set();
|
||||||
settingsOf;
|
settingsOf;
|
||||||
store;
|
store;
|
||||||
|
diagnostics;
|
||||||
client;
|
client;
|
||||||
memoryRemoteFactory;
|
memoryRemoteFactory;
|
||||||
localMemory;
|
localMemory;
|
||||||
|
|
@ -73,6 +76,16 @@ export class BrainKernel {
|
||||||
this.store = store;
|
this.store = store;
|
||||||
const settings = () => store.settings();
|
const settings = () => store.settings();
|
||||||
this.settingsOf = 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.
|
// One client per instance; the settings closures keep it live across edits.
|
||||||
const client = new CloudClient({
|
const client = new CloudClient({
|
||||||
baseUrl: () => settings().baseUrl,
|
baseUrl: () => settings().baseUrl,
|
||||||
|
|
@ -90,6 +103,7 @@ export class BrainKernel {
|
||||||
// lazily on the first memory tool call and needs no token or account.
|
// lazily on the first memory tool call and needs no token or account.
|
||||||
this.localMemory = new LocalMemoryManager({
|
this.localMemory = new LocalMemoryManager({
|
||||||
cwd: () => process.cwd(),
|
cwd: () => process.cwd(),
|
||||||
|
logger: this.diagnostics,
|
||||||
settings: () => ({
|
settings: () => ({
|
||||||
localMemoryEnabled: settings().localMemoryEnabled,
|
localMemoryEnabled: settings().localMemoryEnabled,
|
||||||
cloudMemoryEnabled: settings().cloudMemoryEnabled,
|
cloudMemoryEnabled: settings().cloudMemoryEnabled,
|
||||||
|
|
@ -208,11 +222,24 @@ export class BrainKernel {
|
||||||
if (effective.summaryEnabled && store.summaryToken() === '') {
|
if (effective.summaryEnabled && store.summaryToken() === '') {
|
||||||
logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged');
|
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). */
|
/** Current settings snapshot (live: re-read on every call). */
|
||||||
settings() {
|
settings() {
|
||||||
return this.settingsOf();
|
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. */
|
/** Mark a bundle's entry as applied; feeds `routeDeps()` gating. */
|
||||||
activate(bundle) {
|
activate(bundle) {
|
||||||
this.active.add(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. */
|
/** Test hook: drop the singleton so the next call rebuilds it. */
|
||||||
export function resetBrainKernel() {
|
export function resetBrainKernel() {
|
||||||
instance = undefined;
|
instance = undefined;
|
||||||
|
setRouteErrorHook(undefined);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -83,12 +83,17 @@ export class LocalMemoryManager {
|
||||||
workspaces = new Map();
|
workspaces = new Map();
|
||||||
fixedGlobalRoot;
|
fixedGlobalRoot;
|
||||||
fixedProjectRoot;
|
fixedProjectRoot;
|
||||||
|
loggerOf;
|
||||||
constructor(options = {}) {
|
constructor(options = {}) {
|
||||||
this.cwdOf = options.cwd ?? (() => process.cwd());
|
this.cwdOf = options.cwd ?? (() => process.cwd());
|
||||||
this.defaultWorkspaceOf = options.workspace;
|
this.defaultWorkspaceOf = options.workspace;
|
||||||
this.settingsOf = options.settings ?? (() => ({}));
|
this.settingsOf = options.settings ?? (() => ({}));
|
||||||
this.fixedGlobalRoot = options.globalRoot;
|
this.fixedGlobalRoot = options.globalRoot;
|
||||||
this.fixedProjectRoot = options.projectRoot;
|
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. */
|
/** Bind one operation to a workspace; AsyncLocalStorage keeps concurrent sessions isolated. */
|
||||||
withWorkspace(workspace, job) { return this.workspaceContext.run(workspace, job); }
|
withWorkspace(workspace, job) { return this.workspaceContext.run(workspace, job); }
|
||||||
|
|
@ -163,6 +168,7 @@ export class LocalMemoryManager {
|
||||||
if (!(await stat(initPath).catch(() => undefined)))
|
if (!(await stat(initPath).catch(() => undefined)))
|
||||||
await atomicWrite(initPath, JSON.stringify({ version: 1, globalReady: true, createdAt: new Date().toISOString() }, null, 2) + '\n');
|
await atomicWrite(initPath, JSON.stringify({ version: 1, globalReady: true, createdAt: new Date().toISOString() }, null, 2) + '\n');
|
||||||
await this.repairProjectionsIfDirty();
|
await this.repairProjectionsIfDirty();
|
||||||
|
this.loggerOf?.log({ event: 'memory.ensure', detail: { scope: 'global', root: this.globalRoot } });
|
||||||
return meta;
|
return meta;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -194,6 +200,7 @@ export class LocalMemoryManager {
|
||||||
});
|
});
|
||||||
const state = { root, store, documents };
|
const state = { root, store, documents };
|
||||||
this.workspaces.set(root, state);
|
this.workspaces.set(root, state);
|
||||||
|
this.loggerOf?.log({ event: 'memory.ensure', scope: 'project', workspace: base, detail: { scope: 'project', root } });
|
||||||
return store;
|
return store;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -207,14 +214,19 @@ export class LocalMemoryManager {
|
||||||
}
|
}
|
||||||
/** Add one memory and regenerate the compact projections. */
|
/** Add one memory and regenerate the compact projections. */
|
||||||
async remember(input) {
|
async remember(input) {
|
||||||
|
const startedAt = Date.now();
|
||||||
const workspace = this.workspacePath();
|
const workspace = this.workspacePath();
|
||||||
const scope = input.scope ?? 'project';
|
const scope = input.scope ?? 'project';
|
||||||
const store = await this.storeFor(scope, workspace);
|
const store = await this.storeFor(scope, workspace);
|
||||||
await this.markProjectionDirty();
|
await this.markProjectionDirty();
|
||||||
const result = await store.add({ ...input, projectId: input.projectId ?? (scope === 'project' ? projectIdFor(this.projectRootFor(workspace)) : undefined) });
|
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;
|
||||||
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 add(input) { return this.remember(input); }
|
||||||
async read(id, workspace) {
|
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));
|
.sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt));
|
||||||
}
|
}
|
||||||
async searchHits(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) {
|
async searchHits(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) {
|
||||||
|
const startedAt = Date.now();
|
||||||
const hits = await this.collectHits(query, workspace, projectId);
|
const hits = await this.collectHits(query, workspace, projectId);
|
||||||
const limit = Math.max(1, Math.min(100, Math.trunc(k)));
|
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) {
|
async search(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) {
|
||||||
return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record);
|
return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record);
|
||||||
|
|
@ -271,11 +289,13 @@ export class LocalMemoryManager {
|
||||||
if (globalRecord !== undefined) {
|
if (globalRecord !== undefined) {
|
||||||
const removed = await this.globalStore.forget(id, expectedRevision);
|
const removed = await this.globalStore.forget(id, expectedRevision);
|
||||||
await this.tryRegenerateProjections();
|
await this.tryRegenerateProjections();
|
||||||
|
this.loggerOf?.log({ event: 'memory.forget', scope: 'global', detail: { recordId: id, revision: removed.revision } });
|
||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
const store = await this.ensureProject(workspace);
|
const store = await this.ensureProject(workspace);
|
||||||
const removed = await store.forget(id, expectedRevision);
|
const removed = await store.forget(id, expectedRevision);
|
||||||
await this.tryRegenerateProjections();
|
await this.tryRegenerateProjections();
|
||||||
|
this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace, detail: { recordId: id, revision: removed.revision } });
|
||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
async projects(workspace) {
|
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', 'USER.md'), render('USER', user));
|
||||||
await atomicWrite(join(this.globalRoot, 'runtime', 'MEMORY.md'), render('MEMORY', rules));
|
await atomicWrite(join(this.globalRoot, 'runtime', 'MEMORY.md'), render('MEMORY', rules));
|
||||||
await this.clearProjectionDirty(marker);
|
await this.clearProjectionDirty(marker);
|
||||||
|
this.loggerOf?.log({ event: 'memory.projection', detail: { root: this.globalRoot } });
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
await this.markProjectionDirty(error);
|
await this.markProjectionDirty(error);
|
||||||
|
|
@ -396,8 +417,10 @@ export class LocalMemoryManager {
|
||||||
await atomicWrite(checkpointPath, JSON.stringify(checkpoints, null, 2) + '\n');
|
await atomicWrite(checkpointPath, JSON.stringify(checkpoints, null, 2) + '\n');
|
||||||
if (stored > 0) {
|
if (stored > 0) {
|
||||||
const repair = await this.tryRegenerateProjections();
|
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 };
|
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 };
|
return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -426,6 +449,7 @@ export class LocalMemoryManager {
|
||||||
continue;
|
continue;
|
||||||
await cp(join(this.globalRoot, entry.name), join(path, entry.name), { recursive: true, force: false });
|
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 };
|
return { path };
|
||||||
}
|
}
|
||||||
/** Report legacy .mnemon locations without deleting anything. */
|
/** Report legacy .mnemon locations without deleting anything. */
|
||||||
|
|
|
||||||
|
|
@ -117,6 +117,8 @@ function parseState(raw) {
|
||||||
state.autoSummaryEnabled = source.autoSummaryEnabled;
|
state.autoSummaryEnabled = source.autoSummaryEnabled;
|
||||||
if (typeof source.autoProfileEnabled === 'boolean')
|
if (typeof source.autoProfileEnabled === 'boolean')
|
||||||
state.autoProfileEnabled = source.autoProfileEnabled;
|
state.autoProfileEnabled = source.autoProfileEnabled;
|
||||||
|
if (typeof source.diagnosticsEnabled === 'boolean')
|
||||||
|
state.diagnosticsEnabled = source.diagnosticsEnabled;
|
||||||
const localMemoryK = clampInt(source.localMemoryK, 1, 100);
|
const localMemoryK = clampInt(source.localMemoryK, 1, 100);
|
||||||
if (localMemoryK !== undefined)
|
if (localMemoryK !== undefined)
|
||||||
state.localMemoryK = localMemoryK;
|
state.localMemoryK = localMemoryK;
|
||||||
|
|
@ -241,6 +243,8 @@ export class SettingsStore {
|
||||||
resolved.autoProfileEnabled = this.state.autoProfileEnabled;
|
resolved.autoProfileEnabled = this.state.autoProfileEnabled;
|
||||||
if (this.state.localMemoryK !== undefined)
|
if (this.state.localMemoryK !== undefined)
|
||||||
resolved.localMemoryK = this.state.localMemoryK;
|
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
|
// The split gates inherit `enabled` unless the config or the sidecar set
|
||||||
// them explicitly, so an old configuration keeps its exact behaviour.
|
// them explicitly, so an old configuration keeps its exact behaviour.
|
||||||
if (this.state.activityEnabled === undefined && this.configExplicit.activityEnabled === undefined) {
|
if (this.state.activityEnabled === undefined && this.configExplicit.activityEnabled === undefined) {
|
||||||
|
|
@ -399,7 +403,7 @@ export class SettingsStore {
|
||||||
return { ok: false, error: 'skillsDir too long' };
|
return { ok: false, error: 'skillsDir too long' };
|
||||||
next.skillsDir = skillsDir;
|
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 (patch[key] !== undefined) {
|
||||||
if (typeof patch[key] !== 'boolean')
|
if (typeof patch[key] !== 'boolean')
|
||||||
return { ok: false, error: key + ' must be a boolean' };
|
return { ok: false, error: key + ' must be a boolean' };
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,8 @@ export const DEFAULT_SETTINGS: Settings = {
|
||||||
autoProfileEnabled: true,
|
autoProfileEnabled: true,
|
||||||
/** Default result count for local memory search. */
|
/** Default result count for local memory search. */
|
||||||
localMemoryK: 5,
|
localMemoryK: 5,
|
||||||
|
/** Diagnostic JSONL logs under .dsh/brain/logs; defaults on, inherits enabled. */
|
||||||
|
diagnosticsEnabled: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Effective, fully-resolved settings. */
|
/** Effective, fully-resolved settings. */
|
||||||
|
|
@ -67,6 +69,8 @@ export interface Settings {
|
||||||
autoProfileEnabled: boolean
|
autoProfileEnabled: boolean
|
||||||
/** Default local memory result count. */
|
/** Default local memory result count. */
|
||||||
localMemoryK: number
|
localMemoryK: number
|
||||||
|
/** Diagnostic JSONL logging switch. */
|
||||||
|
diagnosticsEnabled: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Raw row config as it comes out of the cordis loader. */
|
/** 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.autoMemorySpaces === 'boolean') result.autoMemorySpaces = source.autoMemorySpaces
|
||||||
if (typeof source.autoSummaryEnabled === 'boolean') result.autoSummaryEnabled = source.autoSummaryEnabled
|
if (typeof source.autoSummaryEnabled === 'boolean') result.autoSummaryEnabled = source.autoSummaryEnabled
|
||||||
if (typeof source.autoProfileEnabled === 'boolean') result.autoProfileEnabled = source.autoProfileEnabled
|
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)
|
const localMemoryK = boundedInt(source.localMemoryK, 1, 100)
|
||||||
if (localMemoryK !== undefined) result.localMemoryK = localMemoryK
|
if (localMemoryK !== undefined) result.localMemoryK = localMemoryK
|
||||||
return result
|
return result
|
||||||
|
|
|
||||||
|
|
@ -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')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -29,6 +29,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
|
||||||
const logger = ctx.logger('dsh-brain')
|
const logger = ctx.logger('dsh-brain')
|
||||||
const kernel = brainKernel(config, logger)
|
const kernel = brainKernel(config, logger)
|
||||||
kernel.activate('cloudsync')
|
kernel.activate('cloudsync')
|
||||||
|
kernel.logEvent('boot.entry', { bundle: 'cloudsync' })
|
||||||
ctx.effect(() => () => kernel.deactivate('cloudsync'), 'dsh-brain-cloudsync: activation')
|
ctx.effect(() => () => kernel.deactivate('cloudsync'), 'dsh-brain-cloudsync: activation')
|
||||||
|
|
||||||
// The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a
|
// The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a
|
||||||
|
|
|
||||||
|
|
@ -20,5 +20,6 @@ export const inject: string[] = []
|
||||||
export function apply(ctx: CloudMemoryContext, config: unknown): void {
|
export function apply(ctx: CloudMemoryContext, config: unknown): void {
|
||||||
const kernel = brainKernel(config, ctx.logger('dsh-brain'))
|
const kernel = brainKernel(config, ctx.logger('dsh-brain'))
|
||||||
kernel.activate('mcp')
|
kernel.activate('mcp')
|
||||||
|
kernel.logEvent('boot.entry', { bundle: 'mcp' })
|
||||||
ctx.effect(() => () => kernel.deactivate('mcp'), 'dsh-brain-mcp: activation')
|
ctx.effect(() => () => kernel.deactivate('mcp'), 'dsh-brain-mcp: activation')
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
|
||||||
const logger = ctx.logger('dsh-brain')
|
const logger = ctx.logger('dsh-brain')
|
||||||
const kernel = brainKernel(config, logger)
|
const kernel = brainKernel(config, logger)
|
||||||
kernel.activate('memory')
|
kernel.activate('memory')
|
||||||
|
kernel.logEvent('boot.entry', { bundle: 'memory' })
|
||||||
ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation')
|
ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation')
|
||||||
|
|
||||||
ctx.inject(['tools'], (toolsCtx) => {
|
ctx.inject(['tools'], (toolsCtx) => {
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
|
||||||
const logger = ctx.logger('dsh-brain')
|
const logger = ctx.logger('dsh-brain')
|
||||||
const kernel = brainKernel(config, logger)
|
const kernel = brainKernel(config, logger)
|
||||||
kernel.activate('settings-ui')
|
kernel.activate('settings-ui')
|
||||||
|
kernel.logEvent('boot.entry', { bundle: 'settings-ui' })
|
||||||
ctx.effect(() => () => kernel.deactivate('settings-ui'), 'dsh-brain-settings-ui: activation')
|
ctx.effect(() => () => kernel.deactivate('settings-ui'), 'dsh-brain-settings-ui: activation')
|
||||||
|
|
||||||
const webServer = ctx.webServer
|
const webServer = ctx.webServer
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
|
||||||
const logger = ctx.logger('dsh-brain')
|
const logger = ctx.logger('dsh-brain')
|
||||||
const kernel = brainKernel(config, logger)
|
const kernel = brainKernel(config, logger)
|
||||||
kernel.activate('skills')
|
kernel.activate('skills')
|
||||||
|
kernel.logEvent('boot.entry', { bundle: 'skills' })
|
||||||
ctx.effect(() => () => kernel.deactivate('skills'), 'dsh-brain-skills: activation')
|
ctx.effect(() => () => kernel.deactivate('skills'), 'dsh-brain-skills: activation')
|
||||||
|
|
||||||
ctx.inject(['tools'], (toolsCtx) => {
|
ctx.inject(['tools'], (toolsCtx) => {
|
||||||
|
|
|
||||||
12
src/http.ts
12
src/http.ts
|
|
@ -7,6 +7,13 @@ import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||||
/** Largest request body we accept (a settings patch is tiny). */
|
/** Largest request body we accept (a settings patch is tiny). */
|
||||||
export const MAX_BODY_BYTES = 64 * 1024
|
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. */
|
/** Collect a request body as UTF-8 text. */
|
||||||
export async function readBody(req: IncomingMessage, maxBytes = MAX_BODY_BYTES): Promise<string> {
|
export async function readBody(req: IncomingMessage, maxBytes = MAX_BODY_BYTES): Promise<string> {
|
||||||
const chunks: Buffer[] = []
|
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). */
|
/** Emit a plain-text error (page route) or JSON error (API routes). */
|
||||||
export function fail(res: ServerResponse, status: number, message: string, asHtml = false): void {
|
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
|
const text = asHtml
|
||||||
? `<!doctype html><meta charset="utf-8"><title>云端记忆</title><body style="font:14px system-ui;padding:32px">${message}</body>`
|
? `<!doctype html><meta charset="utf-8"><title>云端记忆</title><body style="font:14px system-ui;padding:32px">${message}</body>`
|
||||||
: JSON.stringify({ ok: false, error: message })
|
: JSON.stringify({ ok: false, error: message })
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,9 @@
|
||||||
*/
|
*/
|
||||||
import { join, resolve } from 'node:path'
|
import { join, resolve } from 'node:path'
|
||||||
import { CloudClient } from './api.ts'
|
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 { VERSION } from './version.ts'
|
||||||
import { createCloudMemoryRemoteFactory } from './cloudsync.ts'
|
import { createCloudMemoryRemoteFactory } from './cloudsync.ts'
|
||||||
import type { DepartmentToolDeps } from './memory/departments-tools.ts'
|
import type { DepartmentToolDeps } from './memory/departments-tools.ts'
|
||||||
|
|
@ -69,6 +71,7 @@ export class BrainKernel {
|
||||||
private readonly settingsOf: () => ReturnType<SettingsStore['settings']>
|
private readonly settingsOf: () => ReturnType<SettingsStore['settings']>
|
||||||
|
|
||||||
readonly store: SettingsStore
|
readonly store: SettingsStore
|
||||||
|
readonly diagnostics: BrainLogger
|
||||||
readonly client: CloudClient
|
readonly client: CloudClient
|
||||||
readonly memoryRemoteFactory: ReturnType<typeof createCloudMemoryRemoteFactory>
|
readonly memoryRemoteFactory: ReturnType<typeof createCloudMemoryRemoteFactory>
|
||||||
readonly localMemory: LocalMemoryManager
|
readonly localMemory: LocalMemoryManager
|
||||||
|
|
@ -89,6 +92,17 @@ export class BrainKernel {
|
||||||
const settings = () => store.settings()
|
const settings = () => store.settings()
|
||||||
this.settingsOf = 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.
|
// One client per instance; the settings closures keep it live across edits.
|
||||||
const client = new CloudClient({
|
const client = new CloudClient({
|
||||||
baseUrl: () => settings().baseUrl,
|
baseUrl: () => settings().baseUrl,
|
||||||
|
|
@ -108,6 +122,7 @@ export class BrainKernel {
|
||||||
// lazily on the first memory tool call and needs no token or account.
|
// lazily on the first memory tool call and needs no token or account.
|
||||||
this.localMemory = new LocalMemoryManager({
|
this.localMemory = new LocalMemoryManager({
|
||||||
cwd: () => process.cwd(),
|
cwd: () => process.cwd(),
|
||||||
|
logger: this.diagnostics,
|
||||||
settings: () => ({
|
settings: () => ({
|
||||||
localMemoryEnabled: settings().localMemoryEnabled,
|
localMemoryEnabled: settings().localMemoryEnabled,
|
||||||
cloudMemoryEnabled: settings().cloudMemoryEnabled,
|
cloudMemoryEnabled: settings().cloudMemoryEnabled,
|
||||||
|
|
@ -233,6 +248,15 @@ export class BrainKernel {
|
||||||
if (effective.summaryEnabled && store.summaryToken() === '') {
|
if (effective.summaryEnabled && store.summaryToken() === '') {
|
||||||
logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged')
|
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). */
|
/** Current settings snapshot (live: re-read on every call). */
|
||||||
|
|
@ -240,6 +264,11 @@ export class BrainKernel {
|
||||||
return this.settingsOf()
|
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. */
|
/** Mark a bundle's entry as applied; feeds `routeDeps()` gating. */
|
||||||
activate(bundle: BrainBundle): void {
|
activate(bundle: BrainBundle): void {
|
||||||
this.active.add(bundle)
|
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. */
|
/** Test hook: drop the singleton so the next call rebuilds it. */
|
||||||
export function resetBrainKernel(): void {
|
export function resetBrainKernel(): void {
|
||||||
instance = undefined
|
instance = undefined
|
||||||
|
setRouteErrorHook(undefined)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import { dirname, join, resolve } from 'node:path'
|
||||||
import { dshHome } from '../store.ts'
|
import { dshHome } from '../store.ts'
|
||||||
import { JsonDocumentStore, JsonMemoryStore, containsSecret, localMemoryHash, withFileLock } from './storage.ts'
|
import { JsonDocumentStore, JsonMemoryStore, containsSecret, localMemoryHash, withFileLock } from './storage.ts'
|
||||||
import type { LocalDocument, LocalMemoryAddInput, LocalMemoryRecord, LocalMemoryScope, LocalMemorySettings, LocalSpaceMeta } from './types.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') }
|
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. */
|
/** 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
|
globalRoot?: string
|
||||||
/** Optional explicit project root; defaults to <cwd>/.dsh/brain. */
|
/** Optional explicit project root; defaults to <cwd>/.dsh/brain. */
|
||||||
projectRoot?: string
|
projectRoot?: string
|
||||||
|
/** Optional diagnostic logger; absent means a byte-equivalent no-op. */
|
||||||
|
logger?: BrainLogger
|
||||||
}
|
}
|
||||||
export interface LocalTurn { turnId?: string; user?: string; assistant?: string }
|
export interface LocalTurn { turnId?: string; user?: string; assistant?: string }
|
||||||
interface WorkspaceStores { root: string; store: JsonMemoryStore; documents: JsonDocumentStore }
|
interface WorkspaceStores { root: string; store: JsonMemoryStore; documents: JsonDocumentStore }
|
||||||
|
|
@ -83,12 +86,14 @@ export class LocalMemoryManager {
|
||||||
private readonly workspaces = new Map<string, WorkspaceStores>()
|
private readonly workspaces = new Map<string, WorkspaceStores>()
|
||||||
private readonly fixedGlobalRoot: string | undefined
|
private readonly fixedGlobalRoot: string | undefined
|
||||||
private readonly fixedProjectRoot: string | undefined
|
private readonly fixedProjectRoot: string | undefined
|
||||||
|
private readonly loggerOf: Pick<BrainLogger, 'log'> | undefined
|
||||||
constructor(options: LocalMemoryManagerOptions = {}) {
|
constructor(options: LocalMemoryManagerOptions = {}) {
|
||||||
this.cwdOf = options.cwd ?? (() => process.cwd())
|
this.cwdOf = options.cwd ?? (() => process.cwd())
|
||||||
this.defaultWorkspaceOf = options.workspace
|
this.defaultWorkspaceOf = options.workspace
|
||||||
this.settingsOf = options.settings ?? (() => ({}))
|
this.settingsOf = options.settings ?? (() => ({}))
|
||||||
this.fixedGlobalRoot = options.globalRoot
|
this.fixedGlobalRoot = options.globalRoot
|
||||||
this.fixedProjectRoot = options.projectRoot
|
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. */
|
/** 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) }
|
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')
|
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')
|
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()
|
await this.repairProjectionsIfDirty()
|
||||||
|
this.loggerOf?.log({ event: 'memory.ensure', detail: { scope: 'global', root: this.globalRoot } })
|
||||||
return meta
|
return meta
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -170,6 +176,7 @@ export class LocalMemoryManager {
|
||||||
})
|
})
|
||||||
const state = { root, store, documents }
|
const state = { root, store, documents }
|
||||||
this.workspaces.set(root, state)
|
this.workspaces.set(root, state)
|
||||||
|
this.loggerOf?.log({ event: 'memory.ensure', scope: 'project', workspace: base, detail: { scope: 'project', root } })
|
||||||
return store
|
return store
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -183,13 +190,19 @@ export class LocalMemoryManager {
|
||||||
}
|
}
|
||||||
/** Add one memory and regenerate the compact projections. */
|
/** Add one memory and regenerate the compact projections. */
|
||||||
async remember(input: LocalMemoryAddInput): Promise<{ record: LocalMemoryRecord; duplicate: boolean; projectionPending?: boolean; projectionError?: string }> {
|
async remember(input: LocalMemoryAddInput): Promise<{ record: LocalMemoryRecord; duplicate: boolean; projectionPending?: boolean; projectionError?: string }> {
|
||||||
|
const startedAt = Date.now()
|
||||||
const workspace = this.workspacePath()
|
const workspace = this.workspacePath()
|
||||||
const scope = input.scope ?? 'project'
|
const scope = input.scope ?? 'project'
|
||||||
const store = await this.storeFor(scope, workspace)
|
const store = await this.storeFor(scope, workspace)
|
||||||
await this.markProjectionDirty()
|
await this.markProjectionDirty()
|
||||||
const result = await store.add({ ...input, projectId: input.projectId ?? (scope === 'project' ? projectIdFor(this.projectRootFor(workspace)) : undefined) })
|
const result = await store.add({ ...input, projectId: input.projectId ?? (scope === 'project' ? projectIdFor(this.projectRootFor(workspace)) : undefined) })
|
||||||
if (result.duplicate) return result
|
if (result.duplicate) {
|
||||||
return { ...result, ...(await this.tryRegenerateProjections()) }
|
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 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> {
|
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))
|
.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 }[]> {
|
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 hits = await this.collectHits(query, workspace, projectId)
|
||||||
const limit = Math.max(1, Math.min(100, Math.trunc(k)))
|
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[]> {
|
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)
|
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> {
|
async forget(id: string, expectedRevision?: number, workspace?: string): Promise<LocalMemoryRecord> {
|
||||||
const globalRecord = await this.globalStore.read(id)
|
const globalRecord = await this.globalStore.read(id)
|
||||||
await this.markProjectionDirty()
|
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 store = await this.ensureProject(workspace)
|
||||||
const removed = await store.forget(id, expectedRevision)
|
const removed = await store.forget(id, expectedRevision)
|
||||||
await this.tryRegenerateProjections()
|
await this.tryRegenerateProjections()
|
||||||
|
this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace, detail: { recordId: id, revision: removed.revision } })
|
||||||
return removed
|
return removed
|
||||||
}
|
}
|
||||||
async projects(workspace?: string): Promise<{ id: string; name: string }[]> {
|
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', 'USER.md'), render('USER', user))
|
||||||
await atomicWrite(join(this.globalRoot, 'runtime', 'MEMORY.md'), render('MEMORY', rules))
|
await atomicWrite(join(this.globalRoot, 'runtime', 'MEMORY.md'), render('MEMORY', rules))
|
||||||
await this.clearProjectionDirty(marker)
|
await this.clearProjectionDirty(marker)
|
||||||
|
this.loggerOf?.log({ event: 'memory.projection', detail: { root: this.globalRoot } })
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await this.markProjectionDirty(error)
|
await this.markProjectionDirty(error)
|
||||||
throw 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)
|
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) }
|
checkpoints[input.sessionId] = { ...(lastValue === undefined ? {} : { lastTurn: lastValue }), count: nextCount, processed: [...processedNext].slice(-1000) }
|
||||||
await atomicWrite(checkpointPath, JSON.stringify(checkpoints, null, 2) + '\n')
|
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 }
|
return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false }
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -356,6 +382,7 @@ export class LocalMemoryManager {
|
||||||
if (entry.name === 'backups') continue
|
if (entry.name === 'backups') continue
|
||||||
await cp(join(this.globalRoot, entry.name), join(path, entry.name), { recursive: true, force: false })
|
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 }
|
return { path }
|
||||||
}
|
}
|
||||||
/** Report legacy .mnemon locations without deleting anything. */
|
/** Report legacy .mnemon locations without deleting anything. */
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,7 @@ export interface PersistedState {
|
||||||
autoSummaryEnabled?: boolean
|
autoSummaryEnabled?: boolean
|
||||||
autoProfileEnabled?: boolean
|
autoProfileEnabled?: boolean
|
||||||
localMemoryK?: number
|
localMemoryK?: number
|
||||||
|
diagnosticsEnabled?: boolean
|
||||||
/** Token labels the user cleared — set so an env fallback cannot resurrect them. */
|
/** Token labels the user cleared — set so an env fallback cannot resurrect them. */
|
||||||
clearedTokens?: string[]
|
clearedTokens?: string[]
|
||||||
}
|
}
|
||||||
|
|
@ -156,6 +157,7 @@ function parseState(raw: string): PersistedState {
|
||||||
if (typeof source.autoMemorySpaces === 'boolean') state.autoMemorySpaces = source.autoMemorySpaces
|
if (typeof source.autoMemorySpaces === 'boolean') state.autoMemorySpaces = source.autoMemorySpaces
|
||||||
if (typeof source.autoSummaryEnabled === 'boolean') state.autoSummaryEnabled = source.autoSummaryEnabled
|
if (typeof source.autoSummaryEnabled === 'boolean') state.autoSummaryEnabled = source.autoSummaryEnabled
|
||||||
if (typeof source.autoProfileEnabled === 'boolean') state.autoProfileEnabled = source.autoProfileEnabled
|
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)
|
const localMemoryK = clampInt(source.localMemoryK, 1, 100)
|
||||||
if (localMemoryK !== undefined) state.localMemoryK = localMemoryK
|
if (localMemoryK !== undefined) state.localMemoryK = localMemoryK
|
||||||
const baseUrl = normalizeBaseUrl(source.baseUrl)
|
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.autoSummaryEnabled !== undefined) resolved.autoSummaryEnabled = this.state.autoSummaryEnabled
|
||||||
if (this.state.autoProfileEnabled !== undefined) resolved.autoProfileEnabled = this.state.autoProfileEnabled
|
if (this.state.autoProfileEnabled !== undefined) resolved.autoProfileEnabled = this.state.autoProfileEnabled
|
||||||
if (this.state.localMemoryK !== undefined) resolved.localMemoryK = this.state.localMemoryK
|
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
|
// The split gates inherit `enabled` unless the config or the sidecar set
|
||||||
// them explicitly, so an old configuration keeps its exact behaviour.
|
// them explicitly, so an old configuration keeps its exact behaviour.
|
||||||
if (this.state.activityEnabled === undefined && this.configExplicit.activityEnabled === undefined) {
|
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' }
|
if (skillsDir.length > 512) return { ok: false, error: 'skillsDir too long' }
|
||||||
next.skillsDir = skillsDir
|
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 (patch[key] !== undefined) {
|
||||||
if (typeof patch[key] !== 'boolean') return { ok: false, error: key + ' must be a boolean' }
|
if (typeof patch[key] !== 'boolean') return { ok: false, error: key + ' must be a boolean' }
|
||||||
next[key] = patch[key]
|
next[key] = patch[key]
|
||||||
|
|
|
||||||
|
|
@ -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)
|
||||||
Loading…
Reference in New Issue