Local-first 🧠memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
/**
* Consolidated read tools (token-diet, t_3920db77): `brain_brief`,
* `brain_analytics`, and `schema_inspect` dispatch by `view`. The
* per-view predecessor aliases were removed in 1.0.0 (epic
* t_a77ade0a) - their tombstones live in `REMOVED_TOOLS` and are
* covered by `removed-tools.test.ts`; here every consolidated view
* must keep working on its own.
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { appendLogEvent } from "../../src/core/brain/log.ts";
import { BRAIN_LOG_EVENT_KIND } from "../../src/core/brain/types.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { emitIngestDedupReport } from "../../src/core/brain/dedup-telemetry.ts";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { writePreference } from "../../src/core/brain/preference.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";
const UNKNOWN_TYPE = "no-such-token";
let tmp: string;
let vault: string;
let configPath: string;
let ctx: ServerContext;
const TOOLS = buildToolTable("full");
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-consolidated-"));
vault = join(tmp, "vault");
configPath = join(tmp, "config.yaml");
atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
bootstrapBrain(vault, { configPath });
writePreference(vault, {
slug: "fixture",
topic: "fixture",
principle: "Always test consolidated views.",
created_at: "2026-05-01T10:00:00Z",
unconfirmed_until: "2026-05-15T10:00:00Z",
status: "confirmed",
evidenced_by: [],
});
ctx = { vault, configPath } as unknown as ServerContext;
});
afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
async function run(name: string, args: Record<string, unknown>): Promise<unknown> {
return await findTool(TOOLS, name).handler(ctx, args);
}
describe("brain_brief", () => {
const CASES: ReadonlyArray<{ view: string; args?: Record<string, unknown> }> = [
{ view: "morning" },
{ view: "daily", args: { date: "2026-05-02" } },
{ view: "weekly", args: { week_end: "2026-05-08" } },
{ view: "monthly", args: { month: "2026-05" } },
{ view: "operator", args: { include_dream: false } },
{ view: "digest", args: { since: "2026-05-01T00:00:00Z", until: "2026-05-03T00:00:00Z" } },
{ view: "today" },
];
for (const { view, args } of CASES) {
test(`view=${view} resolves to a structured envelope`, async () => {
const result = await run("brain_brief", { view, ...args });
expect(result).toBeDefined();
expect(typeof result).toBe("object");
});
}
test("view=today returns the dashboard envelope with the pledges member", async () => {
const result = (await run("brain_brief", { view: "today" })) as Record<string, unknown>;
expect(typeof result["text"]).toBe("string");
expect(result["obligations"]).toBeDefined();
expect(result["pledges"]).toBeDefined();
expect(result["open_loops"]).toBeDefined();
expect(result["recent_activity"]).toBeDefined();
expect(result["totals"]).toBeDefined();
expect(result["errors"]).toBeDefined();
expect(result["text"]).toContain("## Obligations");
expect(result["text"]).toContain("## Pledges");
});
test("today is advertised in the brain_brief view enum", () => {
const tool = findTool(TOOLS, "brain_brief");
const view = (tool.inputSchema as { properties: { view: { enum: readonly string[] } } })
.properties.view;
expect(view.enum).toContain("today");
});
test("view=today accepts a zero lookback window and a zero limit", async () => {
// The core builder and CLI both honour 0 (empty recent-activity section);
// the MCP surface must not reject it.
const result = (await run("brain_brief", {
view: "today",
lookback_days: 0,
limit: 0,
})) as Record<string, unknown>;
// 0 is accepted (no INVALID_PARAMS throw); the section computes cleanly.
expect(result["recent_activity"]).toBeDefined();
expect(result["totals"]).toMatchObject({ recentActivityTotal: 0 });
expect(result["errors"]).toEqual([]);
});
test("lookback_days and limit advertise a minimum of 0", () => {
const tool = findTool(TOOLS, "brain_brief");
const props = (
tool.inputSchema as {
properties: Record<string, { minimum?: number }>;
}
).properties;
expect(props["lookback_days"]!.minimum).toBe(0);
expect(props["limit"]!.minimum).toBe(0);
});
test("invalid view raises a clear error", async () => {
await expect(run("brain_brief", { view: "hourly" })).rejects.toThrow(/view/);
});
test("missing view raises a clear error", async () => {
await expect(run("brain_brief", {})).rejects.toThrow(/view/);
});
});
describe("brain_analytics", () => {
test("view=timeline returns an events window", async () => {
const args = { pref_id: "pref-fixture", since: "2026-05-01", until: "2026-06-01" };
const result = (await run("brain_analytics", { view: "timeline", ...args })) as Record<
string,
unknown
>;
expect(Array.isArray(result["events"])).toBe(true);
});
test("view=belief_evolution returns transitions for a preference", async () => {
const result = (await run("brain_analytics", {
view: "belief_evolution",
pref_id: "pref-fixture",
})) as Record<string, unknown>;
expect(result).toBeDefined();
expect(typeof result).toBe("object");
});
test("view=concept_synthesis resolves for a known id", async () => {
const result = await run("brain_analytics", { view: "concept_synthesis", id: "pref-fixture" });
expect(result).toBeDefined();
});
test("view=attention_flows defaults the operation to list", async () => {
const result = (await run("brain_analytics", { view: "attention_flows" })) as Record<
string,
unknown
>;
expect(result).toBeDefined();
expect(typeof result).toBe("object");
});
test("view=dedup summarises the persisted exact-hash ingest dedup records", async () => {
emitIngestDedupReport(vault, {
surface: "scan_inline",
sources: [{ ref: "Daily/2026-07-01.md", exactDeduped: 3 }],
createdAt: "2026-07-01T10:00:00.000Z",
});
const result = (await run("brain_analytics", { view: "dedup" })) as Record<string, unknown>;
expect(result["total_records"]).toBe(1);
expect(result["total_exact_deduped"]).toBe(3);
expect(result["by_surface"]).toEqual({ scan_inline: 3 });
expect(result["trend"]).toEqual([
{ at: "2026-07-01T10:00:00.000Z", surface: "scan_inline", exact_deduped: 3 },
]);
// The semantic detectors nominate and never drop, so no key on this
// surface may be read as a semantic drop count.
for (const key of Object.keys(result)) expect(key).not.toContain("semantic");
});
test("view=dedup on a vault that deduped nothing reports zeros, not a fabricated row", async () => {
const result = (await run("brain_analytics", { view: "dedup" })) as Record<string, unknown>;
expect(result["total_records"]).toBe(0);
expect(result["total_exact_deduped"]).toBe(0);
expect(result["trend"]).toEqual([]);
});
test("view=dedup rejects an unknown surface filter by name", async () => {
await expect(
run("brain_analytics", { view: "dedup", surface: "not_a_surface" }),
).rejects.toThrow(/surface/);
});
test("invalid view raises a clear error", async () => {
await expect(run("brain_analytics", { view: "recurrence" })).rejects.toThrow(/view/);
});
});
describe("schema_inspect", () => {
for (const view of ["graph", "lint", "stats", "orphans", "active_pack", "packs"]) {
test(`view=${view} resolves`, async () => {
const result = await run("schema_inspect", { view });
expect(result).toBeDefined();
});
}
test("view=explain_type forwards the token", async () => {
// The explanation must echo the normalized token, proving the
// argument reaches the underlying handler.
const result = (await run("schema_inspect", {
view: "explain_type",
token: UNKNOWN_TYPE,
})) as Record<string, unknown>;
expect(result["token"]).toBe(UNKNOWN_TYPE);
});
test("invalid view raises a clear error", async () => {
await expect(run("schema_inspect", { view: "everything" })).rejects.toThrow(/view/);
});
});
describe("timezone presentation (t_2ccadc6a)", () => {
test("a configured timezone adds additive local fields to brief envelopes", async () => {
atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\ntimezone: Asia/Tokyo\n`);
const result = (await run("brain_brief", { view: "daily", date: "2026-06-05" })) as Record<
string,
unknown
>;
expect(result["timezone"]).toBe("Asia/Tokyo");
expect(String(result["local_time"])).toContain("+09:00");
});
test("no configured timezone keeps the envelope unchanged", async () => {
const result = (await run("brain_brief", { view: "daily", date: "2026-06-05" })) as Record<
string,
unknown
>;
expect(result["timezone"]).toBeUndefined();
expect(result["local_time"]).toBeUndefined();
});
});
describe("consolidated registration", () => {
test("consolidated tools are registered and advertised", async () => {
for (const name of ["brain_brief", "brain_analytics", "schema_inspect"]) {
expect(() => findTool(TOOLS, name)).not.toThrow();
}
const { MCPServer } = await import("../../src/mcp/server.ts");
const server = new MCPServer({ vault, configPath });
await server.handleRequest({
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: {
protocolVersion: "2025-06-18",
capabilities: {},
clientInfo: { name: "t", version: "0" },
},
});
await server.handleRequest({ jsonrpc: "2.0", method: "notifications/initialized" });
const list = (await server.handleRequest({
jsonrpc: "2.0",
id: 2,
method: "tools/list",
})) as { result: { tools: Array<{ name: string }> } };
const listed = new Set(list.result.tools.map((t) => t.name));
expect(listed.has("brain_brief")).toBe(true);
expect(listed.has("brain_analytics")).toBe(true);
expect(listed.has("schema_inspect")).toBe(true);
// The 1.0.0 sweep removed the alias layer entirely.
expect(listed.has("brain_daily_brief")).toBe(false);
expect(listed.has("schema_stats")).toBe(false);
});
});
describe("brain_analytics view=timeline cursor pagination", () => {
async function initialize(server: MCPServer): Promise<void> {
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 1,
method: "initialize",
params: {
protocolVersion: PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: "analytics-cursor-test", version: "0" },
},
});
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
method: "notifications/initialized",
});
}
test("the input schema declares a described cursor property", () => {
const tool = buildToolTable("full").find((t) => t.name === "brain_analytics")!;
const schema = tool.inputSchema as {
properties: Record<string, { type?: string; maxLength?: number; description?: string }>;
};
expect(schema.properties["cursor"]).toMatchObject({ type: "string", maxLength: 32 });
expect(schema.properties["cursor"]?.description).toBeTruthy();
});
test("each page's next_cursor leads to the next and the pages reassemble the events", async () => {
for (const [index, stamp] of ["10:00:00", "10:05:00", "10:10:00"].entries()) {
appendLogEvent(vault, {
timestamp: `2026-06-15T${stamp}Z`,
eventType: BRAIN_LOG_EVENT_KIND.writeSession,
agent: "tester",
body: { session_id: `sess-tl-${index}`, kind: "note", status: "committed" },
});
}
const server = new MCPServer({ vault, configPath });
await initialize(server);
const total = 3;
const limit = 2;
// A server that never ends the walk would hang an unbounded loop;
// ceil(total / limit) + 1 is one past the walk's own page count.
const maxSteps = Math.ceil(total / limit) + 1;
const stamps: string[] = [];
let cursor: string | null = null;
for (let step = 0; step < maxSteps; step++) {
const response = (await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 60,
method: "tools/call",
params: {
name: "brain_analytics",
arguments: {
view: "timeline",
since: "2026-06-15",
until: "2026-06-16",
limit,
...(cursor !== null ? { cursor } : {}),
},
},
})) as { result?: { structuredContent?: Record<string, unknown> } };
const out = response.result!.structuredContent!;
expect(out["total"]).toBe(total);
// Guard the walk protocol: an ignored cursor would loop forever.
const next = out["next_cursor"];
expect(next === null || typeof next === "string").toBe(true);
stamps.push(
...(out["events"] as ReadonlyArray<Record<string, unknown>>).map((e) => e["at"] as string),
);
cursor = next as string | null;
if (cursor === null) break;
}
// The walk ended because the server exhausted the set, not because
// the step bound fired.
expect(cursor).toBeNull();
expect(stamps).toHaveLength(3);
expect(new Set(stamps).size).toBe(3);
});
test("a malformed cursor is refused as invalid params", async () => {
const server = new MCPServer({ vault, configPath });
await initialize(server);
const response = (await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 61,
method: "tools/call",
params: {
name: "brain_analytics",
arguments: { view: "timeline", cursor: "!!!" },
},
})) as { error?: { code: number } };
expect(response.error?.code).toBe(-32602);
});
});