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
38.4 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import {
  JSONRPC_VERSION,
  MCPServer,
  PROTOCOL_VERSION,
  SERVER_NAME,
  SERVER_VERSION,
  serveStdioFromString,
  slugify,
} from "../../src/mcp/index.ts";
import { createPluginRepo, createSandboxVault } from "../helpers/fixtures.ts";
import { readToolErrorCode } from "../helpers/tool-error-envelope.ts";
import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
import { PARTNER_CODEGRAPH_DISABLED_ENV } from "../../src/core/config.ts";
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";

let tmp: string;
const savedEnv: Record<string, string | undefined> = {};

beforeEach(() => {
  tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-test-"));
  for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {
    savedEnv[k] = process.env[k];
    delete process.env[k];
  }
  // `vault_health` runs the full doctor, which consults the codegraph
  // partner whenever that binary is on PATH. The partner's cache lives
  // under HOME and this suite mandates a clean one, so each consultation
  // costs seconds: these tests failed on bun's default budget on any
  // workstation with codegraph installed and passed on CI, where the
  // binary is absent. Nothing here asserts anything about the partner, so
  // the cost is removed rather than the ceiling raised.
  savedEnv[PARTNER_CODEGRAPH_DISABLED_ENV] = process.env[PARTNER_CODEGRAPH_DISABLED_ENV];
  process.env[PARTNER_CODEGRAPH_DISABLED_ENV] = "true";
});

afterEach(() => {
  rmSync(tmp, { recursive: true, force: true });
  for (const [k, v] of Object.entries(savedEnv)) {
    if (v === undefined) delete process.env[k];
    else process.env[k] = v;
  }
});

async function initialize(server: MCPServer) {
  const r = await server.handleRequest({
    jsonrpc: JSONRPC_VERSION,
    id: 1,
    method: "initialize",
    params: {
      protocolVersion: PROTOCOL_VERSION,
      capabilities: {},
      clientInfo: { name: "test-client", version: "0" },
    },
  });
  await server.handleRequest({
    jsonrpc: JSONRPC_VERSION,
    method: "notifications/initialized",
  });
  return r;
}

async function callTool(
  server: MCPServer,
  name: string,
  args: Record<string, unknown> = {},
  id = 99,
) {
  return server.handleRequest({
    jsonrpc: JSONRPC_VERSION,
    id,
    method: "tools/call",
    params: { name, arguments: args },
  });
}

describe("slugify (re-exported via MCP barrel)", () => {
  test("lowercases and replaces punctuation", () => {
    expect(slugify("Hello, World!")).toBe("hello-world");
  });

  test("empty/non-ASCII inputs fall back to a stable unnamed-<hash>", () => {
    const fallback = /^unnamed-[0-9a-f]{8}$/;
    expect(slugify("   ")).toMatch(fallback);
    expect(slugify("---")).toMatch(fallback);
    expect(slugify("★ ☆ ☃")).toMatch(fallback);
  });

  test("truncates to 64 chars", () => {
    expect(slugify("a".repeat(200)).length).toBe(64);
  });
});

describe("handshake", () => {
  test("initialize returns server info and tools capability", async () => {
    const server = new MCPServer({ vault: tmp });
    const r = (await initialize(server))!;
    expect(r.jsonrpc).toBe(JSONRPC_VERSION);
    expect(r.id).toBe(1);
    const result = (r as any).result;
    expect(result.serverInfo.name).toBe(SERVER_NAME);
    expect(result.serverInfo.version).toBe(SERVER_VERSION);
    expect(result.capabilities.tools).toBeDefined();
    expect(result.protocolVersion).toBe(PROTOCOL_VERSION);
  });

  test("instructions embed resolved agent identity and Brain tools", async () => {
    const vault = join(tmp, "vault");
    mkdirSync(vault);
    const config = join(tmp, "config.yaml");
    writeFileSync(config, "agent_name: hermes-vps-agent\n");
    const server = new MCPServer({ vault, configPath: config });
    const r = (await initialize(server))! as any;
    const inst = r.result.instructions as string;
    expect(inst).toContain("@hermes-vps-agent");
    // v0.9.0+ — instructions advertise Brain tools, not the legacy
    // `second_brain_capture` path. v0.10.8 instructions may mention
    // `event_log_append` once, only as the historical name of the
    // retired tool that `brain_note` now replaces — they must NOT
    // teach the agent to call it.
    expect(inst).toContain("brain_feedback");
    expect(inst).toContain("brain_apply_evidence");
    expect(inst).toContain("brain_note");
    expect(inst).not.toContain("second_brain_capture");
    // Allowed mention is the "retired" reference; reject any wording
    // that frames `event_log_append` as an active tool to call.
    expect(inst).not.toMatch(/call\s+`?event_log_append`?/i);
    expect(inst).not.toMatch(/use\s+`?event_log_append`?/i);
  });

  test("negotiates alternate client version", async () => {
    const server = new MCPServer({ vault: tmp });
    const r = (await server.handleRequest({
      jsonrpc: JSONRPC_VERSION,
      id: 1,
      method: "initialize",
      params: {
        protocolVersion: "2024-11-05",
        capabilities: {},
        clientInfo: { name: "old", version: "0" },
      },
    })) as any;
    expect(r.result.protocolVersion).toBe("2024-11-05");
  });

  test("notifications/initialized is silent (returns null)", async () => {
    const server = new MCPServer({ vault: tmp });
    expect(
      await server.handleRequest({
        jsonrpc: JSONRPC_VERSION,
        method: "notifications/initialized",
      }),
    ).toBeNull();
  });

  test("unknown method returns method-not-found", async () => {
    const server = new MCPServer({ vault: tmp });
    const r = (await server.handleRequest({
      jsonrpc: JSONRPC_VERSION,
      id: 7,
      method: "does/not/exist",
    })) as any;
    expect(r.error.code).toBe(-32601);
  });
});

