Skip to content

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
16.6 KB
Raw Blame
/**
 * `brain_writes` (who-wrote-what, Task A / t_662f4e82).
 *
 * The agent-facing half of the note-write record: the listing, the
 * filters, and the one action that is DECLARED and not yet reachable -
 * `plan_revert`, which is refused by name so an agent learns the
 * capability exists rather than reading an unknown-argument error as a
 * typo.
 *
 * The end-to-end property is pinned here too: a note written through
 * `brain_create_note` shows up under `brain_writes` with the id its own
 * receipt named. Two surfaces, one record.
 */

import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";

import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { appendLogEvent } from "../../src/core/brain/log.ts";
import { BRAIN_LOG_EVENT_KIND } from "../../src/core/brain/types.ts";
import { recordNoteWrite, storeBeforeImage } from "../../src/core/brain/notes/write-record.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { BRAIN_TOOLS } from "../../src/mcp/brain-tools.ts";
import { INVALID_PARAMS, MCPError } from "../../src/mcp/protocol.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";

let vault: string;
let configHome: string;
let ctx: ServerContext;

beforeEach(() => {
  vault = mkdtempSync(join(tmpdir(), "o2b-brain-writes-vault-"));
  configHome = mkdtempSync(join(tmpdir(), "o2b-brain-writes-cfg-"));
  const configPath = join(configHome, "config.yaml");
  atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
  bootstrapBrain(vault, { configPath });
  ctx = { vault, configPath, repoRoot: null };
});

afterEach(() => {
  rmSync(vault, { recursive: true, force: true });
  rmSync(configHome, { recursive: true, force: true });
});

const tool = (name: string) => BRAIN_TOOLS.find((t) => t.name === name)!;

const call = async (name: string, args: Record<string, unknown>) =>
  (await tool(name).handler(ctx, args)) as Record<string, unknown>;

interface WritesReply {
  readonly action: string;
  readonly total_matched: number;
  readonly returned: number;
  readonly writes: ReadonlyArray<Record<string, unknown>>;
  readonly warnings: ReadonlyArray<unknown>;
  readonly next_cursor: string | null;
}

const listWrites = async (args: Record<string, unknown> = {}): Promise<WritesReply> =>
  (await call("brain_writes", args)) as unknown as WritesReply;

/** Await `result`, assert it rejected with an MCPError, and return it. */
async function rejectedMcpError(result: unknown): Promise<MCPError> {
  let thrown: unknown;
  try {
    await result;
  } catch (err) {
    thrown = err;
  }
  expect(thrown).toBeInstanceOf(MCPError);
  return thrown as MCPError;
}

describe("brain_writes registration", () => {
  test("is registered, read-only by shape, and takes no required argument", () => {
    const def = tool("brain_writes");
    expect(def).toBeDefined();
    expect(def.inputSchema.required ?? []).toEqual([]);
    expect(def.previewBudget).toBeGreaterThan(0);
  });

  test("declares both actions now, so the schema pins move once", () => {
    const schema = tool("brain_writes").inputSchema as {
      properties: Record<string, { enum?: ReadonlyArray<string> }>;
    };
    expect(schema.properties["action"]?.enum).toEqual(["list", "plan_revert"]);
    expect(schema.properties["op"]?.enum).toEqual(["create", "update", "append", "revert"]);
  });
});

