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, setDefaultTimeout, test } from "bun:test";
import {
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
existsSync,
readdirSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { BRAIN_INDEX_REL, BRAIN_ROOT_REL } from "../../src/core/brain/paths.ts";
import { isReadinessStatus } from "../../src/core/doctor-readiness.ts";
import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";
import { createPluginRepo, createSandboxVault } from "../helpers/fixtures.ts";
import { runCli } from "../helpers/run-cli.ts";
import { FAKE_GITHUB_SECRET } from "../helpers/fake-credentials.ts";
import { makeTestStore } from "../helpers/test-store.ts";
const GITHUB_REF = "$secret:GITHUB_TOKEN";
setDefaultTimeout(CLI_SPAWN_BUDGET_MS);
let tmp: string;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "o2b-cli-test-"));
});
afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
describe("help", () => {
test("top-level help includes the Brain note verb", async () => {
const r = await runCli(["--help"]);
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("brain note");
});
});
describe("status", () => {
test("reports missing config", async () => {
const config = join(tmp, "missing.yaml");
const r = await runCli(["status"], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("config_exists: false");
expect(r.stdout).toContain(config);
});
});
describe("init", () => {
test("prints initialized vault message", async () => {
const r = await runCli(["init", "--vault", tmp, "--name", "Test"]);
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("initialized vault:");
});
test("with agent-name persists to plugin config", async () => {
const vault = join(tmp, "vault");
const config = join(tmp, "config.yaml");
const r = await runCli(
["init", "--vault", vault, "--name", "Test", "--agent-name", "hermes-vps-agent"],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("agent name persisted to:");
const text = readFileSync(config, "utf8");
expect(text).toContain("agent_name");
expect(text).toContain("hermes-vps-agent");
});
test("persists vault path resolved (absolute) into config", async () => {
const vault = join(tmp, "vault");
const config = join(tmp, "config.yaml");
const r = await runCli(["init", "--vault", vault, "--name", "Test"], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("vault path persisted to:");
const text = readFileSync(config, "utf8");
expect(text).toContain("vault");
// `init` stores the path with forward slashes: the config writer refuses
// a backslash, and Windows accepts `C:/...` everywhere a path is read.
expect(text).toContain(resolve(vault).replace(/\\/g, "/"));
});
test("with timezone persists to plugin config", async () => {
const vault = join(tmp, "vault");
const config = join(tmp, "config.yaml");
const r = await runCli(
[
"init",
"--vault",
vault,
"--name",
"Test",
"--agent-name",
"hermes-vps-agent",
"--timezone",
"Europe/Belgrade",
],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("timezone registered: Europe/Belgrade");
const text = readFileSync(config, "utf8");
expect(text).toContain("Europe/Belgrade");
});
test("rejects invalid timezone", async () => {
const vault = join(tmp, "vault");
const config = join(tmp, "config.yaml");
const r = await runCli(
["init", "--vault", vault, "--name", "Test", "--timezone", "NotARealTimezone"],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).not.toBe(0);
expect(r.stderr).toContain("not a valid IANA name");
expect(existsSync(vault) && readdirSync(vault).length > 0).toBe(false);
});
test("re-init persists agent name", async () => {
const vault = join(tmp, "vault");
const config = join(tmp, "config.yaml");
await runCli(["init", "--vault", vault, "--name", "Test"]);
const r = await runCli(
["init", "--vault", vault, "--name", "Test", "--agent-name", "hermes-vps-agent"],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("agent name persisted to:");
expect(readFileSync(config, "utf8")).toContain("hermes-vps-agent");
});
});
describe("doctor", () => {
test("errors when no vault anywhere", async () => {
const cfg = join(tmp, "config.yaml");
const r = await runCli(["doctor"], {
env: { OPEN_SECOND_BRAIN_CONFIG: cfg },
});
expect(r.returncode).not.toBe(0);
expect(r.stderr.toLowerCase()).toContain("no vault configured");
});
test("checks valid vault", async () => {
const r = await runCli(["doctor", "--vault", tmp], {
env: { OPEN_SECOND_BRAIN_CONFIG: "", XDG_CONFIG_HOME: "", VAULT_DIR: "" },
});
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("[OK]");
expect(r.stdout.toLowerCase()).toContain("vault");
});
test("reports missing vault", async () => {
const r = await runCli(["doctor", "--vault", "/nonexistent/path"]);
expect(r.returncode).toBe(1);
expect(r.stdout).toContain("[FAIL]");
});
test("prints a copy-pasteable fix and an aggregate summary for a failure", async () => {
const r = await runCli(["doctor", "--vault", "/nonexistent/path"]);
expect(r.returncode).toBe(1);
expect(r.stdout).toContain("fix: mkdir -p");
expect(r.stdout).toMatch(/doctor: \d+ checks, [1-9]\d* failed/);
});
test("--json emits a scriptable report with fix and summary", async () => {
const r = await runCli(["doctor", "--vault", "/nonexistent/path", "--json"]);
expect(r.returncode).toBe(1);
const parsed = JSON.parse(r.stdout);
expect(parsed.ok).toBe(false);
expect(parsed.summary.failed).toBeGreaterThan(0);
const failing = parsed.checks.find((c: { ok: boolean }) => !c.ok);
expect(typeof failing.fix).toBe("string");
expect(failing.fix.length).toBeGreaterThan(0);
});
test("--json on a healthy vault reports ok with zero failures", async () => {
const r = await runCli(["doctor", "--vault", tmp, "--json"], {
env: { OPEN_SECOND_BRAIN_CONFIG: "", XDG_CONFIG_HOME: "", VAULT_DIR: "" },
});
expect(r.returncode).toBe(0);
const parsed = JSON.parse(r.stdout);
expect(parsed.ok).toBe(true);
expect(parsed.summary.failed).toBe(0);
// A passing check omits the remediation fix.
expect(parsed.checks.every((c: { fix?: string }) => c.fix === undefined)).toBe(true);
});
test("with --repo checks manifests", async () => {
const vault = createSandboxVault(tmp);
const repo = createPluginRepo(tmp, true);
const r = await runCli(["doctor", "--vault", vault, "--repo", repo]);
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("claude_manifest");
expect(r.stdout).toContain("codex_manifest");
expect(r.stdout).toContain("hermes_manifest");
});
test("with --repo rejects invalid manifest schema", async () => {
const vault = createSandboxVault(tmp);
const repo = createPluginRepo(tmp, false);
const r = await runCli(["doctor", "--vault", vault, "--repo", repo]);
expect(r.returncode).toBe(1);
expect(r.stdout).toContain("[FAIL] claude_manifest");
expect(r.stdout).toContain("[FAIL] codex_manifest");
});
// Semantic search forced off so the readiness probes are deterministic
// (llm_key + embedding_provider skip; adapter construction passes) regardless
// of any embedding env in the developer's shell. HOME is pinned to the
// per-test temp dir for the same reason and a sharper one: the installed-
// runtimes probe reads real runtime configs out of HOME, so a developer's
// own grok or Cursor install would otherwise decide this test's exit code,
// and the suite would pass on a bare runner and fail on a workstation.
// A function because `tmp` is assigned in beforeEach.
const readinessEnv = () => ({
OPEN_SECOND_BRAIN_CONFIG: "",
XDG_CONFIG_HOME: "",
VAULT_DIR: "",
OPEN_SECOND_BRAIN_SEARCH_SEMANTIC: "false",
HOME: tmp,
});
test("without --readiness the output has no readiness section (byte-identical opt-out)", async () => {
const plain = await runCli(["doctor", "--vault", tmp], { env: readinessEnv() });
expect(plain.returncode).toBe(0);
expect(plain.stdout).not.toContain("readiness:");
const withFlag = await runCli(["doctor", "--vault", tmp, "--readiness"], {
env: readinessEnv(),
});
// The readiness run appends its section; the base output is unchanged,
// so the plain output is an exact prefix of the readiness output.
expect(withFlag.stdout.startsWith(plain.stdout)).toBe(true);
});
test("--readiness runs the default probes with explicit outcomes", async () => {
const r = await runCli(["doctor", "--vault", tmp, "--readiness"], { env: readinessEnv() });
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("readiness:");
expect(r.stdout).toContain("llm_key:");
expect(r.stdout).toContain("embedding_provider:");
expect(r.stdout).toContain("runtime_adapter_wiring:");
// No silent pass: skipped surfaces explicitly, and wiring passes.
expect(r.stdout).toContain("[SKIP] llm_key:");
expect(r.stdout).toContain("[PASS] runtime_adapter_wiring:");
});
test("--readiness --json omits the readiness key without the flag and adds it with it", async () => {
const plain = await runCli(["doctor", "--vault", tmp, "--json"], { env: readinessEnv() });
expect(JSON.parse(plain.stdout).readiness).toBeUndefined();
const withFlag = await runCli(["doctor", "--vault", tmp, "--json", "--readiness"], {
env: readinessEnv(),
});
const parsed = JSON.parse(withFlag.stdout);
expect(Array.isArray(parsed.readiness)).toBe(true);
// The probe set is the default registry; assert it is non-empty and that
// every entry carries a status from the closed vocabulary, rather than
// pinning a count that a new probe changes for no behavioural reason.
expect(parsed.readiness.length).toBeGreaterThan(0);
expect(parsed.readiness.every((p: { status: string }) => isReadinessStatus(p.status))).toBe(
true,
);
});
test("--readiness exits 1 with a fail reason when a probe fails", async () => {
// A key-requiring embedding provider (openai-compat) with no key makes the
// llm_key probe fail deterministically - the phase-4 QA scenario.
const cfg = join(tmp, "readiness-fail-config.yaml");
writeFileSync(
cfg,
[
`vault: ${tmp}`,
'search_semantic_enabled: "true"',
'embedding_provider: "openai-compat"',
'embedding_base_url: "https://example.invalid/v1"',
'embedding_model: "test-model"',
].join("\n") + "\n",
"utf8",
);
const r = await runCli(["doctor", "--vault", tmp, "--readiness"], {
env: {
OPEN_SECOND_BRAIN_CONFIG: cfg,
XDG_CONFIG_HOME: "",
VAULT_DIR: "",
// Fall through to the config file (empty = unset), and make sure no
// developer-shell embedding key leaks in to rescue the probe.
OPEN_SECOND_BRAIN_SEARCH_SEMANTIC: "",
OPEN_SECOND_BRAIN_EMBEDDING_KEY: "",
OPEN_SECOND_BRAIN_EMBEDDING_PROVIDER: "",
},
});
expect(r.returncode).toBe(1);
expect(r.stdout).toContain("[FAIL] llm_key:");
// The failure carries a reason, never a silent fail.
expect(r.stdout).toMatch(/\[FAIL\] llm_key:.+/);
});
});
describe("onboarding", () => {
test("init prints the guided onboarding checklist after the search block", async () => {
const vault = join(tmp, "ob-vault");
const config = join(tmp, "ob-config.yaml");
const r = await runCli(["init", "--vault", vault], {
env: { OPEN_SECOND_BRAIN_CONFIG: config, XDG_CONFIG_HOME: "", VAULT_DIR: "" },
});
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("initialized vault");
expect(r.stdout).toContain("Next steps:");
expect(r.stdout).toContain("o2b search index");
});
test("o2b onboarding re-runs the checklist and supports --json", async () => {
const vault = join(tmp, "ob-vault2");
const config = join(tmp, "ob-config2.yaml");
const env = { OPEN_SECOND_BRAIN_CONFIG: config, XDG_CONFIG_HOME: "", VAULT_DIR: "" };
await runCli(["init", "--vault", vault], { env });
const text = await runCli(["onboarding", "--vault", vault, "--config", config], { env });
expect(text.returncode).toBe(0);
expect(text.stdout).toContain("Next steps:");
const json = await runCli(["onboarding", "--vault", vault, "--config", config, "--json"], {
env,
});
const parsed = JSON.parse(json.stdout);
expect(Array.isArray(parsed.steps)).toBe(true);
expect(parsed.steps.find((s: { id: string }) => s.id === "vault_configured").done).toBe(true);
// The notice records keep their three original keys and gain the
// structured command additively (no-dead-ends, task 3).
const missing = parsed.notices.find((n: { code: string }) => n.code === "search_index_missing");
expect(missing).toBeDefined();
expect(Object.keys(missing).toSorted()).toEqual([
"code",
"message",
"next_command",
"severity",
]);
expect(missing.next_command).toBe("o2b search index");
});
});
describe("index", () => {
test("errors when no vault anywhere", async () => {
const cfg = join(tmp, "config.yaml");
const r = await runCli(["index"], {
env: { OPEN_SECOND_BRAIN_CONFIG: cfg },
});
expect(r.returncode).not.toBe(0);
expect(r.stderr.toLowerCase()).toContain("no vault configured");
});
test("generates wikilink index under Brain/", async () => {
const vault = tmp;
mkdirSync(join(vault, BRAIN_ROOT_REL), { recursive: true });
writeFileSync(join(vault, "Concept.md"), "---\ntitle: Concept\n---\n\nBody.");
writeFileSync(join(vault, "Other.md"), "No frontmatter.");
mkdirSync(join(vault, "notes", "deep"), { recursive: true });
writeFileSync(join(vault, "notes", "deep", "Nested.md"), "---\ntitle: Nested\n---\n\nBody.");
const r = await runCli(["index", "--vault", vault]);
expect(r.returncode).toBe(0);
const indexPath = join(vault, BRAIN_INDEX_REL);
expect(existsSync(indexPath)).toBe(true);
const content = readFileSync(indexPath, "utf8");
expect(content).toContain("[[Concept]]");
expect(content).toContain("[[Other]]");
// The listed path is vault-relative and forward-slash on every host:
// stripping the vault prefix by hand left `\notes\deep\Nested.md`
// on Windows.
expect(content).toContain("[[Nested]] `notes/deep/Nested.md`");
expect(content).toContain("[[Concept]] `Concept.md`");
});
});
describe("export-config", () => {
test("writes redacted JSON snapshot", async () => {
const config = join(tmp, "config.yaml");
writeFileSync(config, "api_key: abc\nvault_path: /tmp/vault\n");
const out = join(tmp, "snapshot.json");
const r = await runCli(["export-config", "--config", config, "--output", out]);
expect(r.returncode).toBe(0);
const data = JSON.parse(readFileSync(out, "utf8"));
// `[REDACTED]` until the key-name-only copy in config.ts was collapsed
// into the shared redactor; this is now the one placeholder spelling
// every redaction in the project emits.
expect(data.config.api_key).toBe(REDACTION_PLACEHOLDER);
expect(data.config.vault_path).toBe("/tmp/vault");
});
});
describe("secrets", () => {
test("list reports references without resolved values", async () => {
const config = join(tmp, "config.yaml");
writeFileSync(config, `github_token: ${JSON.stringify(GITHUB_REF)}\nplain: visible\n`);
const r = await runCli(["secrets", "list", "--config", config, "--json"], {
env: {
OPEN_SECOND_BRAIN_CONFIG: config,
GITHUB_TOKEN: FAKE_GITHUB_SECRET,
},
});
expect(r.returncode).toBe(0);
expect(r.stdout).not.toContain(FAKE_GITHUB_SECRET);
const data = JSON.parse(r.stdout);
expect(data.secrets).toEqual([
{
config_key: "github_token",
name: "GITHUB_TOKEN",
available: true,
},
]);
});
test("status never prints the resolved value", async () => {
const config = join(tmp, "config.yaml");
const r = await runCli(["secrets", "status", "GITHUB_TOKEN", "--config", config, "--json"], {
env: {
OPEN_SECOND_BRAIN_CONFIG: config,
GITHUB_TOKEN: FAKE_GITHUB_SECRET,
},
});
expect(r.returncode).toBe(0);
expect(r.stdout).not.toContain(FAKE_GITHUB_SECRET);
expect(JSON.parse(r.stdout)).toEqual({
name: "GITHUB_TOKEN",
available: true,
});
});
test("status exits non-zero for missing secrets", async () => {
const config = join(tmp, "config.yaml");
const r = await runCli(["secrets", "status", "MISSING_SECRET", "--config", config, "--json"], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
expect(r.returncode).toBe(1);
expect(JSON.parse(r.stdout)).toEqual({
name: "MISSING_SECRET",
available: false,
});
});
test("list reports a reference-shaped value the grammar cannot spell as invalid", async () => {
// A body no store name or env name could carry (`has space`) refuses at
// use time no matter what the store or the environment holds; the
// inspection surface must show that instead of silently dropping the
// row. A dashed body like `tg-token` is spellable now - the store and
// the reference grammar agree - see the resolution test below.
const config = join(tmp, "config.yaml");
writeFileSync(config, 'probe_space: "$secret:has space"\n');
const vault = join(tmp, "vault");
mkdirSync(vault, { recursive: true });
const withVault = await runCli(
["secrets", "list", "--config", config, "--vault", vault, "--json"],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(withVault.returncode).toBe(0);
expect(JSON.parse(withVault.stdout).secrets).toEqual([
{ config_key: "probe_space", name: "has space", available: false, invalid: true },
]);
const withVaultText = await runCli(["secrets", "list", "--config", config, "--vault", vault], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
expect(withVaultText.stdout).toContain("probe_space: has space (invalid reference)");
// The env-only surface answers for the same value: a reference that
// can never resolve is not "absent", it is broken.
const envOnly = await runCli(["secrets", "list", "--config", config, "--json"], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
expect(envOnly.returncode).toBe(0);
expect(JSON.parse(envOnly.stdout).secrets).toEqual([
{ config_key: "probe_space", name: "has space", available: false, invalid: true },
]);
});
test("a dashed reference joins the vault's store entry under its normalized name", async () => {
// Write-side trust review: `set tg-token` stores a dashed slug the old
// reference grammar could not spell, so `$secret:tg-token` could never
// resolve and `secrets list` reported the row broken. The store leg now
// normalizes the reference body the way the store normalizes names at
// set time, so the row reports the stored entry as available.
const config = join(tmp, "config.yaml");
writeFileSync(config, 'probe_dash: "$secret:tg-token"\n');
const vault = join(tmp, "vault");
mkdirSync(vault, { recursive: true });
// A bare vault is store-only: the custody audit of `secret set` goes to
// a store of this test's own.
const store = makeTestStore();
try {
const before = await runCli(
["secrets", "list", "--config", config, "--vault", vault, "--json"],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(before.returncode).toBe(0);
expect(JSON.parse(before.stdout).secrets).toEqual([
{ config_key: "probe_dash", name: "tg-token", available: false },
]);
const stored = await runCli(["brain", "secret", "set", "tg-token", "--vault", vault], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
stdin: "fake-stored-value-9d11c2\n",
});
expect(stored.returncode).toBe(0);
const after = await runCli(
["secrets", "list", "--config", config, "--vault", vault, "--json"],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(after.returncode).toBe(0);
expect(JSON.parse(after.stdout).secrets).toEqual([
{ config_key: "probe_dash", name: "tg-token", available: true },
]);
} finally {
store.cleanup();
}
});
test("well-formed reference rows carry no invalid key (additive-only shape)", async () => {
const config = join(tmp, "config.yaml");
writeFileSync(config, `github_token: ${JSON.stringify(GITHUB_REF)}\n`);
const r = await runCli(["secrets", "list", "--config", config, "--json"], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
expect(r.returncode).toBe(0);
const row = (JSON.parse(r.stdout).secrets as Array<Record<string, unknown>>)[0]!;
expect("invalid" in row).toBe(false);
});
test("--help prints the usage line, not the generic URL stub", async () => {
const r = await runCli(["secrets", "--help"]);
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("usage: o2b secrets list|status");
expect(r.stdout).not.toContain("see https://");
});
test("help states the env fallback's verbatim, case-sensitive name read", async () => {
const r = await runCli(["secrets", "--help"]);
expect(r.returncode).toBe(0);
expect(r.stdout).toContain(
"Without --vault, the env fallback reads the reference name verbatim",
);
expect(r.stdout).toContain("case-sensitively");
});
});
describe("mcp subcommand", () => {
test("starts with no vault anywhere and refuses a vault tool with vault_required", async () => {
const cfg = join(tmp, "config.yaml");
const requests = [
{
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "t" } },
},
{ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "second_brain_query" } },
];
const r = await runCli(["mcp"], {
env: {
OPEN_SECOND_BRAIN_CONFIG: cfg,
VAULT_DIR: "",
HOME: tmp,
XDG_STATE_HOME: join(tmp, "state"),
LOCALAPPDATA: join(tmp, "state"),
},
stdin: requests.map((req) => JSON.stringify(req)).join("\n") + "\n",
});
expect(r.returncode).toBe(0);
const responses = r.stdout
.split("\n")
.filter((line) => line.trim().startsWith("{"))
.map((line) => JSON.parse(line) as { id?: number; result?: unknown; error?: unknown });
expect(responses.find((res) => res.id === 1)?.result).toBeDefined();
expect(JSON.stringify(responses.find((res) => res.id === 2))).toContain("vault_required");
});
});