describe("tool listing", () => {
  test("advertises the core and Brain tools (v0.10.8+)", async () => {
    const server = new MCPServer({ vault: tmp });
    await initialize(server);
    const r = (await server.handleRequest({
      jsonrpc: JSONRPC_VERSION,
      id: 2,
      method: "tools/list",
    })) as any;
    const names = r.result.tools.map((tool: { name: string }) => tool.name).toSorted();
    expect(names).toEqual(
      [
        // Runtime capability diagnostics (v0.23.0).
        "second_brain_capabilities",
        // Core read/health (writable legacy tools removed in v0.9.0).
        "second_brain_status",
        // What this install is wired into: linked projects, verified
        // install targets (what-this-install-knows).
        "second_brain_wiring",
        "second_brain_query",
        "vault_health",
        // Preview-budget artifact fetch (added in v0.18.0).
        "brain_artifact_get",
        // Brain (brain_note added in v0.10.8 §32B,
        // brain_context added in v0.10.10,
        // brain_context_pack added in v0.10.15,
        // brain_operator_summary added in v0.10.16,
        // brain_unlinked_mentions / brain_concept_synthesis /
        // brain_moc_audit added in v0.10.17,
        // brain_timeline / brain_belief_evolution / brain_stale_scan /
        // brain_daily_brief / brain_weekly_synthesis added in v0.10.18,
        // brain_agent_query / brain_agent_diff added in v0.15.0,
        // lifecycle review tools added in v0.17.0.
        "brain_feedback",
        "brain_dream",
        "brain_intent_review",
        "brain_retention",
        "brain_review_candidates",
        "brain_apply_evidence",
        "brain_note",
        // Brain Portability & Interop suite: write an actual vault note file.
        "brain_create_note",
        // Recall-trust-and-write-surface W1: update and append existing notes
        // as single-operation batches over the atomic write-batch core.
        "brain_update_note",
        "brain_append_note",
        // Recall-trust-and-write-surface W2: general all-or-nothing multi-op
        // write surface (kernel 2's second consumer).
        "brain_write_batch",
        "brain_pinned_context",
        "brain_context",
        "brain_query",
        "brain_agent_query",
        "brain_agent_diff",
        // Recorded note writes: who wrote what, and what it replaced
        // (who-wrote-what Task A).
        "brain_writes",
        // Destination-keyed fold over the same ledger (actionable-now batch).
        "brain_write_destinations",
        "brain_doctor",
        "brain_health",
        // Unified operator status snapshot (source-pipeline-integrity O3).
        "brain_status",
        "brain_hygiene",
        "brain_mcp_landscape",
        // Canonical entity registry read surface (Memory Integrity Suite).
        "brain_entity",
        "brain_backlinks",
        // Per-preference mutation audit + morning brief (added in v0.21.0).
        "brain_audit",
        // Read-only Ed25519-signed store attestations (delivery-trust wave).
        "brain_attestations",
        // Vault portability suite (added in v0.22.0).
        "brain_sources",
        "brain_switch_vault",
        "brain_context_pack",
        "brain_context_pack_outcome",
        "brain_unlinked_mentions",
        "brain_moc_audit",
        "brain_stale_scan",
        // Pre-compress injection pack (added in v0.20.0).
        "brain_pre_compress_pack",
        // Context continuity and receipts (added in v0.29.0).
        "brain_context_receipts",
        "brain_event_trace",
        "brain_recall_telemetry",
        // Receipt compaction over the receipt ledgers (storage-lifecycle).
        "brain_receipts",
        // The vault storage report (storage-lifecycle).
        "brain_storage",
        // The brain store change probe (brain store and topics, phase 1).
        "brain_changes",
        // Shared brain settings writer (brain store and topics, task 2.11).
        "brain_settings",
        // Observed-use verdict feeding recall ranking (Retrieval & Ranking Quality).
        "brain_observed_use",
        "brain_knowledge_gaps",
        "brain_context_presets",
        "brain_pre_compact_extract",
        "brain_session_grep",
        "brain_session_describe",
        "brain_session_expand",
        // Procedural-learning surfaces (v0.30.0).
        "brain_skill_proposals",
        // Benchmark-gated rewrite status (agent-presence, t_635e3e72):
        // read-only ids-and-rates status; MCP never accepts or scores.
        "brain_skill_rewrite_status",
        "brain_procedural_memory",
        "brain_procedural_graph",
        "brain_recurrence",
        // Consolidated view tools (token-diet, v0.34.0); the per-view
        // names above stay registered as deprecated aliases.
        "brain_brief",
        "brain_analytics",
        "brain_anticipatory_context",
        // Search (added in v0.10.0; recall gate added in v0.27.0;
        // brain_search_expand added with progressive disclosure).
        "brain_recall_feedback",
        "brain_recall_gate",
        "brain_search",
        "brain_search_expand",
        "brain_eval",
        "brain_file_context",
        // Session Knowledge Synthesis Suite (v1.11.0).
        "brain_session_summary",
        // Batch checkpoint save (memory-signal-provenance-lifecycle C4).
        "brain_session_checkpoint",
        "brain_idea_lineage",
        "brain_note_history",
        "brain_note_lifecycle",
        // Schema admin + watchdog recovery probes.
        "schema_apply_mutations",
        "schema_inspect",
        "brain_watchdog",
        // Agent Surface Suite: skill discovery + two-pass hydration.
        "list_skills",
        "get_skill",
        "skills_attach",
        "tool_hydrate",
        "brain_intention",
        // Workspace Insight Suite: trigger queue + proactive insight.
        "brain_trigger",
        "brain_deep_synthesis",
        // Subject diarization (knowledge-intake-and-consolidation, t_28ba3fc4).
        "brain_diarize",
        // Model-mined session signals (salience-lifecycle-enrichment, t_1dace26d).
        "brain_extract_signals",
        // One-shot design note (salience-lifecycle-enrichment, t_c87644b4).
        "brain_design_note",
        "brain_idea_discovery",
        // Entity Truth & Self-Improving Dream Suite.
        "brain_truth",
        "brain_dead_ends",
        "brain_foresight",
        // Hindsight brain-loop ops: inbound, opt-in LLM generation tracing.
        "brain_generation_reports",
        // Write-Time Integrity & Governance Suite.
        "brain_labels",
        "brain_tiers",
        "brain_secrets",
        "brain_maintenance",
        // Belief lifecycle suite (t_7d5a3589): cross-type tombstone + supersede.
        "brain_lifecycle",
        // Link & Recall Intelligence Suite (v0.45.0).
        "brain_bridges",
        "brain_clusters",
        "brain_benchmark",
        "brain_tune",
        // CodeGraph & MCP Operational Readability (v1.12.0).
        "brain_codegraph_report",
        // Belief lifecycle suite (t_6916369f): claim-graph query surface.
        "brain_claims",
        // Belief lifecycle suite (t_ac03214d): decision-record note family.
        "brain_decision",
        // Belief lifecycle suite (t_0e3f2bee): persisted-contradiction lifecycle.
        "brain_tension",
        // Agent Write Contract Suite: provider-agnostic write sessions.
        "brain_write_session",
        // Knowledge Provenance Suite (v1.7.0).
        "brain_intake_entities",
        "brain_ingest_source",
        // Dated-commitments wave: one-off pledge CRUD and its extraction intake.
        "brain_pledge",
        "brain_intake_pledges",
        // Large-folder ingest planner (memory-signal-provenance-lifecycle A3).
        "brain_ingest_batch_plan",
        // Source distillation into atomic claims (ingestion-import-robustness t_2e2e959f).
        "brain_distill_source",
        // Source cleanup: search + delete by exact source file (C6, v1.x).
        "brain_search_by_source",
        "brain_delete_by_source",
        "brain_research_report",
        "brain_derive_fact",
        // Calendar integration: recurring obligations + agenda synthesis.
        "brain_obligation",
        "brain_agenda",
        // Hermes on_memory_write host bridge (memory-subsystem-alignment).
        "brain_memory_bridge",
        // Route-level MCP latency (context-pack-economics-observability).
        "brain_route_metrics",
        "brain_scaffold_stub",
        // Expiration mutation by id (salience-lifecycle-enrichment unit 3c).
        "brain_expire",
        // Shadow-only retrieval advisor (retrieval-quality-and-context-delivery).
        "brain_retrieval_plan",
        // Durable token-impact ledger (context-pack-economics-observability).
        "brain_token_impact",
        // Topics (brain-store-and-topics phase 3).
        "brain_topic",
      ].toSorted(),
    );
    // Explicit grep: legacy writable tools are no longer advertised.
    expect(names.includes("event_log_append")).toBe(false);
    expect(names.includes("second_brain_capture")).toBe(false);
    for (const t of r.result.tools) {
      expect(t.inputSchema.type).toBe("object");
    }
  });
});

