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

fix: the flush that never landed (v1.45.1) (#158)

GMDD5929ea0099c415
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index da645427..70379f8d 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.45.0",
+ "version": "1.45.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.json
index 457167ff..f3788b5f 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.45.0",
+ "version": "1.45.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.md
index 3b9e5330..cafc6e70 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,17 @@ 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.45.1] - 2026-08-15
+
+### Fixed
+
+- **Every Hermes pre-compaction flush has been discarded at the boundary since 0.32.0.** `brain_pre_compact_extract` declares `turn_start` and `turn_end` as turn ids - strings - and the provider sent the buffer's integer offsets. The tool reads them with the argument reader that does not coerce, so the call was rejected with `-32602` before extraction ran; the lifecycle hook swallows bridge errors by design, so neither side said anything and the buffered turns were simply gone. The provider sends strings, which is what the sibling Aider bracket has always sent. Reported and fixed by @GMDD59 in #158.
+- The vendored schema copy carried a comment instructing the next reader to leave that mismatch alone, on the theory that the server coerced it. It does not, and the comment now says so.
+- A payload conformance suite drives the provider's lifecycle hooks and validates what actually crossed the bridge against the vendored schemas - required keys, declared types, enums, string bounds, and the closed property set - and fails when a hook stops calling out at all, because a flush that never happens is the failure mode being guarded. Nothing checked the shape of a provider-built payload before; the Hermes test double accepts anything, which is why a payload the real server always refused looked healthy in every run.
+- The anti-drift gate on the vendored schemas has been failing since 1.45.0, which reworded the `brain_recall_gate` `scores` description without re-vendoring the copy Hermes advertises before its bridge is up. Re-vendored.
+- **A starter vault went stale ninety days after the bundle was authored.** The dropped bundle carries a fictional five-day history with fixed May 2026 dates, one of them the evidence behind a `pinned` preference, so from 13 August 2026 on every vault initialised with `--starter` reported `pinned-without-recent-evidence` on its first `o2b brain doctor` run. The bundle is now aged to the day it is dropped: every date moves by the same whole number of days, so the trial window still open, the evidence two days back and the retired entries months behind all survive the move, and the starter is clean whenever it is installed rather than for one quarter after it was written. `bootstrapBrain`'s `now` seam, reserved for exactly this and until now unused, is what the tests pin it with.
+- A test that deletes `OPEN_SECOND_BRAIN_CONFIG` from the real process environment never put it back, and every test file the runner ordered after it lost the hermetic default the suite's preload installs. On a developer machine the fallback to a real `~/.config/open-second-brain/config.yaml` hid it completely; on a bare runner it was forty-two failures or four, depending on where the ordering landed, and it turned the suite's verdict into a function of the machine it ran on.
+
## [1.45.0] - 2026-08-10
Eight units on one seam: what this system does when it cannot answer. A check that could not run reported the same thing as a check that passed. An archive that omitted a file reported the same thing as one that contained it. A search over a stale index returned the same nothing as a search over a complete one. A rule dropped under budget pressure was reported as dropped without saying which rule. A finding an operator had judged benign had no state meaning benign, only a seven-day timer. A retired preference left every decision built on it looking current.
@@ -6943,6 +6954,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.45.1]: https://github.com/itechmeat/open-second-brain/compare/v1.45.0...v1.45.1
[1.45.0]: https://github.com/itechmeat/open-second-brain/compare/v1.44.1...v1.45.0
[1.44.1]: https://github.com/itechmeat/open-second-brain/compare/v1.44.0...v1.44.1
[1.44.0]: https://github.com/itechmeat/open-second-brain/compare/v1.43.0...v1.44.0
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index d0aa4b3c..16b4c0d6 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.45.0",
+ "version": "1.45.1",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index b6dfd0ad..1758c857 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.45.0",
+ "version": "1.45.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.yaml
index 5afe9c5f..3eebfcf0 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.45.0"
+version: "1.45.1"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index e7b0f41a..fd0c3495 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.45.0",
+ "version": "1.45.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.py
index 57e181e2..49024be7 100644
--- a/plugins/hermes/_schemas.py
+++ b/plugins/hermes/_schemas.py
@@ -12,10 +12,11 @@ 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.
+The copies mirror the live server exactly. Do not "fix" a field here because
+the provider disagrees with it: the server is the source of truth, it does not
+coerce, and a payload whose type diverges is rejected with ``-32602`` before
+the tool body runs. Provider-built payloads are checked against these copies
+by ``ProviderPayloadConformanceTests`` in the same suite.
"""
from __future__ import annotations
@@ -386,11 +387,12 @@ STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = (
'scores': {'type': 'array',
'maxItems': 200,
'items': {'type': 'number'},
- 'description': 'Optional top-k recall relevance '
- 'scores. When given, the gate adds '
+ 'description': 'Optional top-k recall scores. Adds '
'an adequacy verdict: '
'sufficient/proceed, weak/re_recall, '
- 'or insufficient/abstain.'}},
+ 'insufficient/abstain. An empty '
+ 'array adds the negative '
+ 'verdict.'}},
'required': ['prompt'],
'additionalProperties': False}},
{'name': 'brain_context',
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 5afe9c5f..3eebfcf0 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.45.0"
+version: "1.45.1"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/hermes/provider.py b/plugins/hermes/provider.py
index c90c8be1..79426300 100644
--- a/plugins/hermes/provider.py
+++ b/plugins/hermes/provider.py
@@ -552,10 +552,15 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
if not turns:
return
text = "\n\n".join(f"User: {u}\nAssistant: {a}" for u, a in turns)
+ # Turn bounds are turn *ids* on the server contract, so they go over as
+ # strings — the tool reads them with `requiredStringArg`, which does not
+ # coerce, and `_safe_call` swallows the `-32602` it raises. Sending ints
+ # here loses the whole flushed segment with nothing on either side
+ # saying so. Matches the sibling Aider bracket, which also sends "0".
args: dict[str, Any] = {
"session_id": self._session_id or "hermes",
- "turn_start": 0,
- "turn_end": len(turns),
+ "turn_start": "0",
+ "turn_end": str(len(turns)),
"text": text,
}
if interrupted:
diff --git a/pyproject.toml b/pyproject.toml
index c27c0a20..b7b22722 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.45.0"
+version = "1.45.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/src/core/brain/init.ts b/src/core/brain/init.ts
index 459cc11d..40985112 100644
--- a/src/core/brain/init.ts
+++ b/src/core/brain/init.ts
@@ -20,7 +20,15 @@
* never a torn hybrid.
*/
-import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
+import {
+ cpSync,
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ renameSync,
+ statSync,
+} from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -60,6 +68,106 @@ export class BrainStarterError extends Error {
export interface CopyStarterOptions {
/** Override the source directory; defaults to the bundled `templates/brain-starter/`. */
readonly starterPath?: string;
+ /**
+ * Instant the dropped bundle is aged to; defaults to the wall clock.
+ * Passing the bundle's own anchor day reproduces the source bytes
+ * exactly, which is what the fixed-`--now` tests rely on.
+ */
+ readonly now?: Date;
+}
+
+const DAY_MS = 86_400_000;
+const DATE_RE = /\d{4}-\d{2}-\d{2}/g;
+
+/**
+ * The bundle's authored "today": the newest day in its `log/`.
+ *
+ * Read from the bundle rather than declared next to it, because a
+ * constant here is one the next person to extend the log has to
+ * remember to move, and nothing would fail if they did not.
+ * Returns null for a bundle with no dated log day - a custom
+ * `starterPath` in a test, typically - and such a bundle is copied
+ * verbatim.
+ */
+function starterAnchorDay(src: string): string | null {
+ let newest: string | null = null;
+ let entries: string[];
+ try {
+ entries = readdirSync(join(src, "log"));
+ } catch {
+ return null;
+ }
+ for (const name of entries) {
+ const day = /^(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1];
+ if (day !== undefined && (newest === null || day > newest)) newest = day;
+ }
+ return newest;
+}
+
+function shiftDay(day: string, days: number): string {
+ const shifted = new Date(`${day}T00:00:00Z`).getTime() + days * DAY_MS;
+ return new Date(shifted).toISOString().slice(0, 10);
+}
+
+/**
+ * Age one copied entry in place, descending into it when it is a
+ * directory. The copy above is recursive, so a custom `starterPath` may
+ * put a subtree under a starter target and reading it as a file would
+ * fail the whole install with `EISDIR`. Only Markdown bodies are
+ * rewritten - a starter target holds Brain notes, and a bundle that
+ * smuggled a binary in should come back out with its bytes intact.
+ */
+function ageStarterEntry(abs: string, days: number): void {
+ if (statSync(abs).isDirectory()) {
+ for (const child of readdirSync(abs)) {
+ const childAbs = join(abs, child);
+ ageStarterEntry(childAbs, days);
+ const moved = child.replace(DATE_RE, (d) => shiftDay(d, days));
+ if (moved !== child) renameSync(childAbs, join(abs, moved));
+ }
+ return;
+ }
+ if (!abs.endsWith(".md")) return;
+ atomicWriteFileSync(
+ abs,
+ readFileSync(abs, "utf8").replace(DATE_RE, (d) => shiftDay(d, days)),
+ );
+}
+
+/**
+ * Age the copied bundle so its history ends on the day it was dropped.
+ *
+ * The bundle carries a fictional five-day history with fixed dates, and
+ * one of its preferences is `pinned`. Left as authored, that pin passed
+ * `stale_evidence_days` ninety days after the bundle was written and
+ * every vault initialised after that woke up with a doctor warning on
+ * its first run - a bundle that is only clean for one quarter is not a
+ * starting point. Every date moves by the same whole number of days, so
+ * every interval the bundle demonstrates - the trial window still open,
+ * the evidence two days back, the retired entries months behind -
+ * survives the move exactly.
+ */
+function ageStarterCopy(
+ vault: string,
+ copied: ReadonlyArray<string>,
+ days: number,
+): ReadonlyArray<string> {
+ if (days === 0) return copied;
+ const renamed: string[] = [];
+ for (const rel of copied) {
+ const abs = join(vault, rel);
+ ageStarterEntry(abs, days);
+ const name = basename(rel);
+ const moved = name.replace(DATE_RE, (d) => shiftDay(d, days));
+ if (moved === name) {
+ renamed.push(rel);
+ continue;
+ }
+ const target = join(dirname(rel), moved);
+ renameSync(abs, join(vault, target));
+ renamed.push(target);
+ }
+ return Object.freeze(renamed);
}
export interface StarterBundleResult {
@@ -149,16 +257,25 @@ export function copyStarterBundle(
copied.push(join(BRAIN_ROOT_REL, sub, name));
}
}
- return Object.freeze({ copied });
+ const anchor = starterAnchorDay(src);
+ const today = (opts.now ?? new Date()).toISOString().slice(0, 10);
+ const days =
+ anchor === null
+ ? 0
+ : Math.round(
+ (new Date(`${today}T00:00:00Z`).getTime() - new Date(`${anchor}T00:00:00Z`).getTime()) /
+ DAY_MS,
+ );
+ return Object.freeze({ copied: ageStarterCopy(vault, copied, days) });
}
export interface BootstrapBrainOptions {
/** Overwrite `_brain.yaml` and `_BRAIN.md` if they already exist. */
readonly force?: boolean;
/**
- * Injection seam for deterministic tests. Currently unused in the
- * rendered output (templates carry static text), but reserved so
- * future timestamped substitutions stay test-friendly.
+ * Injection seam for deterministic tests. The rendered `_brain.yaml`
+ * and `_BRAIN.md` carry static text and ignore it; `--starter` ages
+ * the dropped bundle to this instant instead of the wall clock.
*/
readonly now?: Date;
/**
@@ -295,6 +412,7 @@ export function bootstrapBrain(
if (opts.starter === true) {
const starterResult = copyStarterBundle(vault, {
starterPath: opts.starterPath,
+ ...(opts.now !== undefined ? { now: opts.now } : {}),
});
created.push(...starterResult.copied);
}
diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.ts
index 5452d4d8..ff7bf1e8 100644
--- a/tests/core/architecture/write-site-census.test.ts
+++ b/tests/core/architecture/write-site-census.test.ts
@@ -633,11 +633,13 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object
// --- Bulk subtree transfer ---------------------------------------------
"src/core/brain/init.ts": {
categories: [C.archiveTransfer],
- calls: ["cpSync"],
+ calls: ["cpSync", "renameSync"],
reason:
"one recursive copy per bootstrap subdirectory into a destination the pre-check " +
"already proved empty. This is also the path that CREATES the tree, so it can " +
- "not be gated on anything the tree is about to contain.",
+ "not be gated on anything the tree is about to contain. The rename re-dates the " +
+ "starter bundle's own log filenames immediately after that copy, inside the same " +
+ "proven-empty destination.",
},
"src/core/brain/snapshot.ts": {
categories: [C.archiveTransfer, C.retentionDelete],
diff --git a/tests/core/brain/starter.test.ts b/tests/core/brain/starter.test.ts
index a1af7f66..4db189a6 100644
--- a/tests/core/brain/starter.test.ts
+++ b/tests/core/brain/starter.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -107,6 +107,39 @@ describe("copyStarterBundle", () => {
expect(readdirSync(join(vault, "Brain", "preferences"))).toEqual(["pref-x.md"]);
});
+ test("ages a custom bundle that nests a subtree instead of failing on it", () => {
+ // The copy is recursive, so a top-level entry can be a directory. Reading
+ // one as a file is `EISDIR` and would take the whole install down with it.
+ const vault = mkVault();
+ for (const sub of ["preferences", "retired", "inbox", "log"]) {
+ mkdirSync(join(vault, "Brain", sub), { recursive: true });
+ }
+ const custom = mkdtempSync(join(tmpdir(), "osb-starter-src-"));
+ tmpRoots.push(custom);
+ for (const sub of ["preferences", "retired", "inbox", "log"]) {
+ mkdirSync(join(custom, sub), { recursive: true });
+ }
+ mkdirSync(join(custom, "preferences", "2026-05-16-nested"), { recursive: true });
+ writeFileSync(join(custom, "log", "2026-05-16.md"), "---\ndate: 2026-05-16\n---\n");
+ writeFileSync(
+ join(custom, "preferences", "2026-05-16-nested", "pref-y.md"),
+ "---\nkind: brain-preference\nid: pref-y\ncreated_at: 2026-05-15T09:00:00Z\n---\n",
+ );
+
+ const result = copyStarterBundle(vault, {
+ starterPath: custom,
+ now: new Date("2026-05-18T00:00:00Z"),
+ });
+
+ // Anchor is the bundle's newest log day (05-16), so everything moves two
+ // days - the nested directory's own name included.
+ expect(result.copied).toContain(join("Brain", "log", "2026-05-18.md"));
+ expect(readdirSync(join(vault, "Brain", "preferences"))).toEqual(["2026-05-18-nested"]);
+ expect(
+ readFileSync(join(vault, "Brain", "preferences", "2026-05-18-nested", "pref-y.md"), "utf8"),
+ ).toContain("created_at: 2026-05-17T09:00:00Z");
+ });
+
test("rejects a starter path that does not exist", () => {
const vault = mkVault();
for (const sub of ["preferences", "retired", "inbox", "log"]) {
@@ -147,11 +180,45 @@ describe("bootstrapBrain --starter", () => {
test("dream is a no-op on the fresh starter at a fixed --now", () => {
const { vault, config } = withRegisteredConfig();
- bootstrapBrain(vault, { configPath: config, starter: true });
- const result = dream(vault, {
- now: new Date("2026-05-17T12:00:00Z"),
- dryRun: true,
- });
+ // Both instants are the bundle's own anchor day, so it is dropped
+ // with a zero shift - byte-identical to the authored source - and
+ // dream then reads it as of the same day the history ends on.
+ const now = new Date("2026-05-17T12:00:00Z");
+ bootstrapBrain(vault, { configPath: config, starter: true, now });
+ const result = dream(vault, { now, dryRun: true });
expect(result.changed).toBe(false);
});
+
+ test("the dropped bundle's history ends on the day it was dropped", () => {
+ // The authored bundle goes stale ninety days after it was written:
+ // a `pinned` preference whose evidence is fixed in May 2026 trips
+ // `pinned-without-recent-evidence` on every vault initialised from
+ // mid-August 2026 on. Ageing the copy is what keeps a freshly
+ // initialised Brain doctor-clean at any point in the future.
+ const { vault, config } = withRegisteredConfig();
+ const now = new Date("2027-11-02T08:30:00Z");
+ bootstrapBrain(vault, { configPath: config, starter: true, now });
+
+ const days = readdirSync(join(vault, "Brain", "log")).sort();
+ expect(days.at(-1)).toBe("2027-11-02.md");
+ // Five consecutive days of log, and the intervals inside the bundle
+ // are preserved rather than collapsed.
+ expect(days).toHaveLength(6);
+ expect(days[0]).toBe("2027-10-28.md");
+
+ const pinned = readFileSync(
+ join(vault, "Brain", "preferences", "pref-no-unexplained-abbreviations.md"),
+ "utf8",
+ );
+ expect(pinned).toContain('_last_evidence_at: "2027-10-31T10:05:00Z"');
+ expect(pinned).not.toContain("2026-05");
+
+ // Read as of the same instant it was installed at. Letting the wall
+ // clock in here would rebuild the time bomb this test exists to
+ // prove gone: the fixture would age past the freshness window and
+ // the assertion would fail on a date rather than on a regression.
+ const doctor = runDoctor(vault, { now });
+ expect(doctor.errors).toEqual([]);
+ expect(doctor.warnings).toEqual([]);
+ });
});
diff --git a/tests/core/config-path.test.ts b/tests/core/config-path.test.ts
index e336f772..30b1d6dd 100644
--- a/tests/core/config-path.test.ts
+++ b/tests/core/config-path.test.ts
@@ -55,11 +55,29 @@ describe("resolveDefaultConfigPath — supported platforms", () => {
test("the zero-argument form reads the real process and still resolves here", () => {
// This test process runs on a supported platform; the refusal must be
// unreachable for it, and the answer unchanged from before the branch.
+ //
+ // The two overrides are removed and PUT BACK. bun runs every test file in
+ // one process, so dropping `OPEN_SECOND_BRAIN_CONFIG` for good takes the
+ // hermetic default `tests/setup.ts` installs away from every file ordered
+ // after this one - which is invisible on a machine that has a real
+ // `~/.config/open-second-brain/config.yaml` to fall back on, and is 40-odd
+ // failures on a bare runner that does not.
+ const saved = {
+ config: process.env["OPEN_SECOND_BRAIN_CONFIG"],
+ xdg: process.env["XDG_CONFIG_HOME"],
+ };
delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
delete process.env["XDG_CONFIG_HOME"];
- expect(defaultConfigPath()).toBe(
- join(homedir(), ".config", "open-second-brain", "config.yaml"),
- );
+ try {
+ expect(defaultConfigPath()).toBe(
+ join(homedir(), ".config", "open-second-brain", "config.yaml"),
+ );
+ } finally {
+ if (saved.config === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = saved.config;
+ if (saved.xdg === undefined) delete process.env["XDG_CONFIG_HOME"];
+ else process.env["XDG_CONFIG_HOME"] = saved.xdg;
+ }
});
});
diff --git a/tests/python/test_memory_provider.py b/tests/python/test_memory_provider.py
index d3586b2d..1c4a0db5 100644
--- a/tests/python/test_memory_provider.py
+++ b/tests/python/test_memory_provider.py
@@ -560,6 +560,8 @@ class ProviderLifecycleTests(unittest.TestCase):
self.assertEqual(len(extract_calls), 1)
self.assertIn("u1", extract_calls[0]["text"])
self.assertIn("a2", extract_calls[0]["text"])
+ self.assertEqual(extract_calls[0]["turn_start"], "0")
+ self.assertEqual(extract_calls[0]["turn_end"], "2")
# Buffer cleared: a second flush makes no further extract call.
provider.on_session_end([])
self.assertEqual(
@@ -791,7 +793,7 @@ class InPlaceCompactionLifecycleTests(unittest.TestCase):
self.assertNotIn("u-t1", extract_calls[2]["text"])
# turn_end reflects the per-boundary buffer size (1), not a cumulative
# count — no unbounded growth across in-place compaction cycles.
- self.assertTrue(all(c["turn_end"] == 1 for c in extract_calls))
+ self.assertTrue(all(c["turn_end"] == "1" for c in extract_calls))
class _ScriptedReader:
diff --git a/tests/python/test_static_schemas.py b/tests/python/test_static_schemas.py
index 6847744e..9aef3ce5 100644
--- a/tests/python/test_static_schemas.py
+++ b/tests/python/test_static_schemas.py
@@ -12,9 +12,11 @@ from __future__ import annotations
import copy
import json
+import os
import shutil
import subprocess
import sys
+import tempfile
import threading
import unittest
from pathlib import Path
@@ -275,5 +277,228 @@ class ProviderNormalizeSurvivalTests(unittest.TestCase):
self.assertNotIn("inputSchema", entry)
+_JSON_TYPES: dict[str, tuple[type, ...]] = {
+ "string": (str,),
+ "integer": (int,),
+ "number": (int, float),
+ "boolean": (bool,),
+ "array": (list, tuple),
+ "object": (dict,),
+}
+
+
+def _type_matches(expected: str, value: object) -> bool:
+ """JSON-Schema type check with Python's bool/int overlap handled.
+
+ ``isinstance(True, int)`` is true in Python, and every numeric type accepts
+ a bool, so a naive check would pass a boolean off as an integer. JSON draws
+ the line where the server does, so this does too.
+ """
+ types = _JSON_TYPES.get(expected)
+ if types is None:
+ return True
+ if expected == "boolean":
+ return isinstance(value, bool)
+ if isinstance(value, bool):
+ return False
+ if expected == "integer":
+ return isinstance(value, int)
+ return isinstance(value, types)
+
+
+def schema_violations(schema: dict, args: dict) -> list[str]:
+ """Return every way ``args`` fails ``schema``; empty means conforming.
+
+ Deliberately narrow - required keys, declared types, enums, numeric and
+ string bounds, and the ``additionalProperties: false`` closure. That is the surface the
+ server's own argument readers enforce, and the surface a provider-built
+ payload can violate without anything saying so.
+ """
+ violations: list[str] = []
+ properties = schema.get("properties", {})
+ for key in schema.get("required", []):
+ if key not in args:
+ violations.append(f"missing required arg {key!r}")
+ if schema.get("additionalProperties") is False:
+ for key in args:
+ if key not in properties:
+ violations.append(f"unknown arg {key!r}")
+ for key, value in args.items():
+ declared = properties.get(key)
+ if not isinstance(declared, dict):
+ continue
+ expected = declared.get("type")
+ if isinstance(expected, str) and not _type_matches(expected, value):
+ violations.append(
+ f"{key!r} must be {expected}, got {type(value).__name__} ({value!r})"
+ )
+ enum = declared.get("enum")
+ if isinstance(enum, list) and value not in enum:
+ violations.append(f"{key!r} must be one of {enum}, got {value!r}")
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ low = declared.get("minimum")
+ if isinstance(low, (int, float)) and value < low:
+ violations.append(f"{key!r} is below minimum {low}, got {value!r}")
+ high = declared.get("maximum")
+ if isinstance(high, (int, float)) and value > high:
+ violations.append(f"{key!r} is above maximum {high}, got {value!r}")
+ if isinstance(value, str):
+ # The server's own string reader rejects a blank value outright, so
+ # a declared minLength of 1 is not the only way to fail here.
+ minimum = declared.get("minLength")
+ if len(value.strip()) == 0:
+ violations.append(f"{key!r} must be a non-empty string")
+ elif isinstance(minimum, int) and len(value) < minimum:
+ violations.append(f"{key!r} is shorter than minLength {minimum}")
+ maximum = declared.get("maxLength")
+ if isinstance(maximum, int) and len(value) > maximum:
+ violations.append(f"{key!r} is longer than maxLength {maximum}")
+ return violations
+
+
+class ProviderPayloadConformanceTests(unittest.TestCase):
+ """Payloads the provider BUILDS must satisfy the schema the server publishes.
+
+ The server does not coerce: `requiredStringArg` rejects a non-string with
+ `-32602` before the tool body runs, and `_safe_call` swallows that error so
+ a lifecycle hook cannot break a turn. A type mismatch on a provider-built
+ payload is therefore a silent, total loss of whatever that call carried,
+ with nothing on either side saying so. `brain_pre_compact_extract` shipped
+ exactly that shape - `turn_start`/`turn_end` sent as ints against a string
+ schema - so every buffered turn was dropped at the boundary.
+
+ Asserting on one payload's literal values would not have caught it; this
+ drives the lifecycle and validates what actually crossed the bridge.
+ """
+
+ _ENV_KEYS = ("VAULT_AGENT_NAME", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG")
+
+ # Tools the provider builds payloads for itself. `handle_tool_call` is
+ # excluded by construction: those args come from the model, so a violation
+ # there is the model's to fix and the server's to report.
+ _PROVIDER_BUILT = frozenset(
+ {
+ "brain_context",
+ "brain_recall_gate",
+ "brain_context_pack",
+ "brain_pre_compact_extract",
+ }
+ )
+
+ def setUp(self):
+ self._saved = {k: os.environ.pop(k, None) for k in self._ENV_KEYS}
+
+ def tearDown(self):
+ for k in self._ENV_KEYS:
+ os.environ.pop(k, None)
+ if self._saved[k] is not None:
+ os.environ[k] = self._saved[k]
+
+ @staticmethod
+ def _drive_lifecycle(home: str) -> list[tuple[str, dict]]:
+ """Run every provider hook that builds a payload; return the calls made."""
+ bridge = FakeBrainBridge(
+ results={
+ "brain_context": {"structuredContent": {"content": "ACTIVE PREFS"}},
+ "brain_recall_gate": {"structuredContent": {"retrieve": True}},
+ "brain_context_pack": {"content": [{"type": "text", "text": "RECALLED"}]},
+ "brain_pre_compact_extract": {"structuredContent": {}},
+ }
+ )
+ provider = OpenSecondBrainMemoryProvider(bridge=bridge)
+ provider.initialize("sess-1", hermes_home=home)
+ provider.system_prompt_block()
+ provider.prefetch("what did we decide", session_id="sess-1")
+ provider.sync_turn("u1", "a1", session_id="sess-1")
+ provider.sync_turn("u2", "a2", session_id="sess-1")
+ provider._drain_captures()
+ provider.on_pre_compress([])
+ provider.sync_turn("u3", "a3", session_id="sess-1")
+ provider._drain_captures()
+ provider.on_session_end([], interrupted=True)
+ return list(bridge.calls)
+
+ def test_every_provider_built_payload_conforms_to_its_vendored_schema(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ calls = self._drive_lifecycle(tmp)
+ schemas = {s["name"]: s["inputSchema"] for s in STATIC_TOOL_SCHEMAS}
+ exercised = set()
+ for name, args in calls:
+ schema = schemas.get(name)
+ if schema is None:
+ continue
+ exercised.add(name)
+ with self.subTest(tool=name):
+ self.assertEqual(
+ schema_violations(schema, args),
+ [],
+ f"{name} payload violates the vendored schema: {args!r}",
+ )
+ # Without this the test passes when a hook stops calling out entirely -
+ # a silent flush is the failure mode being guarded, so an unexercised
+ # path must fail here rather than read as a clean run.
+ self.assertEqual(exercised, self._PROVIDER_BUILT)
+
+ def test_the_flush_payload_carries_both_turn_bounds_as_strings(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ calls = self._drive_lifecycle(tmp)
+ flushes = [args for name, args in calls if name == "brain_pre_compact_extract"]
+ self.assertEqual(len(flushes), 2, "one flush per boundary that had buffered turns")
+ for args in flushes:
+ with self.subTest(turn_end=args.get("turn_end")):
+ self.assertIsInstance(args["turn_start"], str)
+ self.assertIsInstance(args["turn_end"], str)
+ # Per-boundary bounds, not cumulative: two turns then one.
+ self.assertEqual([a["turn_end"] for a in flushes], ["2", "1"])
+
+ def test_the_validator_catches_the_regression_it_guards(self):
+ # A guard that cannot fail is not a guard. This is the exact payload
+ # `_flush_buffer` used to send.
+ schema = next(
+ s["inputSchema"] for s in STATIC_TOOL_SCHEMAS if s["name"] == "brain_pre_compact_extract"
+ )
+ violations = schema_violations(
+ schema,
+ {"session_id": "s", "turn_start": 0, "turn_end": 2, "text": "User: u\nAssistant: a"},
+ )
+ self.assertEqual(len(violations), 2, violations)
+ self.assertTrue(any("turn_start" in v for v in violations))
+ self.assertTrue(any("turn_end" in v for v in violations))
+
+ def test_the_validator_catches_missing_and_unknown_args(self):
+ schema = next(
+ s["inputSchema"] for s in STATIC_TOOL_SCHEMAS if s["name"] == "brain_pre_compact_extract"
+ )
+ violations = schema_violations(schema, {"session_id": "s", "turn_start": "0", "typo": 1})
+ self.assertTrue(any("missing required arg 'turn_end'" in v for v in violations))
+ self.assertTrue(any("missing required arg 'text'" in v for v in violations))
+ self.assertTrue(any("unknown arg 'typo'" in v for v in violations))
+
+ def test_the_validator_does_not_pass_a_bool_off_as_a_number(self):
+ # Python's bool-is-int overlap is the one place a naive isinstance check
+ # would call a wrong payload conforming.
+ schema = next(
+ s["inputSchema"] for s in STATIC_TOOL_SCHEMAS if s["name"] == "brain_context_pack"
+ )
+ self.assertEqual(schema_violations(schema, {"max_tokens": 1024}), [])
+ self.assertTrue(schema_violations(schema, {"max_tokens": True}))
+ self.assertTrue(schema_violations(schema, {"max_tokens": 1024.5}))
+ self.assertEqual(schema_violations(schema, {"max_tokens": 1, "lanes": True}), [])
+ self.assertTrue(schema_violations(schema, {"max_tokens": 1, "lanes": 1}))
+
+ def test_the_validator_enforces_declared_numeric_bounds(self):
+ # `max_tokens` is `minimum: 1`. A zero budget is the right type and
+ # still a payload the server refuses.
+ schema = next(
+ s["inputSchema"] for s in STATIC_TOOL_SCHEMAS if s["name"] == "brain_context_pack"
+ )
+ violations = schema_violations(schema, {"max_tokens": 0})
+ self.assertTrue(any("below minimum 1" in v for v in violations), violations)
+ gate = next(
+ s["inputSchema"] for s in STATIC_TOOL_SCHEMAS if s["name"] == "brain_recall_gate"
+ )
+ self.assertTrue(schema_violations(gate, {"prompt": "x" * 4001}))
+
+
if __name__ == "__main__":
unittest.main()