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: reuse and reap Hermes MCP bridges (v1.44.1) (#156)

Dan Bennett34f96b842d36
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 8bea0c53..328c3613 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.44.0",
+ "version": "1.44.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 9885d9f7..5b87f700 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.44.0",
+ "version": "1.44.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/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 70f9018e..823a4d1e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -43,6 +43,21 @@ jobs:
- name: Verify manifest version sync
run: bun run sync-version:check
+ - name: OpenClaw bundle is in sync with sources
+ shell: bash
+ run: |
+ set -euo pipefail
+ # The release workflow has always checked this, but only on a tag -
+ # so a stale `openclaw/index.js` shipped to plugin users and turned
+ # the release job red two versions running before anyone looked.
+ # Checking it here fails the pull request that caused it instead.
+ bun build src/openclaw/index.ts \
+ --outfile /tmp/openclaw-rebuild.js \
+ --target=node --format=esm \
+ --external openclaw/plugin-sdk/plugin-entry
+ diff -q /tmp/openclaw-rebuild.js openclaw/index.js \
+ || { echo "openclaw/index.js is out of date; run: bun run build:openclaw" >&2; exit 1; }
+
- name: Broken-link ratchet
run: bun run link-ratchet:check
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7950fc78..3175b3b8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,15 @@ 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.44.1] - 2026-08-08
+
+### Fixed
+
+- **Reuse and reap Hermes MCP bridges.** A Hermes memory provider is constructed per agent while the MCP server is a gateway resource, so every new session spawned its own Bun child - and cache eviction released the client without shutting the provider down, so nothing reaped it. A long-lived backend accumulated processes and descriptors until it hit `EMFILE` and lost its listening socket. Providers now share one bridge per effective vault, repository and command; shutdown terminates, escalates, reaps and closes the child's pipes rather than only waiting on the process; a failed handshake no longer leaves its child alive; and POSIX children run under the host's parent-death watchdog so a hard gateway exit cannot orphan them. Reported and fixed by @DanBennettUK in #156.
+- One shared bridge is one stdio stream, so its calls are serialised - which makes a child that stops answering everyone's problem rather than one session's. Every request therefore carries a deadline, and a bridge that misses one is torn down and restarted rather than holding the gateway behind an unbounded read. There was no read timeout anywhere in this transport before, and with a bridge per session that was survivable; with a shared one it is not.
+- **The committed OpenClaw bundle was two releases stale, and the gate that would have said so only ran on a tag.** `openclaw/index.js` was last rebuilt at 1.37.0 while its source changed at 1.43.0, so the plugin bundle OpenClaw users install did not contain that release's quarantine filter - the release workflow failed on exactly this check for both 1.43.0 and 1.44.0 and skipped its publish job, which is why the releases were cut by hand and the breakage went unread. The bundle is rebuilt, and the same check now runs on every pull request so the change that staled it fails rather than the tag that ships it.
+- The parent-death watchdog is optional by construction - the host module may be absent in a standalone checkout - and its absence was silent, so descendant cleanup could disappear in a rename without a word. It says so now, once per process.
+
## [1.44.0] - 2026-08-08
Thirteen units on the retrieval path and the store beneath it. A reconnaissance pass ran before any design and falsified the load-bearing premise of nine of the eleven tasks in scope, and what survived had a shape none of the task descriptions predicted: with two exceptions these were not missing capabilities but values the system already computed and discarded before anything could see them, and checks that were never run at all. A structure recording which candidates were evaluated, surfaced and excluded was built on every gated search and serialized by nothing. A content hash had been on every chunk since the first schema version and was never read back. A match-centred snippet function was written, tested, and mounted on the wrong surface. An expiry filter took an as-of date as a parameter and no caller ever passed one. A ranker accepted an injected clock and the stage above it did not inject.
@@ -6886,6 +6895,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.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
[1.43.0]: https://github.com/itechmeat/open-second-brain/compare/v1.42.0...v1.43.0
[1.42.0]: https://github.com/itechmeat/open-second-brain/compare/v1.41.0...v1.42.0
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index e41c60c5..251147b1 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.44.0",
+ "version": "1.44.1",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/index.js b/openclaw/index.js
index 6f903543..d81d0ae6 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -1554,21 +1554,24 @@ var require_proper_lockfile = __commonJS((exports, module) => {
// src/openclaw/index.ts
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
-import { existsSync as existsSync4 } from "node:fs";
// src/core/config.ts
-import { mkdirSync, readFileSync } from "node:fs";
-var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
+import { mkdirSync, readFileSync, statSync as statSync2 } from "node:fs";
+var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
import { homedir } from "node:os";
-import { dirname, join } from "node:path";
+import { dirname, isAbsolute, join, resolve } from "node:path";
+
+// src/core/brain/portability/profiles.ts
+var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
// src/core/fs-utils.ts
-import { existsSync, statSync } from "node:fs";
-function isFile(p) {
- if (!existsSync(p))
- return false;
+import { statSync } from "node:fs";
+function statOrAbsent(p) {
+ return statSync(p, { throwIfNoEntry: false });
+}
+function isDir(p) {
try {
- return statSync(p).isFile();
+ return statOrAbsent(p)?.isDirectory() ?? false;
} catch {
return false;
}
@@ -1584,17 +1587,47 @@ var WIKI_LINK_FORMATS = Object.freeze([
"full",
"short"
]);
+var SUFFIX_INDEX_MEMO = new WeakMap;
// src/core/config.ts
var SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"];
-function defaultConfigPath() {
- const override = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+var UNSUPPORTED_CONFIG_PLATFORMS = Object.freeze(["win32"]);
+
+class UnsupportedPlatformError extends Error {
+ platform;
+ constructor(platform) {
+ super(`open-second-brain has no configuration layout for platform '${platform}': ` + "the default path $HOME/.config/open-second-brain/config.yaml is a POSIX " + "convention and this build does not implement the Windows one. Set " + "OPEN_SECOND_BRAIN_CONFIG to an explicit config file, or XDG_CONFIG_HOME " + "to a configuration root, to choose the location yourself.");
+ this.name = "UnsupportedPlatformError";
+ this.platform = platform;
+ }
+}
+
+class ConfigReadError extends Error {
+ path;
+ constructor(path, reason) {
+ super(`failed to read plugin config ${path}: ${reason}. The file is present, so its ` + "settings are NOT in force and are not read as absent; make it readable " + `(chmod u+r "${path}") or set OPEN_SECOND_BRAIN_CONFIG to a readable config file.`);
+ this.name = "ConfigReadError";
+ this.path = path;
+ }
+}
+function resolveDefaultConfigPath(source) {
+ const override = source.env["OPEN_SECOND_BRAIN_CONFIG"];
if (override)
return expandTilde(override);
- const xdg = process.env["XDG_CONFIG_HOME"];
+ const xdg = source.env["XDG_CONFIG_HOME"];
if (xdg)
return join(expandTilde(xdg), "open-second-brain", "config.yaml");
- return join(homedir(), ".config", "open-second-brain", "config.yaml");
+ if (UNSUPPORTED_CONFIG_PLATFORMS.includes(source.platform)) {
+ throw new UnsupportedPlatformError(source.platform);
+ }
+ return join(source.home, ".config", "open-second-brain", "config.yaml");
+}
+function defaultConfigPath() {
+ return resolveDefaultConfigPath({
+ platform: process.platform,
+ home: homedir(),
+ env: process.env
+ });
}
function parseSimpleYaml(text) {
const data = {};
@@ -1618,14 +1651,33 @@ function parseSimpleYaml(text) {
}
function discoverConfig(path) {
const resolved = path ?? defaultConfigPath();
- if (!isFile(resolved)) {
+ const stat = statConfigPath(resolved);
+ if (stat === undefined) {
return { path: resolved, exists: false, data: {} };
}
+ if (!stat.isFile()) {
+ throw new ConfigReadError(resolved, "path exists but is not a regular file");
+ }
+ return { path: resolved, exists: true, data: parseSimpleYaml(readConfigText(resolved)) };
+}
+function statConfigPath(resolved) {
try {
- const text = readFileSync(resolved, "utf8");
- return { path: resolved, exists: true, data: parseSimpleYaml(text) };
- } catch {
- return { path: resolved, exists: false, data: {} };
+ return statSync2(resolved, { throwIfNoEntry: false });
+ } catch (err) {
+ throw new ConfigReadError(resolved, err.message ?? String(err));
+ }
+}
+function readConfigText(resolved) {
+ let bytes;
+ try {
+ bytes = readFileSync(resolved);
+ } catch (err) {
+ throw new ConfigReadError(resolved, err.message ?? String(err));
+ }
+ try {
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
+ } catch (err) {
+ throw new ConfigReadError(resolved, `not valid UTF-8: ${err.message ?? String(err)}`);
}
}
function resolveAgentName(configPath) {
@@ -1658,9 +1710,24 @@ function expandTilde(p) {
return p;
}
+// src/core/vault-presence.ts
+function vaultUnexaminable(vault, err) {
+ const reason = err?.message ?? String(err);
+ return {
+ error: `cannot determine whether the vault directory ${vault} exists: ${reason}. ` + "It is NOT reported as absent - a path that cannot be examined is not a " + "path that is not there; make it and every parent directory traversable " + "(chmod u+rx), or set VAULT_DIR to a vault this process can read."
+ };
+}
+function probeVaultDirectory(vault) {
+ try {
+ return { present: statOrAbsent(vault)?.isDirectory() === true, unexaminable: null };
+ } catch (err) {
+ return { present: false, unexaminable: vaultUnexaminable(vault, err) };
+ }
+}
+
// src/core/doctor.ts
import {
- existsSync as existsSync3,
+ existsSync as existsSync2,
mkdirSync as mkdirSync2,
openSync,
readFileSync as readFileSync2,
@@ -1671,8 +1738,59 @@ import {
import { dirname as dirname3, join as join3 } from "node:path";
// src/core/partner/codegraph.ts
-import { existsSync as existsSync2, readdirSync, statSync as statSync2 } from "node:fs";
-import { dirname as dirname2, join as join2, resolve } from "node:path";
+import { existsSync, readdirSync, realpathSync } from "node:fs";
+import { dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";
+
+// src/core/partner/codegraph-health.ts
+function stripTrailingSlash(p) {
+ return p.replace(/\/+$/, "");
+}
+function samePath(a, b) {
+ return stripTrailingSlash(a) === stripTrailingSlash(b);
+}
+function assessGraphHealth(input) {
+ const warnings = [];
+ const nodes = Number.isFinite(input.nodeCount) ? input.nodeCount : 0;
+ const edges = Number.isFinite(input.edgeCount) ? input.edgeCount : 0;
+ if (nodes <= 0) {
+ warnings.push({
+ code: "empty-graph",
+ message: "index is initialized but holds 0 nodes; extraction produced an empty graph - " + "labeling and recall will find nothing until it is re-indexed"
+ });
+ } else if (edges <= 0) {
+ warnings.push({
+ code: "collapsed-edges",
+ message: `graph has ${nodes} node(s) but 0 edges; relationship extraction collapsed - ` + "callers/callees/impact traversal will be empty"
+ });
+ }
+ if (input.danglingRefs !== undefined && input.danglingRefs > 0) {
+ warnings.push({
+ code: "dangling-references",
+ message: `${input.danglingRefs} dangling reference(s): edges point at nodes absent from the ` + "index; derived labels/imports built from them would reference missing symbols"
+ });
+ }
+ if (input.selfLoops !== undefined && input.selfLoops > 0) {
+ warnings.push({
+ code: "self-loops",
+ message: `${input.selfLoops} self-loop edge(s): a node references itself; ` + "impact and traversal surfaces may double-count or cycle"
+ });
+ }
+ if (input.indexRoot && input.worktreeRoot && !samePath(input.indexRoot, input.worktreeRoot)) {
+ warnings.push({
+ code: "cache-root-mismatch",
+ message: `index was built for '${input.indexRoot}' but is being read from ` + `'${input.worktreeRoot}'; file and line references may be stale for this tree - ` + "re-index the current root before trusting graph-derived artifacts"
+ });
+ }
+ return { ok: warnings.length === 0, warnings };
+}
+function summarizeGraphHealth(report) {
+ if (report.warnings.length === 0)
+ return "ok";
+ const codes = report.warnings.map((w) => w.code).join(", ");
+ return `${report.warnings.length} warning(s) [${codes}]`;
+}
+
+// src/core/partner/codegraph.ts
var CODE_MANIFESTS = [
"package.json",
"pyproject.toml",
@@ -1685,20 +1803,13 @@ var CODE_MANIFESTS = [
"pom.xml"
];
var DEFAULT_LIMIT = 50;
-function isDir(path) {
- try {
- return statSync2(path).isDirectory();
- } catch {
- return false;
- }
-}
function isCodeProject(dir) {
try {
- if (!existsSync2(dir))
+ if (!existsSync(dir))
return false;
if (!isDir(join2(dir, ".git")))
return false;
- return CODE_MANIFESTS.some((m) => existsSync2(join2(dir, m)));
+ return CODE_MANIFESTS.some((m) => existsSync(join2(dir, m)));
} catch {
return false;
}
@@ -1711,7 +1822,7 @@ function findCodeProjects(opts) {
const consider = (raw) => {
if (scanned >= limit)
return;
- const path = resolve(raw);
+ const path = resolve2(raw);
if (seen.has(path))
return;
seen.add(path);
@@ -1722,7 +1833,7 @@ function findCodeProjects(opts) {
found.push(path);
};
consider(opts.cwd);
- const vaultParent = dirname2(resolve(opts.vault));
+ const vaultParent = dirname2(resolve2(opts.vault));
if (isDir(vaultParent)) {
let entries = [];
try {
@@ -1751,6 +1862,20 @@ function defaultWhichCodegraph() {
}
return null;
}
+var CODEGRAPH_PROJECT_PATH_USAGE_TOKEN = /\[path\]/;
+function defaultDetectProjectPathSupport() {
+ try {
+ const proc = Bun.spawnSync({
+ cmd: ["codegraph", "status", "--help"],
+ stdout: "pipe",
+ stderr: "pipe"
+ });
+ const help = new TextDecoder().decode(proc.stdout) + new TextDecoder().decode(proc.stderr);
+ return CODEGRAPH_PROJECT_PATH_USAGE_TOKEN.test(help);
+ } catch {
+ return false;
+ }
+}
function defaultRunStatusJson(projectPath) {
try {
const proc = Bun.spawnSync({
@@ -1778,23 +1903,52 @@ function defaultRunStatusJson(projectPath) {
return { ok: false, error: exc.message ?? String(exc) };
}
}
-var CODEGRAPH_PROJECT_PATH_USAGE_TOKEN = /\[path\]/;
-function defaultDetectProjectPathSupport() {
- try {
- const proc = Bun.spawnSync({
- cmd: ["codegraph", "status", "--help"],
- stdout: "pipe",
- stderr: "pipe"
- });
- const help = new TextDecoder().decode(proc.stdout) + new TextDecoder().decode(proc.stderr);
- return CODEGRAPH_PROJECT_PATH_USAGE_TOKEN.test(help);
- } catch {
- return false;
+function checkCodegraph(opts, deps) {
+ if (opts.disabled)
+ return null;
+ const projects = findCodeProjects(opts);
+ if (projects.length === 0)
+ return null;
+ const whichFn = deps?.whichCodegraph ?? defaultWhichCodegraph;
+ const cliPath = whichFn();
+ if (!cliPath) {
+ return null;
+ }
+ if (projects.length === 1) {
+ return evaluateProjectStatus(projects[0], deps);
}
+ const detectFn = deps?.detectProjectPathSupport ?? defaultDetectProjectPathSupport;
+ if (!detectFn()) {
+ const first = evaluateProjectStatus(projects[0], deps);
+ return {
+ name: "code_graph",
+ ok: first.ok,
+ message: `${first.message}; note: codegraph CLI has no per-query project_path support - reported 1 of ${projects.length} discovered projects only`
+ };
+ }
+ const results = projects.map((project) => evaluateProjectStatus(project, deps));
+ const header = `${projects.length} code projects:`;
+ return {
+ name: "code_graph",
+ ok: results.every((r) => r.ok),
+ message: [header, ...results.map((r) => `- ${r.message}`)].join(`
+`)
+ };
}
function evaluateProjectStatus(project, deps) {
const indexDir = join2(project, ".codegraph");
- if (!isDir(indexDir)) {
+ let indexed;
+ try {
+ indexed = statOrAbsent(indexDir)?.isDirectory() === true;
+ } catch (exc) {
+ return {
+ name: "code_graph",
+ ok: false,
+ message: `code project at ${project}: index directory unreadable: ${exc.message ?? exc}`,
+ fix: `chmod u+rx "${indexDir}"`
+ };
+ }
+ if (!indexed) {
return {
name: "code_graph",
ok: false,
@@ -1819,49 +1973,41 @@ function evaluateProjectStatus(project, deps) {
}
const nodes = status.data.nodeCount ?? 0;
const files = status.data.fileCount ?? 0;
+ const base = `code project at ${project}: indexed (${nodes} nodes, ${files} files)`;
+ const health = assessGraphHealth({
+ nodeCount: nodes,
+ edgeCount: status.data.edgeCount ?? 0,
+ ...status.data.danglingRefs !== undefined ? { danglingRefs: status.data.danglingRefs } : {},
+ ...status.data.selfLoops !== undefined ? { selfLoops: status.data.selfLoops } : {},
+ indexRoot: resolveRealpath(status.data.worktreeMismatch?.indexRoot ?? status.data.projectPath ?? null),
+ worktreeRoot: resolveRealpath(status.data.worktreeMismatch?.worktreeRoot ?? project)
+ });
return {
name: "code_graph",
ok: true,
- message: `code project at ${project}: indexed (${nodes} nodes, ${files} files)`
+ message: health.ok ? base : `${base}; graph-health: ${summarizeGraphHealth(health)} - run: o2b partner codegraph report`
};
}
-function checkCodegraph(opts, deps) {
- if (opts.disabled)
+function resolveRealpath(value) {
+ if (!value)
return null;
- const projects = findCodeProjects(opts);
- if (projects.length === 0)
- return null;
- const whichFn = deps?.whichCodegraph ?? defaultWhichCodegraph;
- const cliPath = whichFn();
- if (!cliPath) {
- return null;
- }
- if (projects.length === 1) {
- return evaluateProjectStatus(projects[0], deps);
- }
- const detectFn = deps?.detectProjectPathSupport ?? defaultDetectProjectPathSupport;
- if (!detectFn()) {
- const first = evaluateProjectStatus(projects[0], deps);
- return {
- name: "code_graph",
- ok: first.ok,
- message: `${first.message}; note: codegraph CLI has no per-query project_path support - reported 1 of ${projects.length} discovered projects only`
- };
+ try {
+ return realpathSync(value);
+ } catch {
+ return value;
}
- const results = projects.map((project) => evaluateProjectStatus(project, deps));
- const header = `${projects.length} code projects:`;
- return {
- name: "code_graph",
- ok: results.every((r) => r.ok),
- message: [header, ...results.map((r) => `- ${r.message}`)].join(`
-`)
- };
}
// src/core/doctor.ts
+var MANIFEST_FIX = "o2b update";
function checkVaultWriteable(vault) {
- if (!existsSync3(vault)) {
- return { name: "vault_writeable", ok: false, message: `vault directory missing: ${vault}` };
+ if (!existsSync2(vault)) {
+ return {
+ name: "vault_writeable",
+ ok: false,
+ message: `vault directory missing: ${vault}`,
+ fix: `mkdir -p "${vault}"`
+ };
}
const probe = join3(vault, ".open-second-brain-doctor-test");
try {
@@ -1872,7 +2018,8 @@ function checkVaultWriteable(vault) {
return {
name: "vault_writeable",
ok: false,
- message: `cannot write to vault: ${exc.message ?? exc}`
+ message: `cannot write to vault: ${exc.message ?? exc}`,
+ fix: `chmod u+rwx "${vault}"`
};
}
return { name: "vault_writeable", ok: true, message: `vault exists and is writable: ${vault}` };
@@ -1881,7 +2028,7 @@ function checkConfigWriteable(config) {
let createdForCheck = false;
try {
mkdirSync2(dirname3(config), { recursive: true });
- if (!existsSync3(config))
+ if (!existsSync2(config))
createdForCheck = true;
const fd = openSync(config, "a");
writeSync(fd, "");
@@ -1892,15 +2039,32 @@ function checkConfigWriteable(config) {
return {
name: "config_writeable",
ok: false,
- message: `cannot write config ${config}: ${exc.message ?? exc}`
+ message: `cannot write config ${config}: ${exc.message ?? exc}`,
+ fix: `mkdir -p "${dirname3(config)}" && chmod u+rwx "${dirname3(config)}"`
};
}
return { name: "config_writeable", ok: true, message: `config writable: ${config}` };
}
+function manifestFileProblem(path) {
+ let stat;
+ try {
+ stat = statOrAbsent(path);
+ } catch (exc) {
+ return {
+ absent: false,
+ message: `unreadable: ${path} (${exc.message ?? exc})`,
+ fix: `chmod u+r "${path}"`
+ };
+ }
+ if (stat?.isFile() === true)
+ return null;
+ return { absent: true, message: `missing: ${path}`, fix: MANIFEST_FIX };
+}
function loadJsonManifest(path, name) {
- if (!isFile(path)) {
+ const problem = manifestFileProblem(path);
+ if (problem !== null) {
return {
- result: { name, ok: false, message: `missing: ${path}` },
+ result: { name, ok: false, message: problem.message, fix: problem.fix },
data: null
};
}
@@ -1909,13 +2073,18 @@ function loadJsonManifest(path, name) {
data = JSON.parse(readFileSync2(path, "utf8"));
} catch (exc) {
return {
- result: { name, ok: false, message: `invalid JSON: ${path} (${exc.message})` },
+ result: {
+ name,
+ ok: false,
+ message: `invalid JSON: ${path} (${exc.message})`,
+ fix: MANIFEST_FIX
+ },
data: null
};
}
if (!data || typeof data !== "object" || Array.isArray(data)) {
return {
- result: { name, ok: false, message: `invalid manifest object: ${path}` },
+ result: { name, ok: false, message: `invalid manifest object: ${path}`, fix: MANIFEST_FIX },
data: null
};
}
@@ -1974,7 +2143,8 @@ function checkCodexManifest(path) {
return {
name: "codex_manifest",
ok: false,
- message: `schema invalid: ${path} (${problems.join("; ")})`
+ message: `schema invalid: ${path} (${problems.join("; ")})`,
+ fix: MANIFEST_FIX
};
}
return { name: "codex_manifest", ok: true, message: `valid Codex manifest: ${path}` };
@@ -2013,14 +2183,16 @@ function checkClaudeManifest(path) {
return {
name: "claude_manifest",
ok: false,
- message: `schema invalid: ${path} (${problems.join("; ")})`
+ message: `schema invalid: ${path} (${problems.join("; ")})`,
+ fix: MANIFEST_FIX
};
}
return { name: "claude_manifest", ok: true, message: `valid Claude manifest: ${path}` };
}
function checkHermesManifest(path) {
- if (!isFile(path)) {
- return { name: "hermes_manifest", ok: false, message: `missing: ${path}` };
+ const problem = manifestFileProblem(path);
+ if (problem !== null) {
+ return { name: "hermes_manifest", ok: false, message: problem.message, fix: problem.fix };
}
let text;
try {
@@ -2029,7 +2201,8 @@ function checkHermesManifest(path) {
return {
name: "hermes_manifest",
ok: false,
- message: `invalid text: ${path} (${exc.message ?? exc})`
+ message: `invalid text: ${path} (${exc.message ?? exc})`,
+ fix: MANIFEST_FIX
};
}
const required = ["name", "version", "description"];
@@ -2042,7 +2215,8 @@ function checkHermesManifest(path) {
return {
name: "hermes_manifest",
ok: false,
- message: `schema invalid: ${path} (missing ${missing.join(", ")})`
+ message: `schema invalid: ${path} (missing ${missing.join(", ")})`,
+ fix: MANIFEST_FIX
};
}
return { name: "hermes_manifest", ok: true, message: `readable Hermes manifest: ${path}` };
@@ -2063,7 +2237,8 @@ function checkOpenclawManifest(path) {
return {
name: "openclaw_manifest",
ok: false,
- message: `schema invalid: ${path} (${problems.join("; ")})`
+ message: `schema invalid: ${path} (${problems.join("; ")})`,
+ fix: MANIFEST_FIX
};
}
return { name: "openclaw_manifest", ok: true, message: `valid OpenClaw manifest: ${path}` };
@@ -2081,7 +2256,8 @@ function checkOpenclawInstallability(repoRoot) {
results.push({
name: "openclaw_package_json_extensions",
ok: false,
- message: "package.json missing or empty openclaw.extensions array"
+ message: "package.json missing or empty openclaw.extensions array",
+ fix: MANIFEST_FIX
});
return results;
}
@@ -2095,12 +2271,14 @@ function checkOpenclawInstallability(repoRoot) {
results.push({
name: `openclaw_entry_invalid_${typeof entry}`,
ok: false,
- message: `extension entry must be a string, got: ${typeof entry}`
+ message: `extension entry must be a string, got: ${typeof entry}`,
+ fix: MANIFEST_FIX
});
continue;
}
const entryPath = join3(repoRoot, entry);
- if (isFile(entryPath)) {
+ const problem = manifestFileProblem(entryPath);
+ if (problem === null) {
results.push({
name: `openclaw_entry_${entry}`,
ok: true,
@@ -2110,7 +2288,8 @@ function checkOpenclawInstallability(repoRoot) {
results.push({
name: `openclaw_entry_${entry}`,
ok: false,
- message: `missing extension entry: ${entry}`
+ message: problem.absent ? `missing extension entry: ${entry}` : `extension entry ${entry} ${problem.message}`,
+ fix: problem.fix
});
}
}
@@ -2142,9 +2321,9 @@ function doctor(opts) {
// src/core/identity-reminder.ts
import { readFileSync as readFileSync3 } from "node:fs";
-import { dirname as dirname4, resolve as resolve2 } from "node:path";
+import { dirname as dirname4, resolve as resolve3 } from "node:path";
import { fileURLToPath } from "node:url";
-var TEMPLATE_PATH = resolve2(dirname4(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");
+var TEMPLATE_PATH = resolve3(dirname4(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");
var KNOWN_RUNTIME_TARGETS = ["hermes", "openclaw"];
function isRuntimeTarget(value) {
return typeof value === "string" && KNOWN_RUNTIME_TARGETS.includes(value);
@@ -2163,8 +2342,8 @@ function loadReminderTemplate() {
});
}
}
-var TEMPLATES_DIR = resolve2(dirname4(fileURLToPath(import.meta.url)), "..", "..", "templates");
-var PER_TARGET_PATHS = Object.freeze(Object.fromEntries(KNOWN_RUNTIME_TARGETS.map((t) => [t, resolve2(TEMPLATES_DIR, `identity-reminder.${t}.txt`)])));
+var TEMPLATES_DIR = resolve3(dirname4(fileURLToPath(import.meta.url)), "..", "..", "templates");
+var PER_TARGET_PATHS = Object.freeze(Object.fromEntries(KNOWN_RUNTIME_TARGETS.map((t) => [t, resolve3(TEMPLATES_DIR, `identity-reminder.${t}.txt`)])));
var TEMPLATE_CACHE = new Map;
function tryReadTargetTemplate(target) {
const cached = TEMPLATE_CACHE.get(target);
@@ -2208,8 +2387,56 @@ function buildReminder(agent, target) {
// src/core/vault.ts
import { mkdirSync as mkdirSync3, readFileSync as readFileSync4, readdirSync as readdirSync2, writeFileSync } from "node:fs";
import { dirname as dirname5, join as join4, relative } from "node:path";
+
+// src/core/integrity/degradation.ts
+var DEGRADATION_CODE = Object.freeze({
+ frontmatterLineDropped: "frontmatter-line-dropped",
+ frontmatterUnreadable: "frontmatter-unreadable",
+ vaultWalkEntrySkipped: "vault-walk-entry-skipped",
+ sessionLinkAbstained: "session-link-abstained",
+ lineageObservationDropped: "lineage-observation-dropped",
+ lineageChainBroken: "lineage-chain-broken",
+ vaultMarkerAbsent: "vault-marker-absent",
+ vaultMarkerMismatch: "vault-marker-mismatch"
+});
+
+class DegradationNoticeError extends Error {
+ field;
+ constructor(field, message) {
+ super(`degradation notice: ${field}: ${message}`);
+ this.name = "DegradationNoticeError";
+ this.field = field;
+ }
+}
+function requireNonBlank(field, value) {
+ if (value.trim().length === 0) {
+ throw new DegradationNoticeError(field, "must be a non-blank string");
+ }
+ return value;
+}
+function degradationNotice(input) {
+ const site = requireNonBlank("site", input.site);
+ const detail = requireNonBlank("detail", input.detail);
+ const path = input.path === undefined ? undefined : requireNonBlank("path", input.path);
+ return Object.freeze({
+ code: input.code,
+ site,
+ ...path !== undefined ? { path } : {},
+ detail
+ });
+}
+function emitDegradationNotice(sink, input) {
+ const notice = degradationNotice(input);
+ sink.push(notice);
+ return notice;
+}
+
+// src/core/vault.ts
var FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;
-var KEY_VALUE_RE = /^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$/;
+var FRONTMATTER_KEY_PATTERN = "[a-zA-Z_][a-zA-Z0-9_-]*";
+var FRONTMATTER_KEY_RE = new RegExp(`^${FRONTMATTER_KEY_PATTERN}$`);
+var KEY_VALUE_RE = new RegExp(`^(${FRONTMATTER_KEY_PATTERN})\\s*:\\s*(.*?)\\s*$`);
+var DASH_ITEM_RE = /^-(?:\s+(.*))?$/;
var MEDIA_EXTENSIONS = new Set([
".png",
".jpg",
@@ -2235,33 +2462,83 @@ var MEDIA_EXTENSIONS = new Set([
]);
var DEFAULT_SKIP_DIRS = [".git", ".obsidian", ".trash", ".stversions"];
var DEFAULT_SKIP_FILES = ["index.md", "log.md"];
-function parseFrontmatter(path) {
+var FRONTMATTER_SITE = "vault.parseFrontmatter";
+var NOTICE_LINE_MAX = 120;
+var NOTICE_LINE_ELLIPSIS = "…";
+function parseFrontmatterWithNotices(path, opts = {}) {
+ const site = opts.site ?? FRONTMATTER_SITE;
let text;
try {
text = readFileSync4(path, "utf8");
- } catch {
- return [{}, ""];
+ } catch (err) {
+ const notices = [];
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.frontmatterUnreadable,
+ site,
+ path,
+ detail: `frontmatter read failed: ${err instanceof Error ? err.message : String(err)}`
+ });
+ return [{}, "", notices];
}
- return parseFrontmatterText(text);
+ return parseFrontmatterTextWithNotices(text, { site, path });
}
-function parseFrontmatterText(text) {
+function parseFrontmatterTextWithNotices(text, opts = {}) {
+ const notices = [];
+ const site = opts.site ?? FRONTMATTER_SITE;
const match = FRONTMATTER_RE.exec(text);
if (!match) {
- return [{}, text.trim()];
+ return [{}, text.trim(), notices];
}
const fmBlock = match[1];
const body = text.slice(match[0].length).trim();
const metadata = {};
- for (const rawLine of fmBlock.split(`
-`)) {
- const line = rawLine.trim();
+ const lines = fmBlock.split(`
+`);
+ let blockKey = null;
+ for (let i = 0;i < lines.length; i++) {
+ const line = lines[i].trim();
if (!line || line.startsWith("#"))
continue;
+ const dash = DASH_ITEM_RE.exec(line);
+ if (dash && blockKey !== null) {
+ const arr = metadata[blockKey] ?? [];
+ arr.push(stripQuotes(dash[1] ?? ""));
+ metadata[blockKey] = arr;
+ continue;
+ }
+ blockKey = null;
const kv = KEY_VALUE_RE.exec(line);
- if (!kv)
+ if (!kv) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.frontmatterLineDropped,
+ site,
+ ...opts.path !== undefined ? { path: opts.path } : {},
+ detail: `frontmatter line ${i + 1} is not a supported key/value or list item: ${clipNoticeLine(line)}`
+ });
continue;
+ }
const key = kv[1];
let value = kv[2].trim();
+ if (value === "") {
+ let j = i + 1;
+ let nextMeaningful = null;
+ while (j < lines.length) {
+ const cand = lines[j].trim();
+ if (!cand || cand.startsWith("#")) {
+ j++;
+ continue;
+ }
+ nextMeaningful = cand;
+ break;
+ }
+ if (nextMeaningful !== null && DASH_ITEM_RE.test(nextMeaningful)) {
+ metadata[key] = [];
+ blockKey = key;
+ } else {
+ metadata[key] = "";
+ }
+ continue;
+ }
if (value.startsWith("[") && value.endsWith("]")) {
const inner = value.slice(1, -1).trim();
metadata[key] = inner ? splitInlineArray(inner) : [];
@@ -2269,21 +2546,36 @@ function parseFrontmatterText(text) {
}
metadata[key] = stripQuotes(value);
}
- return [metadata, body];
+ return [metadata, body, notices];
}
+function clipNoticeLine(line) {
+ return line.length <= NOTICE_LINE_MAX ? line : line.slice(0, NOTICE_LINE_MAX) + NOTICE_LINE_ELLIPSIS;
+}
+var LIST_VAULT_PAGES_SITE = "vault.listVaultPages";
function listVaultPages(vaultDir, opts = {}) {
const skipDirs = new Set(opts.skipDirs ?? DEFAULT_SKIP_DIRS);
const skipFiles = new Set((opts.skipFiles ?? DEFAULT_SKIP_FILES).map((f) => f.toLowerCase()));
const pages = [];
- walk(vaultDir, vaultDir, skipDirs, skipFiles, pages);
+ walk(vaultDir, vaultDir, skipDirs, skipFiles, pages, {
+ sink: opts.notices,
+ site: opts.site ?? LIST_VAULT_PAGES_SITE
+ });
pages.sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase()));
return pages;
}
-function walk(root, dir, skipDirs, skipFiles, out) {
+function walk(root, dir, skipDirs, skipFiles, out, notices) {
let entries;
try {
entries = readdirSync2(dir, { withFileTypes: true });
- } catch {
+ } catch (err) {
+ if (notices.sink !== undefined) {
+ emitDegradationNotice(notices.sink, {
+ code: DEGRADATION_CODE.vaultWalkEntrySkipped,
+ site: notices.site,
+ path: dir,
+ detail: `directory listing failed: ${err instanceof Error ? err.message : String(err)}`
+ });
+ }
return;
}
for (const entry of entries) {
@@ -2291,7 +2583,7 @@ function walk(root, dir, skipDirs, skipFiles, out) {
if (entry.isDirectory()) {
if (skipDirs.has(entry.name))
continue;
- walk(root, full, skipDirs, skipFiles, out);
+ walk(root, full, skipDirs, skipFiles, out, notices);
continue;
}
if (!entry.isFile())
@@ -2304,12 +2596,9 @@ function walk(root, dir, skipDirs, skipFiles, out) {
const parts = rel.split(/[\\/]/);
if (parts.some((p) => skipDirs.has(p)))
continue;
- let meta;
- try {
- [meta] = parseFrontmatter(full);
- } catch {
- continue;
- }
+ const [meta, , pageNotices] = parseFrontmatterWithNotices(full, { site: notices.site });
+ if (notices.sink !== undefined)
+ notices.sink.push(...pageNotices);
const titleVal = meta["title"];
const title = typeof titleVal === "string" && titleVal ? titleVal : stem(entry.name);
out.push({ title, path: full, metadata: meta });
@@ -2369,6 +2658,41 @@ function splitInlineArray(inner) {
return out;
}
+// src/core/brain/entities/types.ts
+var BRAIN_ENTITY_STATUS = {
+ active: "active",
+ archived: "archived",
+ quarantine: "quarantine"
+};
+var BRAIN_ENTITY_STATUS_VALUES = Object.freeze(Object.values(BRAIN_ENTITY_STATUS));
+var BRAIN_ENTITY_KIND = "brain-entity";
+
+// src/core/brain/entities/status-scope.ts
+var ENTITY_STATUS_SCOPE = {
+ canonical: "canonical",
+ readable: "readable"
+};
+var SCOPES_ADMITTING = Object.freeze({
+ [BRAIN_ENTITY_STATUS.active]: Object.freeze([
+ ENTITY_STATUS_SCOPE.canonical,
+ ENTITY_STATUS_SCOPE.readable
+ ]),
+ [BRAIN_ENTITY_STATUS.archived]: Object.freeze([ENTITY_STATUS_SCOPE.readable]),
+ [BRAIN_ENTITY_STATUS.quarantine]: Object.freeze([])
+});
+var SCOPES_BY_STATUS = new Map(Object.entries(SCOPES_ADMITTING));
+function entityStatusInScope(status, scope) {
+ return SCOPES_BY_STATUS.get(status)?.includes(scope) ?? false;
+}
+
+// src/core/brain/entities/page-scope.ts
+function vaultPageInStatusScope(metadata, scope) {
+ if (metadata["kind"] !== BRAIN_ENTITY_KIND)
+ return true;
+ const status = metadata["status"];
+ return typeof status === "string" && entityStatusInScope(status, scope);
+}
+
// src/core/agent-identity.ts
var PLACEHOLDER_AGENT_VALUES = new Set([
"agent",
@@ -2417,9 +2741,9 @@ function deriveRuntimeAgentName(runtimeId, operatorName) {
}
// src/core/path-safety.ts
-import { dirname as dirname6, posix, relative as relative2, resolve as resolve3, sep } from "node:path";
+import { dirname as dirname6, posix, relative as relative2, resolve as resolve4, sep } from "node:path";
function vaultRelative(target, vault) {
- const rel = relative2(resolve3(vault), resolve3(target));
+ const rel = relative2(resolve4(vault), resolve4(target));
return rel.split(/[\\/]/).filter((p) => p.length > 0).join(posix.sep);
}
@@ -2449,13 +2773,14 @@ var openclaw_default = definePluginEntry({
async execute() {
const vault = resolveVaultPath(api);
const discovery = discoverConfig();
+ const presence = probeVaultDirectory(vault);
const result = {
config_path: discovery.path,
config_exists: discovery.exists,
config_keys: Object.keys(discovery.data).toSorted(),
config: redactMapping(discovery.data),
vault_path: vault,
- vault_exists: existsSync4(vault)
+ vault_exists: presence.unexaminable ?? presence.present
};
return {
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
@@ -2483,13 +2808,16 @@ var openclaw_default = definePluginEntry({
},
async execute(_id, params) {
const vault = resolveVaultPath(api);
- if (!existsSync4(vault))
+ const presence = probeVaultDirectory(vault);
+ if (presence.unexaminable)
+ throw new Error(presence.unexaminable.error);
+ if (!presence.present)
throw new Error(`vault directory missing: ${vault}`);
const pattern = params["pattern"] ?? null;
const limit = typeof params["limit"] === "number" ? params["limit"] : 50;
if (limit < 1 || limit > 500)
throw new Error("argument 'limit' must be between 1 and 500");
- const pages = listVaultPages(vault);
+ const pages = listVaultPages(vault).filter((p) => vaultPageInStatusScope(p.metadata, ENTITY_STATUS_SCOPE.readable));
const needle = pattern ? pattern.toLowerCase() : null;
const matched = (needle === null ? pages : pages.filter((p) => p.title.toLowerCase().includes(needle))).slice(0, limit).map((p) => ({
title: p.title,
@@ -2532,7 +2860,8 @@ var openclaw_default = definePluginEntry({
checks: results.map((r) => ({
name: r.name,
ok: r.ok,
- message: r.message
+ message: r.message,
+ ...r.fix !== undefined ? { fix: r.fix } : {}
}))
};
return {
diff --git a/package.json b/package.json
index e22eada8..3627e974 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.44.0",
+ "version": "1.44.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 2d1f4fe5..f6c342d0 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.44.0"
+version: "1.44.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 c8b3345b..309fe66f 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.44.0",
+ "version": "1.44.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/bridge.py b/plugins/hermes/bridge.py
index 7b6eef86..e4c4267a 100644
--- a/plugins/hermes/bridge.py
+++ b/plugins/hermes/bridge.py
@@ -14,13 +14,51 @@ unit-tested against in-memory streams.
from __future__ import annotations
import json
+import logging
+import os
import subprocess
+import sys
import threading
import time
from typing import Any, Protocol, runtime_checkable
PROTOCOL_VERSION = "2025-06-18"
CLIENT_NAME = "open-second-brain-hermes-provider"
+logger = logging.getLogger(__name__)
+
+
+# A shared bridge is one stdio stream, so its calls are serialised: a child
+# that stops answering blocks every agent in the gateway rather than one
+# session. Nothing in this transport bounded a read before - with a bridge per
+# session that was survivable, and with a shared one it is not. The deadline is
+# generous on purpose: a tool call can legitimately take tens of seconds when
+# it opens the store for writing and the integrity scan runs.
+DEFAULT_REQUEST_TIMEOUT_SECONDS = 120.0
+REQUEST_TIMEOUT_ENV = "OPEN_SECOND_BRAIN_MCP_TIMEOUT"
+
+
+def resolve_request_timeout() -> float | None:
+ """Seconds a single JSON-RPC round trip may take, or None to wait forever.
+
+ A non-positive value disables the deadline, which is the escape hatch for
+ an operator whose vault legitimately outruns it; it is spelled explicitly
+ rather than reached by a malformed value, and a malformed value falls back
+ to the default rather than to no bound at all.
+ """
+ raw = os.environ.get(REQUEST_TIMEOUT_ENV)
+ if raw is None or raw.strip() == "":
+ return DEFAULT_REQUEST_TIMEOUT_SECONDS
+ try:
+ seconds = float(raw)
+ except ValueError:
+ logger.warning(
+ "%s is not a number (%r); using the %.0fs default",
+ REQUEST_TIMEOUT_ENV,
+ raw,
+ DEFAULT_REQUEST_TIMEOUT_SECONDS,
+ )
+ return DEFAULT_REQUEST_TIMEOUT_SECONDS
+ return None if seconds <= 0 else seconds
class BridgeError(RuntimeError):
@@ -36,6 +74,16 @@ class BridgeTransportError(BridgeError):
"""
+class BridgeTimeoutError(BridgeTransportError):
+ """The child is alive but did not answer inside the request deadline.
+
+ A subclass of the transport error on purpose: the restart-and-retry ladder
+ that already handles a dead child is the right response to an unresponsive
+ one too, and a bridge nobody can get an answer from is not usefully
+ different from a bridge that died.
+ """
+
+
@runtime_checkable
class BrainBridge(Protocol):
"""Minimal contract the provider depends on (Dependency Inversion)."""
@@ -63,10 +111,11 @@ class JsonRpcStdioClient:
block, surfacing as a silent EOF on the JSON-RPC channel.
"""
- def __init__(self, writer: Any, reader: Any) -> None:
+ def __init__(self, writer: Any, reader: Any, timeout: float | None = None) -> None:
self._writer = writer
self._reader = reader
self._id = 0
+ self._timeout = timeout
def notify(self, method: str, params: dict[str, Any] | None = None) -> None:
frame: dict[str, Any] = {"jsonrpc": "2.0", "method": method}
@@ -93,9 +142,46 @@ class JsonRpcStdioClient:
except (BrokenPipeError, ValueError, OSError) as exc:
raise BridgeTransportError(f"write failed: {exc}") from exc
+ def _readline(self, deadline: float | None) -> Any:
+ """One line, or a timeout. Blocks plainly when no deadline is set.
+
+ A blocking ``readline`` on a pipe cannot be interrupted, so the read
+ runs on a daemon thread whose result is collected with the remaining
+ budget. The thread is left behind on a timeout deliberately: the caller
+ tears the child down, which closes the pipe and releases it. Daemon,
+ because a thread stuck on a dead pipe must never hold up interpreter
+ exit - the failure this whole change is about is a process that would
+ not go away.
+ """
+ if deadline is None:
+ return self._reader.readline()
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise BridgeTimeoutError("no response from MCP server within the deadline")
+ box: list[Any] = []
+ error: list[BaseException] = []
+
+ def pump() -> None:
+ try:
+ box.append(self._reader.readline())
+ except BaseException as exc: # noqa: BLE001 - reported to the caller
+ error.append(exc)
+
+ worker = threading.Thread(target=pump, daemon=True)
+ worker.start()
+ worker.join(remaining)
+ if worker.is_alive():
+ raise BridgeTimeoutError(
+ f"no response from MCP server within {self._timeout:.0f}s"
+ )
+ if error:
+ raise BridgeTransportError(f"read failed: {error[0]}") from error[0]
+ return box[0] if box else None
+
def _read_response(self, rid: int) -> Any:
+ deadline = None if self._timeout is None else time.monotonic() + self._timeout
while True:
- line = self._reader.readline()
+ line = self._readline(deadline)
# EOF arrives as b"" from a bytes reader, as "" from a str reader
# (e.g. the StringIO-based _ScriptedReader in test_memory_provider),
# and as None from a closed pipe. All three terminate the read.
@@ -139,6 +225,10 @@ class McpBrainBridge:
self._command = command
self._spawn = spawn or self._default_spawn
self._cwd = cwd
+ # A gateway may serve several AIAgents concurrently, but one shared
+ # bridge has one request/response stream. Serialise lifecycle and RPC
+ # operations so request ids and stdout frames cannot interleave.
+ self._lock = threading.RLock()
self._proc: Any = None
self._client: JsonRpcStdioClient | None = None
self._tools: list[dict[str, Any]] = []
@@ -155,6 +245,46 @@ class McpBrainBridge:
argv += ["--repo", self._repo_root]
return argv
+ _watchdog_absent_warned = False
+
+ @classmethod
+ def _warn_watchdog_absent(cls) -> None:
+ if cls._watchdog_absent_warned:
+ return
+ cls._watchdog_absent_warned = True
+ logger.warning(
+ "parent-death watchdog module unavailable; open-second-brain MCP "
+ "children will not be reaped if this process exits abruptly"
+ )
+
+ @staticmethod
+ def _watchdog_argv(argv: list[str]) -> list[str]:
+ """Wrap POSIX MCP children in Hermes' parent-death watchdog."""
+ if os.name != "posix":
+ return argv
+ try:
+ from tools import mcp_stdio_watchdog
+ except ImportError:
+ # The plugin can still operate from a standalone checkout; the
+ # host's normal runtime has this module and gets descendant
+ # cleanup. Say so rather than degrading in silence: if the module
+ # is ever renamed, the guarantee disappears and nothing else would
+ # report it. Once per process, because this is a property of the
+ # installation and not of the call.
+ McpBrainBridge._warn_watchdog_absent()
+ return argv
+ watchdog_path = getattr(mcp_stdio_watchdog, "__file__", None)
+ if not watchdog_path:
+ return argv
+ return [
+ sys.executable,
+ str(watchdog_path),
+ "--ppid",
+ str(os.getpid()),
+ "--",
+ *argv,
+ ]
+
def _default_spawn(self, argv: list[str]) -> Any:
# Use a small thread to drain stderr continuously; otherwise the child
# can block on a full stderr pipe after logging init warnings and
@@ -163,8 +293,11 @@ class McpBrainBridge:
# avoids the line-buffering deadlock that `text=True, bufsize=1`
# classically triggers with Popen pipes: a fast child writer +
# a slow parent reader fills the kernel buffer and both block.
+ # Hermes' watchdog owns the real child process group, forwards the
+ # stdio streams transparently, and kills the group when this gateway
+ # exits unexpectedly.
process = subprocess.Popen( # noqa: S603 - argv is a fixed command + config path
- argv,
+ self._watchdog_argv(argv),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
@@ -202,33 +335,45 @@ class McpBrainBridge:
pass
def start(self) -> None:
- if self._started:
- return
- self._proc = self._spawn(self._argv())
- self._client = JsonRpcStdioClient(self._proc.stdin, self._proc.stdout)
- try:
- self._client.request(
- "initialize",
- {
- "protocolVersion": PROTOCOL_VERSION,
- "capabilities": {},
- "clientInfo": {"name": CLIENT_NAME, "version": "1"},
- },
+ with self._lock:
+ if self._started:
+ return
+ self._proc = self._spawn(self._argv())
+ self._client = JsonRpcStdioClient(
+ self._proc.stdin, self._proc.stdout, timeout=resolve_request_timeout()
)
- self._client.notify("notifications/initialized")
- result = self._client.request("tools/list", {})
- except BaseException:
- # A failed handshake must not leak the spawned process.
- self.stop()
- raise
- self._tools = list((result or {}).get("tools", []))
- self._started = True
+ pid = getattr(self._proc, "pid", "unknown")
+ logger.debug("open-second-brain MCP child spawned pid=%s", pid)
+ try:
+ self._client.request(
+ "initialize",
+ {
+ "protocolVersion": PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {"name": CLIENT_NAME, "version": "1"},
+ },
+ )
+ self._client.notify("notifications/initialized")
+ result = self._client.request("tools/list", {})
+ except BaseException:
+ # A failed handshake must not leak the spawned process.
+ logger.warning("open-second-brain MCP handshake failed pid=%s", pid)
+ self.stop()
+ raise
+ self._tools = list((result or {}).get("tools", []))
+ self._started = True
+ logger.debug("open-second-brain MCP child ready pid=%s", pid)
def list_tools(self) -> list[dict[str, Any]]:
- self._ensure_started()
- return self._tools
+ with self._lock:
+ self._ensure_started()
+ return list(self._tools)
def call_tool(self, name: str, args: dict[str, Any]) -> dict[str, Any]:
+ with self._lock:
+ return self._call_tool(name, args)
+
+ def _call_tool(self, name: str, args: dict[str, Any]) -> dict[str, Any]:
# Hard cap on restarts: o2b mcp can flake under load (e.g. bun runtime
# SIGPIPE on a parent process briefly holding the pipe). One restart is
# not enough; a bounded retry with backoff turns a transient subproc
@@ -290,24 +435,45 @@ class McpBrainBridge:
return poll() is not None
def stop(self) -> None:
- proc = self._proc
- self._started = False
- self._client = None
- self._proc = None
- if proc is None:
- return
- try:
- proc.terminate()
- proc.wait(timeout=5)
- except Exception: # noqa: BLE001 - never raise on shutdown
- kill = getattr(proc, "kill", None)
- if callable(kill):
- kill()
- # Reap the killed child so it cannot linger as a zombie.
+ with self._lock:
+ proc = self._proc
+ self._started = False
+ self._client = None
+ self._proc = None
+ if proc is None:
+ return
+ pid = getattr(proc, "pid", "unknown")
try:
- proc.wait(timeout=5)
- except Exception: # noqa: BLE001
+ poll = getattr(proc, "poll", None)
+ if not callable(poll) or poll() is None:
+ proc.terminate()
+ except Exception: # noqa: BLE001 - shutdown is best-effort
pass
+ try:
+ proc.wait(timeout=8)
+ except Exception: # noqa: BLE001 - escalate once, then still reap
+ kill = getattr(proc, "kill", None)
+ if callable(kill):
+ try:
+ kill()
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ proc.wait(timeout=5)
+ except Exception: # noqa: BLE001
+ pass
+ finally:
+ # Release the parent's pipe descriptors as well as reaping the
+ # child. The old implementation only waited for the process.
+ for stream_name in ("stdin", "stdout", "stderr"):
+ stream = getattr(proc, stream_name, None)
+ close = getattr(stream, "close", None)
+ if callable(close):
+ try:
+ close()
+ except Exception: # noqa: BLE001
+ pass
+ logger.debug("open-second-brain MCP child stopped pid=%s", pid)
def _ensure_started(self) -> None:
if not self._started:
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 2d1f4fe5..f6c342d0 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.44.0"
+version: "1.44.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 5f828c13..c90c8be1 100644
--- a/plugins/hermes/provider.py
+++ b/plugins/hermes/provider.py
@@ -12,6 +12,7 @@ are added alongside.
from __future__ import annotations
+import atexit
import json
import os
import re
@@ -54,6 +55,62 @@ _CONFIG_KEYS: tuple[str, ...] = ("vault", "agent_name", "timezone")
# Token budget for the recall slice fetched on each prefetch.
_PREFETCH_MAX_TOKENS = 1024
+# A provider instance is created per AIAgent, but the MCP server is a gateway
+# resource rather than a session resource. Keep one bridge per effective server
+# configuration in this Python process. Cache eviction deliberately calls
+# AIAgent.release_clients() without shutting down memory providers, so
+# constructing one Bun child per provider leaks a child for every new session.
+_SHARED_BRIDGES: dict[tuple[str | None, str | None, tuple[str, ...]], BrainBridge] = {}
+_SHARED_BRIDGES_LOCK = threading.RLock()
+
+
+def _shared_bridge_key(
+ vault: str | None,
+ repo_root: str | None,
+ command: tuple[str, ...],
+) -> tuple[str | None, str | None, tuple[str, ...]]:
+ return (vault, repo_root, tuple(command))
+
+
+def _get_shared_bridge(
+ *,
+ vault: str | None,
+ repo_root: str | None,
+ command: tuple[str, ...],
+) -> BrainBridge:
+ """Return the one bridge for this gateway/configuration key."""
+ key = _shared_bridge_key(vault, repo_root, command)
+ with _SHARED_BRIDGES_LOCK:
+ bridge = _SHARED_BRIDGES.get(key)
+ if bridge is None:
+ bridge = McpBrainBridge(
+ vault=vault,
+ repo_root=repo_root,
+ command=command,
+ )
+ _SHARED_BRIDGES[key] = bridge
+ return bridge
+
+
+def _shutdown_shared_bridges() -> None:
+ """Stop all gateway-owned bridges during normal interpreter shutdown."""
+ with _SHARED_BRIDGES_LOCK:
+ bridges = list(_SHARED_BRIDGES.values())
+ _SHARED_BRIDGES.clear()
+ for bridge in bridges:
+ try:
+ bridge.stop()
+ except Exception: # noqa: BLE001 - shutdown is best-effort
+ pass
+
+
+def _reset_shared_bridges_for_tests() -> None:
+ """Clear the process registry without exposing it as provider API."""
+ _shutdown_shared_bridges()
+
+
+atexit.register(_shutdown_shared_bridges)
+
def _fallback_exe_dirs() -> tuple[Path, ...]:
"""Directories scanned for an executable when a tiny inherited ``PATH``
@@ -110,6 +167,7 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
def __init__(self, bridge: BrainBridge | None = None) -> None:
self._bridge_override = bridge
self._bridge: BrainBridge | None = None
+ self._bridge_shared = False
self._hermes_home: str | None = None
self._session_id: str = ""
self._buffer: list[tuple[str, str]] = []
@@ -131,19 +189,32 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
"""Start the bridge to the TS core. Fail-soft: never break gateway boot."""
self._session_id = session_id or ""
self._hermes_home = kwargs.get("hermes_home")
- if self._bridge is not None:
+ old_bridge = self._bridge
+ old_bridge_shared = self._bridge_shared
+ self._bridge = None
+ self._bridge_shared = False
+ if old_bridge is not None and not old_bridge_shared:
# Re-initialization (a new session on a reused instance) must not
- # leak the previous bridge's subprocess.
+ # leak an injected/test bridge's subprocess. Gateway bridges are
+ # shared and intentionally remain alive for the gateway lifetime.
try:
- self._bridge.stop()
+ old_bridge.stop()
except Exception: # noqa: BLE001
pass
- self._bridge = self._bridge_override or McpBrainBridge(
- vault=config.resolve_vault(),
- repo_root=self._repo_root(),
- command=self._resolve_command(),
- )
+ if self._bridge_override is not None:
+ self._bridge = self._bridge_override
+ else:
+ vault = config.resolve_vault()
+ repo_root = self._repo_root()
+ command = self._resolve_command()
+ self._bridge = _get_shared_bridge(
+ vault=vault,
+ repo_root=repo_root,
+ command=command,
+ )
+ self._bridge_shared = True
try:
+ assert self._bridge is not None
self._bridge.start()
except Exception: # noqa: BLE001 - degrade to inert; tool calls surface errors
pass
@@ -390,12 +461,18 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
self._safe_call("brain_memory_bridge", args)
def shutdown(self) -> None:
- """Drain captures, flush, and stop the bridge. Never raises."""
+ """Drain captures, flush, and stop owned test bridges. Never raises."""
self._drain_captures()
self._flush_buffer()
- if self._bridge is not None:
+ bridge = self._bridge
+ bridge_shared = self._bridge_shared
+ self._bridge = None
+ self._bridge_shared = False
+ # Shared production bridges belong to the gateway, not an evictable
+ # session. The process registry/atexit hook owns their final stop.
+ if bridge is not None and not bridge_shared:
try:
- self._bridge.stop()
+ bridge.stop()
except Exception: # noqa: BLE001 - shutdown is best-effort
pass
diff --git a/pyproject.toml b/pyproject.toml
index db06fc7f..a5b0dde9 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.44.0"
+version = "1.44.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.py
index d4b41922..d3586b2d 100644
--- a/tests/python/test_memory_provider.py
+++ b/tests/python/test_memory_provider.py
@@ -12,6 +12,8 @@ import json
import os
import sys
import tempfile
+import threading
+import time
import unittest
from pathlib import Path
from unittest.mock import patch
@@ -26,17 +28,23 @@ from plugins.hermes._base import ( # noqa: E402
MemoryProvider,
_FallbackMemoryProviderBase,
)
+from plugins.hermes import bridge as bridge_module # noqa: E402
from plugins.hermes.bridge import ( # noqa: E402
+ DEFAULT_REQUEST_TIMEOUT_SECONDS,
+ REQUEST_TIMEOUT_ENV,
BridgeError,
+ BridgeTimeoutError,
BridgeTransportError,
FakeBrainBridge,
JsonRpcStdioClient,
McpBrainBridge,
+ resolve_request_timeout,
)
from plugins.hermes.provider import ( # noqa: E402
MEMORY_TOOLS,
OpenSecondBrainMemoryProvider,
_find_executable,
+ _reset_shared_bridges_for_tests,
)
from plugins.hermes.cli import register_cli # noqa: E402
@@ -658,6 +666,39 @@ class ProviderLifecycleTests(unittest.TestCase):
provider.shutdown()
+class SharedProviderBridgeTests(unittest.TestCase):
+ def tearDown(self):
+ _reset_shared_bridges_for_tests()
+
+ def test_provider_instances_share_one_gateway_bridge(self):
+ shared = FakeBrainBridge()
+ with patch("plugins.hermes.provider.McpBrainBridge", return_value=shared) as factory:
+ with patch("plugins.hermes.provider.config.resolve_vault", return_value="/vault"):
+ with patch.object(
+ OpenSecondBrainMemoryProvider,
+ "_repo_root",
+ return_value="/repo",
+ ):
+ with patch.object(
+ OpenSecondBrainMemoryProvider,
+ "_resolve_command",
+ return_value=("bun", "run", "main.ts", "mcp"),
+ ):
+ first = OpenSecondBrainMemoryProvider()
+ second = OpenSecondBrainMemoryProvider()
+ first.initialize("session-1", hermes_home="/hh")
+ second.initialize("session-2", hermes_home="/hh")
+
+ self.assertEqual(factory.call_count, 1)
+ self.assertTrue(shared.started)
+ first.shutdown()
+ second.shutdown()
+ self.assertFalse(shared.stopped)
+
+ _reset_shared_bridges_for_tests()
+ self.assertTrue(shared.stopped)
+
+
class InPlaceCompactionLifecycleTests(unittest.TestCase):
"""Regression guards for Hermes PR #52658 (compression.in_place default
False->True). Compaction now keeps ONE durable session id instead of
@@ -954,6 +995,135 @@ class McpBrainBridgeTests(unittest.TestCase):
result = bridge.call_tool("brain_query", {"topic": "x"})
self.assertEqual(result, {"ok": True})
self.assertEqual(spawn.state["n"], 3)
+ self.assertTrue(broken.terminated)
+
+
+class BridgeRequestDeadlineTests(unittest.TestCase):
+ """A shared bridge is one stream, so an unanswered call is everyone's.
+
+ Before the bridge became shared, a child that stopped answering blocked the
+ one session that owned it. Sharing it made that block gateway-wide, and
+ nothing in this transport bounded a read - so the deadline is not a nicety
+ here, it is what keeps the fix from trading a descriptor leak for a stall.
+ """
+
+ class _MuteReader:
+ """Answers the handshake, then never answers again."""
+
+ def __init__(self, frames):
+ self._frames = list(frames)
+ self.reads_after_handshake = 0
+
+ def readline(self):
+ if self._frames:
+ return (json.dumps(self._frames.pop(0)) + "\n").encode("utf-8")
+ self.reads_after_handshake += 1
+ time.sleep(30)
+ return b""
+
+ class _MuteProcess:
+ pid = 4242
+
+ def __init__(self, frames):
+ self.stdin = io.BytesIO()
+ self.stdout = BridgeRequestDeadlineTests._MuteReader(frames)
+ self.stderr = io.BytesIO()
+ self.terminated = False
+
+ def poll(self):
+ return None
+
+ def terminate(self):
+ self.terminated = True
+
+ def wait(self, timeout=None):
+ return 0
+
+ HANDSHAKE = [
+ {"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-06-18"}},
+ {"jsonrpc": "2.0", "id": 2, "result": {"tools": []}},
+ ]
+
+ def test_a_child_that_stops_answering_raises_instead_of_blocking(self):
+ spawned = []
+
+ def spawn(argv):
+ proc = self._MuteProcess(list(self.HANDSHAKE))
+ spawned.append(proc)
+ return proc
+
+ bridge = McpBrainBridge(vault="/v", spawn=spawn)
+ with patch.dict(os.environ, {REQUEST_TIMEOUT_ENV: "0.2"}):
+ bridge.start()
+ started = time.monotonic()
+ with self.assertRaises(BridgeTimeoutError):
+ bridge.call_tool("brain_query", {})
+ elapsed = time.monotonic() - started
+
+ # Bounded, not merely non-infinite: three attempts at 0.2s plus the
+ # existing backoff. The generous ceiling keeps this off the flake list
+ # on a loaded runner while still failing outright if the read is
+ # unbounded again.
+ self.assertLess(elapsed, 10.0)
+ # The stuck child is torn down rather than left holding the stream.
+ self.assertTrue(spawned[0].terminated)
+
+ def test_a_timed_out_bridge_does_not_hold_the_next_caller(self):
+ """The property the shared bridge actually needs: the lock is released."""
+
+ def spawn(argv):
+ return self._MuteProcess(list(self.HANDSHAKE))
+
+ bridge = McpBrainBridge(vault="/v", spawn=spawn)
+ unblocked = threading.Event()
+
+ with patch.dict(os.environ, {REQUEST_TIMEOUT_ENV: "0.2"}):
+ bridge.start()
+
+ def first():
+ try:
+ bridge.call_tool("brain_query", {})
+ except BridgeTimeoutError:
+ pass
+
+ worker = threading.Thread(target=first, daemon=True)
+ worker.start()
+ time.sleep(0.05)
+
+ def second():
+ bridge.list_tools()
+ unblocked.set()
+
+ threading.Thread(target=second, daemon=True).start()
+ self.assertTrue(unblocked.wait(10.0))
+
+ def test_the_deadline_is_configurable_and_its_absence_is_explicit(self):
+ with patch.dict(os.environ, {}, clear=False):
+ os.environ.pop(REQUEST_TIMEOUT_ENV, None)
+ self.assertEqual(resolve_request_timeout(), DEFAULT_REQUEST_TIMEOUT_SECONDS)
+ with patch.dict(os.environ, {REQUEST_TIMEOUT_ENV: "45"}):
+ self.assertEqual(resolve_request_timeout(), 45.0)
+ # Non-positive is the deliberate escape hatch for a vault that
+ # legitimately outruns any bound.
+ with patch.dict(os.environ, {REQUEST_TIMEOUT_ENV: "0"}):
+ self.assertIsNone(resolve_request_timeout())
+ # A malformed value falls back to the default, never to no bound:
+ # a typo must not silently remove the protection.
+ with patch.dict(os.environ, {REQUEST_TIMEOUT_ENV: "soon"}):
+ self.assertEqual(resolve_request_timeout(), DEFAULT_REQUEST_TIMEOUT_SECONDS)
+
+ def test_a_missing_parent_death_watchdog_says_so_once(self):
+ McpBrainBridge._watchdog_absent_warned = False
+ argv = ["o2b", "mcp"]
+ with patch.dict(sys.modules, {"tools": None}):
+ with self.assertLogs("plugins.hermes.bridge", level="WARNING") as logs:
+ self.assertEqual(McpBrainBridge._watchdog_argv(argv), argv)
+ self.assertTrue(any("watchdog" in line for line in logs.output))
+ # Once per process: a property of the installation, not the call.
+ with patch.object(bridge_module.logger, "warning") as warn:
+ McpBrainBridge._watchdog_argv(argv)
+ warn.assert_not_called()
+ McpBrainBridge._watchdog_absent_warned = False
class FakeBrainBridgeTests(unittest.TestCase):