describe("brain_writes action list", () => {
  test("lists what the note-write tools recorded, by the id they reported", async () => {
    const created = await call("brain_create_note", {
      path: "Notes/One.md",
      content: "first body",
    });
    await call("brain_update_note", { path: "Notes/One.md", content: "second body" });

    const reply = await listWrites({});
    expect(reply.action).toBe("list");
    expect(reply.total_matched).toBe(2);
    expect(reply.returned).toBe(2);
    // Newest first, so the update leads.
    expect(reply.writes.map((w) => w["op"])).toEqual(["update", "create"]);
    expect(reply.writes.map((w) => w["target"])).toEqual(["Notes/One.md", "Notes/One.md"]);
    // The very id the create receipt named: two surfaces, one record.
    expect(reply.writes.map((w) => w["write_id"])).toContain(created["write_id"]);
    expect(reply.writes[0]!["agent"]).toBe("claude");
  });

  test("defaults to list when no action is sent", async () => {
    await call("brain_create_note", { path: "Notes/One.md", content: "body" });
    expect((await listWrites({})).action).toBe("list");
  });

  test("filters by op and by path", async () => {
    await call("brain_create_note", { path: "Notes/One.md", content: "body" });
    await call("brain_create_note", { path: "Notes/Two.md", content: "body" });
    await call("brain_append_note", { path: "Notes/One.md", content: "more" });

    expect((await listWrites({ op: "append" })).total_matched).toBe(1);
    expect((await listWrites({ path: "Notes/Two.md" })).total_matched).toBe(1);
    expect((await listWrites({ agent: "nobody" })).total_matched).toBe(0);
  });

  test("limit caps the rows and total_matched still names the whole match", async () => {
    await call("brain_create_note", { path: "Notes/One.md", content: "body" });
    await call("brain_create_note", { path: "Notes/Two.md", content: "body" });

    const reply = await listWrites({ limit: 1 });
    expect(reply.total_matched).toBe(2);
    expect(reply.returned).toBe(1);
    expect(reply.writes).toHaveLength(1);
  });

  test("an empty vault answers with an empty list, not an error", async () => {
    const reply = await listWrites({});
    expect(reply.total_matched).toBe(0);
    expect(reply.writes).toEqual([]);
    expect(reply.warnings).toEqual([]);
  });

  test("an unknown op is refused by name", async () => {
    const err = await rejectedMcpError(call("brain_writes", { op: "delete" }));
    expect(err.code).toBe(INVALID_PARAMS);
    expect(err.message).toContain("create, update, append, revert");
  });
});

describe("brain_writes cursor pagination", () => {
  test("the input schema declares a described cursor property", () => {
    const schema = tool("brain_writes").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 log", async () => {
    await call("brain_create_note", { path: "Notes/One.md", content: "body" });
    await call("brain_create_note", { path: "Notes/Two.md", content: "body" });
    await call("brain_create_note", { path: "Notes/Three.md", content: "body" });

    const total = 3;
    const limit = 2;
    // Bound the walk by the page arithmetic: ceil(total/limit) pages plus one
    // slack step, so a next_cursor that never turns null (a never-exhausting
    // tool) exhausts the budget and fails here instead of hanging the suite.
    const maxSteps = Math.ceil(total / limit) + 1;
    const targets: Array<unknown> = [];
    let cursor: string | null = null;
    for (let step = 0; step < maxSteps; step += 1) {
      const reply = await listWrites({ limit, ...(cursor !== null ? { cursor } : {}) });
      expect(reply.total_matched).toBe(total);
      // Guard the walk protocol itself: an undefined next_cursor (a tool
      // that ignores the cursor) is a shape violation, not a stop condition.
      expect(reply.next_cursor === null || typeof reply.next_cursor === "string").toBe(true);
      targets.push(...reply.writes.map((w) => w["target"]));
      cursor = reply.next_cursor;
      if (cursor === null) break;
    }
    expect(cursor).toBeNull();
    // Newest first, so a full walk reads the log backwards.
    expect(targets).toEqual(["Notes/Three.md", "Notes/Two.md", "Notes/One.md"]);
  });

  test("a page that fits the whole match reports next_cursor null", async () => {
    await call("brain_create_note", { path: "Notes/One.md", content: "body" });
    const reply = await listWrites({ limit: 2 });
    expect(reply.total_matched).toBe(1);
    expect(reply.next_cursor).toBeNull();
  });

  test("a malformed cursor is INVALID_PARAMS", async () => {
    const err = await rejectedMcpError(listWrites({ cursor: "!!!not-base64!!!" }));
    expect(err.code).toBe(INVALID_PARAMS);
    expect(err.message).toContain("cursor");
  });
});

