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
/**
* Write-Time Integrity & Governance Suite MCP tools: brain_labels
* (fail-closed vocabulary classification), brain_tiers (staged
* identity-drift repair), brain_secrets (list metadata / allowlisted
* run, never values), brain_maintenance (gated lane run/status).
*/
import { afterEach, beforeEach, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { freezeVault, unfreezeVault } from "../../src/core/brain/freeze.ts";
import { resetFreezeMarkerCache } from "../../src/core/brain/freeze-marker.ts";
import { setSecret } from "../../src/core/brain/secrets/store.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { MAINTENANCE_RUN_LOCAL_ONLY } from "../../src/mcp/brain/admin-tools.ts";
let tmp: string;
let vault: string;
let configHome: string;
let configPath: string;
const savedEnv: Record<string, string | undefined> = {};
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-gov-"));
vault = join(tmp, "vault");
configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-gov-cfg-"));
configPath = join(configHome, "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 });
rmSync(configHome, { 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: "gov-test", version: "0" },
},
});
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
method: "notifications/initialized",
});
}
async function call(
server: MCPServer,
tool: string,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const res = (await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 99,
method: "tools/call",
params: { name: tool, arguments: args },
})) as { result?: { content?: Array<{ text?: string }> }; error?: { message: string } };
if (res.error !== undefined) throw new Error(res.error.message);
return JSON.parse(res.result!.content![0]!.text!) as Record<string, unknown>;
}
test("brain_labels assigns within the vocabulary and fails closed outside it", async () => {
writeFileSync(
join(vault, "Brain", "_brain.yaml"),
["schema_version: 1", "schema:", " labels:", " - priority=low", " - priority=high"].join(
"\n",
) + "\n",
);
mkdirSync(join(vault, "notes"), { recursive: true });
writeFileSync(join(vault, "notes", "rollout.md"), "# Rollout\n\nCanary first.\n");
const server = new MCPServer({ vault, configPath });
await initialize(server);
const assigned = await call(server, "brain_labels", {
operation: "assign",
path: "notes/rollout.md",
dimension: "priority",
value: "high",
});
expect(assigned["labels"]).toEqual(["priority/high"]);
const shown = await call(server, "brain_labels", {
operation: "show",
path: "notes/rollout.md",
});
expect(shown["labels"]).toEqual(["priority/high"]);
await expect(
call(server, "brain_labels", {
operation: "assign",
path: "notes/rollout.md",
dimension: "priority",
value: "urgent",
}),
).rejects.toThrow(/allowed values: low, high/);
});
/**
* a-label-is-not-a-boundary, U12: the argument name in the complaint.
*
* `brain_labels {operation:"show", id:"…"}` answered "path must be a
* vault-relative string" - a sentence about the SHAPE of an argument the
* caller never sent, for an argument name (`id`) the tool never declared.
* A caller reading it has no way to learn that `path` is the name, or
* that `id` is not one.
*
* The resolution is stated at the handler: the argument is right and the
* VALIDATOR's message was wrong. This test pins all three answers - the
* documented call, the undeclared name, and the genuinely absent one -
* because the first two are what tell those two failures apart.
*/
test("brain_labels show names the argument that is actually wrong", async () => {
mkdirSync(join(vault, "notes"), { recursive: true });
writeFileSync(join(vault, "notes", "rollout.md"), "# Rollout\n\nCanary first.\n");
const server = new MCPServer({ vault, configPath });
await initialize(server);
// The DOCUMENTED call: `path`, exactly as `inputSchema` declares it.
const shown = await call(server, "brain_labels", {
operation: "show",
path: "notes/rollout.md",
});
expect(shown).toEqual({ path: "notes/rollout.md", labels: [] });
// An undeclared name is refused BY NAME, with the declared set in hand.
await expect(
call(server, "brain_labels", { operation: "show", id: "notes/rollout.md" }),
).rejects.toThrow(/unknown argument 'id'/);
// An ABSENT required argument is reported as absent, not as malformed.
await expect(call(server, "brain_labels", { operation: "show" })).rejects.toThrow(
/brain_labels show: path is required/,
);
});
test("brain_labels show answers a reserved note as an absent one at remote reach", async () => {
mkdirSync(join(vault, "notes"), { recursive: true });
writeFileSync(
join(vault, "notes", "secret.md"),
"---\nvisibility: [private]\nlabels: [priority/high]\n---\n\nSecret.\n",
);
const args = { operation: "show", path: "notes/secret.md" };
const local = new MCPServer({ vault, configPath }, { reach: "local" });
await initialize(local);
expect((await call(local, "brain_labels", args))["labels"]).toEqual(["priority/high"]);
const remote = new MCPServer({ vault, configPath }, { reach: "remote" });
await initialize(remote);
const reserved = await call(remote, "brain_labels", args).catch((e: Error) => e.message);
const absent = await call(remote, "brain_labels", {
operation: "show",
path: "notes/missing.md",
}).catch((e: Error) => e.message);
expect(reserved).toBe("brain_labels show: note does not exist: notes/secret.md");
expect(absent).toBe("brain_labels show: note does not exist: notes/missing.md");
});
test("brain_tiers check is empty on a fresh vault; restore demands apply", async () => {
const server = new MCPServer({ vault, configPath });
await initialize(server);
const checked = await call(server, "brain_tiers", { operation: "check" });
expect(checked["findings"]).toEqual([]);
await expect(
call(server, "brain_tiers", { operation: "restore", path: "Brain/x.md" }),
).rejects.toThrow(/apply=true/);
});
test("brain_tiers cannot write into a frozen vault (t_sec_tiers_freeze)", async () => {
// Both write operations answer to the freeze: `restore` rewrites a
// note's frontmatter, `accept` rewrites the tier snapshot. A repair
// surface is still a write surface.
freezeVault(vault, { agent: "tester", now: new Date("2026-06-05T10:00:00Z") });
resetFreezeMarkerCache();
try {
const server = new MCPServer({ vault, configPath });
await initialize(server);
await expect(
call(server, "brain_tiers", { operation: "restore", path: "notes/x.md", apply: true }),
).rejects.toThrow(/frozen/i);
await expect(
call(server, "brain_tiers", { operation: "accept", path: "notes/x.md" }),
).rejects.toThrow(/frozen/i);
} finally {
unfreezeVault(vault, { agent: "tester" });
resetFreezeMarkerCache();
}
});
test("brain_secrets lists metadata only and refuses a non-allowlisted run", async () => {
setSecret(vault, {
name: "api-key",
value: "sk-mcp-secret-777",
allow: ["bun -e *"],
agent: "tester",
now: new Date("2026-06-05T10:00:00Z"),
});
const server = new MCPServer({ vault, configPath });
await initialize(server);
const listed = await call(server, "brain_secrets", { operation: "list" });
expect(JSON.stringify(listed)).not.toContain("sk-mcp-secret-777");
expect((listed["secrets"] as Array<{ name: string }>)[0]!.name).toBe("api-key");
await expect(
call(server, "brain_secrets", {
operation: "run",
name: "api-key",
command: ["bash", "-c", "env"],
}),
).rejects.toThrow(/allowlist/);
const ran = await call(server, "brain_secrets", {
operation: "run",
name: "api-key",
command: ["bun", "-e", "console.log('v=' + process.env.API_KEY)"],
});
expect(ran["exit_code"]).toBe(0);
expect(String(ran["stdout"])).not.toContain("sk-mcp-secret-777");
});
test("brain_maintenance run executes the lane; status reads the journal", async () => {
// A lane run is the operator's own operation: local reach only.
const server = new MCPServer({ vault, configPath }, { reach: "local" });
await initialize(server);
const ran = await call(server, "brain_maintenance", { operation: "run" });
expect(ran["verdict"]).toBe("run");
const tasks = ran["tasks"] as Array<{ name: string; ok: boolean }>;
// Same lane contract as the CLI verb (link-recall-intelligence).
expect(tasks.map((t) => t.name)).toEqual(["dream", "reindex", "bridges", "clusters", "relink"]);
expect(tasks.every((t) => t.ok)).toBe(true);
const status = await call(server, "brain_maintenance", { operation: "status" });
expect(status["lease"]).toBeNull();
expect((status["journal"] as unknown[]).length).toBeGreaterThanOrEqual(2);
});
test("brain_maintenance run is allowed at local reach when the owner scope gate is enforced", async () => {
// The guard is the transport reach, not the owner gate: a local caller
// with `owner_scope_delivery: fail` is still the operator.
const brainYaml = join(vault, "Brain", "_brain.yaml");
const existing = readFileSync(brainYaml, "utf8");
if (/^integrity:/m.test(existing)) throw new Error("fixture already has an integrity block");
writeFileSync(brainYaml, `${existing.trimEnd()}\nintegrity:\n owner_scope_delivery: fail\n`);
const server = new MCPServer({ vault, configPath }, { reach: "local" });
await initialize(server);
const ran = await call(server, "brain_maintenance", { operation: "run", force: true });
expect(ran["verdict"]).toBe("run");
});
/** Every file under `root` with its bytes. */
function treeBytes(root: string, rel = ""): Record<string, string> {
const out: Record<string, string> = {};
for (const entry of readdirSync(join(root, rel), { withFileTypes: true })) {
const child = rel === "" ? entry.name : `${rel}/${entry.name}`;
if (entry.isDirectory()) Object.assign(out, treeBytes(root, child));
else out[child] = readFileSync(join(root, child), "utf8");
}
return out;
}
test("brain_maintenance run is refused below local reach before the lease or any write", async () => {
const before = treeBytes(vault);
const server = new MCPServer({ vault, configPath }, { reach: "remote" });
await initialize(server);
await expect(
call(server, "brain_maintenance", { operation: "run", force: true }),
).rejects.toThrow(MAINTENANCE_RUN_LOCAL_ONLY);
expect(treeBytes(vault)).toEqual(before);
// Reading the lane's state is not a run, and stays open.
const status = await call(server, "brain_maintenance", { operation: "status" });
expect(status["lease"]).toBeNull();
});