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(hermes): the bridge child inherits a PATH that can find Bun (v1.50.3) (#176)

Sol Aitken86544b9b2edd
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index a71f9707..352072f6 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.50.2",
+ "version": "1.50.3",
"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 e8efb12f..a2097d0d 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.50.2",
+ "version": "1.50.3",
"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 39b7ea2d..7983af99 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,22 @@ 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.50.3] - 2026-08-22
+
+Reported as [#173](https://github.com/itechmeat/open-second-brain/issues/173): in a Hermes deployment the memory tools were advertised and every call to them was refused, with nothing anywhere naming a cause. The gateway starts its providers with a minimal inherited `PATH`, and Open Second Brain already knew how to work around that for itself - the fallback scan finds an absolute `o2b` that `PATH` cannot see. What it did not do was carry that knowledge into the process it launched, so the wrapper checked its own `PATH` for the Bun runtime, missed, and exited before writing a byte. The transport reported the consequence. The reason was on the child's standard error, which this bridge read and discarded by design.
+
+### Fixed
+
+- **The MCP child is launched with a `PATH` that contains Bun.** Resolving an absolute `o2b` was only half the job: the wrapper is a shell script whose first act is `command -v bun`, run against whatever environment it inherits. When `PATH` cannot see Bun and the fallback scan can, the child now starts with that Bun's directory first on its `PATH`. The `o2b` wrapper remains the preferred command - it is what sources the macOS sqlite-vec shim - and is skipped only when no Bun exists anywhere for its precheck to find, which is the one case where preferring it buys a command guaranteed to exit 127.
+- **A failed handshake carries what the child said.** The stderr drain existed to stop a chatty child from blocking on a full pipe, and read every line into the void, so `error: 'bun' is not on PATH.` was discarded one buffer away from an operator who saw only "unexpected EOF from MCP server". The last twenty lines are kept, capped at 8 KiB, and appended to the transport error. The drain is still a daemon thread that never blocks and never grows without bound.
+- **The Bun precheck looks before it advises.** `command -v bun` missing means "not on this `PATH`", not "not installed", and the script answered the second question with install instructions for a runtime already present. Both the precheck and the `o2b-hook` wrapper, which does not source it, now adopt the standard install location before deciding Bun is absent. The version gate still runs against whatever was adopted, and a machine with no Bun anywhere still gets the instructions and exit 127.
+- **An empty context pack no longer leaks its own JSON into the prompt.** Per-turn recall read the structured item bodies and dropped to the legacy text channel whenever it assembled nothing - but an empty pack is an ordinary answer, and that text channel carries the raw pack JSON, local vault path included, or the transport's preview envelope. A result carrying an `items` key is now taken at its word; the text fallback is reserved for a result that omits it, which is the only shape that really is an older server.
+
+### Notes
+
+- Two children launched with different search paths are now distinct entries in the gateway's shared-bridge registry. One bridge per server configuration is still the rule; the environment is part of that configuration.
+- The end-to-end repair was measured against the reported shape: a minimal `PATH`, Bun installed at `~/.bun/bin`, `o2b` symlinked into `~/.local/bin`. Before, the handshake failed at EOF; after, the bridge starts and lists the full live tool surface.
+
## [1.50.2] - 2026-08-20
Hermes asked Open Second Brain for a token-bounded context pack before each substantive turn, then read only the MCP transport text. The transport deliberately replaces a large result with a 2,000-character preview envelope, even though the complete structured context pack is present beside it, so the provider injected transport metadata instead of the recalled memory bodies.
@@ -7286,6 +7302,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.50.3]: https://github.com/itechmeat/open-second-brain/compare/v1.50.2...v1.50.3
[1.50.2]: https://github.com/itechmeat/open-second-brain/compare/v1.50.1...v1.50.2
[1.50.1]: https://github.com/itechmeat/open-second-brain/compare/v1.50.0...v1.50.1
[1.50.0]: https://github.com/itechmeat/open-second-brain/compare/v1.49.0...v1.50.0
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 706da24d..35f6189a 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.50.2",
+ "version": "1.50.3",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 3f3444f0..3389a611 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.50.2",
+ "version": "1.50.3",
"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 45293a55..6b94736e 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.50.2"
+version: "1.50.3"
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 eb036a91..c20e7a18 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.50.2",
+ "version": "1.50.3",
"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 e4c4267a..71947956 100644
--- a/plugins/hermes/bridge.py
+++ b/plugins/hermes/bridge.py
@@ -20,6 +20,8 @@ import subprocess
import sys
import threading
import time
+from collections import deque
+from collections.abc import Mapping
from typing import Any, Protocol, runtime_checkable
PROTOCOL_VERSION = "2025-06-18"
@@ -36,6 +38,22 @@ logger = logging.getLogger(__name__)
DEFAULT_REQUEST_TIMEOUT_SECONDS = 120.0
REQUEST_TIMEOUT_ENV = "OPEN_SECOND_BRAIN_MCP_TIMEOUT"
+# The child's stderr is where the runtime says why it refused to start ("error:
+# 'bun' is not on PATH."), and the JSON-RPC channel only ever reports the
+# consequence ("unexpected EOF"). Keep the tail of it so the exception can
+# carry the cause. Bounded twice over - by line count and by total bytes - so a
+# child that floods stderr cannot grow the parent's memory.
+STDERR_TAIL_LINES = 20
+STDERR_TAIL_MAX_BYTES = 8 * 1024
+# Stderr is read in fixed-size chunks rather than by line. `readline` returns
+# only at a newline or at EOF, so a child emitting one enormous unterminated
+# record would be held whole in the parent before any truncation could apply -
+# which is the exact failure this buffer exists to rule out.
+STDERR_CHUNK_BYTES = 4096
+# Time allowed for the drain thread to finish after the child is torn down,
+# so the excerpt includes the last thing the child managed to write.
+_STDERR_DRAIN_JOIN_SECONDS = 1.0
+
def resolve_request_timeout() -> float | None:
"""Seconds a single JSON-RPC round trip may take, or None to wait forever.
@@ -209,6 +227,12 @@ class McpBrainBridge:
``spawn`` is injectable so tests substitute a fake process and never need a
live Bun runtime. A crashed channel is restarted once on the next call.
+
+ ``env`` is the complete environment the child runs with; ``None`` means
+ inherit this process's. A Hermes gateway can start the provider with a
+ ``PATH`` too small to contain Bun, and the ``o2b`` wrapper refuses to run
+ when its own ``command -v bun`` misses - so the caller that resolved an
+ absolute Bun passes an environment carrying that Bun's directory.
"""
def __init__(
@@ -219,12 +243,18 @@ class McpBrainBridge:
command: tuple[str, ...] = ("o2b", "mcp"),
spawn: Any = None,
cwd: str | None = None,
+ env: Mapping[str, str] | None = None,
) -> None:
self._vault = vault
self._repo_root = repo_root
self._command = command
self._spawn = spawn or self._default_spawn
self._cwd = cwd
+ self._env = dict(env) if env is not None else None
+ # deque append/clear are atomic under the GIL, so the drain thread
+ # writes it and start() reads it with no extra lock.
+ self._stderr_tail: deque[str] = deque(maxlen=STDERR_TAIL_LINES)
+ self._stderr_thread: threading.Thread | None = None
# 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.
@@ -303,6 +333,7 @@ class McpBrainBridge:
stderr=subprocess.PIPE,
bufsize=0,
cwd=self._cwd,
+ env=self._env,
)
stderr_thread = threading.Thread(
target=self._drain_stderr,
@@ -310,34 +341,93 @@ class McpBrainBridge:
daemon=True,
name="o2b-mcp-stderr-drain",
)
+ self._stderr_thread = stderr_thread
stderr_thread.start()
return process
- @staticmethod
- def _drain_stderr(process: Any) -> None:
- """Read stderr line-by-line until the child exits; discard contents.
+ def _append_stderr_line(self, raw: bytes) -> None:
+ """Record one child stderr line, decoded and clipped to the budget."""
+ line = raw.decode("utf-8", errors="replace").rstrip("\r\n")
+ if line:
+ self._stderr_tail.append(line[:STDERR_TAIL_MAX_BYTES])
+
+ def _drain_stderr(self, process: Any) -> None:
+ """Read stderr until the child exits, keeping a bounded tail of it.
Runs in a daemon thread so a misbehaving child (one that floods
stderr) cannot wedge the parent. Without this, a `stderr=PIPE` child
that writes more than the kernel pipe buffer (~64 KiB on Linux) will
block on its next stderr write, which surfaces in the parent as a
silent death of the JSON-RPC channel.
+
+ Chunked rather than line-oriented, and the in-progress line is clipped
+ as it grows, so nothing here is proportional to what the child writes:
+ at most :data:`STDERR_TAIL_LINES` lines are kept and each is capped at
+ the byte budget, including a record that never sends a newline at all.
+ `read1` is preferred where the stream offers it, because a buffered
+ `read` waits for the full chunk and would hold the excerpt back until
+ the child had said that much more.
"""
try:
stream = getattr(process, "stderr", None)
if stream is None:
return
- for _line in iter(stream.readline, b""):
- # Drain and discard; we do not currently surface stderr to
- # the agent, but a future diagnostic flag could log it.
- pass
+ read = getattr(stream, "read1", None) or getattr(stream, "read", None)
+ if not callable(read):
+ return
+ partial = b""
+ while True:
+ chunk = read(STDERR_CHUNK_BYTES)
+ if not chunk:
+ break
+ if isinstance(chunk, str):
+ chunk = chunk.encode("utf-8", errors="replace")
+ *complete, partial = (partial + chunk).split(b"\n")
+ for raw in complete:
+ self._append_stderr_line(raw)
+ # Keep the head of an over-long record: it is where a runtime
+ # puts the message, and clipping here is what keeps a child
+ # that never emits a newline from growing the parent.
+ if len(partial) > STDERR_TAIL_MAX_BYTES:
+ partial = partial[:STDERR_TAIL_MAX_BYTES]
+ self._append_stderr_line(partial)
except Exception: # noqa: BLE001 - drain must never raise
pass
+ def _stderr_excerpt(self) -> str:
+ """Buffered child stderr, newest lines last, capped at the byte budget."""
+ lines = list(self._stderr_tail)
+ excerpt = "\n".join(lines)
+ if len(excerpt) > STDERR_TAIL_MAX_BYTES:
+ excerpt = excerpt[-STDERR_TAIL_MAX_BYTES:]
+ return excerpt.strip()
+
+ def _with_stderr_excerpt(self, exc: BaseException) -> BaseException:
+ """The handshake failure, re-stated with what the child said on stderr.
+
+ ``stop()`` has already torn the child down, so the drain thread is
+ about to see EOF; give it a bounded moment to land its last lines
+ rather than reporting a truncated cause. Only transport failures are
+ rewritten - a JSON-RPC rejection came from a server that is talking,
+ and its stderr is noise - and the original exception is returned
+ untouched when the child said nothing.
+ """
+ if not isinstance(exc, BridgeTransportError):
+ return exc
+ thread = self._stderr_thread
+ if thread is not None and thread.is_alive():
+ thread.join(_STDERR_DRAIN_JOIN_SECONDS)
+ excerpt = self._stderr_excerpt()
+ if not excerpt:
+ return exc
+ return type(exc)(f"{exc}\n--- child stderr (last lines) ---\n{excerpt}")
+
def start(self) -> None:
with self._lock:
if self._started:
return
+ self._stderr_tail.clear()
+ self._stderr_thread = None
self._proc = self._spawn(self._argv())
self._client = JsonRpcStdioClient(
self._proc.stdin, self._proc.stdout, timeout=resolve_request_timeout()
@@ -355,11 +445,14 @@ class McpBrainBridge:
)
self._client.notify("notifications/initialized")
result = self._client.request("tools/list", {})
- except BaseException:
+ except BaseException as exc:
# A failed handshake must not leak the spawned process.
logger.warning("open-second-brain MCP handshake failed pid=%s", pid)
self.stop()
- raise
+ explained = self._with_stderr_excerpt(exc)
+ if explained is exc:
+ raise
+ raise explained from exc
self._tools = list((result or {}).get("tools", []))
self._started = True
logger.debug("open-second-brain MCP child ready pid=%s", pid)
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 45293a55..6b94736e 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.50.2"
+version: "1.50.3"
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 fcaa84ff..2c1cf8f3 100644
--- a/plugins/hermes/provider.py
+++ b/plugins/hermes/provider.py
@@ -23,7 +23,7 @@ from collections.abc import Callable
from typing import TYPE_CHECKING, Any, NamedTuple
if TYPE_CHECKING:
- from collections.abc import Iterable
+ from collections.abc import Iterable, Mapping
from . import config
from ._base import MemoryProvider
@@ -149,7 +149,8 @@ _PREFETCH_MAX_TOKENS = 1024
# 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] = {}
+_SharedBridgeKey = tuple[str | None, str | None, tuple[str, ...], str | None]
+_SHARED_BRIDGES: dict[_SharedBridgeKey, BrainBridge] = {}
_SHARED_BRIDGES_LOCK = threading.RLock()
@@ -157,8 +158,16 @@ 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))
+ env: Mapping[str, str] | None = None,
+) -> _SharedBridgeKey:
+ """Identity of a bridge: what it runs, where, and the ``PATH`` it runs with.
+
+ ``PATH`` is the only part of the overlay this provider ever rewrites, and
+ two children launched with different search paths are different servers -
+ sharing one bridge between them would hand the second caller a child that
+ resolved its runtime somewhere else.
+ """
+ return (vault, repo_root, tuple(command), None if env is None else env.get("PATH"))
def _get_shared_bridge(
@@ -166,9 +175,10 @@ def _get_shared_bridge(
vault: str | None,
repo_root: str | None,
command: tuple[str, ...],
+ env: Mapping[str, str] | None = None,
) -> BrainBridge:
"""Return the one bridge for this gateway/configuration key."""
- key = _shared_bridge_key(vault, repo_root, command)
+ key = _shared_bridge_key(vault, repo_root, command, env)
with _SHARED_BRIDGES_LOCK:
bridge = _SHARED_BRIDGES.get(key)
if bridge is None:
@@ -176,6 +186,7 @@ def _get_shared_bridge(
vault=vault,
repo_root=repo_root,
command=command,
+ env=env,
)
_SHARED_BRIDGES[key] = bridge
return bridge
@@ -217,6 +228,16 @@ def _fallback_exe_dirs() -> tuple[Path, ...]:
)
+def _path_with_dir_prepended(
+ directory: str, base: Mapping[str, str] | None = None
+) -> dict[str, str]:
+ """Copy of ``base`` (default ``os.environ``) with ``directory`` first on ``PATH``."""
+ env = dict(os.environ if base is None else base)
+ current = env.get("PATH", "")
+ env["PATH"] = f"{directory}{os.pathsep}{current}" if current else directory
+ return env
+
+
def _find_executable(name: str, search_dirs: Iterable[Path] | None = None) -> str | None:
"""Resolve ``name`` to an absolute executable path.
@@ -328,6 +349,7 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
vault=vault,
repo_root=repo_root,
command=command,
+ env=self._resolve_env(),
)
self._bridge_shared = True
try:
@@ -351,6 +373,29 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
root = Path(__file__).resolve().parents[2]
return str(root) if (root / "skills").is_dir() else None
+ @staticmethod
+ def _resolve_env() -> dict[str, str] | None:
+ """Environment for the MCP child, or ``None`` to inherit this process's.
+
+ Resolving an absolute ``o2b`` is only half the job: the wrapper is a
+ bash script that runs ``command -v bun`` against its own ``PATH``, and
+ a Hermes gateway can hand the provider a ``PATH`` with no Bun on it -
+ so the wrapper exits 127 and the handshake dies at EOF. When Bun was
+ found only by the fallback scan, put its directory on the child's
+ ``PATH`` so every branch of :meth:`_resolve_command` launches into an
+ environment where Bun resolves.
+
+ ``None`` when ``PATH`` already resolves Bun (nothing to add) or when no
+ Bun exists to point at, which keeps the common case inheriting exactly
+ what it inherits today.
+ """
+ if shutil.which("bun"):
+ return None
+ bun = _find_executable("bun")
+ if not bun:
+ return None
+ return _path_with_dir_prepended(str(Path(bun).parent))
+
@classmethod
def _resolve_command(cls) -> tuple[str, ...]:
"""Determine the right argv prefix for the ``o2b mcp`` subprocess.
@@ -365,20 +410,24 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
cross-platform path is the repo-local TypeScript entry point via
``bun run``.
"""
- # On non-Windows, a globally installed or user-local o2b works directly.
- if os.name != "nt":
+ # The o2b wrapper is preferred - it also sources the macOS sqlite-vec
+ # shim, which the bare entry point does not - but it is a bash script
+ # whose first act is to check its own PATH for Bun. Preferring it when
+ # no Bun exists anywhere buys a command that can only exit 127, so the
+ # branch is gated on a Bun the child will be able to see: found here,
+ # and put on the child's PATH by :meth:`_resolve_env`.
+ bun = _find_executable("bun")
+ if os.name != "nt" and bun:
o2b = _find_executable("o2b")
if o2b:
return (o2b, "mcp")
# Resolve via repo-local TypeScript entry point + bun.
root = cls._repo_root()
- if root:
+ if root and bun:
entry = Path(root) / "src" / "cli" / "main.ts"
if entry.is_file():
- bun = _find_executable("bun")
- if bun:
- return (bun, "run", str(entry), "mcp")
+ return (bun, "run", str(entry), "mcp")
# Last resort: hope o2b is reachable (e.g. npm global install on
# Windows created an o2b.cmd shim, or the user's shell can run it).
@@ -722,17 +771,23 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
"""Recall text from ``brain_context_pack``: prefer structured bodies.
Structured item bodies are the budgeted recall payload; using them also
- bypasses the MCP transport's preview envelope. Fall back to
- ``content[0].text`` for older servers that only expose legacy text.
+ bypasses the MCP transport's preview envelope. ``content[0].text`` is
+ the fallback for older servers that only expose legacy text.
+
+ A server that answered with an ``items`` key has spoken the structured
+ contract, so its answer stands even when it is empty: an empty pack
+ means there was nothing to recall, and dropping to the text channel
+ there would inject the raw pack JSON - vault paths and all - or the
+ preview envelope into the prompt. Only a result with no ``items`` key
+ at all is treated as legacy.
"""
structured = OpenSecondBrainMemoryProvider._structured(result)
- bodies = [
- str(item.get("body"))
- for item in (structured.get("items") or [])
- if isinstance(item, dict) and str(item.get("body") or "").strip()
- ]
- if bodies:
- return "\n\n".join(bodies)
+ if "items" in structured:
+ return "\n\n".join(
+ str(item.get("body"))
+ for item in (structured.get("items") or [])
+ if isinstance(item, dict) and str(item.get("body") or "").strip()
+ )
return OpenSecondBrainMemoryProvider._text(result)
def _append_turn(self, user: str, assistant: str, session_id: str) -> None:
diff --git a/pyproject.toml b/pyproject.toml
index 613767bc..5d7e2583 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.50.2"
+version = "1.50.3"
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/scripts/_bun-precheck.sh b/scripts/_bun-precheck.sh
index 2e2b017f..870fea6d 100755
--- a/scripts/_bun-precheck.sh
+++ b/scripts/_bun-precheck.sh
@@ -14,6 +14,14 @@ MIN_BUN_MAJOR=1
MIN_BUN_MINOR=1
MIN_BUN_PATCH=0
+# A caller launched with a minimal inherited PATH (a Hermes gateway spawns
+# its plugins that way) can miss a Bun that is installed and one directory
+# away. Adopt the standard install location before deciding it is absent.
+if ! command -v bun >/dev/null 2>&1 && [[ -x "${HOME:-}/.bun/bin/bun" ]]; then
+ PATH="${HOME}/.bun/bin${PATH:+:${PATH}}"
+ export PATH
+fi
+
if ! command -v bun >/dev/null 2>&1; then
cat >&2 <<EOS
error: 'bun' is not on PATH.
diff --git a/scripts/o2b-hook b/scripts/o2b-hook
index 159b8410..81f10bb1 100755
--- a/scripts/o2b-hook
+++ b/scripts/o2b-hook
@@ -62,6 +62,14 @@ ROOT=$(resolve_root) || {
exit 0
}
+# This wrapper does not source scripts/_bun-precheck.sh, so it repeats that
+# script's PATH repair: a minimal inherited PATH can hide an installed Bun,
+# and skipping the hook over that is a silent loss of behaviour.
+if ! command -v bun >/dev/null 2>&1 && [[ -x "${HOME:-}/.bun/bin/bun" ]]; then
+ PATH="${HOME}/.bun/bin${PATH:+:${PATH}}"
+ export PATH
+fi
+
if ! command -v bun >/dev/null 2>&1; then
warn "bun not on PATH; skipping ${HOOK_NAME}"
exit 0
diff --git a/tests/hooks/o2b-hook.test.ts b/tests/hooks/o2b-hook.test.ts
index e06ca4ca..9914cfb7 100644
--- a/tests/hooks/o2b-hook.test.ts
+++ b/tests/hooks/o2b-hook.test.ts
@@ -10,7 +10,15 @@
*/
import { afterEach, describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
-import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync, cpSync } from "node:fs";
+import {
+ chmodSync,
+ cpSync,
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -76,6 +84,38 @@ describe("o2b-hook resilience", () => {
expect(r.status).not.toBe(2);
});
+ test("adopts ~/.bun/bin when a minimal PATH hides an installed Bun", () => {
+ // The wrapper does not source scripts/_bun-precheck.sh, so it carries its
+ // own copy of that PATH repair. Without it a gateway-spawned hook skips
+ // over a Bun sitting one directory away (issue #173).
+ const root = freshRoot("probe");
+ const home = mkdtempSync(join(tmpdir(), "o2bhome-"));
+ tmps.push(home);
+ const bunBin = join(home, ".bun", "bin");
+ mkdirSync(bunBin, { recursive: true });
+ symlinkSync(process.execPath, join(bunBin, "bun"));
+ chmodSync(bunBin, 0o755);
+
+ // The wrapper's own utilities and provably no bun, so the only Bun the
+ // child can reach is the one the repair is supposed to find.
+ const bin = mkdtempSync(join(tmpdir(), "o2bbin-iso-"));
+ tmps.push(bin);
+ for (const name of ["bash", "realpath", "dirname", "cat", "tr", "head"]) {
+ const resolved = Bun.which(name);
+ if (!resolved) throw new Error(`test prerequisite missing from this machine: ${name}`);
+ symlinkSync(resolved, join(bin, name));
+ }
+ expect(Bun.which("bun", { PATH: bin })).toBeNull();
+
+ const r = spawnSync("bash", [WRAPPER, "probe"], {
+ env: { HOME: home, PATH: bin, CLAUDE_PLUGIN_ROOT: root },
+ encoding: "utf8",
+ });
+ expect(r.status).toBe(0);
+ expect(r.stderr).not.toContain("bun not on PATH");
+ expect(r.stdout).toContain("PROBE_OK:probe");
+ });
+
test("CLAUDE_PLUGIN_ROOT wins over a stale wrapper location (heals broken install)", () => {
// Simulate the broken Mac: a ~/.local/bin symlink that points into an OLD
// checkout which lacks the hook, while Claude Code passes the current root.
diff --git a/tests/python/test_memory_provider.py b/tests/python/test_memory_provider.py
index 06508b95..a78e3286 100644
--- a/tests/python/test_memory_provider.py
+++ b/tests/python/test_memory_provider.py
@@ -532,29 +532,125 @@ class ProviderStaticSchemaFallbackTests(unittest.TestCase):
self.assertEqual(json.loads(result), {"ok": True})
self.assertEqual(bridge.calls, [("brain_note", {"text": "hi"})])
+ @staticmethod
+ def _fake_bin(home, relative, name):
+ """Create an executable stub at ``<home>/<relative>/<name>``."""
+ directory = Path(home).joinpath(*relative)
+ directory.mkdir(parents=True, exist_ok=True)
+ exe = directory / name
+ exe.write_text("#!/bin/sh\n")
+ os.chmod(exe, 0o755)
+ return exe
+
+ @staticmethod
+ def _sandboxed_scan(home, *dirs):
+ """Patches that confine executable discovery to ``home``.
+
+ Both the PATH lookup and the fallback scan are pinned: leaving the scan
+ on its real directory list would let a Bun installed on the machine
+ running the tests decide the outcome.
+ """
+ return (
+ patch.dict(os.environ, {"PATH": ""}),
+ patch.object(Path, "home", return_value=Path(home)),
+ patch("shutil.which", return_value=None),
+ patch.object(
+ provider_module,
+ "_fallback_exe_dirs",
+ return_value=tuple(Path(home).joinpath(*d) for d in dirs),
+ ),
+ )
+
@unittest.skipIf(os.name == "nt", "o2b bash wrapper is POSIX-only")
def test_resolve_command_uses_user_local_o2b_when_path_is_tiny(self):
# A tiny inherited PATH hides o2b from shutil.which; the fallback scan
- # must still find a real user-local o2b. Hermetic: a fake ~/.local/bin
- # under a temp HOME, so the assertion never depends on what the test
- # machine happens to have installed.
+ # must still find a real user-local o2b. The wrapper is only preferred
+ # when a Bun exists for it to run, so the sandbox carries one too.
+ # Hermetic: fake bins under a temp HOME and a scan list confined to it,
+ # so the assertion never depends on what this machine has installed.
with tempfile.TemporaryDirectory() as home:
- local_bin = Path(home) / ".local" / "bin"
- local_bin.mkdir(parents=True)
- fake_o2b = local_bin / "o2b"
- fake_o2b.write_text("#!/bin/sh\n")
- os.chmod(fake_o2b, 0o755)
+ fake_o2b = self._fake_bin(home, (".local", "bin"), "o2b")
+ self._fake_bin(home, (".bun", "bin"), "bun")
- with (
- patch.dict(os.environ, {"PATH": ""}),
- patch.object(Path, "home", return_value=Path(home)),
- patch("shutil.which", return_value=None),
- ):
+ with contextlib.ExitStack() as stack:
+ for ctx in self._sandboxed_scan(home, (".local", "bin"), (".bun", "bin")):
+ stack.enter_context(ctx)
command = OpenSecondBrainMemoryProvider._resolve_command()
self.assertEqual(command, (str(fake_o2b), "mcp"))
self.assertTrue(Path(command[0]).is_absolute())
+ @unittest.skipIf(os.name == "nt", "o2b bash wrapper is POSIX-only")
+ def test_resolve_command_skips_o2b_wrapper_when_no_bun_is_discoverable(self):
+ # The wrapper is a bash script that exits 127 when its own PATH has no
+ # bun. Preferring it with no bun anywhere yields a command that can only
+ # fail, so resolution must fall through to the repo-local branch.
+ with tempfile.TemporaryDirectory() as home:
+ self._fake_bin(home, (".local", "bin"), "o2b")
+ entry = Path("/repo/src/cli/main.ts")
+
+ with contextlib.ExitStack() as stack:
+ for ctx in self._sandboxed_scan(home, (".local", "bin")):
+ stack.enter_context(ctx)
+ stack.enter_context(
+ patch.object(
+ OpenSecondBrainMemoryProvider, "_repo_root", return_value="/repo"
+ )
+ )
+ stack.enter_context(patch.object(Path, "is_file", return_value=True))
+ command = OpenSecondBrainMemoryProvider._resolve_command()
+
+ # No bun means the bun+entry branch cannot be built either, so the
+ # last-resort bare command is what is left - never the wrapper.
+ self.assertEqual(command, ("o2b", "mcp"))
+ self.assertNotIn(str(entry), command)
+
+ @unittest.skipIf(os.name == "nt", "o2b bash wrapper is POSIX-only")
+ def test_resolve_command_uses_bun_entry_when_only_bun_is_discoverable(self):
+ with tempfile.TemporaryDirectory() as home:
+ fake_bun = self._fake_bin(home, (".bun", "bin"), "bun")
+
+ with contextlib.ExitStack() as stack:
+ for ctx in self._sandboxed_scan(home, (".bun", "bin")):
+ stack.enter_context(ctx)
+ stack.enter_context(
+ patch.object(
+ OpenSecondBrainMemoryProvider, "_repo_root", return_value="/repo"
+ )
+ )
+ stack.enter_context(patch.object(Path, "is_file", return_value=True))
+ command = OpenSecondBrainMemoryProvider._resolve_command()
+
+ self.assertEqual(command[0], str(fake_bun))
+ self.assertEqual(command[1], "run")
+ self.assertEqual(command[-1], "mcp")
+
+ def test_resolve_env_puts_the_discovered_bun_directory_first_on_path(self):
+ # Issue #173: the o2b wrapper checks `command -v bun` against the PATH
+ # it inherits. Resolving an absolute bun here is useless unless the
+ # child can see it too.
+ with tempfile.TemporaryDirectory() as home:
+ fake_bun = self._fake_bin(home, (".bun", "bin"), "bun")
+
+ with contextlib.ExitStack() as stack:
+ for ctx in self._sandboxed_scan(home, (".bun", "bin")):
+ stack.enter_context(ctx)
+ env = OpenSecondBrainMemoryProvider._resolve_env()
+
+ self.assertIsNotNone(env)
+ self.assertEqual(env["PATH"].split(os.pathsep)[0], str(fake_bun.parent))
+
+ def test_resolve_env_inherits_when_path_already_resolves_bun(self):
+ with patch("shutil.which", return_value="/usr/bin/bun"):
+ self.assertIsNone(OpenSecondBrainMemoryProvider._resolve_env())
+
+ def test_resolve_env_inherits_when_no_bun_exists_anywhere(self):
+ with tempfile.TemporaryDirectory() as home:
+ with contextlib.ExitStack() as stack:
+ for ctx in self._sandboxed_scan(home, (".bun", "bin")):
+ stack.enter_context(ctx)
+ self.assertIsNone(OpenSecondBrainMemoryProvider._resolve_env())
+
def test_find_executable_prefers_which(self):
with patch("shutil.which", return_value="/somewhere/on/path/o2b"):
self.assertEqual(_find_executable("o2b"), "/somewhere/on/path/o2b")
@@ -747,6 +843,66 @@ class ProviderLifecycleTests(unittest.TestCase):
self.assertNotIn("bytes_preview", out)
self.assertNotIn("art-deadbeef", out)
+ def test_prefetch_drops_an_empty_structured_pack_instead_of_its_json(self):
+ # A server that answered with an `items` key has spoken the structured
+ # contract; an empty pack means nothing to recall. Falling back to the
+ # text channel there would inject the raw pack JSON - local vault path
+ # included - into the prompt.
+ os.environ["VAULT_AGENT_NAME"] = "pf-agent"
+ raw_pack = json.dumps({"items": [], "vault": "/home/agent/private-vault"})
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": True, "reason": "hit"}},
+ "brain_context_pack": {
+ "structuredContent": {"items": []},
+ "content": [{"type": "text", "text": raw_pack}],
+ },
+ }
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ out = provider.prefetch("any query", session_id="sess-1")
+
+ self.assertNotIn("private-vault", out)
+ self.assertNotIn("items", out)
+ self.assertIn("@pf-agent", out) # the identity reminder still lands
+
+ def test_prefetch_drops_a_pack_whose_item_bodies_are_all_blank(self):
+ os.environ["VAULT_AGENT_NAME"] = "pf-agent"
+ raw_pack = json.dumps({"vault": "/home/agent/private-vault"})
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": True, "reason": "hit"}},
+ "brain_context_pack": {
+ "structuredContent": {
+ "items": [{"title": "a", "body": " "}, {"title": "b", "body": ""}]
+ },
+ "content": [{"type": "text", "text": raw_pack}],
+ },
+ }
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ out = provider.prefetch("any query", session_id="sess-1")
+
+ self.assertNotIn("private-vault", out)
+
+ def test_prefetch_falls_back_to_text_when_the_server_omits_items(self):
+ # A genuinely legacy server exposes no `items` key at all; its text
+ # payload is still the only recall it can offer.
+ os.environ["VAULT_AGENT_NAME"] = "pf-agent"
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": True, "reason": "hit"}},
+ "brain_context_pack": {
+ "structuredContent": {"generated_at": "2026-08-22"},
+ "content": [{"type": "text", "text": "LEGACY RECALL TEXT"}],
+ },
+ }
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ out = provider.prefetch("any query", session_id="sess-1")
+
+ self.assertIn("LEGACY RECALL TEXT", out)
+
def test_prefetch_appends_skills_attach_block_when_enabled(self):
os.environ["VAULT_AGENT_NAME"] = "pf-agent"
bridge = FakeBrainBridge(
@@ -1062,12 +1218,49 @@ class _ScriptedReader:
return line
+class _ScriptedStderr:
+ """Stderr stand-in that survives the close() the bridge performs.
+
+ A real pipe is closed by ``stop()`` while the drain thread may still be
+ reading it; a closed ``BytesIO`` would make the excerpt race with teardown.
+ This one keeps serving its scripted payload and then reports EOF, so the
+ drain thread always terminates on its own and the assertion is about the
+ buffer rather than about thread timing.
+
+ Reads are served in whatever size is asked for, like the raw pipe the
+ bridge gets from ``Popen(bufsize=0)`` - never rounded up to a line, since
+ the drain must not depend on the child having sent one.
+ """
+
+ def __init__(self, lines):
+ self._payload = b"".join(
+ line.encode("utf-8") if isinstance(line, str) else line for line in lines
+ )
+ self._i = 0
+ self.closed = False
+ self.max_read_size = 0
+
+ def read(self, size=-1):
+ if self._i >= len(self._payload):
+ return b""
+ end = len(self._payload) if size is None or size < 0 else self._i + size
+ chunk = self._payload[self._i : end]
+ self._i = end
+ self.max_read_size = max(self.max_read_size, len(chunk))
+ return chunk
+
+ def close(self):
+ self.closed = True
+
+
class _FakeProcess:
"""Minimal Popen stand-in: captures stdin writes, scripts stdout reads."""
- def __init__(self, responses):
+ def __init__(self, responses, stderr_lines=None):
self.stdin = io.BytesIO()
self.stdout = _ScriptedReader(responses)
+ self.stderr = _ScriptedStderr(stderr_lines or [])
+ self.pid = 4242
self.terminated = False
self._returncode = None
@@ -1251,6 +1444,160 @@ class McpBrainBridgeTests(unittest.TestCase):
self.assertTrue(broken.terminated)
+class BridgeChildEnvironmentTests(unittest.TestCase):
+ """Issue #173: what the MCP child inherits decides whether it can run.
+
+ The o2b wrapper resolves its own runtime with ``command -v bun``, so a
+ gateway PATH without Bun turns a perfectly good wrapper into exit 127 - and
+ the JSON-RPC channel only ever reported the consequence.
+ """
+
+ def _handshake_frames(self):
+ return [
+ {"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-06-18"}},
+ {"jsonrpc": "2.0", "id": 2, "result": {"tools": []}},
+ ]
+
+ def test_default_spawn_passes_the_env_overlay_to_popen(self):
+ proc = _FakeProcess(self._handshake_frames())
+ overlay = {"PATH": "/opt/bun/bin:/usr/bin", "HOME": "/home/agent"}
+ with patch.object(bridge_module.subprocess, "Popen", return_value=proc) as popen:
+ McpBrainBridge(
+ vault="/v", command=("/home/agent/.local/bin/o2b", "mcp"), env=overlay
+ ).start()
+
+ env = popen.call_args.kwargs["env"]
+ self.assertEqual(env["PATH"].split(os.pathsep)[0], "/opt/bun/bin")
+ # A copy, not the caller's dict: the bridge must not be mutated from
+ # under the child by a later edit of the overlay.
+ self.assertIsNot(env, overlay)
+
+ def test_default_spawn_inherits_when_no_env_overlay_is_given(self):
+ proc = _FakeProcess(self._handshake_frames())
+ with patch.object(bridge_module.subprocess, "Popen", return_value=proc) as popen:
+ McpBrainBridge(vault="/v").start()
+
+ self.assertIsNone(popen.call_args.kwargs["env"])
+
+
+class BridgeStderrDiagnosticTests(unittest.TestCase):
+ """Issue #173: the reason a child refused to start is on its stderr.
+
+ The JSON-RPC channel can only report the consequence ("unexpected EOF"),
+ which is a true statement about the transport and a useless one about the
+ cause. Draining stderr into a bounded tail lets the failure carry it.
+ """
+
+ def test_handshake_failure_carries_the_child_stderr_excerpt(self):
+ # The child dies before its first stdout frame, so the transport sees
+ # EOF. The reason it died is on stderr and must reach the message.
+ proc = _FakeProcess(
+ [],
+ stderr_lines=[
+ b"error: 'bun' is not on PATH.\n",
+ b"Install it with: curl -fsSL https://bun.sh/install | bash\n",
+ ],
+ )
+ with patch.object(bridge_module.subprocess, "Popen", return_value=proc):
+ bridge = McpBrainBridge(vault="/v")
+ with self.assertRaises(BridgeTransportError) as ctx:
+ bridge.start()
+
+ message = str(ctx.exception)
+ self.assertIn("unexpected EOF from MCP server", message)
+ self.assertIn("error: 'bun' is not on PATH.", message)
+ self.assertIn("https://bun.sh/install", message)
+
+ def test_handshake_failure_without_stderr_keeps_the_bare_message(self):
+ proc = _FakeProcess([])
+ with patch.object(bridge_module.subprocess, "Popen", return_value=proc):
+ bridge = McpBrainBridge(vault="/v")
+ with self.assertRaises(BridgeTransportError) as ctx:
+ bridge.start()
+
+ self.assertEqual(str(ctx.exception), "unexpected EOF from MCP server")
+
+ def test_an_unterminated_flood_is_clipped_as_it_arrives(self):
+ # `readline` returns only at a newline or at EOF, so a child that emits
+ # one enormous record with no newline would be held whole in the parent
+ # before any truncation could apply. The drain reads fixed-size chunks
+ # and clips the in-progress line instead.
+ flood = b"E" * (bridge_module.STDERR_TAIL_MAX_BYTES * 40)
+ proc = _FakeProcess([], stderr_lines=[flood])
+ with patch.object(bridge_module.subprocess, "Popen", return_value=proc):
+ bridge = McpBrainBridge(vault="/v")
+ with self.assertRaises(BridgeTransportError) as ctx:
+ bridge.start()
+
+ # Nothing the parent held was proportional to what the child wrote.
+ self.assertLessEqual(proc.stderr.max_read_size, bridge_module.STDERR_CHUNK_BYTES)
+ excerpt = str(ctx.exception).split("--- child stderr (last lines) ---\n", 1)[1]
+ self.assertLessEqual(len(excerpt), bridge_module.STDERR_TAIL_MAX_BYTES)
+ self.assertEqual(len(bridge._stderr_tail), 1)
+
+ def test_stderr_tail_is_bounded_to_the_last_lines(self):
+ noisy = [f"line-{i}\n".encode("utf-8") for i in range(500)]
+ proc = _FakeProcess([], stderr_lines=noisy)
+ with patch.object(bridge_module.subprocess, "Popen", return_value=proc):
+ bridge = McpBrainBridge(vault="/v")
+ with self.assertRaises(BridgeTransportError) as ctx:
+ bridge.start()
+
+ message = str(ctx.exception)
+ self.assertIn("line-499", message)
+ self.assertNotIn("line-0\n", message)
+ excerpt = message.split("--- child stderr (last lines) ---\n", 1)[1]
+ self.assertLessEqual(len(excerpt.splitlines()), bridge_module.STDERR_TAIL_LINES)
+ self.assertLessEqual(len(excerpt), bridge_module.STDERR_TAIL_MAX_BYTES)
+
+
+class ProviderChildEnvironmentTests(unittest.TestCase):
+ """The overlay the provider computes has to reach the bridge it builds."""
+
+ def tearDown(self):
+ _reset_shared_bridges_for_tests()
+
+ def test_initialize_hands_the_bun_bearing_env_to_the_bridge(self):
+ overlay = {"PATH": "/opt/bun/bin:/usr/bin"}
+ with (
+ patch(
+ "plugins.hermes.provider.McpBrainBridge", return_value=FakeBrainBridge()
+ ) as factory,
+ patch("plugins.hermes.provider.config.resolve_vault", return_value="/vault"),
+ patch.object(OpenSecondBrainMemoryProvider, "_repo_root", return_value="/repo"),
+ patch.object(
+ OpenSecondBrainMemoryProvider,
+ "_resolve_command",
+ return_value=("/home/agent/.local/bin/o2b", "mcp"),
+ ),
+ patch.object(OpenSecondBrainMemoryProvider, "_resolve_env", return_value=overlay),
+ ):
+ OpenSecondBrainMemoryProvider().initialize("session-1", hermes_home="/hh")
+
+ self.assertEqual(factory.call_args.kwargs["env"], overlay)
+
+ def test_bridges_with_different_search_paths_are_not_shared(self):
+ paths = iter(({"PATH": "/a/bin"}, {"PATH": "/b/bin"}))
+ with (
+ patch(
+ "plugins.hermes.provider.McpBrainBridge",
+ side_effect=lambda **_: FakeBrainBridge(),
+ ) as factory,
+ patch("plugins.hermes.provider.config.resolve_vault", return_value="/vault"),
+ patch.object(OpenSecondBrainMemoryProvider, "_repo_root", return_value="/repo"),
+ patch.object(
+ OpenSecondBrainMemoryProvider, "_resolve_command", return_value=("o2b", "mcp")
+ ),
+ patch.object(
+ OpenSecondBrainMemoryProvider, "_resolve_env", side_effect=lambda: next(paths)
+ ),
+ ):
+ OpenSecondBrainMemoryProvider().initialize("session-1", hermes_home="/hh")
+ OpenSecondBrainMemoryProvider().initialize("session-2", hermes_home="/hh")
+
+ self.assertEqual(factory.call_count, 2)
+
+
class BridgeRequestDeadlineTests(unittest.TestCase):
"""A shared bridge is one stream, so an unanswered call is everyone's.
diff --git a/tests/scripts/bun-precheck.test.ts b/tests/scripts/bun-precheck.test.ts
new file mode 100644
index 00000000..0333ac9c
--- /dev/null
+++ b/tests/scripts/bun-precheck.test.ts
@@ -0,0 +1,104 @@
+/**
+ * Tests for `scripts/_bun-precheck.sh`.
+ *
+ * The precheck is sourced by `scripts/o2b` and `scripts/vault-log`; it is
+ * exercised here in isolation by sourcing it from a one-liner shell with a
+ * fully controlled PATH and HOME. A Hermes gateway spawns its plugins with a
+ * minimal inherited PATH, which is the environment reproduced below: Bun is
+ * installed at the standard location and simply not on the search path.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const PRECHECK = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "scripts",
+ "_bun-precheck.sh",
+);
+
+const tmps: string[] = [];
+function freshHome(): string {
+ const home = mkdtempSync(join(tmpdir(), "o2b-precheck-"));
+ tmps.push(home);
+ return home;
+}
+
+// Everything `_bun-precheck.sh` reaches for that is not a shell builtin. The
+// child's PATH is built from exactly these, so a Bun installed anywhere on this
+// machine cannot satisfy the check the test is about.
+const REQUIRED_UTILITIES = ["bash", "cat", "tr", "head"];
+
+/** A PATH holding the script's utilities and provably no `bun`. */
+function isolatedPath(): string {
+ const bin = mkdtempSync(join(tmpdir(), "o2b-precheck-bin-"));
+ tmps.push(bin);
+ for (const name of REQUIRED_UTILITIES) {
+ const resolved = Bun.which(name);
+ if (!resolved) throw new Error(`test prerequisite missing from this machine: ${name}`);
+ symlinkSync(resolved, join(bin, name));
+ }
+ if (Bun.which("bun", { PATH: bin })) throw new Error("isolated PATH leaked a bun");
+ return bin;
+}
+
+/** Plant an executable `bun` stub reporting `version` at `<home>/.bun/bin`. */
+function plantBun(home: string, version: string): void {
+ const bin = join(home, ".bun", "bin");
+ mkdirSync(bin, { recursive: true });
+ const stub = join(bin, "bun");
+ writeFileSync(stub, `#!/bin/sh\nprintf '%s\\n' "${version}"\n`);
+ chmodSync(stub, 0o755);
+}
+
+async function runPrecheck(home: string): Promise<{ code: number; stderr: string }> {
+ // PATH deliberately excludes every directory a Bun install could live in.
+ const proc = Bun.spawn(["bash", "-c", `. "${PRECHECK}"; echo PRECHECK_PASSED`], {
+ env: { HOME: home, PATH: isolatedPath() },
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const stderr = await new Response(proc.stderr).text();
+ const code = await proc.exited;
+ return { code, stderr };
+}
+
+afterEach(() => {
+ while (tmps.length) {
+ try {
+ rmSync(tmps.pop()!, { recursive: true, force: true });
+ } catch {
+ // ignore
+ }
+ }
+});
+
+describe("_bun-precheck.sh PATH repair", () => {
+ test("adopts ~/.bun/bin when a minimal PATH hides an installed Bun", async () => {
+ const home = freshHome();
+ plantBun(home, "1.4.0");
+ const { code, stderr } = await runPrecheck(home);
+ expect(code).toBe(0);
+ expect(stderr).not.toContain("'bun' is not on PATH");
+ });
+
+ test("still refuses with 127 when no Bun exists anywhere", async () => {
+ const home = freshHome();
+ const { code, stderr } = await runPrecheck(home);
+ expect(code).toBe(127);
+ expect(stderr).toContain("'bun' is not on PATH");
+ });
+
+ test("the adopted Bun is still version-checked", async () => {
+ const home = freshHome();
+ plantBun(home, "1.0.9");
+ const { code, stderr } = await runPrecheck(home);
+ expect(code).toBe(1);
+ expect(stderr).toContain("is older than the required");
+ });
+});