describe("brain_writes action plan_revert", () => {
  /** Do what the write seams do, so the plan reads a real history. */
  function seedNote(opts: {
    readonly target: string;
    readonly bytes: string;
    readonly agent: string;
    readonly at: string;
  }): void {
    const abs = join(vault, opts.target);
    const before = existsSync(abs) ? readFileSync(abs, "utf8") : null;
    mkdirSync(dirname(abs), { recursive: true });
    if (before !== null) storeBeforeImage(vault, before);
    atomicWriteFileSync(abs, opts.bytes);
    recordNoteWrite(vault, {
      op: before === null ? "create" : "update",
      target: opts.target,
      before: before === null ? null : { bytes: before },
      after: { bytes: opts.bytes },
      timestamp: opts.at,
      agent: opts.agent,
    });
  }

  const TARGET = "notes/A.md";

  /** One raw note-write row appended to a named device's shard. */
  function seedWriteOnDevice(opts: {
    readonly timestamp: string;
    readonly target: string;
    readonly deviceId: string;
  }): void {
    appendLogEvent(
      vault,
      {
        timestamp: opts.timestamp,
        eventType: BRAIN_LOG_EVENT_KIND.noteWrite,
        agent: "claude",
        body: {
          write_id: `nw_${opts.timestamp.replace(/\D/g, "")}_${opts.deviceId}_${opts.target}`,
          op: "update",
          target: opts.target,
          hash_before: "a".repeat(64),
          hash_after: "b".repeat(64),
          bytes_before: "10",
          bytes_after: "20",
          agent: "claude",
        },
      },
      { deviceId: opts.deviceId },
    );
  }

  test('device "" is a bounded selector scoped to the legacy un-sharded shard', async () => {
    // coerceStr treats emptiness as absence, so the empty device used to
    // fall out of the selector and the call was refused as unbounded -
    // pushing a caller toward the path-only selector that reverts every
    // device's writes. The empty string is a filter value, the same
    // contract the list action already keeps. The call answers at the
    // reach that filters nothing: the seeded rows name a file this test
    // never wrote, and at the fail-closed default reach the entry is
    // withheld rather than planned - this test pins the selector.
    seedWriteOnDevice({ timestamp: "2026-03-04T01:00:00Z", target: TARGET, deviceId: "" });
    seedWriteOnDevice({ timestamp: "2026-03-04T02:00:00Z", target: TARGET, deviceId: "laptop" });

    const reply = (await tool("brain_writes").handler(
      { ...ctx, reach: "local" },
      { action: "plan_revert", device: "" },
    )) as Record<string, unknown>;
    expect(reply["selector"]).toEqual({ device: "" });
    const entries = reply["entries"] as ReadonlyArray<{ writes: ReadonlyArray<string> }>;
    expect(entries).toHaveLength(1);
    expect(entries[0]!.writes).toHaveLength(1);
  });

  test('device "" beside a path keeps the device filter the path alone would drop', async () => {
    seedWriteOnDevice({ timestamp: "2026-03-04T01:00:00Z", target: TARGET, deviceId: "" });
    seedWriteOnDevice({ timestamp: "2026-03-04T02:00:00Z", target: TARGET, deviceId: "laptop" });

    // Reach "local" explicitly, like the selector test above: the seeded
    // rows name a file this test never wrote, and at the fail-closed
    // default reach the entry is withheld rather than planned, which
    // would make the selection assertions below pass vacuously.
    const reply = (await tool("brain_writes").handler(
      { ...ctx, reach: "local" },
      { action: "plan_revert", device: "", path: TARGET },
    )) as Record<string, unknown>;
    expect(reply["selector"]).toEqual({ device: "", path: TARGET });
    // The filter is pinned by its SELECTION, not its echo: the reply
    // reads `selector` back verbatim, so an echoed selector proves
    // nothing about what the read selected. Only the un-sharded write
    // may be planned - the laptop write on the same target would ride in
    // here if the device filter were dropped between the echo and the
    // read.
    const entries = reply["entries"] as ReadonlyArray<{ writes: ReadonlyArray<string> }>;
    expect(entries).toHaveLength(1);
    expect(entries[0]!.writes).toHaveLength(1);
  });

  test("returns the entries and the digest, and no apply path", async () => {
    seedNote({ target: TARGET, bytes: "v0", agent: "seed", at: "2026-03-04T01:00:00Z" });
    seedNote({ target: TARGET, bytes: "v1", agent: "claude", at: "2026-03-04T02:00:00Z" });

    const reply = await call("brain_writes", { action: "plan_revert", agent: "claude" });
    expect(reply["action"]).toBe("plan_revert");
    expect(reply["digest"]).toMatch(/^[0-9a-f]{64}$/);
    const entries = reply["entries"] as ReadonlyArray<Record<string, unknown>>;
    expect(entries).toHaveLength(1);
    expect(entries[0]!["target"]).toBe(TARGET);
    expect(entries[0]!["action"]).toBe("restore");
    // The plan is a report: the tool has no apply and moved nothing.
    expect(readFileSync(join(vault, TARGET), "utf8")).toBe("v1");
    expect(Object.keys(reply)).not.toContain("applied");
  });

  test("reports a refused target by name rather than dropping it", async () => {
    seedNote({ target: TARGET, bytes: "v0", agent: "seed", at: "2026-03-04T01:00:00Z" });
    seedNote({ target: TARGET, bytes: "v1", agent: "claude", at: "2026-03-04T02:00:00Z" });
    atomicWriteFileSync(join(vault, TARGET), "drifted");

    const reply = await call("brain_writes", { action: "plan_revert", path: TARGET });
    const entries = reply["entries"] as ReadonlyArray<Record<string, unknown>>;
    expect(entries[0]!["action"]).toBe("refuse");
    expect(entries[0]!["reason"]).toBe("drift");
  });

  test("an unbounded selector is refused with the code, not an empty plan", async () => {
    const err = await rejectedMcpError(
      call("brain_writes", { action: "plan_revert", since: "2026-03-04" }),
    );
    expect(err.code).toBe(INVALID_PARAMS);
    expect(err.message).toContain("unbounded_selector");
  });

  test("no apply reaches this tool: an --apply-shaped argument is rejected", () => {
    const schema = tool("brain_writes").inputSchema as {
      properties: Record<string, unknown>;
      additionalProperties?: boolean;
    };
    expect(schema.additionalProperties).toBe(false);
    expect(Object.keys(schema.properties)).not.toContain("apply");
    expect(Object.keys(schema.properties)).not.toContain("digest");
  });
});