describe("tool calls", () => {
  test("second_brain_status returns an opaque store reference by default", async () => {
    const vault = join(tmp, "vault");
    mkdirSync(vault);
    const config = join(tmp, "config.yaml");
    writeFileSync(config, "vault_path: /tmp/vault\napi_key: secret\n");
    const server = new MCPServer({ vault, configPath: config });
    await initialize(server);
    const r = (await callTool(server, "second_brain_status"))! as any;
    const s = r.result.structuredContent;
    // Default (expose_host_paths unset): the absolute host path is redacted
    // to a stable opaque reference, never the raw path.
    expect(s.vault_path).toMatch(/^vault:\/\/[0-9a-f]{32}$/);
    expect(s.vault_path).not.toBe(vault);
    // The raw host path must not leak through any field, including nested
    // ones like config.vault_path.
    expect(JSON.stringify(s)).not.toContain(vault);
    expect(s.vault_exists).toBe(true);
    // Was `[REDACTED]`: the key-name-only copy in config.ts is now the
    // shared redactor's structured pass, and with it the one placeholder.
    expect(s.config.api_key).toBe(REDACTION_PLACEHOLDER);
    expect(s.config_keys).toContain("vault_path");
  });

  test("the store reference is stable across calls for the same vault", async () => {
    const vault = join(tmp, "vault");
    mkdirSync(vault);
    const config = join(tmp, "config.yaml");
    writeFileSync(config, "vault_path: /tmp/vault\n");
    const server = new MCPServer({ vault, configPath: config });
    await initialize(server);
    const a = ((await callTool(server, "second_brain_status"))! as any).result.structuredContent;
    const b = ((await callTool(server, "second_brain_status"))! as any).result.structuredContent;
    expect(a.vault_path).toBe(b.vault_path);
  });

  test("expose_host_paths=true restores the raw absolute path", async () => {
    const vault = join(tmp, "vault");
    mkdirSync(vault);
    const config = join(tmp, "config.yaml");
    writeFileSync(config, "vault_path: /tmp/vault\nexpose_host_paths: true\n");
    const server = new MCPServer({ vault, configPath: config });
    await initialize(server);
    const r = (await callTool(server, "second_brain_status"))! as any;
    const s = r.result.structuredContent;
    expect(s.vault_path).toBe(vault);
  });

  test("second_brain_status includes a `brain` section with counts and activity", async () => {
    const vault = join(tmp, "vault");
    mkdirSync(vault);
    const config = join(tmp, "config.yaml");
    writeFileSync(config, "vault_path: /tmp/vault\n");
    // Brain layer absent → `brain.present` is `false` with zero counts.
    const server = new MCPServer({ vault, configPath: config });
    await initialize(server);
    const r = (await callTool(server, "second_brain_status"))! as any;
    const s = r.result.structuredContent;
    expect(s.brain).toBeDefined();
    expect(s.brain.present).toBe(false);
    expect(s.brain.counts.preferences).toBe(0);
    expect(s.brain.last_dream_at).toBeNull();
    expect(s.brain.sanity.signals_awaiting_dream).toBe(0);
    // Brain absent -> the same honest never_dreamed/zero shape as an
    // empty-but-present Brain, not an error (nothing-writes-silently, D).
    expect(s.brain.maintenance_debt).toEqual({
      status: "never_dreamed",
      log_events_since_dream: 0,
    });
  });

  test("second_brain_status `brain.maintenance_debt` derives from the log shards", async () => {
    const vault = join(tmp, "vault");
    mkdirSync(vault);
    const config = join(tmp, "config.yaml");
    writeFileSync(config, `vault_path: ${vault}\n`);
    bootstrapBrain(vault, { configPath: config });
    appendLogEvent(vault, {
      timestamp: "2026-05-10T09:00:00Z",
      eventType: BRAIN_LOG_EVENT_KIND.note,
      agent: "tester",
      body: { text: "note" },
    });
    appendLogEvent(vault, {
      timestamp: "2026-05-11T09:00:00Z",
      eventType: BRAIN_LOG_EVENT_KIND.note,
      agent: "tester",
      body: { text: "note" },
    });

    const server = new MCPServer({ vault, configPath: config });
    await initialize(server);
    const r = (await callTool(server, "second_brain_status"))! as any;
    const s = r.result.structuredContent;
    expect(s.brain.maintenance_debt).toEqual({
      status: "never_dreamed",
      log_events_since_dream: 2,
    });
  });

  test("second_brain_status includes a `vault` block (v0.10.9)", async () => {
    const vault = join(tmp, "vault");
    mkdirSync(vault);
    mkdirSync(join(vault, ".obsidian"));
    writeFileSync(join(vault, ".obsidian", "app.json"), "{}");
    writeFileSync(join(vault, "note.md"), "# x\n");
    const config = join(tmp, "config.yaml");
    writeFileSync(config, "vault_path: /tmp/vault\n");
    const server = new MCPServer({ vault, configPath: config });
    await initialize(server);
    const r = (await callTool(server, "second_brain_status"))! as any;
    const s = r.result.structuredContent;
    expect(s.vault).toBeDefined();
    expect(s.vault.ignore_source).toBeDefined();
    expect(["_brain.yaml", "defaults"]).toContain(s.vault.ignore_source);
    expect(Array.isArray(s.vault.rules)).toBe(true);
    expect(s.vault.rules.some((r: { raw: string }) => r.raw === ".obsidian")).toBe(true);
    expect(typeof s.vault.included.files).toBe("number");
    expect(typeof s.vault.included.dirs).toBe("number");
    expect(typeof s.vault.excluded.dirs).toBe("number");
    expect(typeof s.vault.excluded.files).toBe("number");
    expect(s.vault.excluded.dirs).toBeGreaterThanOrEqual(1);
  });

  test("second_brain_status omits `vault` block when vault directory missing", async () => {
    const vault = join(tmp, "missing-vault");
    const config = join(tmp, "config.yaml");
    writeFileSync(config, "vault_path: /tmp/vault\n");
    const server = new MCPServer({ vault, configPath: config });
    await initialize(server);
    const r = (await callTool(server, "second_brain_status"))! as any;
    const s = r.result.structuredContent;
    expect(s.vault_exists).toBe(false);
    expect(s.vault).toBeUndefined();
  });

  test("second_brain_status degrades vault block to {error} when _brain.yaml is malformed (v0.10.9)", async () => {
    // Fail-closed resolver (design §5) makes walkers and the CLI
    // vault verb refuse to proceed on a malformed config. The MCP
    // status tool is a read-only diagnostic — it should still
    // expose the other blocks (brain / search / config) so the
    // operator can see what is wrong without losing the rest.
    const vault = join(tmp, "vault");
    mkdirSync(vault);
    mkdirSync(join(vault, "Brain"));
    writeFileSync(
      join(vault, "Brain", "_brain.yaml"),
      // entry contains a backslash → rejected by validator.
      `schema_version: 1\nvault:\n  ignore_paths:\n    - "bad\\\\entry"\n`,
    );
    const config = join(tmp, "config.yaml");
    writeFileSync(config, "vault_path: /tmp/vault\n");
    const server = new MCPServer({ vault, configPath: config });
    await initialize(server);
    const r = (await callTool(server, "second_brain_status"))! as any;
    const s = r.result.structuredContent;
    // Other blocks must remain present.
    expect(s.config_path).toBeDefined();
    expect(s.vault_exists).toBe(true);
    expect(s.brain).toBeDefined();
    // Vault block degraded with the error message.
    expect(s.vault).toBeDefined();
    expect(typeof s.vault.error).toBe("string");
    expect(s.vault.error).toContain("vault.ignore_paths");
  });

  test("second_brain_query filters and limits", async () => {
    const vault = createSandboxVault(tmp);
    const server = new MCPServer({ vault });
    await initialize(server);
    const r = (await callTool(server, "second_brain_query", {
      pattern: "Sandbox",
      limit: 5,
    })) as any;
    const s = r.result.structuredContent;
    expect(s.limit).toBe(5);
    expect(s.total_pages).toBeGreaterThanOrEqual(1);
    expect(s.pages.some((p: { title: string }) => p.title.includes("Sandbox"))).toBe(true);
  });

  test("second_brain_query walks pages by cursor to exhaustion", async () => {
    const vault = createSandboxVault(tmp);
    for (const n of [1, 2, 3]) {
      writeFileSync(
        join(vault, `CursorPage${n}.md`),
        `---\ntitle: Cursor Walk ${n}\n---\n\nbody\n`,
      );
    }
    const server = new MCPServer({ vault });
    await initialize(server);
    // The test created exactly three matching pages; bound the walk by that
    // arithmetic: ceil(total/limit) pages plus one slack step, so a
    // next_cursor that never turns null exhausts the budget and fails here
    // instead of hanging the suite.
    const total = 3;
    const limit = 2;
    const maxSteps = Math.ceil(total / limit) + 1;
    const seen: string[] = [];
    let cursor: string | null = null;
    let totalPages: number | null = null;
    for (let step = 0; step < maxSteps; step += 1) {
      const r = (await callTool(server, "second_brain_query", {
        pattern: "Cursor Walk",
        limit,
        ...(cursor !== null ? { cursor } : {}),
      })) as any;
      const s = r.result.structuredContent;
      // `total_pages` is the vault's whole page count, stable across the walk.
      if (totalPages === null) totalPages = s.total_pages;
      expect(s.total_pages).toBe(totalPages);
      expect(s.returned).toBeLessThanOrEqual(limit);
      // Guard the walk protocol: an ignored cursor is a shape violation,
      // not a stop condition.
      expect(s.next_cursor === null || typeof s.next_cursor === "string").toBe(true);
      seen.push(...s.pages.map((p: { title: string }) => p.title));
      cursor = s.next_cursor;
      if (cursor === null) break;
    }
    expect(cursor).toBeNull();
    // Path order, so the walk reads the pages back in the same order an
    // unpaginated call lists them.
    expect(seen).toEqual(["Cursor Walk 1", "Cursor Walk 2", "Cursor Walk 3"]);
    const bad = (await callTool(server, "second_brain_query", {
      pattern: "x",
      cursor: "!!!",
    })) as any;
    expect(bad.error?.code).toBe(-32602);
  });

  // `second_brain_capture` and `event_log_append` are no longer
  // advertised through MCP in v0.9.0 (design doc §11.1). The handler
  // functions remain in `src/mcp/tools.ts` for shell-side use
  // (`o2b append-event`); their behaviour is covered by the CLI / core
  // event-log tests. Here we only assert that the tool registry no
  // longer exposes them.
  test("removed legacy writable tools return method-not-found", async () => {
    const server = new MCPServer({ vault: tmp });
    await initialize(server);
    for (const name of ["second_brain_capture", "event_log_append"]) {
      const r = (await callTool(server, name, {
        title: "x",
        content: "y",
        message: "z",
      })) as any;
      expect(r.error.code).toBe(-32601);
    }
  });

  test("vault_health runs doctor", async () => {
    const vault = createSandboxVault(tmp);
    const repo = createPluginRepo(tmp, true);
    const server = new MCPServer({ vault, repoRoot: repo });
    await initialize(server);
    const r = (await callTool(server, "vault_health", {})) as any;
    const s = r.result.structuredContent;
    expect(s.ok).toBe(true);
    const names = new Set(s.checks.map((c: { name: string }) => c.name));
    expect(names.has("vault_writeable")).toBe(true);
    expect(names.has("claude_manifest")).toBe(true);
    expect(names.has("hermes_manifest")).toBe(true);
    // Runtime-state notices ride the pull surface too (array, empty when clean).
    expect(Array.isArray(s.notices)).toBe(true);
  });

  test("vault_health notices carry the next command as a field, additively", async () => {
    // The sandbox vault has a Brain tree with no identity marker and no
    // search index, so one notice with a registered exit and one without
    // are both present (no-dead-ends, task 3).
    const vault = createSandboxVault(tmp);
    const server = new MCPServer({ vault });
    await initialize(server);
    const r = (await callTool(server, "vault_health", {})) as any;
    const notices = r.result.structuredContent.notices as Array<Record<string, unknown>>;

    const missing = notices.find((n) => n["code"] === "search_index_missing");
    expect(missing).toBeDefined();
    // The three fields this surface has always carried are untouched...
    expect(missing!["severity"]).toBe("info");
    expect(String(missing!["message"])).not.toContain("Run:");
    // ...and the command is a field rather than a sentence to regex.
    expect(missing!["next_command"]).toBe("o2b search index");

    // A code with no registered exit contributes no key at all: absent,
    // never present-and-null.
    const marker = notices.find((n) => n["code"] === "vault_marker_absent");
    expect(marker).toBeDefined();
    expect(Object.keys(marker!).toSorted()).toEqual(["code", "message", "severity"]);
  });

  test("unknown tool returns method-not-found", async () => {
    const server = new MCPServer({ vault: tmp });
    await initialize(server);
    const r = (await callTool(server, "not_a_tool")) as any;
    expect(r.error.code).toBe(-32601);
  });

  test("tool output contract failure becomes a tool-level error", async () => {
    const server = new MCPServer({ vault: tmp });
    await initialize(server);
    (server as any).tools = [
      {
        name: "bad_contract",
        description: "test tool",
        inputSchema: {
          type: "object",
          properties: {},
          additionalProperties: false,
        },
        outputSchema: {
          type: "object",
          required: ["ok"],
          properties: { ok: { type: "boolean" } },
          additionalProperties: false,
        },
        handler: () => ({ ok: "yes" }),
      },
    ];
    const r = (await callTool(server, "bad_contract")) as any;
    expect(r.result.isError).toBe(true);
    expect(r.result.structuredContent).toBeUndefined();
    expect(r.result.content[0].text).toContain("bad_contract output contract failed");
    // The code rides on `_meta`, never on `structuredContent`, which a
    // strict client would validate against the very schema that failed.
    expect(readToolErrorCode(r.result)).toBe("output_contract_failed");
  });
});

