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
fix(hermes): advertise static tool schemas so the provider registers with its full tool set (#81)
Sol Aitken72bac527c6cc
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 50195acd..e06364cd 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.0.0",+ "version": "1.0.1","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 95bdfb26..4ec65ec4 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.0.0",+ "version": "1.0.1","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 28bf7477..12d5be7e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,34 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.0.1] - 2026-06-07++Hermes registration fix. The memory provider now advertises its curated+`brain_*` tool set from the very first `get_tool_schemas()` call, so a fresh+gateway start registers it with the full tool count instead of zero and tool+calls route correctly.++### Fixed++- **Hermes registered the provider with 0 tools and `brain_*` calls failed as+ "Unknown tool"**: Hermes builds its memory-tool routing table at provider+ registration, before `initialize()` starts the `o2b mcp` bridge, and never+ rebuilds it - while the provider only produced schemas from the live bridge.+ `get_tool_schemas()` now falls back to vendored static copies of the curated+ tool schemas (`plugins/hermes/_schemas.py`) whenever the bridge is not+ available or the live listing fails; once the bridge is up, live `tools/list`+ schemas win as before. The `handle_tool_call()` initialization guard is+ unchanged.++### Notes++- The vendored copies are verbatim (name, description, inputSchema) projections+ of the live server's `tools/list` and are locked by an anti-drift test+ (`tests/python/test_static_schemas.py`) that compares them against a live+ `o2b mcp` in CI, so they cannot silently diverge from the TypeScript core.+- Lifecycle hooks (prefetch, sync_turn, system prompt block, pre-compress,+ session end) were unaffected by the bug and are unchanged.+## [1.0.0] - 2026-06-05Stability & Trust: the first major release formalizes what elevendiff --git a/docs/brainstorm/hermes-static-tool-schemas/cli-output/claude.md b/docs/brainstorm/hermes-static-tool-schemas/cli-output/claude.mdnew file mode 100644index 00000000..d8d18ba1--- /dev/null+++ b/docs/brainstorm/hermes-static-tool-schemas/cli-output/claude.md@@ -0,0 +1,32 @@+### Variant 1: Hand-authored static schema literals+- **Approach**: Embed the 10 MEMORY_TOOLS schemas (name, description, inputSchema) as a Python dict literal in a new module (e.g. `plugins/hermes/_schemas.py`). `get_tool_schemas()` returns these when `self._bridge is None`, and switches to the live-filtered list once the bridge is up. The anti-drift unittest spawns `o2b mcp`, fetches `tools/list`, and asserts the static literals match the live MEMORY_TOOLS subset by name and inputSchema.+- **Trade-offs**:+ - Pro: stdlib-only, zero import-time I/O, no Bun needed for the import path; the schemas are readable and reviewable in-tree.+ - Pro: trivially fail-soft — the static path can never block or throw at gateway boot.+ - Con: a second hand-maintained copy of schema text that can drift; relies entirely on the anti-drift test (skippable when Bun absent) to catch divergence.+ - Con: full inputSchema bodies are verbose to hand-transcribe and review.+- **Complexity**: small+- **Risk**: low++### Variant 2: Vendored JSON snapshot generated from the TS core+- **Approach**: Add a generator (a script / `bun`-backed step) that calls `o2b mcp` `tools/list`, filters to MEMORY_TOOLS, and writes a committed JSON artifact under `plugins/hermes/`. `get_tool_schemas()` loads this JSON (cached at import) when the bridge is not started. The anti-drift test regenerates into a temp file and asserts byte/structure equality with the committed snapshot.+- **Trade-offs**:+ - Pro: single authored source (TS core); the Python copy is mechanically derived, so drift is a regeneration step rather than manual editing.+ - Pro: the snapshot doubles as a documented contract artifact; full inputSchemas are exact, not transcribed.+ - Con: introduces a build/codegen step and a generated file that must be regenerated and committed on every schema change — easy to forget, and CI must enforce freshness.+ - Con: adds file-read I/O at import and a packaging concern (the JSON must ship with the shim).+- **Complexity**: medium+- **Risk**: medium++### Variant 3: Lazy eager-bridge fetch at schema-request time+- **Approach**: On the first `get_tool_schemas()` call while `self._bridge is None`, attempt a short, time-boxed synchronous bridge start to fetch live schemas, caching the result; if the start fails or times out, fall back to a minimal static name/description stub. No full static schema copy is maintained as the primary source.+- **Trade-offs**:+ - Pro: schemas always come from the live TS core when reachable — essentially no drift surface.+ - Pro: removes the need for a committed schema duplicate.+ - Con: risks the fail-soft contract — a synchronous start during gateway registration can block boot or surface Bun-unavailability into a hot path; needs careful timeout/guard handling.+ - Con: the fallback stub still ships incomplete inputSchemas, so the "N >= 1 with real schemas" guarantee degrades exactly when Bun is missing; harder to test deterministically with FakeBrainBridge alone.+- **Complexity**: medium+- **Risk**: high++### Recommended: Variant 1+**Rationale**: It is the smallest change that satisfies every acceptance criterion while honoring the hard constraints — stdlib-only, fail-soft (the static path cannot block or throw at boot), unchanged public signatures, and MEMORY_TOOLS as the single subset source. The drift risk that distinguishes it from Variant 2 is precisely what the required anti-drift test against live `o2b mcp` neutralizes, without paying Variant 2's codegen/regeneration ceremony or Variant 3's fail-soft hazard during gateway registration.diff --git a/docs/brainstorm/hermes-static-tool-schemas/cli-output/prompt.md b/docs/brainstorm/hermes-static-tool-schemas/cli-output/prompt.mdnew file mode 100644index 00000000..c6214f2d--- /dev/null+++ b/docs/brainstorm/hermes-static-tool-schemas/cli-output/prompt.md@@ -0,0 +1,101 @@+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++## Fix: `brain_*` tools register as "Unknown tool" in Hermes (provider advertises 0 tools at registration)++### Root cause (verified against live hermes-agent source)++Hermes builds its memory-tool routing table in `MemoryManager.add_provider()`+(hermes-agent: `agent/memory_manager.py:285-302`, "registered (N tools)" log) and+only afterwards calls `initialize_all()` (`agent/agent_init.py:1101` vs `:1144`). The+table is never rebuilt. Our provider (`plugins/hermes/provider.py`) starts+McpBrainBridge in `initialize()` (fail-soft by design) and `get_tool_schemas()`+returns `[]` while `self._bridge is None` (`provider.py:96-104`). Result: gateway+logs "Memory provider 'open-second-brain' registered (0 tools)", the model+still SEES `brain_*` tools (`agent_init.py:1153+` collects schemas post-init), but+dispatch via `memory_manager.has_tool()` hits the empty routing table and falls+through to "Unknown tool". Lifecycle hooks (prefetch, sync_turn,+system_prompt_block, on_pre_compress, on_session_end) are unaffected.++### Fix direction (our side, plugins/hermes)++1. Provide schemas (name, description, inputSchema) for the curated+ MEMORY_TOOLS set from `get_tool_schemas()` when the bridge is+ not started yet. After bridge start, keep returning the live-filtered list+ as today (or reconcile static vs live by name).+2. Keep the `handle_tool_call()` guard unchanged: bridge None -> BridgeError.+3. Anti-drift: a test that compares the pre-init schemas against the live+ `o2b mcp` tools/list (MEMORY_TOOLS subset) so they cannot silently diverge.+4. Tests: (a) `get_tool_schemas()` BEFORE `initialize()` returns the full curated+ set; (b) after `initialize()` the name set is identical; (c) simulate Hermes+ ordering (schemas requested pre-init, tool call post-init) end-to-end with+ FakeBrainBridge.++### Acceptance++- Fresh gateway start logs "Memory provider 'open-second-brain' registered (N tools)" with N >= 1+- A `brain_*` tool call from the model routes through memory_manager (no "Unknown tool")+- Full Python test suite green++# Project context++Open Second Brain - agent-owned second brain in an Obsidian-compatible Markdown vault.+Core is TypeScript on Bun (`src/`); the Hermes memory provider is a thin Python shim+(`plugins/hermes/`: provider.py, bridge.py, config.py, cli.py, _base.py) that forwards+all work to the TS core over an `o2b mcp` stdio JSON-RPC bridge (McpBrainBridge).+Python >= 3.11, stdlib-only (no runtime dependencies allowed in the shim).+Python tests: `python -m unittest discover -s tests/python -v` (CI runs this; no pytest).+TS side: `bun test`, `oxlint`, `oxfmt`, `tsc --noEmit`.++The live `o2b mcp` server advertises 77 tools; all 10 MEMORY_TOOLS names+(brain_feedback, brain_apply_evidence, brain_note, brain_pinned_context, brain_query,+brain_search, brain_recall_gate, brain_context, brain_context_pack,+brain_pre_compact_extract) are present in `tools/list` with full inputSchema.+Tool schemas are defined in the TS core (`src/mcp/brain-tools.ts` and siblings).++Recent commits:+ff43abd fix(ci): treat an existing release as success in the release workflow (#80)+957a403 feat!: Stability & Trust - 1.0.0 API freeze, deprecation sweep, safeguard, staged dream, timezone, report deltas (#79)+786b0f5 fix(openclaw): rebuild stale plugin bundle so the release verify gate passes (#78)+6d09d3c feat: Link & Recall Intelligence Suite - alias resolution, bridge discovery, communities, recall benchmark, self-tuning (#77)+789e3e3 feat: Write-Time Integrity & Governance Suite - schema ontology, tier guard, secret custody, maintenance lane (#76)+c03d569 fix(hermes): root cli.py shim completes the upstream CLI discovery contract (#75)+0952dfc feat: become a native Hermes memory provider (#62)++Related files:+- plugins/hermes/provider.py (get_tool_schemas, handle_tool_call, MEMORY_TOOLS allowlist)+- plugins/hermes/bridge.py (BrainBridge protocol, McpBrainBridge, FakeBrainBridge)+- tests/python/test_memory_provider.py (unittest, FakeBrainBridge-based)+- src/mcp/brain-tools.ts (TS source of truth for tool schemas)+- install/hermes.md (user-facing install doc)++Conventions:+- Conventional commits; one PR = one CHANGELOG version; 1.0.0 API freeze is in effect (no breaking changes; this must be a patch release).+- The Python shim must never reimplement deterministic memory logic; it forwards to the TS core.+- Provider is fail-soft: gateway boot must never break because of the bridge.+- Tests use unittest + FakeBrainBridge, no network/Bun required for unit tests; an anti-drift test MAY spawn the live `o2b mcp` (Bun available in CI after bun-precheck) but must be skippable when the runtime is unavailable.++Constraints:+- Do not change existing public APIs (1.0.0 freeze): get_tool_schemas/handle_tool_call signatures stay.+- No new external Python dependencies (stdlib only).+- handle_tool_call guard stays: bridge None -> BridgeError.+- The curated MEMORY_TOOLS allowlist stays the single source of the tool subset.+- Upstream hermes-agent changes are out of scope for this PR.++# Required output format++Produce exactly 3 distinct architectural variants. For each variant:++### Variant N: <short name>+- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/hermes-static-tool-schemas/design.md b/docs/brainstorm/hermes-static-tool-schemas/design.mdnew file mode 100644index 00000000..46ae65ca--- /dev/null+++ b/docs/brainstorm/hermes-static-tool-schemas/design.md@@ -0,0 +1,88 @@+# Static tool schemas for the Hermes memory provider - fix "Unknown tool" registration++**Status:** approved+**Author:** claude-dev-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Hermes builds its memory-tool routing table in `MemoryManager.add_provider()` from+`provider.get_tool_schemas()` and only afterwards calls `initialize_all()`; the table+is never rebuilt. Our provider starts the `o2b mcp` bridge in `initialize()` and+`get_tool_schemas()` returns `[]` while the bridge is absent, so the gateway registers+the provider with 0 tools. The model still sees `brain_*` tools (schemas are collected+post-init), but dispatch hits the empty routing table and fails with "Unknown tool".++## Scope++- New module `plugins/hermes/_schemas.py` embedding static schemas (name, description,+ inputSchema) for every name in the curated `MEMORY_TOOLS` set, copied verbatim from+ the live `o2b mcp` `tools/list`.+- `get_tool_schemas()` returns the static set when the bridge is not available+ (`self._bridge is None`) and also when the live listing fails, instead of `[]`.+ After a successful bridge start it keeps returning the live-filtered list as today.+- Anti-drift test that spawns the live `o2b mcp`, fetches `tools/list`, and asserts the+ embedded copies match the live MEMORY_TOOLS subset field-by-field (name, description,+ inputSchema). Skipped cleanly when the Bun runtime / `o2b` CLI is unavailable.+- Unit tests: pre-init schema availability, pre/post-init name-set identity, fallback+ on listing failure, and an end-to-end simulation of the Hermes ordering+ (schemas requested pre-init, tool call post-init) with `FakeBrainBridge`.+- CHANGELOG entry and `install/hermes.md` adjustment.++## Out of scope++- Upstream hermes-agent change (rebuilding `_tool_to_provider` after `initialize_all()`+ or lazy dispatch lookup) - proposed separately.+- Any change to `handle_tool_call()`: the `bridge is None -> BridgeError` guard stays.+- Changes to the MEMORY_TOOLS allowlist itself.++## Chosen approach++Variant 1 from the consultant round: hand-vendored static schema literals in a+dedicated stdlib-only module, guarded against drift by a live-server comparison test.+The static copies are mechanically transcribed from the current `tools/list` output+(all 10 MEMORY_TOOLS are present on the live server, verified 2026-06-07), so the+initial copies are exact. The provider treats the static set strictly as a fallback:+once the bridge is up, live schemas win.++## Design decisions++- **Separate `_schemas.py` module, not inline in `provider.py`**: the literals are+ ~200 lines of data; keeping them out of the orchestrator preserves single+ responsibility (SRP) and keeps `provider.py` reviewable.+- **Static fallback also covers a failed live listing** (bridge present but+ `list_tools()` raises): Hermes built its routing table from the static names at+ registration; returning `[]` later would hide the tools from the model while the+ routing still exists. Returning the static set keeps both surfaces consistent and+ is strictly more useful than an empty list. The post-init schema collection then+ matches the registration-time name set in every failure mode.+- **Accessor returns deep copies** (`static_tool_schemas()`): Hermes and tests may+ mutate the returned dicts; the module-level literals must stay pristine.+- **Anti-drift compares only the embedded fields** (name, description, inputSchema):+ the live server may add sibling keys (annotations, outputSchema) without breaking+ the provider contract; comparing the embedded projection keeps the test signal+ precise.+- **Anti-drift test is environment-gated, not mocked**: its whole value is catching+ real divergence between `_schemas.py` and the TS core; it skips (with a visible+ reason) when `o2b`/Bun is unavailable, and CI has Bun so it runs there.+- **`handle_tool_call()` unchanged**: by the time the model can call a tool,+ `initialize()` has already run; a pre-init call is a programming error and keeps+ raising `BridgeError`.++## File changes++- New: `plugins/hermes/_schemas.py` (static literals + `static_tool_schemas()` accessor).+- Modified: `plugins/hermes/provider.py` (`get_tool_schemas()` fallback path only).+- Modified: `tests/python/test_memory_provider.py` (unit tests for fallback + ordering).+- New: `tests/python/test_static_schemas.py` (integrity + anti-drift against live `o2b mcp`).+- Modified: `CHANGELOG.md`, `install/hermes.md`.++## Risks and open questions++- The anti-drift test spawns a real subprocess; it needs a hard timeout so a hung+ server cannot stall the suite. Mitigation: bounded reader with `timeout` and+ `skipTest` on spawn failure.+- If the TS core later renames or removes a MEMORY_TOOLS tool, the anti-drift test+ fails loudly in CI - that is the intended behavior, not a flake.+- Schema size: 10 embedded schemas add a few KB to the shim; no runtime cost beyond+ one import.diff --git a/docs/brainstorm/hermes-static-tool-schemas/plan.md b/docs/brainstorm/hermes-static-tool-schemas/plan.mdnew file mode 100644index 00000000..a9f07787--- /dev/null+++ b/docs/brainstorm/hermes-static-tool-schemas/plan.md@@ -0,0 +1,38 @@+# Static tool schemas for the Hermes memory provider - implementation plan++## Tasks++### Task 1: Vendored static schemas module+- **Files**: `plugins/hermes/_schemas.py` (new), `tests/python/test_static_schemas.py` (new)+- **Acceptance**: failing-first unit tests pass: every `MEMORY_TOOLS` name has exactly one+ static schema (bijection, no extras), each entry carries non-empty `name`,+ `description`, and an object-typed `inputSchema`; `static_tool_schemas()` returns+ deep copies (mutating a returned dict does not affect a second call).+- **Depends on**: none++### Task 2: `get_tool_schemas()` static fallback+- **Files**: `plugins/hermes/provider.py`, `tests/python/test_memory_provider.py`+- **Acceptance**: failing-first tests pass: (a) `get_tool_schemas()` BEFORE+ `initialize()` returns the full curated set; (b) after `initialize()` the name set is+ identical (live schemas win); (c) when the bridge raises on `list_tools()` the static+ set is returned instead of `[]`; (d) Hermes-ordering end-to-end with+ `FakeBrainBridge`: routing table built from pre-init schemas contains the tool, the+ post-init `handle_tool_call()` through that table succeeds; (e) the pre-init+ `handle_tool_call()` guard still raises `BridgeError`.+- **Depends on**: Task 1++### Task 3: Anti-drift test against the live server+- **Files**: `tests/python/test_static_schemas.py`+- **Acceptance**: a test spawns `o2b mcp`, performs the MCP handshake, fetches+ `tools/list`, and asserts that for every `MEMORY_TOOLS` name the live+ (name, description, inputSchema) projection equals the static copy. Skips with a+ visible reason when the `o2b` CLI / Bun runtime is unavailable or the handshake+ times out. Runs green locally against the live server.+- **Depends on**: Task 1++### Task 4: Docs and changelog+- **Files**: `CHANGELOG.md`, `install/hermes.md`+- **Acceptance**: CHANGELOG gains the next patch version entry describing the fix;+ `install/hermes.md` no longer implies tools appear only after initialization and+ mentions that the provider registers its curated tool set at gateway start.+- **Depends on**: Task 2, Task 3diff --git a/docs/brainstorm/hermes-static-tool-schemas/variants.md b/docs/brainstorm/hermes-static-tool-schemas/variants.mdnew file mode 100644index 00000000..500758b8--- /dev/null+++ b/docs/brainstorm/hermes-static-tool-schemas/variants.md@@ -0,0 +1,87 @@+# Variants audit trail - hermes-static-tool-schemas++Consultant: Claude Code CLI (`claude -p`), single pass, 2026-06-07.+Raw output: `cli-output/claude.md`. Prompt: `cli-output/prompt.md`.+Fallback consultant (Codex) not invoked - primary returned 3 parseable variants.++## Variant 1: Hand-authored static schema literals++- **Approach**: Embed the 10 MEMORY_TOOLS schemas (name, description, inputSchema) as a+ Python dict literal in a new module (e.g. `plugins/hermes/_schemas.py`).+ `get_tool_schemas()` returns these when `self._bridge is None`, and switches to the+ live-filtered list once the bridge is up. The anti-drift unittest spawns `o2b mcp`,+ fetches `tools/list`, and asserts the static literals match the live MEMORY_TOOLS+ subset by name and inputSchema.+- **Trade-offs**:+ - Pro: stdlib-only, zero import-time I/O, no Bun needed for the import path; the+ schemas are readable and reviewable in-tree.+ - Pro: trivially fail-soft - the static path can never block or throw at gateway boot.+ - Con: a second hand-maintained copy of schema text that can drift; relies entirely+ on the anti-drift test (skippable when Bun absent) to catch divergence.+ - Con: full inputSchema bodies are verbose to hand-transcribe and review.+- **Complexity**: small+- **Risk**: low++## Variant 2: Vendored JSON snapshot generated from the TS core++- **Approach**: Add a generator (a script / `bun`-backed step) that calls `o2b mcp`+ `tools/list`, filters to MEMORY_TOOLS, and writes a committed JSON artifact under+ `plugins/hermes/`. `get_tool_schemas()` loads this JSON (cached at import) when the+ bridge is not started. The anti-drift test regenerates into a temp file and asserts+ byte/structure equality with the committed snapshot.+- **Trade-offs**:+ - Pro: single authored source (TS core); the Python copy is mechanically derived, so+ drift is a regeneration step rather than manual editing.+ - Pro: the snapshot doubles as a documented contract artifact; full inputSchemas are+ exact, not transcribed.+ - Con: introduces a build/codegen step and a generated file that must be regenerated+ and committed on every schema change - easy to forget, and CI must enforce freshness.+ - Con: adds file-read I/O at import and a packaging concern (the JSON must ship with+ the shim).+- **Complexity**: medium+- **Risk**: medium++## Variant 3: Lazy eager-bridge fetch at schema-request time++- **Approach**: On the first `get_tool_schemas()` call while `self._bridge is None`,+ attempt a short, time-boxed synchronous bridge start to fetch live schemas, caching+ the result; if the start fails or times out, fall back to a minimal static+ name/description stub. No full static schema copy is maintained as the primary source.+- **Trade-offs**:+ - Pro: schemas always come from the live TS core when reachable - essentially no+ drift surface.+ - Pro: removes the need for a committed schema duplicate.+ - Con: risks the fail-soft contract - a synchronous start during gateway registration+ can block boot or surface Bun-unavailability into a hot path; needs careful+ timeout/guard handling.+ - Con: the fallback stub still ships incomplete inputSchemas, so the "N >= 1 with+ real schemas" guarantee degrades exactly when Bun is missing; harder to test+ deterministically with FakeBrainBridge alone.+- **Complexity**: medium+- **Risk**: high++## Consultant recommendation++Variant 1. "It is the smallest change that satisfies every acceptance criterion while+honoring the hard constraints - stdlib-only, fail-soft (the static path cannot block or+throw at boot), unchanged public signatures, and MEMORY_TOOLS as the single subset+source. The drift risk that distinguishes it from Variant 2 is precisely what the+required anti-drift test against live `o2b mcp` neutralizes, without paying Variant 2's+codegen/regeneration ceremony or Variant 3's fail-soft hazard during gateway+registration."++## Orchestrator decision++Agree with the consultant: **Variant 1**. Two project-context refinements on top:++1. The initial literals are transcribed mechanically from the live `tools/list`+ (verified 2026-06-07: all 10 MEMORY_TOOLS present on the 77-tool server), so the+ "verbose to hand-transcribe" con is paid once and exactly.+2. The static fallback also covers a failed live listing (bridge present but+ `list_tools()` raises), not only `bridge is None` - this keeps the post-init schema+ surface consistent with the registration-time routing table in every failure mode.++Variant 3 was rejected outright: starting the bridge inside `get_tool_schemas()` runs+during `add_provider()` at gateway boot, which directly violates the provider's+fail-soft contract. Variant 2's codegen ceremony buys exactness we already get from+Variant 1 plus the anti-drift test, at a higher maintenance cost.diff --git a/install/hermes.md b/install/hermes.mdindex d180064d..f6dc61c9 100644--- a/install/hermes.md+++ b/install/hermes.md@@ -95,6 +95,12 @@ hermes memory status`available ✓` once active. Run the daily-identity check described in`install/prerequisites.md`.+On a fresh gateway start the log shows+`Memory provider 'open-second-brain' registered (10 tools)` - the+provider advertises its curated `brain_*` tool set at registration+time, before the internal `o2b mcp` bridge starts. A `(0 tools)`+registration line indicates a version older than 1.0.1.+> A provider-specific `hermes open-second-brain` subcommand is not> surfaced on current Hermes. Use `hermes memory status` for provider> state and `o2b doctor` for the full readiness suite - together theydiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 0257c212..4a61d894 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "1.0.0",+ "version": "1.0.1","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 51247436..8793e003 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.0.0",+ "version": "1.0.1","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 3aaedbed..dfba1bde 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.0.0"+version: "1.0.1"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex dba6086f..91fe8328 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.0.0",+ "version": "1.0.1","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/_schemas.py b/plugins/hermes/_schemas.pynew file mode 100644index 00000000..4528ef62--- /dev/null+++ b/plugins/hermes/_schemas.py@@ -0,0 +1,375 @@+"""Vendored static schemas for the curated Hermes memory-tool surface.++Hermes builds its memory-tool routing table from ``get_tool_schemas()`` at+provider registration time, BEFORE ``initialize()`` starts the ``o2b mcp``+bridge. These vendored copies let the provider advertise its curated tools+while the bridge is not available yet; once the bridge is up, live schemas+from ``tools/list`` win.++Each entry is a verbatim (name, description, inputSchema) projection of the+live server's ``tools/list`` output. ``tests/python/test_static_schemas.py``+compares these copies against the live server (anti-drift), so edits here+that diverge from the TS core fail CI. To re-vendor after a schema change in+the TS core, copy the projection from a live ``o2b mcp`` ``tools/list``.++The copies mirror the live server exactly, including spots where the provider+relies on server-side coercion (e.g. ``brain_pre_compact_extract`` declares+``turn_start``/``turn_end`` as strings while ``_flush_buffer`` passes ints).+Do not "fix" such fields here; the server is the source of truth.+"""++from __future__ import annotations++import copy+from typing import Any++STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = (+ {'name': 'brain_feedback',+ 'description': 'Record one Brain taste signal in `Brain/inbox/sig-*.md`. With '+ '`force_confirmed: true`, create the preference directly (skips the dream '+ 'trial window).',+ 'inputSchema': {'type': 'object',+ 'properties': {'topic': {'type': 'string',+ 'description': 'Stable kebab-slug for the rule, e.g. '+ '`no-internal-abbrev`.'},+ 'signal': {'type': 'string',+ 'enum': ['positive', 'negative'],+ 'description': '`positive` when the principle is '+ 'the rule to follow, `negative` when '+ "it's what to avoid."},+ 'principle': {'type': 'string',+ 'description': 'One-line, agent-readable '+ 'formulation of the rule '+ '(imperative voice).'},+ 'scope': {'type': 'string',+ 'description': 'Optional soft category for later '+ 'application-scope matching, e.g. '+ '`writing`, `coding`.'},+ 'source': {'type': 'array',+ 'items': {'type': 'string'},+ 'description': 'Optional wikilinks to the artifacts '+ 'or notes that triggered the '+ 'signal.'},+ 'agent': {'type': 'string',+ 'description': 'Optional agent identity override; '+ 'defaults to the server-resolved '+ 'name.'},+ 'raw': {'type': 'string',+ 'description': 'Optional free-form raw quote (rendered '+ 'under `## Raw` in the signal file).'},+ 'force_confirmed': {'type': 'boolean',+ 'description': 'When true, also creates an '+ 'immediately-active '+ 'confirmed `pref-*` '+ 'alongside the inbox '+ 'signal, skipping the '+ 'dream-pass promotion '+ 'step.'}},+ 'required': ['topic', 'signal', 'principle'],+ 'additionalProperties': False}},+ {'name': 'brain_apply_evidence',+ 'description': 'Record whether an active preference was applied, violated, or marked outdated '+ 'against a freshly-produced durable artifact. Appends one event to '+ '`Brain/log/<today>.md`. A single `outdated` event triggers retire on the next '+ 'dream pass.',+ 'inputSchema': {'type': 'object',+ 'properties': {'pref_id': {'type': 'string',+ 'description': 'Preference id (`pref-<slug>` or '+ 'bare `<slug>`).'},+ 'artifact': {'type': 'string',+ 'description': 'Wikilink identifying the '+ 'artifact; optional inclusive '+ 'line-range suffix, e.g. '+ '`[[src/cli/main.ts:120-145]]`.'},+ 'result': {'type': 'string',+ 'enum': ['applied', 'violated', 'outdated'],+ 'description': '`applied` if the rule held, '+ '`violated` if broken, `outdated` if '+ 'the artifact shows the rule itself '+ 'is obsolete.'},+ 'agent': {'type': 'string',+ 'description': 'Optional agent identity override; '+ 'defaults to the server-resolved '+ 'name.'},+ 'outcome': {'type': 'string',+ 'enum': ['success', 'failure', 'unknown'],+ 'description': 'Optional downstream outcome of the '+ 'artifact (t_d478df53): did the '+ 'work the rule was applied to '+ 'actually succeed? `unknown` is '+ 'treated like an absent outcome.'},+ 'note': {'type': 'string',+ 'description': 'Optional one-line context.'}},+ 'required': ['pref_id', 'artifact', 'result'],+ 'additionalProperties': False}},+ {'name': 'brain_note',+ 'description': 'Append one narrative-milestone line (release shipped, PR merged, fact '+ "discovered) to today's Brain log under the `note` event kind. Use when "+ 'neither brain_feedback nor brain_apply_evidence fits.',+ 'inputSchema': {'type': 'object',+ 'properties': {'text': {'type': 'string',+ 'description': 'One-line narrative description. '+ 'Newlines collapse to single spaces; '+ 'the shared redactor strips '+ 'secret-shaped tokens.'},+ 'agent': {'type': 'string',+ 'description': 'Optional agent identity override; '+ 'defaults to the server-resolved '+ 'name.'}},+ 'required': ['text'],+ 'additionalProperties': False}},+ {'name': 'brain_pinned_context',+ 'description': 'Read, write, append, or clear the transient current-task scratchpad at '+ '`Brain/pinned.md`. Use for facts that should survive context rotation but '+ 'should not become permanent preferences.',+ 'inputSchema': {'type': 'object',+ 'properties': {'operation': {'type': 'string',+ 'enum': ['read', 'write', 'append', 'clear'],+ 'description': 'Operation to perform. Defaults '+ 'to read.'},+ 'content': {'type': 'string',+ 'description': 'Pinned context body for '+ 'write/append operations.'}},+ 'additionalProperties': False}},+ {'name': 'brain_query',+ 'description': 'Read-only lookup: one preference + its evidence trail, all artifacts under a '+ 'topic, or every log event after a timestamp. Exactly one of `preference`, '+ '`topic`, `since` must be supplied.',+ 'inputSchema': {'type': 'object',+ 'properties': {'preference': {'type': 'string',+ 'description': 'Preference id (`pref-...` or '+ '`ret-...`) to look up with its '+ 'evidence trail.'},+ 'topic': {'type': 'string',+ 'description': 'Topic slug to aggregate signals + '+ 'active/retired preference + log '+ 'events.'},+ 'since': {'type': 'string',+ 'description': 'ISO-8601 timestamp; returns every '+ 'Brain log event with timestamp >= '+ 'since.'},+ 'format': {'type': 'string',+ 'enum': ['markdown', 'json'],+ 'description': 'Reserved for forward-compat; the '+ 'structured response is the same '+ 'regardless.'},+ 'telemetry': {'type': 'boolean',+ 'description': 'Opt-in recall telemetry: emit '+ 'one continuity record (mode '+ "'query', kind-only payload) for "+ 'this call.'},+ 'telemetry_host': {'type': 'string', 'maxLength': 200},+ 'session_id': {'type': 'string', 'maxLength': 512},+ 'turn_id': {'type': 'string', 'maxLength': 512}},+ 'additionalProperties': False}},+ {'name': 'brain_search',+ 'description': 'Full-text search across the vault. Optional semantic layer when configured. '+ 'Read-only.',+ 'inputSchema': {'type': 'object',+ 'properties': {'query': {'type': 'string', 'minLength': 1, 'maxLength': 2000},+ 'query_document': {'type': 'string',+ 'minLength': 1,+ 'maxLength': 4000},+ 'focus_query': {'type': 'string',+ 'minLength': 1,+ 'maxLength': 1000},+ 'focus_path_prefix': {'type': 'string',+ 'minLength': 1,+ 'maxLength': 256},+ 'focus_session': {'type': 'string',+ 'minLength': 1,+ 'maxLength': 128,+ 'description': 'Session id whose bound focus '+ 'applies (falls back to the '+ 'global focus).'},+ 'evidence_pack': {'type': 'boolean'},+ 'include_superseded': {'type': 'boolean',+ 'description': 'History mode for '+ 'relation polarity: keep '+ 'matched superseded '+ 'predecessors undemoted '+ 'and skip successor '+ 'pull-in. Default '+ 'false.'},+ 'since': {'type': 'string',+ 'maxLength': 64,+ 'description': 'Time-aware recall: only documents '+ 'modified at/after this point. ISO '+ "date/datetime, 'today', 'yesterday', "+ "'last week', 'last month', or "+ '<n>h/<n>d/<n>w.'},+ 'until': {'type': 'string',+ 'maxLength': 64,+ 'description': 'Time-aware recall: only documents '+ 'modified at/before this point. Same '+ "forms as 'since'."},+ 'limit': {'type': 'integer', 'minimum': 1, 'maximum': 50},+ 'semantic': {'type': 'boolean'},+ 'keyword_only': {'type': 'boolean'},+ 'record_access': {'type': 'boolean',+ 'description': 'Record the surfaced paths as '+ 'one activation access event '+ '(feeds the usage-aware '+ 'ranking layer). Default '+ 'true; never recorded for '+ 'global searches.'},+ 'global': {'type': 'boolean',+ 'description': 'Cross-vault union: search profile '+ 'vaults and read-only recall sources '+ 'too, merging results with origin '+ 'labels. Default false (active vault '+ 'only).'},+ 'path_prefix': {'type': 'string', 'maxLength': 256},+ 'telemetry': {'type': 'boolean'},+ 'telemetry_host': {'type': 'string', 'maxLength': 200},+ 'session_id': {'type': 'string', 'maxLength': 512},+ 'turn_id': {'type': 'string', 'maxLength': 512},+ 'properties': {'type': 'object',+ 'description': 'Optional frontmatter property '+ 'filter (v0.10.17). Each key '+ 'maps to one or more accepted '+ 'scalar values; multi-value '+ 'within a key is OR, multiple '+ 'keys is AND.',+ 'additionalProperties': {'type': 'array',+ 'items': {'type': 'string'}}},+ 'visibility': {'type': 'array',+ 'description': 'Optional content-visibility '+ 'scope; untagged pages always '+ 'match, tagged pages only when '+ 'this scope includes one of '+ 'their values.',+ 'items': {'type': 'string'}}},+ 'required': ['query'],+ 'additionalProperties': False}},+ {'name': 'brain_recall_gate',+ 'description': 'Classify whether an automatic recall/surfacing attempt should run. '+ 'Diagnostics only; does not search.',+ 'inputSchema': {'type': 'object',+ 'properties': {'prompt': {'type': 'string', 'minLength': 1, 'maxLength': 4000},+ 'previous_prompt': {'type': 'string', 'maxLength': 4000},+ 'explicit': {'type': 'boolean'},+ 'telemetry_host': {'type': 'string', 'maxLength': 200},+ 'session_id': {'type': 'string', 'maxLength': 512}},+ 'required': ['prompt'],+ 'additionalProperties': False}},+ {'name': 'brain_context',+ 'description': 'Pull the current Brain/active.md body, pinned current-task context, and '+ 'active-preference counts. Use at session start when SessionStart hook is '+ 'unavailable (Cursor, Aider, raw Claude API). Read-only.',+ 'inputSchema': {'type': 'object', 'properties': {}, 'additionalProperties': False}},+ {'name': 'brain_context_pack',+ 'description': 'Return the highest-tier, most recent vault slice that fits under '+ '`max_tokens`. Ordered core → supporting → peripheral, newest first; stops '+ 'adding pages when the next page would exceed the budget. Read-only.',+ 'inputSchema': {'type': 'object',+ 'properties': {'max_tokens': {'type': 'integer',+ 'minimum': 1,+ 'description': 'Strict upper bound on the '+ "returned slice's token count."},+ 'query': {'type': 'string',+ 'description': 'Optional case/Unicode-insensitive '+ 'substring filter on topic + '+ 'principle.'},+ 'focus_session': {'type': 'string',+ 'minLength': 1,+ 'maxLength': 128,+ 'description': 'Session id whose bound '+ 'search focus boosts matching '+ 'memories (requires '+ 'search_focus_context_pack).'},+ 'max_chars_per_memory': {'type': 'integer',+ 'minimum': 1,+ 'description': 'Optional per-page '+ 'character cap so one '+ 'huge page cannot '+ 'crowd out the rest; '+ 'trimmed pages carry '+ '`trimmed: true`.'},+ 'max_total_chars': {'type': 'integer',+ 'minimum': 1,+ 'description': 'Optional second ceiling '+ '(code points) on the '+ 'cumulative size of the '+ 'returned slice. '+ 'Lowest-priority overflow '+ 'is dropped with an '+ '`over-char-budget` skip '+ 'reason.'},+ 'lanes': {'type': 'boolean',+ 'description': 'When true, also return '+ 'polarity-aware directives, '+ 'constraints, and consider lanes. '+ 'Legacy flat `items` remains '+ 'present.'},+ 'cache_stable': {'type': 'boolean',+ 'description': 'When true, reorder the '+ 'selected items by stable id '+ 'and annotate their original '+ 'rank.'},+ 'dedup_repeated': {'type': 'boolean',+ 'description': 'When true, replace repeated '+ 'context bodies with '+ 'reference hints to an '+ 'earlier emitted item.'},+ 'attention_flow_ids': {'type': 'array',+ 'items': {'type': 'string'},+ 'description': 'Optional declarative '+ 'attention flow ids to '+ 'inject as a synthetic '+ 'context block.'},+ 'receipt': {'type': 'boolean',+ 'description': 'When true, emit an opt-in context '+ 'receipt for this context-pack '+ 'run.'},+ 'receipt_host': {'type': 'string',+ 'description': 'Optional host/runtime name '+ 'for emitted receipts; '+ 'defaults to `mcp`.'},+ 'telemetry': {'type': 'boolean',+ 'description': 'When true, emit an opt-in recall '+ 'telemetry record for this '+ 'context-pack run.'},+ 'telemetry_host': {'type': 'string',+ 'description': 'Optional host/runtime name '+ 'for emitted telemetry; '+ 'defaults to `mcp`.'},+ 'session_id': {'type': 'string',+ 'description': 'Optional session id recorded on '+ 'emitted telemetry.'},+ 'turn_id': {'type': 'string',+ 'description': 'Optional turn id recorded on '+ 'emitted telemetry.'}},+ 'required': ['max_tokens'],+ 'additionalProperties': False}},+ {'name': 'brain_pre_compact_extract',+ 'description': 'Extract typed Decision/Commitment/Outcome/Rule/Open question records from '+ 'bounded text into continuity storage.',+ 'inputSchema': {'type': 'object',+ 'properties': {'session_id': {'type': 'string',+ 'description': 'Session identifier used for '+ 'idempotency and source refs.'},+ 'turn_start': {'type': 'string',+ 'description': 'First source turn id in the '+ 'extracted segment.'},+ 'turn_end': {'type': 'string',+ 'description': 'Last source turn id in the '+ 'extracted segment.'},+ 'text': {'type': 'string',+ 'description': 'Bounded text segment to scan for '+ 'labeled extraction lines.'},+ 'host': {'type': 'string',+ 'description': 'Optional host/client label.'},+ 'max_chars': {'type': 'integer',+ 'minimum': 1,+ 'description': 'Optional maximum input '+ 'characters to scan before '+ 'extracting.'}},+ 'required': ['session_id', 'turn_start', 'turn_end', 'text'],+ 'additionalProperties': False}},+)+++def static_tool_schemas() -> list[dict[str, Any]]:+ """Deep copies of the vendored schemas; callers may mutate freely."""+ return [copy.deepcopy(schema) for schema in STATIC_TOOL_SCHEMAS]diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 3aaedbed..dfba1bde 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.0.0"+version: "1.0.1"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/hermes/provider.py b/plugins/hermes/provider.pyindex b799cfa5..0971947f 100644--- a/plugins/hermes/provider.py+++ b/plugins/hermes/provider.py@@ -20,6 +20,7 @@ from typing import Anyfrom . import configfrom ._base import MemoryProvider+from ._schemas import static_tool_schemasfrom .bridge import BrainBridge, BridgeError, McpBrainBridge# Curated, memory-relevant subset of the full MCP tool surface. Schemas still@@ -94,13 +95,20 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):passdef get_tool_schemas(self) -> list[dict[str, Any]]:- """Return the memory-relevant subset of the server's advertised tools."""+ """Return the memory-relevant subset of the server's advertised tools.++ Hermes builds its tool routing table from this method at provider+ registration time, BEFORE ``initialize()`` starts the bridge. The+ vendored static schemas cover that window (and a failed live listing),+ so the provider never registers with zero tools; once the bridge is+ up, live schemas from ``tools/list`` win.+ """if self._bridge is None:- return []+ return static_tool_schemas()try:tools = self._bridge.list_tools()- except Exception: # noqa: BLE001 - no tools rather than a crash- return []+ except Exception: # noqa: BLE001 - static fallback rather than a crash+ return static_tool_schemas()return [t for t in tools if t.get("name") in MEMORY_TOOLS]def handle_tool_call(self, tool_name: str, args: dict[str, Any], **_kwargs: Any) -> Any:diff --git a/pyproject.toml b/pyproject.tomlindex cd44898d..b5918b46 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "1.0.0"+version = "1.0.1"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/tests/python/test_memory_provider.py b/tests/python/test_memory_provider.pyindex 9fb27544..fecdc7c2 100644--- a/tests/python/test_memory_provider.py+++ b/tests/python/test_memory_provider.py@@ -224,6 +224,71 @@ class ProviderRequiredSurfaceTests(unittest.TestCase):self.assertEqual(cfg.resolve_vault(), win)+class ProviderStaticSchemaFallbackTests(unittest.TestCase):+ """Hermes builds its tool routing table BEFORE initialize(); the provider+ must advertise the curated tool set from the very first+ get_tool_schemas() call, not only after the bridge is up."""++ def _curated_live_tools(self):+ return [+ {"name": name, "description": f"live {name}", "inputSchema": {"type": "object"}}+ for name in MEMORY_TOOLS+ ]++ def test_get_tool_schemas_before_initialize_returns_curated_set(self):+ provider = OpenSecondBrainMemoryProvider(bridge=FakeBrainBridge())+ schemas = provider.get_tool_schemas() # no initialize() yet+ self.assertEqual({s["name"] for s in schemas}, set(MEMORY_TOOLS))+ for schema in schemas:+ self.assertTrue(schema["description"])+ self.assertEqual(schema["inputSchema"].get("type"), "object")++ def test_get_tool_schemas_after_initialize_keeps_name_set(self):+ bridge = FakeBrainBridge(tools=self._curated_live_tools())+ provider = OpenSecondBrainMemoryProvider(bridge=bridge)+ before = {s["name"] for s in provider.get_tool_schemas()}+ provider.initialize("s", hermes_home="/tmp/hh")+ after = {s["name"] for s in provider.get_tool_schemas()}+ self.assertEqual(before, after)+ # Live schemas win once the bridge is up.+ self.assertTrue(+ all(s["description"].startswith("live ") for s in provider.get_tool_schemas())+ )++ def test_get_tool_schemas_falls_back_to_static_when_listing_fails(self):+ class _ListingFailsBridge(FakeBrainBridge):+ def list_tools(self):+ raise BridgeError("listing failed")++ provider = OpenSecondBrainMemoryProvider(bridge=_ListingFailsBridge())+ provider.initialize("s", hermes_home="/tmp/hh")+ names = {s["name"] for s in provider.get_tool_schemas()}+ self.assertEqual(names, set(MEMORY_TOOLS))++ def test_handle_tool_call_before_initialize_still_raises(self):+ provider = OpenSecondBrainMemoryProvider(bridge=FakeBrainBridge())+ with self.assertRaises(BridgeError):+ provider.handle_tool_call("brain_note", {"text": "early"})++ def test_hermes_registration_ordering_end_to_end(self):+ # Simulate MemoryManager.add_provider(): the routing table is built+ # from get_tool_schemas() BEFORE initialize_all() runs.+ bridge = FakeBrainBridge(+ tools=self._curated_live_tools(),+ results={"brain_note": {"ok": True}},+ )+ provider = OpenSecondBrainMemoryProvider(bridge=bridge)+ routing_table = {s["name"]: provider for s in provider.get_tool_schemas()}+ self.assertGreaterEqual(len(routing_table), 1) # "registered (N tools)", N >= 1+ self.assertIn("brain_note", routing_table)++ # initialize_all() runs after registration; the model then calls a tool.+ provider.initialize("sess-1", hermes_home="/tmp/hh")+ result = routing_table["brain_note"].handle_tool_call("brain_note", {"text": "hi"})+ self.assertEqual(result, {"ok": True})+ self.assertEqual(bridge.calls, [("brain_note", {"text": "hi"})])++class CliTests(unittest.TestCase):_ENV_KEYS = ("VAULT_AGENT_NAME", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG")diff --git a/tests/python/test_static_schemas.py b/tests/python/test_static_schemas.pynew file mode 100644index 00000000..c3b3853a--- /dev/null+++ b/tests/python/test_static_schemas.py@@ -0,0 +1,148 @@+"""Static tool schemas: integrity of the vendored copies and anti-drift.++The integrity tests are pure-Python and always run. The anti-drift test+spawns the live ``o2b mcp`` server and compares the vendored+(name, description, inputSchema) projection against ``tools/list``; it skips+with a visible reason when the CLI or the Bun runtime is unavailable, so unit+runs without the TS toolchain stay green while CI (which has Bun) enforces+the contract.+"""++from __future__ import annotations++import copy+import json+import shutil+import subprocess+import sys+import threading+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from plugins.hermes._schemas import STATIC_TOOL_SCHEMAS, static_tool_schemas # noqa: E402+from plugins.hermes.provider import MEMORY_TOOLS # noqa: E402++# Fields the provider vendors for each tool; the anti-drift comparison is+# limited to this projection so unrelated server-side additions (annotations,+# outputSchema) cannot break the contract test.+_EMBEDDED_FIELDS = ("name", "description", "inputSchema")++_HANDSHAKE_TIMEOUT = 30.0+++class StaticSchemaIntegrityTests(unittest.TestCase):+ def test_static_names_are_exactly_the_curated_set(self):+ self.assertEqual(+ {s["name"] for s in STATIC_TOOL_SCHEMAS},+ set(MEMORY_TOOLS),+ )+ self.assertEqual(len(STATIC_TOOL_SCHEMAS), len(MEMORY_TOOLS))++ def test_every_static_schema_is_complete(self):+ for schema in STATIC_TOOL_SCHEMAS:+ with self.subTest(tool=schema.get("name")):+ self.assertEqual(sorted(schema), sorted(_EMBEDDED_FIELDS))+ self.assertTrue(schema["name"])+ self.assertTrue(schema["description"])+ self.assertIsInstance(schema["inputSchema"], dict)+ self.assertEqual(schema["inputSchema"].get("type"), "object")++ def test_accessor_returns_deep_copies(self):+ first = static_tool_schemas()+ first[0]["inputSchema"]["properties"]["__mutated__"] = True+ first[0]["name"] = "mutated"+ second = static_tool_schemas()+ self.assertNotEqual(second[0]["name"], "mutated")+ self.assertNotIn("__mutated__", second[0]["inputSchema"]["properties"])+++def _live_memory_tool_projection() -> list[dict]:+ """Fetch tools/list from a live ``o2b mcp`` and project the curated subset."""+ proc = subprocess.Popen( # noqa: S603 - fixed argv, test-only+ ["o2b", "mcp"],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ text=True,+ bufsize=1,+ )+ # Deadline for the whole handshake: if the server stays alive but never+ # answers, the timer kills it, readline() sees EOF, and the caller skips.+ watchdog = threading.Timer(_HANDSHAKE_TIMEOUT, proc.kill)+ watchdog.start()+ try:+ def request(rid: int, method: str, params: dict) -> dict:+ assert proc.stdin is not None and proc.stdout is not None+ frame = {"jsonrpc": "2.0", "id": rid, "method": method, "params": params}+ proc.stdin.write(json.dumps(frame) + "\n")+ proc.stdin.flush()+ while True:+ line = proc.stdout.readline()+ if line == "":+ raise RuntimeError("unexpected EOF from o2b mcp")+ try:+ message = json.loads(line)+ except json.JSONDecodeError:+ continue+ if isinstance(message, dict) and message.get("id") == rid:+ if "error" in message:+ raise RuntimeError(str(message["error"]))+ return message.get("result") or {}++ request(+ 1,+ "initialize",+ {+ "protocolVersion": "2025-06-18",+ "capabilities": {},+ "clientInfo": {"name": "anti-drift-test", "version": "1"},+ },+ )+ assert proc.stdin is not None+ proc.stdin.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + "\n")+ proc.stdin.flush()+ tools = request(2, "tools/list", {}).get("tools", [])+ finally:+ watchdog.cancel()+ for stream in (proc.stdin, proc.stdout):+ if stream is not None:+ stream.close()+ proc.terminate()+ try:+ proc.wait(timeout=_HANDSHAKE_TIMEOUT)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait(timeout=_HANDSHAKE_TIMEOUT)+ return [+ {field: tool.get(field) for field in _EMBEDDED_FIELDS}+ for tool in tools+ if tool.get("name") in MEMORY_TOOLS+ ]+++class AntiDriftTests(unittest.TestCase):+ """The vendored schemas must match the live server, field by field."""++ def test_static_schemas_match_live_tools_list(self):+ if shutil.which("o2b") is None:+ self.skipTest("o2b CLI not on PATH; anti-drift needs the live server")+ try:+ live = _live_memory_tool_projection()+ except (OSError, RuntimeError) as exc:+ self.skipTest(f"live o2b mcp unavailable: {exc}")+ live_by_name = {t["name"]: t for t in live}+ self.assertEqual(set(live_by_name), set(MEMORY_TOOLS), "curated tool missing from live tools/list")+ for schema in STATIC_TOOL_SCHEMAS:+ with self.subTest(tool=schema["name"]):+ self.assertEqual(+ copy.deepcopy(schema),+ live_by_name[schema["name"]],+ "vendored schema drifted from the live server; "+ "re-vendor plugins/hermes/_schemas.py from `o2b mcp` tools/list",+ )+++if __name__ == "__main__":+ unittest.main()