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
/**
* `brain_extract_signals` MCP tool (salience-lifecycle-enrichment,
* unit 2, t_1dace26d). Claims pinned here:
*
* 1. Called without `items` the tool is the read-only plan phase and
* returns exactly one needs-llm-step envelope.
* 2. Called with `items` it commits, and the written signals carry the
* new `auto_extract` source type.
* 3. An over-cap payload is refused as a caller error, not a server
* fault, and nothing is written.
* 4. The tool is full-tier, absent from the writer surface.
* 5. A committed signal's path is vault-relative: no MCP response of
* this tool carries the absolute host path.
* 6. Every `turns_mined` entry carries the turn's stored timestamp
* verbatim, and the CLI `--json` plan over the same fixture carries
* the identical projection.
* 7. A session tombstoned by a barren commit gets no envelope: the plan
* carries the tombstone reason and the recorded breakdown, `force`
* bypasses it for one call, and a ledger failure rides the commit
* response by name.
*/
import { afterEach, beforeEach, expect, setDefaultTimeout, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { AUTO_EXTRACT_PER_SESSION_CAP } from "../../src/core/brain/extract-signals.ts";
import { sessionMiningLedgerPath } from "../../src/core/brain/session-mining-ledger.ts";
import { sessionMiningSurveysPath } from "../../src/core/brain/session-mining-surveys.ts";
import { importSessionRecall } from "../../src/core/brain/session-recall.ts";
import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";
import { runCli } from "../helpers/run-cli.ts";
import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";
// Tests here spawn processes; see tests/helpers/cli-timeout.ts.
setDefaultTimeout(CLI_SPAWN_BUDGET_MS);
const TOOL = "brain_extract_signals";
const SESSION = "sess-mcp";
let tmp: string;
let vault: string;
let ctx: ServerContext;
function tool() {
return findTool(buildToolTable("full"), TOOL);
}
function inboxCount(): number {
const dir = join(vault, "Brain", "inbox");
return existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".md")).length : 0;
}
const ITEM = {
topic: "heading-style",
signal: "positive",
principle: "Name the release theme in the heading.",
confidence: 0.88,
};
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "o2b-extract-mcp-"));
vault = join(tmp, "vault");
mkdirSync(join(vault, "Brain"), { recursive: true });
const configPath = join(tmp, "config.yaml");
writeFileSync(configPath, `vault: "${vault}"\n`);
importSessionRecall(vault, {
sessionId: SESSION,
turns: [
{
turnId: "t1",
timestamp: "2026-08-22T09:01:00Z",
role: "user",
text: "Always name the release theme in the heading.",
},
],
createdAt: "2026-08-22T10:00:00Z",
});
ctx = { vault, configPath, repoRoot: null };
});
afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
test("without items it plans and returns one needs-llm-step envelope", async () => {
const res = (await tool().handler(ctx, { session: SESSION })) as {
phase: string;
turns_mined: ReadonlyArray<{ turn_id: string }>;
llm_step: { status: string; step: string; target_path: string };
};
expect(res.phase).toBe("plan");
expect(res.turns_mined.map((t) => t.turn_id)).toEqual(["t1"]);
expect(res.llm_step.status).toBe("needs-llm-step");
expect(res.llm_step.step).toBe("extract-signals");
expect(res.llm_step.target_path).toBe("Brain/inbox");
expect(inboxCount()).toBe(0);
});
test("with items it commits them as auto_extract signals", async () => {
const res = (await tool().handler(ctx, { session: SESSION, items: [ITEM] })) as {
phase: string;
written: ReadonlyArray<{ topic: string }>;
};
expect(res.phase).toBe("commit");
expect(res.written.map((w) => w.topic)).toEqual(["heading-style"]);
expect(inboxCount()).toBe(1);
});
test("the committed path is vault-relative, never the host path", async () => {
const res = (await tool().handler(ctx, { session: SESSION, items: [ITEM] })) as {
written: ReadonlyArray<{ path: string }>;
};
expect(res.written[0]!.path).toMatch(/^Brain[/\\]inbox[/\\]sig-/);
expect(JSON.stringify(res)).not.toContain(vault);
});
test("an over-cap payload is refused and writes nothing", async () => {
const items = Array.from({ length: AUTO_EXTRACT_PER_SESSION_CAP + 1 }, (_v, i) => ({
...ITEM,
topic: `topic-${i}`,
}));
await expect(Promise.resolve(tool().handler(ctx, { session: SESSION, items }))).rejects.toThrow(
String(AUTO_EXTRACT_PER_SESSION_CAP),
);
expect(inboxCount()).toBe(0);
});
test("is a full-tier tool, absent from the writer surface", () => {
expect(buildToolTable("full").find((t) => t.name === TOOL)).toBeDefined();
expect(buildToolTable("writer").find((t) => t.name === TOOL)).toBeUndefined();
});
test("turns_mined carries the stored turn timestamp, on the tool and the CLI alike", async () => {
const expected = [
{
turn_id: "t1",
text: "Always name the release theme in the heading.",
timestamp: "2026-08-22T09:01:00Z",
},
];
const res = (await tool().handler(ctx, { session: SESSION })) as {
turns_mined: ReadonlyArray<Record<string, unknown>>;
};
expect(res.turns_mined).toEqual(expected);
const cli = await runCli(["brain", "extract-signals", SESSION, "--json", "--vault", vault], {
env: { OPEN_SECOND_BRAIN_CONFIG: ctx.configPath! },
});
expect(cli.returncode).toBe(0);
const payload = JSON.parse(cli.stdout) as { turns_mined: unknown };
expect(payload.turns_mined).toEqual(expected);
});
// ----- The zero-yield mining tombstone on the tool (session-mining-economy)
//
// 7. A session tombstoned by a barren commit gets no envelope: the plan
// carries the tombstone reason and the recorded breakdown, and no turn
// text rides out to the caller. Answering the envelope is enough:
// the commit keys the record on the session's current turns, and a
// relayed surveyed_turns_hash is only a check.
// 8. The `force` argument bypasses the tombstone for exactly one plan
// call, and the tool declares it; so does the surveyed_turns_hash
// argument the commit relays.
// 9. A ledger write failure on a successful commit rides the commit
// response by name; the tool description documents both behaviors.
function corruptMiningLedger(): void {
mkdirSync(dirname(sessionMiningLedgerPath(vault)), { recursive: true });
writeFileSync(sessionMiningLedgerPath(vault), "{ truncated");
}
/** The plan response's surveyed hash, for the commit that answers it. */
async function surveyedHash(): Promise<string> {
const plan = (await tool().handler(ctx, { session: SESSION })) as {
surveyed_turns_hash: string;
};
return plan.surveyed_turns_hash;
}
test("a tombstoned session returns the recorded breakdown instead of an envelope", async () => {
const hash = await surveyedHash();
const mine = (await tool().handler(ctx, {
session: SESSION,
items: [],
surveyed_turns_hash: hash,
})) as {
phase: string;
written: unknown[];
};
expect(mine.phase).toBe("commit");
expect(mine.written).toEqual([]);
const plan = (await tool().handler(ctx, { session: SESSION })) as {
llm_step: unknown;
turns_mined: unknown[];
skipped?: {
reason: string;
mining_outcome?: Record<string, number>;
};
};
expect(plan.skipped?.reason).toBe("mining_tombstone");
expect(plan.skipped?.mining_outcome).toEqual({
written: 0,
staged: 0,
deduped: 0,
durability_rejected: 0,
});
expect(plan.llm_step).toBeNull();
expect(plan.turns_mined).toEqual([]);
});
test("the documented flow - plan, then commit the answer - tombstones without any relay", async () => {
// The skill's flow: call with {session}, answer the envelope with
// {session, items}. Nothing tells the caller to echo a hash, so the
// tombstone must land without one.
await tool().handler(ctx, { session: SESSION });
const mine = (await tool().handler(ctx, { session: SESSION, items: [] })) as {
phase: string;
mining_ledger_failure?: string;
};
expect(mine.phase).toBe("commit");
expect(mine.mining_ledger_failure).toBeUndefined();
const plan = (await tool().handler(ctx, { session: SESSION })) as {
skipped?: { reason: string };
};
expect(plan.skipped?.reason).toBe("mining_tombstone");
});
test("a relayed hash the session no longer matches records nothing and says so", async () => {
// A hash from another plan (or a session that changed since) must not
// overwrite the record with one that never matches.
const foreign = "0".repeat(64);
const mine = (await tool().handler(ctx, {
session: SESSION,
items: [],
surveyed_turns_hash: foreign,
})) as { mining_ledger_failure?: string };
expect(mine.mining_ledger_failure).toContain(foreign);
const plan = (await tool().handler(ctx, { session: SESSION })) as { skipped?: unknown };
expect(plan.skipped).toBeUndefined();
});
test("an empty relayed hash is refused as malformed, not read as absent", async () => {
await tool().handler(ctx, { session: SESSION });
await expect(
tool().handler(ctx, { session: SESSION, items: [], surveyed_turns_hash: "" }),
).rejects.toThrow("surveyed_turns_hash must be the 64-character lowercase hex digest");
// The refusal came before any record, so the next plan still offers the turns.
const plan = (await tool().handler(ctx, { session: SESSION })) as { skipped?: unknown };
expect(plan.skipped).toBeUndefined();
});
test("force bypasses the tombstone for exactly one plan call and is declared", async () => {
const hash = await surveyedHash();
await tool().handler(ctx, { session: SESSION, items: [], surveyed_turns_hash: hash });
const forced = (await tool().handler(ctx, { session: SESSION, force: true })) as {
llm_step: { status: string } | null;
skipped?: unknown;
};
expect(forced.skipped).toBeUndefined();
expect(forced.llm_step?.status).toBe("needs-llm-step");
const after = (await tool().handler(ctx, { session: SESSION })) as {
skipped?: { reason: string };
};
expect(after.skipped?.reason).toBe("mining_tombstone");
// The arguments are part of the published contract, not hidden escapes.
const schema = tool().inputSchema as {
properties: { force?: { type: string }; surveyed_turns_hash?: { type: string } };
};
expect(schema.properties.force?.type).toBe("boolean");
expect(schema.properties.surveyed_turns_hash?.type).toBe("string");
});
test("the tool description documents the tombstone and the force escape", () => {
const description = tool().description;
expect(description).toContain("tombstone");
expect(description).toContain("force");
});
test("a ledger write failure on a successful commit rides the commit response by name", async () => {
const hash = await surveyedHash();
corruptMiningLedger();
const res = (await tool().handler(ctx, {
session: SESSION,
items: [],
surveyed_turns_hash: hash,
})) as {
phase: string;
written: unknown[];
mining_ledger_failure?: string;
};
expect(res.phase).toBe("commit");
expect(res.written).toEqual([]);
expect(res.mining_ledger_failure).toContain("session mining ledger is corrupted JSON");
});
test("a survey store failure reaches a caller below local reach without the host path", async () => {
// This context minted no reach, so it answers fail-closed below local.
mkdirSync(dirname(sessionMiningSurveysPath(vault)), { recursive: true });
writeFileSync(sessionMiningSurveysPath(vault), "{ truncated");
const plan = (await tool().handler(ctx, { session: SESSION })) as {
survey_record_failure?: string;
};
expect(plan.survey_record_failure).toBe("session mining surveys store failed (error)");
const mine = (await tool().handler(ctx, { session: SESSION, items: [] })) as {
mining_ledger_failure?: string;
};
expect(mine.mining_ledger_failure).toContain("session mining surveys store failed (error)");
expect(mine.mining_ledger_failure).not.toContain(tmp);
});