describe("stdio loop", () => {
  test("processes initialize and tools/list", async () => {
    const payload =
      [
        JSON.stringify({
          jsonrpc: JSONRPC_VERSION,
          id: 1,
          method: "initialize",
          params: {
            protocolVersion: PROTOCOL_VERSION,
            capabilities: {},
            clientInfo: { name: "t", version: "0" },
          },
        }),
        JSON.stringify({
          jsonrpc: JSONRPC_VERSION,
          method: "notifications/initialized",
        }),
        JSON.stringify({
          jsonrpc: JSONRPC_VERSION,
          id: 2,
          method: "tools/list",
        }),
      ].join("\n") + "\n";
    const out = await serveStdioFromString({ vault: tmp }, payload);
    const lines = out.trim().split("\n");
    expect(lines.length).toBe(2);
    const init = JSON.parse(lines[0]!);
    const list = JSON.parse(lines[1]!);
    expect(init.id).toBe(1);
    expect(list.id).toBe(2);
    // The stdio loop advertises exactly the full-scope table minus hidden
    // entries: nothing withheld without a capability window, nothing
    // duplicated, nothing hidden leaking into the paid-for list.
    const advertised = (list.result.tools as Array<{ name: string }>).map((t) => t.name).toSorted();
    const expected = buildToolTable("full")
      .filter((t) => t.hidden !== true)
      .map((t) => t.name)
      .toSorted();
    expect(advertised).toEqual(expected);
  });

  test("returns parse error for invalid JSON", async () => {
    const out = await serveStdioFromString({ vault: tmp }, "{not json}\n");
    const r = JSON.parse(out.trim());
    expect(r.error.code).toBe(-32700);
  });

  test("returns invalid request for batch", async () => {
    const batch = JSON.stringify([
      { jsonrpc: JSONRPC_VERSION, id: 1, method: "ping" },
      { jsonrpc: JSONRPC_VERSION, id: 2, method: "ping" },
    ]);
    const out = await serveStdioFromString({ vault: tmp }, batch + "\n");
    const r = JSON.parse(out.trim());
    expect(r.error.code).toBe(-32600);
    expect(r.error.message.toLowerCase()).toContain("batch");
  });
});