describe("brain_writes at remote reach", () => {
  const RESERVED = "notes/zzreservedzz.md";
  const OPEN = "notes/open.md";

  /** Record a write to each note: one reserved against remote reads, one not. */
  function seedBoth(): void {
    for (const [target, bytes] of [
      [OPEN, "open body"],
      [RESERVED, "---\nvisibility: [private]\n---\n\nreserved body"],
    ] as const) {
      const abs = join(vault, target);
      mkdirSync(dirname(abs), { recursive: true });
      atomicWriteFileSync(abs, bytes);
      recordNoteWrite(vault, {
        op: "create",
        target,
        before: null,
        after: { bytes },
        timestamp: "2026-03-04T01:00:00Z",
        agent: "claude",
      });
    }
  }

  const callAt = async (reach: "local" | "remote", args: Record<string, unknown>) =>
    (await tool("brain_writes").handler({ ...ctx, reach }, args)) as Record<string, unknown>;

  test("list names a reserved note locally and withholds it remotely", async () => {
    seedBoth();
    const local = (await callAt("local", {})) as unknown as WritesReply;
    expect(local.writes.map((w) => w["target"]).toSorted()).toEqual([OPEN, RESERVED].toSorted());

    const remote = (await callAt("remote", {})) as unknown as WritesReply;
    expect(remote.writes.map((w) => w["target"])).toEqual([OPEN]);
    // The total counts only what the caller may see.
    expect(remote.total_matched).toBe(1);
  });

  test("plan_revert names a reserved note locally and withholds it remotely", async () => {
    seedBoth();
    const args = { action: "plan_revert", agent: "claude" };
    expect(JSON.stringify(await callAt("local", args))).toContain("zzreservedzz");
    const remote = await callAt("remote", args);
    expect(JSON.stringify(remote)).not.toContain("zzreservedzz");
    const entries = remote["entries"] as ReadonlyArray<Record<string, unknown>>;
    expect(entries.map((e) => e["target"])).toEqual([OPEN]);
  });
});