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
11.5 KB
Raw Blame
/**
 * The schema pack on a store-only machine (design D14 item 3, task 2.11):
 * `schema_apply_mutations` / `o2b brain schema apply` write the pack as
 * shared `brain.schema.<field>` settings records and audit to the store,
 * readers see the stored pack, and nothing under `Brain/` changes. An
 * unswitched machine keeps writing `_brain.yaml`.
 */
import { afterEach, describe, expect, setDefaultTimeout, test } from "bun:test";
import { cpSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";

import { freezeVault, unfreezeVault } from "../../../src/core/brain/freeze.ts";
import { VaultFrozenError } from "../../../src/core/brain/freeze-marker.ts";
import { brainConfigPath } from "../../../src/core/brain/paths.ts";
import { setBrainSetting } from "../../../src/core/brain/policy/settings-write.ts";
import { applySchemaAdminMutations } from "../../../src/core/brain/schema-admin.ts";
import { assessSchemaPackIntegrity } from "../../../src/core/brain/schema-integrity.ts";
import { SCHEMA_AUDIT_STORE_NAME } from "../../../src/core/brain/schema-mutate-store.ts";
import type { SchemaMutation } from "../../../src/core/brain/schema-mutate.ts";
import { STORE_SCHEMA_PACK_SOURCE } from "../../../src/core/brain/schema-pack-store.ts";
import { loadSchemaPack, readSchemaPackSource } from "../../../src/core/brain/schema-pack.ts";
import {
  SETTING_ENTRY_KIND,
  SETTING_SET_KIND,
  SETTING_UNSET_KIND,
} from "../../../src/core/store/constants.ts";
import { holdMigrationGate, releaseMigrationGate } from "../../../src/core/migration-gate.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../../src/mcp/index.ts";
import { runCli } from "../../helpers/run-cli.ts";
import { makeStoreEnv, type StoreEnv } from "../store/fixtures/store-env.ts";
import {
  brainTreeDigest,
  ledgerRows,
  partitionRecords,
  switchDevice,
} from "./store-only/fixtures.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);

let env: StoreEnv | null = null;
afterEach(() => {
  env?.cleanup();
  env = null;
});

const ADD_PAPER: SchemaMutation = { op: "add_type", category: "page_types", token: "paper" };
const ALIAS: SchemaMutation = { op: "add_alias", token: "paper", alias: "article" };

function schemaRecords(e: StoreEnv) {
  return partitionRecords(e.storeRoot, "shared").filter(
    (r) =>
      (r.kind === SETTING_SET_KIND ||
        r.kind === SETTING_UNSET_KIND ||
        r.kind === SETTING_ENTRY_KIND) &&
      String(r.body["key"]).startsWith("brain.schema."),
  );
}

function schemaAuditRows(e: StoreEnv): unknown[] {
  return [
    ...ledgerRows(e.storeRoot, "shared", "reliability-audit"),
    ...ledgerRows(e.storeRoot, "private", "reliability-audit"),
  ].filter((row) => (row as { audit_dir?: string }).audit_dir === "schema-mutations");
}

describe("schema apply on a store-only machine", () => {
  test("writes brain.schema.* records, audits to the store, and leaves Brain/ alone", async () => {
    env = makeStoreEnv("osb-schema-store-");
    switchDevice(env.storeRoot);
    const before = brainTreeDigest(env.vault);

    const result = await applySchemaAdminMutations(env.vault, [ADD_PAPER, ALIAS], {
      actor: "test",
    });
    expect(result.audit_path).toBe(SCHEMA_AUDIT_STORE_NAME);
    expect(brainTreeDigest(env.vault)).toBe(before);

    const records = schemaRecords(env);
    // One entry record per entry added, never the whole list (task 3.12).
    expect(records.map((r) => [r.kind, r.body["key"], r.body["entry"], r.body["present"]])).toEqual(
      [
        [SETTING_ENTRY_KIND, "brain.schema.aliases", "paper=article", true],
        [SETTING_ENTRY_KIND, "brain.schema.page_types", "paper", true],
      ],
    );
    // Not from the CLI: an agent wrote these.
    expect(records.every((r) => r.body["authority"] === "agent")).toBe(true);
    // The attestation in `shared`, the whole row in `private`.
    expect(schemaAuditRows(env)).toHaveLength(2);

    const source = readSchemaPackSource(env.vault);
    expect(source.path).toBe(STORE_SCHEMA_PACK_SOURCE);
    expect(source.present).toBe(true);
    expect(source.pack.declarations.page_types).toEqual(["paper"]);
    expect(source.pack.aliases).toEqual({ paper: ["article"] });

    const integrity = assessSchemaPackIntegrity(env.vault);
    expect(integrity.status).toBe("ok");
    expect(integrity).toMatchObject({ audit_path: SCHEMA_AUDIT_STORE_NAME });
  });

  test("an entry the pack drops is removed; the next apply builds on the stored pack", async () => {
    env = makeStoreEnv("osb-schema-store-unset-");
    switchDevice(env.storeRoot);
    await applySchemaAdminMutations(env.vault, [ADD_PAPER, ALIAS], { actor: "t" });
    await applySchemaAdminMutations(
      env.vault,
      [{ op: "remove_alias", token: "paper", alias: "article" }],
      { actor: "t" },
    );
    const last = schemaRecords(env).at(-1)!;
    expect(last.kind).toBe(SETTING_ENTRY_KIND);
    expect(last.body).toMatchObject({
      key: "brain.schema.aliases",
      entry: "paper=article",
      present: false,
    });
    const pack = loadSchemaPack(env.vault);
    expect(pack.aliases).toEqual({});
    expect(pack.declarations.page_types).toEqual(["paper"]);
  });

  test("the CLI writes with human authority, and an agent cannot remove the operator's entry", async () => {
    env = makeStoreEnv("osb-schema-store-cli-");
    switchDevice(env.storeRoot);
    const cli = await runCli(
      ["brain", "schema", "apply", "--mutation", JSON.stringify(ADD_PAPER), "--json"],
      { env: { OPEN_SECOND_BRAIN_CONFIG: env.configPath } },
    );
    expect(cli.returncode).toBe(0);
    expect(schemaRecords(env)[0]!.body["authority"]).toBe("human");

    const server = new MCPServer({ vault: env.vault, configPath: env.configPath });
    await server.handleRequest({
      jsonrpc: JSONRPC_VERSION,
      id: 1,
      method: "initialize",
      params: {
        protocolVersion: PROTOCOL_VERSION,
        capabilities: {},
        clientInfo: { name: "t", version: "0" },
      },
    });
    const r = (await server.handleRequest({
      jsonrpc: JSONRPC_VERSION,
      id: 2,
      method: "tools/call",
      params: {
        name: "schema_apply_mutations",
        arguments: {
          mutations: [{ op: "remove_type", category: "page_types", token: "paper" }],
        },
      },
    })) as { result?: { isError?: boolean; content: Array<{ text: string }> }; error?: unknown };
    const answer = JSON.stringify(r);
    expect(r.error !== undefined || r.result?.isError === true).toBe(true);
    expect(answer).toContain("human_value_in_force");
    expect(schemaRecords(env)).toHaveLength(1);
    expect(loadSchemaPack(env.vault).declarations.page_types).toEqual(["paper"]);
  });
});

/** A second store-only machine of the same store that holds only `shared`, synced from `from`. */
function sharedOnlyPeer(from: StoreEnv): StoreEnv {
  const peer = makeStoreEnv("osb-schema-peer-", { partitions: ["shared"], device: "dev-b" });
  rmSync(join(peer.storeRoot, "shared"), { recursive: true, force: true });
  cpSync(join(from.storeRoot, "shared"), join(peer.storeRoot, "shared"), { recursive: true });
  switchDevice(peer.storeRoot, "dev-b");
  return peer;
}

describe("the content-write gates on a store-only machine", () => {
  test("a frozen machine refuses a schema apply and a settings write; a leftover gate does not", async () => {
    env = makeStoreEnv("osb-schema-store-gates-");
    switchDevice(env.storeRoot);
    const vault = env.vault;
    const settings = { vault, authority: "human" as const, agent: "test" };
    freezeVault(vault, { agent: "@operator", reason: "moving machines" });
    try {
      await expect(applySchemaAdminMutations(vault, [ADD_PAPER], { actor: "t" })).rejects.toThrow(
        VaultFrozenError,
      );
      expect(() => setBrainSetting(settings, "schema.page_types", ["paper"])).toThrow(
        VaultFrozenError,
      );
    } finally {
      unfreezeVault(vault);
    }
    expect(schemaRecords(env)).toHaveLength(0);
    expect(schemaAuditRows(env)).toHaveLength(0);
    // A migration gate left naming the vault refuses no store write.
    holdMigrationGate(vault, "run-schema-gates");
    try {
      await applySchemaAdminMutations(vault, [ADD_PAPER], { actor: "t" });
    } finally {
      releaseMigrationGate(vault, "run-schema-gates");
    }
    expect(schemaRecords(env)).toHaveLength(1);
  });
});

describe("a schema apply seen from a machine that holds only shared", () => {
  let other: StoreEnv | null = null;
  afterEach(() => {
    other?.cleanup();
    other = null;
  });

  test("is attested, not modified: the audit row lives with the pack it attests", async () => {
    env = makeStoreEnv("osb-schema-attest-");
    switchDevice(env.storeRoot);
    await applySchemaAdminMutations(env.vault, [ADD_PAPER, ALIAS], {
      actor: "t",
      reason: "operator note about the paper type",
    });
    // The reason stays where audit rows always went, off the shared row.
    expect(JSON.stringify(ledgerRows(env.storeRoot, "shared", "reliability-audit"))).not.toContain(
      "operator note",
    );
    expect(JSON.stringify(ledgerRows(env.storeRoot, "private", "reliability-audit"))).toContain(
      "operator note",
    );
    other = sharedOnlyPeer(env);
    const integrity = assessSchemaPackIntegrity(other.vault);
    expect(integrity.status).toBe("ok");
    expect(integrity.mismatches).toEqual([]);
    expect(loadSchemaPack(other.vault).declarations.page_types).toEqual(["paper"]);
  });

  test("a reason that names a private page stays off the shared row", async () => {
    env = makeStoreEnv("osb-schema-attest-private-");
    switchDevice(env.storeRoot);
    await applySchemaAdminMutations(env.vault, [ADD_PAPER], {
      actor: "t",
      // A preference the store cannot resolve is judged private (fail closed).
      reason: "[[pref-hidden]]",
    });
    const shared = JSON.stringify(ledgerRows(env.storeRoot, "shared", "reliability-audit"));
    expect(shared).toContain("pack_digest");
    expect(shared).not.toContain("pref-hidden");
    // The machine that holds private keeps the batch and the reason on its own row.
    expect(JSON.stringify(ledgerRows(env.storeRoot, "private", "reliability-audit"))).toContain(
      "pref-hidden",
    );
    other = sharedOnlyPeer(env);
    expect(assessSchemaPackIntegrity(other.vault).status).toBe("ok");
  });

  test("a reason with a private region still attests the apply", async () => {
    env = makeStoreEnv("osb-schema-attest-region-");
    switchDevice(env.storeRoot);
    await applySchemaAdminMutations(env.vault, [ADD_PAPER], {
      actor: "t",
      reason: "for <private>the board</private>",
    });
    const shared = JSON.stringify(ledgerRows(env.storeRoot, "shared", "reliability-audit"));
    expect(shared).toContain("pack_digest");
    expect(shared).not.toContain("the board");
    other = sharedOnlyPeer(env);
    expect(assessSchemaPackIntegrity(other.vault).status).toBe("ok");
  });
});

describe("schema apply on an unswitched machine", () => {
  test("writes _brain.yaml and no schema settings record", async () => {
    env = makeStoreEnv("osb-schema-legacy-");
    const result = await applySchemaAdminMutations(env.vault, [ADD_PAPER], { actor: "t" });
    expect(readFileSync(brainConfigPath(env.vault), "utf8")).toContain("    - paper");
    expect(result.audit_path).toContain("schema-mutations");
    expect(schemaRecords(env)).toHaveLength(0);
    expect(readSchemaPackSource(env.vault).path).toBe(brainConfigPath(env.vault));
    expect(assessSchemaPackIntegrity(env.vault).status).toBe("ok");
  });
});