describe("MCPServer serverName override", () => {
  test("default ctor uses SERVER_NAME constant", async () => {
    const server = new MCPServer({ vault: tmp });
    const r = (await initialize(server))! as any;
    expect(r.result.serverInfo.name).toBe("open-second-brain");
  });

  test("explicit serverName flows into initialize response", async () => {
    const server = new MCPServer(
      { vault: tmp, configPath: null, repoRoot: null },
      { serverName: "open-second-brain-writer" },
    );
    const r = (await initialize(server))! as any;
    expect(r.result.serverInfo.name).toBe("open-second-brain-writer");
  });
});

describe("serveStdioFromString respects scope+name", () => {
  test("tools/list serializes exactly the wire contract per tool", async () => {
    // Wire identity (parallel-reads classification, task D1): the
    // registry now carries a required `kind` (and already carried
    // `hidden` and `previewBudget`), and none of it may reach the
    // payload every client pays tokens for. The projection in
    // `handleToolsList` picks its fields explicitly; this pins the exact
    // serialized key set so an added advertised field fails here even
    // if the projection is later rewritten to spread.
    for (const scope of ["full", "writer", "catalog"] as const) {
      const server = new MCPServer({ vault: tmp }, { scope });
      const r = (await server.handleRequest({
        jsonrpc: JSONRPC_VERSION,
        id: 2,
        method: "tools/list",
        params: {},
      }))! as any;
      const tools = r.result.tools as Array<Record<string, unknown>>;
      expect(tools.length).toBeGreaterThan(0);
      for (const tool of tools) {
        // Exactly the wire contract: the three mandatory members, plus
        // outputSchema for the two tools that declare one - and nothing
        // else, now that the definition also carries `kind`.
        expect(Object.keys(tool).toSorted()).toEqual(
          [
            "description",
            "inputSchema",
            "name",
            ...("outputSchema" in tool ? ["outputSchema"] : []),
          ].toSorted(),
        );
      }
      // The optional outputSchema half of the same contract: the wire
      // payload mirrors the definition's declared shape exactly - a tool
      // advertises outputSchema iff its definition declares one, and no
      // registry member (kind, hidden, previewBudget) leaks instead.
      const table = new Map(buildToolTable(scope).map((t) => [t.name, t]));
      const withOutput = tools
        .filter((t) => "outputSchema" in t)
        .map((t) => t.name)
        .toSorted();
      const declared = [...table.values()]
        .filter((t) => t.outputSchema !== undefined && t.hidden !== true)
        .map((t) => t.name)
        .toSorted();
      expect(withOutput).toEqual(declared);
    }
  });

  test("writer scope filters tools/list response", async () => {
    const ctx = { vault: "/tmp/x", configPath: null, repoRoot: null };
    const initReq = JSON.stringify({
      jsonrpc: "2.0",
      id: 1,
      method: "initialize",
      params: { protocolVersion: "2025-06-18", capabilities: {} },
    });
    const listReq = JSON.stringify({
      jsonrpc: "2.0",
      id: 2,
      method: "tools/list",
      params: {},
    });
    const out = await serveStdioFromString(ctx, `${initReq}\n${listReq}\n`, {
      scope: "writer",
      serverName: "open-second-brain-writer",
    });
    const lines = out
      .trim()
      .split("\n")
      .map((l) => JSON.parse(l));
    expect(lines[0].result.serverInfo.name).toBe("open-second-brain-writer");
    const toolNames = (lines[1].result.tools as Array<{ name: string }>)
      .map((t) => t.name)
      .toSorted();
    expect(toolNames).toEqual([
      "brain_apply_evidence",
      "brain_context",
      "brain_feedback",
      "brain_note",
      "brain_pinned_context",
    ]);
  });

  test("writer-scope initialize carries the resolved identity to the client", async () => {
    // End to end over the transport the always-loaded server actually
    // runs on, because `buildInstructions` returning the line is only
    // half the claim: the handshake has to deliver it.
    process.env["VAULT_AGENT_NAME"] = "vps-agent";
    const ctx = { vault: "/tmp/x", configPath: null, repoRoot: null };
    const initReq = JSON.stringify({
      jsonrpc: "2.0",
      id: 1,
      method: "initialize",
      params: { protocolVersion: "2025-06-18", capabilities: {} },
    });
    const out = await serveStdioFromString(ctx, `${initReq}\n`, {
      scope: "writer",
      serverName: "open-second-brain-writer",
    });
    const instructions = JSON.parse(out.trim()).result.instructions as string;
    expect(instructions).toContain("You are @vps-agent on this Open Second Brain vault.");
    expect(instructions).toContain("brain_feedback");
  });
});

