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
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import {
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
symlinkSync,
utimesSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { SCHEMA_TOOLS } from "../../src/mcp/schema-tools.ts";
import { INVALID_PARAMS, MCPError } from "../../src/mcp/protocol.ts";
import { toPosix } from "../../src/core/path-safety.ts";
/** Schema tokens used by the cases below. */
const DECISION = "decision";
const UNDECLARED = "undeclared";
let tmp: string;
let vault: string;
let configPath: string;
const savedEnv: Record<string, string | undefined> = {};
/**
* Epoch seconds stamped onto `Brain/_brain.yaml` before a dry run, far
* enough in the past that any write during the preview would move the
* modification time to now rather than leaving it within a coarse
* filesystem timestamp of where it started.
*/
const PAST_MTIME_SECONDS = Date.UTC(2020, 0, 1) / 1000;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-schema-"));
vault = join(tmp, "vault");
configPath = join(tmp, "config.yaml");
for (const key of [
"VAULT_AGENT_NAME",
"VAULT_TIMEZONE",
"VAULT_DIR",
"OPEN_SECOND_BRAIN_CONFIG",
]) {
savedEnv[key] = process.env[key];
delete process.env[key];
}
process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
bootstrapBrain(vault, { configPath });
});
afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
for (const [key, value] of Object.entries(savedEnv)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
async function initialize(server: MCPServer): Promise<void> {
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 1,
method: "initialize",
params: {
protocolVersion: PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: "schema-test", version: "0" },
},
});
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
method: "notifications/initialized",
});
}
async function call(
server: MCPServer,
name: string,
args: Record<string, unknown> = {},
): Promise<any> {
return server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 99,
method: "tools/call",
params: { name, arguments: args },
});
}
function makeServer(reach?: typeof TRANSPORT_REACH.local): MCPServer {
return new MCPServer({ vault, configPath }, reach !== undefined ? { reach } : {});
}
describe("schema MCP tools", () => {
test("registers the schema administration surface", async () => {
const server = makeServer();
await initialize(server);
const response = await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 50,
method: "tools/list",
});
const names = ((response as any).result.tools as ReadonlyArray<{ name: string }>).map(
(tool) => tool.name,
);
// token-diet consolidated the per-view readers into schema_inspect;
// the 1.0.0 sweep removed the hidden aliases entirely.
expect(names).toContain("schema_inspect");
expect(names).toContain("schema_apply_mutations");
expect(names).not.toContain("schema_stats");
});
test("applies schema mutations through the MCP handler", async () => {
const server = makeServer();
await initialize(server);
const applied = await call(server, "schema_apply_mutations", {
mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
});
expect((applied as any).result.structuredContent.applied).toBe(1);
const pack = await call(server, "schema_inspect", { view: "active_pack" });
expect((pack as any).result.structuredContent.pack.declarations.preference_types).toContain(
"decision",
);
});
test("a document deny rides the request identity and answers the named envelope", async () => {
// A document closing `codex` (the token's agent) out of the ingest
// action the schema consult answers; the config declares `claude`, so
// only the credential-minted subject can be what this refusal names.
atomicWriteFileSync(
join(vault, "Brain", "_permissions.yaml"),
"version: 1\ndefault_action: allow\nentries:\n - id: freeze\n agent: codex\n" +
" action: ingest\n verdict: deny\n",
);
const packBefore = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");
const tool = SCHEMA_TOOLS.find((t) => t.name === "schema_apply_mutations")!;
const ctx = {
vault,
configPath,
repoRoot: null,
requestIdentity: { agent: "codex", via: "token" as const },
};
try {
await tool.handler(ctx as any, {
mutations: [{ op: "add_type", category: "preference_types", token: UNDECLARED }],
});
throw new Error("expected MCPError");
} catch (err) {
expect(err).toBeInstanceOf(MCPError);
const refused = err as MCPError;
expect(refused.code).toBe(INVALID_PARAMS);
expect(refused.data).toMatchObject({
code: "write-refused",
rule: "entry:freeze",
agent: "codex",
});
}
// The pack is untouched: the consult ran before the rewrite.
expect(readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8")).toBe(packBefore);
});
test("schema graph namespaces link type node ids", async () => {
const server = makeServer();
await initialize(server);
await call(server, "schema_apply_mutations", {
mutations: [
{ op: "add_type", category: "preference_types", token: DECISION },
{ op: "add_link_type", token: DECISION },
],
});
const graph = await call(server, "schema_inspect", { view: "graph" });
const nodes = (graph as any).result.structuredContent.nodes as ReadonlyArray<{ id: string }>;
expect(nodes.map((node) => node.id)).toContain("decision");
expect(nodes.map((node) => node.id)).toContain("link:decision");
});
test("dry_run previews the resulting pack and its diff without touching _brain.yaml", async () => {
const server = makeServer();
await initialize(server);
const brainConfig = join(vault, "Brain", "_brain.yaml");
utimesSync(brainConfig, PAST_MTIME_SECONDS, PAST_MTIME_SECONDS);
// Base64 so the later comparison is over raw bytes, not decoded text.
const bytesBefore = readFileSync(brainConfig).toString("base64");
const mtimeBefore = statSync(brainConfig).mtimeMs;
const preview = await call(server, "schema_apply_mutations", {
mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
dry_run: true,
});
const structured = (preview as any).result.structuredContent;
expect(structured.dry_run).toBe(true);
expect(structured.would_apply).toBe(1);
expect(structured.pack.declarations.preference_types).toContain("decision");
expect(structured.diff).toEqual([
{ path: "declarations.preference_types", before: null, after: "decision" },
]);
// A preview must never look like an apply: no audit record was written,
// so there is no audit path to report.
expect(structured.audit_path).toBeUndefined();
expect(readFileSync(brainConfig).toString("base64")).toBe(bytesBefore);
expect(statSync(brainConfig).mtimeMs).toBe(mtimeBefore);
const pack = await call(server, "schema_inspect", { view: "active_pack" });
expect(
(pack as any).result.structuredContent.pack.declarations.preference_types ?? [],
).not.toContain("decision");
});
test("an apply with no dry_run argument behaves exactly as today", async () => {
const server = makeServer();
await initialize(server);
const applied = await call(server, "schema_apply_mutations", {
mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
});
const structured = (applied as any).result.structuredContent;
expect(structured.applied).toBe(1);
expect(typeof structured.audit_path).toBe("string");
expect(structured.pack.declarations.preference_types).toContain("decision");
// The dry-run key exists only on a preview; an apply carries neither it
// nor the diff, exactly as before dry_run was added.
expect("dry_run" in structured).toBe(false);
expect("diff" in structured).toBe(false);
const pack = await call(server, "schema_inspect", { view: "active_pack" });
expect((pack as any).result.structuredContent.pack.declarations.preference_types).toContain(
"decision",
);
});
test("active_pack and packs forward the integrity verdict unchanged", async () => {
const server = makeServer();
await initialize(server);
// A freshly bootstrapped vault has no audited apply behind it, so the
// pack it reports is unverified rather than intact.
const fresh = await call(server, "schema_inspect", { view: "active_pack" });
expect((fresh as any).result.structuredContent.exists).toBe(true);
expect((fresh as any).result.structuredContent.integrity.status).toBe("unverified");
expect((fresh as any).result.structuredContent.integrity.unverified_reason).toBe(
"no-apply-recorded",
);
const applied = await call(server, "schema_apply_mutations", {
mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
});
const digest = (applied as any).result.structuredContent.pack_digest;
expect(typeof digest).toBe("string");
const sealed = await call(server, "schema_inspect", { view: "active_pack" });
expect((sealed as any).result.structuredContent.integrity.status).toBe("ok");
expect((sealed as any).result.structuredContent.integrity.digest).toBe(digest);
const packs = await call(server, "schema_inspect", { view: "packs" });
const listed = (packs as any).result.structuredContent.packs as ReadonlyArray<{
exists: boolean;
integrity: { status: string; digest: string };
}>;
expect(listed).toHaveLength(1);
expect(listed[0]?.exists).toBe(true);
expect(listed[0]?.integrity.status).toBe("ok");
expect(listed[0]?.integrity.digest).toBe(digest);
});
test("active_pack reports a hand-edited pack as modified", async () => {
const server = makeServer();
await initialize(server);
await call(server, "schema_apply_mutations", {
mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
});
const brainConfig = join(vault, "Brain", "_brain.yaml");
atomicWriteFileSync(
brainConfig,
readFileSync(brainConfig, "utf8").replace(" - decision", " - decision\n - tactic"),
);
const pack = await call(server, "schema_inspect", { view: "active_pack" });
const integrity = (pack as any).result.structuredContent.integrity;
expect(integrity.status).toBe("modified");
expect(integrity.mismatches).toHaveLength(1);
expect(integrity.mismatches[0].field).toBe("pack_digest");
expect(integrity.mismatches[0].expected).not.toBe(integrity.mismatches[0].actual);
});
test("a rejected preview returns the same error envelope the apply returns", async () => {
const server = makeServer();
await initialize(server);
const rejected = [{ op: "add_prefix", prefix: "pref", token: UNDECLARED }];
const preview = await call(server, "schema_apply_mutations", {
mutations: rejected,
dry_run: true,
});
const apply = await call(server, "schema_apply_mutations", { mutations: rejected });
expect((preview as any).result.isError).toBe(true);
expect((preview as any).result.content[0].text).toBe(
"schema.prefixes.pref: token is not declared",
);
expect((preview as any).result).toEqual((apply as any).result);
});
test("a non-boolean dry_run is an invalid param", async () => {
const server = makeServer();
await initialize(server);
const response = await call(server, "schema_apply_mutations", {
mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
dry_run: "yes",
});
expect((response as any).error.code).toBe(INVALID_PARAMS);
expect((response as any).error.message).toContain("dry_run");
});
test("schema apply reports coercion failures as invalid params", async () => {
const server = makeServer();
await initialize(server);
const response = await call(server, "schema_apply_mutations", {
mutations: "not an array",
});
expect((response as any).error.code).toBe(INVALID_PARAMS);
expect((response as any).error.message).toContain("mutations must be an array");
});
});
/**
* a-label-is-not-a-boundary, U12: the lint that died on its own subject.
*
* `view=lint` and `view=orphans` exist to REPORT malformed Brain
* artifacts, and both raised on the first one they met - the parse error
* escaped `buildSchemaReport` unhandled, so a single bad file cost the
* caller every finding in the vault. The message carried the absolute
* host path as well, which is the leak `vaultPathField` closes on the
* same surface.
*
* Two shapes are driven, because two different mechanisms produced the
* same silence: a parse failure (a retired preference missing a required
* field, which THREW) and a read failure (a directory occupying a `.md`
* name under the log dir, which was swallowed by a bare
* `catch { continue }` and reported nothing at all).
*/
describe("schema_inspect reports the malformed artifact instead of dying on it", () => {
/** Plant every malformed artifact; returns their vault-relative paths. */
function plantMalformedArtifacts(): { retired: string; log: string; dangling: string } {
const retiredRel = join("Brain", "retired", "ret-broken.md");
mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
atomicWriteFileSync(
join(vault, retiredRel),
// `retired_at` is required by `parseRetired`; without it the parse
// throws a BrainParseError naming the absolute path.
[
"---",
"kind: brain-retired",
"_status: retired",
"id: ret-broken",
"---",
"",
"body",
"",
].join("\n"),
);
// A DIRECTORY under a `.md` name: `readFileSync` fails with EISDIR on
// every platform and for every user, which a chmod-based fixture does
// not (a test run as root reads a 0000 file).
const logRel = join("Brain", "log", "2026-08-16.md");
mkdirSync(join(vault, logRel), { recursive: true });
// A DANGLING SYMLINK. Neither fixture above produces a message with a
// host path in it - `BrainParseError` keeps the location in its own
// `path` field, and EISDIR reads `illegal operation on a directory,
// read` with no path at all - so `locationFreeDetail` had nothing to
// rewrite and its only test could not fail: replacing the whole
// function body with `return raw` left 15 pass, 0 fail. ENOENT is the
// shape the function's own docblock cites, and it embeds the absolute
// path INSIDE the message: `ENOENT: no such file or directory, open
// '/tmp/…/Brain/log/2026-08-15.md'`.
const danglingRel = join("Brain", "log", "2026-08-15.md");
symlinkSync(join(vault, "Brain", "log", "nothing-here.md"), join(vault, danglingRel));
// The report names artifacts by their vault identity, which is POSIX on
// every host; the fixture paths above are host-joined.
return { retired: toPosix(retiredRel), log: toPosix(logRel), dangling: toPosix(danglingRel) };
}
for (const view of ["lint", "orphans"] as const) {
test(`view=${view} answers with findings, not an error`, async () => {
const planted = plantMalformedArtifacts();
// At local reach: below it, a record whose file cannot be read is
// treated as one the caller may not read, and is not named.
const server = makeServer(TRANSPORT_REACH.local);
await initialize(server);
const response = await call(server, "schema_inspect", { view });
expect((response as any).error).toBeUndefined();
// A raised handler comes back as `isError: true` with the raw
// message as text - which is how this surface used to answer, and
// the message named the absolute host path.
expect((response as any).result.isError).not.toBe(true);
const payload = (response as any).result.structuredContent as Record<string, unknown>;
const findings = (payload["findings"] ?? payload["orphans"]) as ReadonlyArray<
Record<string, unknown>
>;
const unreadable = findings.filter((f) => f["kind"] === "unreadable-artifact");
expect(unreadable.map((f) => f["path"]).toSorted()).toEqual(
[planted.dangling, planted.log, planted.retired].toSorted(),
);
// The reason travels with the report, so the operator can act on it
// without re-running the parser by hand.
expect(unreadable.every((f) => typeof f["detail"] === "string" && f["detail"] !== "")).toBe(
true,
);
// The one fixture whose raw message really carries the host path.
// Asserted on the DETAIL rather than only on the payload, so the
// failure names the field that leaked rather than the whole
// response, and so the rewrite is measured where it happens.
const dangling = unreadable.find((f) => f["path"] === planted.dangling);
const detail = String(dangling?.["detail"]);
expect(detail).toContain("ENOENT");
expect(detail).not.toContain(vault);
// Rewritten to the vault-relative form, not merely deleted: a
// message that lost the filename would name nothing at all.
expect(detail).toContain(planted.dangling);
// …and the absolute host path stays out of the payload entirely.
expect(JSON.stringify(payload)).not.toContain(vault);
});
}
});