import { buildInstructions } from "../../src/mcp/instructions.ts";
import { evaluateToolCapabilities } from "../../src/mcp/capabilities.ts";
import { buildToolTable } from "../../src/mcp/tools.ts";
import { TOOL_SCOPE, TOOL_SCOPES, type ToolScope } from "../../src/mcp/tool-contract.ts";

/**
 * The capability report of a runtime that withholds nothing. The
 * withheld cases have their own file
 * (`tests/mcp/instruction-segments.test.ts`); these tests are about the
 * identity line, which is the same on every runtime.
 */
function fullCapabilities(scope: ToolScope) {
  return evaluateToolCapabilities(buildToolTable(scope), {
    scope,
    serverName: "open-second-brain-test",
  }).report;
}

describe("buildInstructions writer mode", () => {
  test("writer instructions name both tools and point at the full server", () => {
    const text = buildInstructions({
      agent: "@agent",
      scope: TOOL_SCOPE.writer,
      capabilities: fullCapabilities(TOOL_SCOPE.writer),
    });
    expect(text).toContain("brain_feedback");
    expect(text).toContain("brain_apply_evidence");
    expect(text).toContain("open-second-brain"); // points at sibling server
    expect(text).not.toMatch(/brain_dream/);
  });
});

describe("buildInstructions states the identity on every scope", () => {
  // The writer scope is the always-loaded surface an agent carries into
  // every session, and the four writers on it are exactly the
  // identity-bearing ones - so the surface where the name matters most was
  // the one that never said it. The identity line is not decoration: it is
  // the standing instruction to log under one name and not invent another,
  // and a scope that omits it leaves that instruction to chance.
  const AGENT = "vps-agent";

  // Driven off the membership list, not a copy of it: a fourth scope
  // shipped without an identity line fails here without anyone
  // remembering to extend this loop.
  for (const scope of TOOL_SCOPES) {
    test(`${scope} scope names the resolved agent`, () => {
      const text = buildInstructions({
        agent: AGENT,
        scope,
        capabilities: fullCapabilities(scope),
      });
      expect(text).toContain(`You are @${AGENT} on this Open Second Brain vault.`);
    });

    test(`${scope} scope renders a refusal, never a name, when identity is unresolved`, () => {
      const reason = new Error("config unreadable: /etc/open-second-brain/config.yaml");
      const text = buildInstructions({
        agent: reason,
        scope,
        capabilities: fullCapabilities(scope),
      });
      expect(text).toContain("UNRESOLVED");
      expect(text).toContain(reason.message);
      expect(text).not.toContain("You are @");
    });
  }
});