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: make plugin updates self-healing (v0.31.1) (#60)

Sol Aitken496dd2d07a7c
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 46de3852..d1049238 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.31.0",
+ "version": "0.31.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 bf3965fa..dffd71f9 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.31.0",
+ "version": "0.31.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/.githooks/pre-commit b/.githooks/pre-commit
new file mode 100755
index 00000000..c6db3415
--- /dev/null
+++ b/.githooks/pre-commit
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+# Pre-commit gate: never commit unformatted or lint-erroring code.
+# Enabled via `git config core.hooksPath .githooks` (wired by the package
+# `prepare` script on `bun install`, or `bun run hooks:install`).
+#
+# This is a fast local guard, not the source of truth - CI's required
+# `validate` check enforces the same on every PR. Bypass in a pinch with
+# `git commit --no-verify`.
+set -euo pipefail
+
+SELF=$(realpath -- "${BASH_SOURCE[0]}")
+REPO=$(cd -- "$(dirname -- "$SELF")/.." && pwd)
+cd -- "$REPO"
+
+if ! command -v bun >/dev/null 2>&1; then
+ echo "pre-commit: bun not on PATH; skipping fmt/lint checks" >&2
+ exit 0
+fi
+
+echo "pre-commit: bun run fmt:check" >&2
+if ! bun run fmt:check; then
+ echo "pre-commit: formatting check failed - run 'bun run fmt' and re-stage." >&2
+ exit 1
+fi
+
+echo "pre-commit: bun run lint" >&2
+bun run lint
diff --git a/.githooks/pre-push b/.githooks/pre-push
new file mode 100755
index 00000000..d0083811
--- /dev/null
+++ b/.githooks/pre-push
@@ -0,0 +1,17 @@
+#!/usr/bin/env bash
+# Pre-push gate: typecheck before code leaves the machine. The full test
+# suite is intentionally NOT run here (~minutes) - CI's required `validate`
+# check runs it on the PR. Bypass with `git push --no-verify`.
+set -euo pipefail
+
+SELF=$(realpath -- "${BASH_SOURCE[0]}")
+REPO=$(cd -- "$(dirname -- "$SELF")/.." && pwd)
+cd -- "$REPO"
+
+if ! command -v bun >/dev/null 2>&1; then
+ echo "pre-push: bun not on PATH; skipping typecheck" >&2
+ exit 0
+fi
+
+echo "pre-push: bun run typecheck" >&2
+bun run typecheck
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 00000000..6c6f863d
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,59 @@
+name: CI
+
+# Runs the full validation gate on every pull request and on pushes to main.
+# This is the check branch protection should require, so unformatted,
+# lint-erroring, or type-broken code can never merge to main again.
+
+on:
+ pull_request:
+ push:
+ branches:
+ - main
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ validate:
+ name: validate
+ runs-on: ubuntu-latest
+ steps:
+ - name: Check out repository
+ uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+
+ - name: Set up Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: latest
+
+ - name: Set up Python (Hermes shim test only)
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+
+ - name: Install JS dependencies
+ run: bun install --frozen-lockfile
+
+ - name: Verify manifest version sync
+ run: bun run sync-version:check
+
+ - name: Formatting check
+ run: bun run fmt:check
+
+ - name: Lint
+ run: bun run lint
+
+ - name: Typecheck
+ run: bun run typecheck
+
+ - name: TypeScript test suite
+ run: bun test
+
+ - name: Python shim tests
+ run: python -m unittest discover -s tests/python -v
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b148e8e6..c5b092da 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,50 @@ 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).
+## [0.31.1] - 2026-06-01
+
+Update-resilience and repair. Plugin updates no longer strand the hooks or
+require manual symlink surgery, a broken attention-flow guard integration is
+fixed, and CI now gates formatting, lint, types, and tests on every pull
+request so regressions cannot merge to `main` again.
+
+### Fixed
+
+- Hooks are now fail-soft and version-current. `scripts/o2b-hook` never exits 2
+ (the only hook exit code Claude Code treats as blocking) and resolves the
+ plugin checkout from `$CLAUDE_PLUGIN_ROOT` first, then its own location, then
+ `$OSB_PLUGIN_ROOT`. `hooks/hooks.json` commands resolve the launcher via
+ `$CLAUDE_PLUGIN_ROOT` with a PATH fallback for Codex and always `exit 0`, so a
+ stale `~/.local/bin` symlink left by a previous version can no longer block
+ the agent - and the next update repairs an already-broken install with no
+ user action.
+- `o2b install-cli` re-points a dangling or stale Open Second Brain symlink to
+ the current checkout instead of erroring (no manual `rm`), while still
+ refusing to touch a real file or a symlink owned by another tool.
+- Repaired the `attention_flow_ids` context-pack path, which called the context
+ safety guard with a stale API shape and failed to typecheck (and would have
+ thrown at runtime).
+
+### Added
+
+- Automatic CLI symlink self-heal: the `SessionStart` hook repairs dangling or
+ plugin-cache-stale `~/.local/bin/{o2b,o2b-hook,vault-log}` symlinks from the
+ current checkout, leaving stable-directory installs and foreign symlinks
+ untouched.
+- A `CI` workflow that runs `sync-version:check`, `fmt:check`, lint, typecheck,
+ and the full test suite on every pull request and push to `main`.
+- [`docs/updating.md`](docs/updating.md): the update-safety contract and the
+ invariants any change to the hooks, launcher, or `install-cli` must preserve.
+- Optional local git hooks under `.githooks/` (enabled via `core.hooksPath` by
+ the `prepare` script or `bun run hooks:install`): `fmt:check` + lint on
+ pre-commit and typecheck on pre-push. The required `CI` check stays the
+ enforced gate; the hooks just catch issues earlier and are bypassable with
+ `--no-verify`.
+
+### Notes
+
+- Applied the `oxfmt` baseline to files that had merged unformatted in 0.29.0-0.31.0.
+
## [0.31.0] - 2026-06-01
Procedural attention suite. The procedural-learning foundations gain an operator-visible attention layer and stronger ingestion controls: deterministic procedural graph and hint projections, declarative attention-flow recipes for open loops and recurrent learnings, and scoped session import with a filtered write mode. Behavior stays local-first and review-first, and the new surfaces are exposed consistently across CLI and MCP.
@@ -3701,6 +3745,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.
+[0.31.1]: https://github.com/itechmeat/open-second-brain/compare/v0.31.0...v0.31.1
[0.30.0]: https://github.com/itechmeat/open-second-brain/compare/v0.29.0...v0.30.0
[0.29.0]: https://github.com/itechmeat/open-second-brain/compare/v0.28.0...v0.29.0
[0.28.0]: https://github.com/itechmeat/open-second-brain/compare/v0.27.0...v0.28.0
diff --git a/README.md b/README.md
index 9d27f662..e5e1c552 100644
--- a/README.md
+++ b/README.md
@@ -175,7 +175,12 @@ o2b update # detect runtimes, skip unchanged, apply, verify
o2b doctor # confirm the new manifest validates
```
-Per-runtime upgrade paths and the canonical version source live in [`install.md`](install.md).
+Updates need no manual symlink surgery: hooks resolve the active plugin version
+on their own and the `~/.local/bin` CLI symlinks self-heal on the next session
+start. Per-runtime upgrade paths and the canonical version source live in
+[`install.md`](install.md); the update-safety contract (and the invariants any
+change to hooks/launcher/install must keep) lives in
+[`docs/updating.md`](docs/updating.md).
## Documentation
@@ -184,6 +189,7 @@ Per-runtime upgrade paths and the canonical version source live in [`install.md`
| Mental model, vault layout, dream mechanics | [`docs/how-it-works.md`](docs/how-it-works.md) |
| MCP protocol, tools, lifecycle, writer split | [`docs/mcp.md`](docs/mcp.md) |
| Full CLI reference (every verb, every flag) | [`docs/cli-reference.md`](docs/cli-reference.md) |
+| Update safety contract + hook/launcher invariants | [`docs/updating.md`](docs/updating.md) |
| Pay Memory - audit for paid agent actions | [`docs/pay-memory.md`](docs/pay-memory.md) |
| Hermes cron jobs (daily digest, discipline report) | [`docs/hermes-cron.md`](docs/hermes-cron.md) |
| Cross-project pointer (multi-host vaults) | [`docs/cross-project-pointer.md`](docs/cross-project-pointer.md) |
diff --git a/bunfig.toml b/bunfig.toml
new file mode 100644
index 00000000..e070f168
--- /dev/null
+++ b/bunfig.toml
@@ -0,0 +1,3 @@
+[test]
+# Hermetic default config/vault for the whole suite. See tests/setup.ts.
+preload = ["./tests/setup.ts"]
diff --git a/docs/brainstorm/hook-update-resilience/design.md b/docs/brainstorm/hook-update-resilience/design.md
new file mode 100644
index 00000000..db4f3fda
--- /dev/null
+++ b/docs/brainstorm/hook-update-resilience/design.md
@@ -0,0 +1,68 @@
+# Hook update resilience - self-healing plugin hooks and CLI symlinks
+
+**Status:** draft
+**Author:** claude-vps-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+After a Claude Code plugin update, Open Second Brain hooks break and block the agent. Every `UserPromptSubmit` is rejected with `o2b-hook: <old-version-path>/hooks/session-capture.ts not found`. The agent becomes unusable until the user manually deletes stale symlinks - an unacceptable per-update workaround.
+
+## Root cause
+
+- `hooks/hooks.json` invokes hooks as `o2b-hook <name>`, a wrapper found on `PATH`.
+- `o2b install-cli` creates `~/.local/bin/o2b-hook` as a symlink into a *versioned* plugin install dir (`~/.claude/plugins/cache/open-second-brain/open-second-brain/<version>/scripts/o2b-hook`).
+- Claude Code has no stable (non-versioned) plugin path; on update the active version dir changes. The `~/.local/bin` symlink keeps pointing at the old version, so the wrapper resolves an outdated checkout (`REPO_ROOT = realpath(self)/..`) whose `hooks/<name>.ts` may not exist.
+- `o2b-hook` then runs `exit 2`. Per Claude Code semantics, **exit code 2 from a hook blocks** the operation; any other non-zero code is non-blocking. So the stale path plus the hard `exit 2` brick the agent.
+- `o2b install-cli` refuses to overwrite a symlink that points at a different checkout, which is why recovery currently needs a manual `rm`.
+
+Verified host facts:
+- Claude Code sets `CLAUDE_PLUGIN_ROOT` in the hook process and substitutes `${CLAUDE_PLUGIN_ROOT}` in hook `command` strings; it always points at the active version. There is no stable non-versioned path.
+- Codex does **not** provide a plugin-root substitution (`hooks/README.md`), which is why the `o2b-hook` PATH wrapper exists. On Codex/VPS the wrapper points at a stable directory marketplace, so it does not go stale there.
+- `hooks/hooks.json` is shared by both runtimes (`plugins/codex/hooks -> ../../hooks`).
+- Hook exit 2 blocks; other exit codes do not.
+
+## Scope
+
+- `scripts/o2b-hook`: never `exit 2`; resolve the hook root robustly (`$CLAUDE_PLUGIN_ROOT` -> own realpath -> `$OSB_PLUGIN_ROOT` -> PATH-derived); on any failure warn to stderr and `exit 0`. When running from a valid current root, opportunistically re-point a stale/dangling OSB-owned `~/.local/bin` symlink to the current checkout (self-heal the global CLI).
+- `hooks/hooks.json`: each command resolves via `$CLAUDE_PLUGIN_ROOT/scripts/o2b-hook` when that env is present (Claude Code, current version), else falls back to PATH `o2b-hook` (Codex / stable dir), else no-ops without blocking. This is what heals an already-broken install on the next update: Claude Code reads the new `hooks.json` from the active version and bypasses the stale PATH symlink.
+- `scripts/_bun-precheck.sh` usage in hook context must not produce a blocking exit (route through o2b-hook's soft-fail).
+- `o2b install-cli`: idempotent re-point of OSB-owned or dangling symlinks (no manual `rm`); still refuse to clobber a symlink owned by an unrelated tool or a real non-symlink file.
+- Hard update-safety instruction: `CLAUDE.md` <-> `AGENTS.md` (mirrored) plus `docs/`.
+
+## Out of scope
+
+- Changing the Codex plugin-root story (Codex has no env to use; PATH fallback is correct there).
+- Reworking the `.mcp.json` `${CLAUDE_PLUGIN_ROOT}` project-vs-plugin warning (tracked separately; non-blocking).
+
+## Chosen approach
+
+Two independent guarantees, each sufficient on its own, applied together (defense in depth):
+
+1. **Fail-soft**: a hook can never block the agent. `o2b-hook` exits 0 on every internal error path; only the real hook script's own decisions can ever influence the runtime, and those scripts are already silent-on-failure.
+2. **Version-current resolution**: the hook command prefers `$CLAUDE_PLUGIN_ROOT` (always the active version) over the PATH symlink, so updates never strand the hook. Because Claude Code reads `hooks.json` fresh from the active version, shipping this command form means the *next* update repairs any already-broken install with no user action.
+
+Self-healing of the global `o2b`/`o2b-hook`/`vault-log` symlinks is a convenience layer on top: when a hook runs from a known-good current root and detects an OSB-owned PATH symlink that is dangling or points at a different OSB checkout, it re-points it (best-effort, never fatal).
+
+## Design decisions
+
+- Prefer env-based resolution over PATH for Claude Code because PATH is the thing that goes stale. Keep PATH fallback for Codex, which has no env and a stable target.
+- `exit 0` (not 2, not 1) on wrapper failure: 0 is unambiguously non-blocking and signals "nothing to do" rather than "soft error" that some runtimes might surface.
+- Self-heal only OSB-owned symlinks (target path under an `open-second-brain` checkout) or dangling links; never touch a symlink a different tool owns, and never replace a real file.
+- One shared `hooks.json` command shape that is safe whether `$CLAUDE_PLUGIN_ROOT` is substituted by the host, present as an env var, or absent.
+
+## File changes
+
+- `scripts/o2b-hook` (rewrite resolution + soft-fail + self-heal).
+- `hooks/hooks.json` (robust command for all 8 hook entries).
+- `scripts/_bun-precheck.sh` (ensure non-fatal in hook context, or guard at call site).
+- `src/cli/install-cli.ts` (idempotent re-point of OSB-owned/dangling links).
+- `CLAUDE.md` + `AGENTS.md` (mirrored update-safety section).
+- `docs/updating.md` (new) + reference from README.
+- Tests: `tests/hooks/o2b-hook.test.ts` (new), extend `tests/cli/install-cli.test.ts`, a hooks.json command-shape assertion.
+
+## Risks and open questions
+
+- `hooks.json` is live on this VPS for Hermes and Codex. The new command shape must be validated against both before merge (Codex env-absent fallback; Hermes/Claude env-present path).
+- Claude Code's exact `${CLAUDE_PLUGIN_ROOT}` substitution vs shell env expansion: use the bare env var (`$CLAUDE_PLUGIN_ROOT`) so the shell expands it (CC sets the env; Codex leaves it empty) and avoid relying on host placeholder substitution inside compound shell.
+- Self-heal must be race-safe and never fatal; wrap in best-effort with full error suppression.
diff --git a/docs/brainstorm/hook-update-resilience/plan.md b/docs/brainstorm/hook-update-resilience/plan.md
new file mode 100644
index 00000000..109c3891
--- /dev/null
+++ b/docs/brainstorm/hook-update-resilience/plan.md
@@ -0,0 +1,44 @@
+# Hook update resilience - implementation plan
+
+## Tasks
+
+### Task 1: o2b-hook fail-soft + robust resolution
+- **Files**: `scripts/o2b-hook`, `tests/hooks/o2b-hook.test.ts` (new)
+- **Acceptance**:
+ - Given a hook name whose `.ts` file is missing, the wrapper writes a warning to stderr and exits `0` (never `2`).
+ - Resolution order: `$CLAUDE_PLUGIN_ROOT/hooks/<name>.ts` if present, else own-realpath root, else `$OSB_PLUGIN_ROOT`, else PATH-derived; first existing wins.
+ - Bun-missing/precheck failure in hook context does not produce a blocking exit.
+- **Depends on**: none
+
+### Task 2: hooks.json version-current command
+- **Files**: `hooks/hooks.json`, command-shape test
+- **Acceptance**:
+ - Every hook command resolves `o2b-hook` via `$CLAUDE_PLUGIN_ROOT/scripts/o2b-hook` when the env is set, else PATH `o2b-hook`, and never blocks if neither resolves.
+ - Codex (env absent) still runs the PATH wrapper.
+- **Depends on**: Task 1
+
+### Task 3: self-heal stale ~/.local/bin OSB symlinks
+- **Files**: `scripts/o2b-hook` (or a small lib), `src/cli/install-cli.ts`, tests
+- **Acceptance**:
+ - When invoked from a valid current root, a dangling or different-OSB-checkout `~/.local/bin/o2b-hook|o2b|vault-log` symlink is re-pointed to the current checkout; best-effort, never fatal.
+ - A symlink owned by an unrelated tool, or a real (non-symlink) file, is never touched.
+- **Depends on**: Task 1
+
+### Task 4: install-cli idempotent re-point
+- **Files**: `src/cli/install-cli.ts`, `tests/cli/install-cli.test.ts`
+- **Acceptance**:
+ - Re-running `install-cli` re-points an OSB-owned or dangling symlink to the current checkout without manual `rm`.
+ - Still refuses to clobber a non-symlink file or an unrelated tool's symlink (clear error).
+- **Depends on**: none
+
+### Task 5: hard update-safety instruction
+- **Files**: `docs/updating.md` (new, canonical), `hooks/README.md` (resolution + invariants), `README.md` pointer. (This repo has no `CLAUDE.md`/`AGENTS.md`; agent-facing instructions live in `docs/` + `hooks/README.md`, linked from README.)
+- **Acceptance**:
+ - A documented invariant set: updates must not require manual symlink surgery; hooks must fail-soft (never exit 2); CLI/hook resolution self-heals after update.
+ - The invariants are referenced from the code's docs path so future edits see them.
+- **Depends on**: Tasks 1-4 (document the shipped behavior)
+
+### Task 6: QA + release
+- Full `bun run validate` (typecheck, lint, test suite) green.
+- Smoke: simulate stale symlink + run hook -> agent not blocked; run hook with CLAUDE_PLUGIN_ROOT set -> resolves current version.
+- Version bump + CHANGELOG, PR, release per feature-release-playbook (separate bump handled in release phase).
diff --git a/docs/brainstorm/hook-update-resilience/variants.md b/docs/brainstorm/hook-update-resilience/variants.md
new file mode 100644
index 00000000..fc968bfd
--- /dev/null
+++ b/docs/brainstorm/hook-update-resilience/variants.md
@@ -0,0 +1,29 @@
+# Variants and rationale
+
+This fix is constrained by verified host behavior, not an open design space, so
+the orchestrator decided the approach directly rather than generating speculative
+architectural variants. The constraints that close the space:
+
+- Claude Code has no stable (non-versioned) plugin path; it does provide
+ `CLAUDE_PLUGIN_ROOT` for hooks. -> resolution must key off that env, not a
+ PATH symlink that goes stale.
+- Codex provides no plugin-root substitution and uses a stable directory. -> a
+ PATH fallback is required and is safe there.
+- Hook exit code 2 blocks; other codes do not. -> the wrapper must never exit 2.
+- `hooks.json` is read fresh from the active version, so the command shape itself
+ is the self-heal vector for already-broken installs.
+
+Approaches considered and rejected:
+
+- **A. Re-run `install-cli` on every update (status quo + docs).** Rejected: needs
+ user action every update; does not heal a broken install; the operator explicitly
+ ruled out manual steps.
+- **B. Pin a stable symlink target.** Rejected: Claude Code exposes no stable path;
+ every install dir is versioned.
+- **C. Drop the PATH wrapper and inline `${CLAUDE_PLUGIN_ROOT}/scripts/o2b-hook`
+ only.** Rejected as sole fix: breaks Codex, which has no such env.
+
+Chosen: **D. env-first resolution with PATH fallback + unconditional fail-soft +
+opportunistic self-heal** (see design.md). It satisfies all four constraints,
+heals already-broken installs on the next update with no user action, and keeps
+Codex working.
diff --git a/docs/updating.md b/docs/updating.md
new file mode 100644
index 00000000..6a7716de
--- /dev/null
+++ b/docs/updating.md
@@ -0,0 +1,78 @@
+# Updating Open Second Brain safely
+
+Open Second Brain installs into version-rotating plugin caches (Claude Code:
+`~/.claude/plugins/cache/<marketplace>/<plugin>/<version>/`; Codex: a local or
+git marketplace snapshot). **An update must never break an existing install or
+the agent.** This document is the contract that guarantees it, for both
+operators and any agent that edits the plugin.
+
+## For operators
+
+Normal updates need no manual steps:
+
+```bash
+# Claude Code
+claude plugin update open-second-brain@open-second-brain # restart to apply
+
+# Codex
+codex plugin marketplace upgrade # git marketplaces
+codex plugin add open-second-brain@open-second-brain # re-stage local marketplace
+
+# Hermes (server: the plugin dir is a symlink to the checkout)
+hermes plugins update open-second-brain
+```
+
+You do **not** need to delete or re-create any `~/.local/bin` symlink by hand.
+The hooks resolve the current version on their own, and the global
+`o2b`/`o2b-hook`/`vault-log` symlinks self-heal on the next session start. If
+you ever want to force a re-point explicitly:
+
+```bash
+o2b install-cli # idempotent: re-points dangling or stale OSB symlinks
+```
+
+`o2b install-cli` only touches its own (Open Second Brain) symlinks or dangling
+links; it never overwrites a real file or a symlink owned by another tool.
+
+## Why updates used to break (and no longer do)
+
+`hooks/hooks.json` previously invoked the bare `o2b-hook` launcher through a
+`~/.local/bin` symlink that `o2b install-cli` pinned to a *versioned* cache
+directory. When Claude Code rotated that directory on update, the symlink
+dangled, the launcher resolved an old checkout, and it `exit 2`-ed — the one
+hook exit code that blocks the agent. Every prompt was rejected until the user
+deleted the symlink by hand. That manual step is exactly what this design
+removes.
+
+## Invariants — REQUIRED for any change to hooks, the launcher, or install-cli
+
+If you are an agent (or human) editing `hooks/`, `scripts/o2b-hook`,
+`scripts/o2b`, or `src/cli/install-cli.ts`, you MUST preserve all of these.
+**A later update must always be able to repair an install made by an earlier
+version — never assume a clean prior state.**
+
+1. **Resolve version-currently, never version-pinned.** Resolve the launcher
+ via `$CLAUDE_PLUGIN_ROOT` first (Claude Code sets it to the active version
+ and re-reads `hooks.json` from that version every session — so a correct
+ command shape here repairs an already-broken install on the next update),
+ then the script's own realpath, then `$OSB_PLUGIN_ROOT`. Never hard-code a
+ version, a cache path, or a stored absolute path that a future update will
+ orphan.
+2. **Hooks fail soft — never block.** `scripts/o2b-hook` and every
+ `hooks.json` command must `exit 0` on any internal error (unresolved hook,
+ missing Bun, missing launcher). Never `exit 2`; never let a hard
+ `command not found` be the only outcome. A broken hook must degrade to a
+ no-op, not a bricked agent.
+3. **Self-heal conservatively.** Symlink repair (`healCliSymlinks`, and
+ `install-cli`'s reclaim path) may re-point only dangling links or stale
+ Open Second Brain `scripts/<name>` links; it must never touch a real file,
+ a foreign tool's symlink, or a stable-directory install (e.g. a server
+ checkout under `/srv/...` shared by Hermes/Codex).
+4. **Codex has no plugin-root env var.** Keep the PATH `o2b-hook` fallback so
+ Codex (and any runtime without `CLAUDE_PLUGIN_ROOT`) still works.
+
+These properties are locked by tests; do not weaken them:
+
+- `tests/hooks/o2b-hook.test.ts` — fail-soft + `$CLAUDE_PLUGIN_ROOT`-first resolution.
+- `tests/hooks/hooks-json-shape.test.ts` — every command is version-current, has a PATH fallback, and ends with `exit 0`.
+- `tests/cli/install-cli.test.ts` — idempotent reclaim and conservative self-heal.
diff --git a/hooks/README.md b/hooks/README.md
index ffba8f05..fe0e7ec5 100644
--- a/hooks/README.md
+++ b/hooks/README.md
@@ -95,24 +95,52 @@ payload:{type:"function_call"|"custom_tool_call", name}}`).
## How both runtimes find the hook commands
-`hooks.json` invokes the bare `o2b-hook <name>` command. That
-launcher is installed on PATH by `o2b install-cli` (one of
-`["o2b", "vault-log", "o2b-hook"]`) and lives at
-`scripts/o2b-hook` inside the plugin checkout. The launcher follows
-its own symlink, walks up one directory to find the plugin root,
-runs the Bun precheck, and execs the requested `hooks/<name>.ts`.
-
-This path resolution is intentionally PATH-based rather than relying
-on `${CLAUDE_PLUGIN_ROOT}` (which Claude Code substitutes natively)
-or `${CODEX_PLUGIN_ROOT}` (which doesn't exist on the Codex side as
-of CLI 0.129). One PATH-discoverable shim works in both runtimes
-without per-runtime branching.
-
-If `o2b install-cli` was skipped (or the install was wiped without
-running it), the hooks fail closed: the runtime sees a
-`command not found`, exits non-zero with a stderr trace, and
-proceeds with the turn. The Stop guardrail's `decision: "block"`
-only fires when the script runs successfully.
+Each `hooks.json` command resolves the launcher version-currently, with
+a fallback, and can never block:
+
+```sh
+r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then exec "$r/scripts/o2b-hook" <name>; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook <name>; exit 0
+```
+
+- **Claude Code** sets `CLAUDE_PLUGIN_ROOT` to the *active* plugin
+ version directory, so the command runs `scripts/o2b-hook` from the
+ version Claude Code just loaded — never a stale copy.
+- **Codex** does not export a plugin-root env var, so it falls through
+ to the PATH `o2b-hook` shim (`o2b install-cli` puts it on PATH; on a
+ server it points at the stable checkout, which never rotates).
+- If neither resolves, the command `exit 0`s — a missing launcher is a
+ no-op, never a blocked turn.
+
+`scripts/o2b-hook` itself resolves the checkout root in the same order
+(`$CLAUDE_PLUGIN_ROOT` → its own realpath → `$OSB_PLUGIN_ROOT`) and is
+**fail-soft**: any unresolved hook, missing Bun, or other internal
+error prints a warning to stderr and exits `0`. It must never `exit 2`
+— that is the only hook exit code Claude Code treats as blocking.
+
+The global `~/.local/bin/{o2b,o2b-hook,vault-log}` symlinks are
+self-healing: the `SessionStart` `active-inject` hook calls
+`healCliSymlinks()` from the current checkout, re-pointing a dangling
+or plugin-cache-stale OSB symlink with no user action (it leaves
+stable-directory installs, foreign symlinks, and real files untouched).
+
+> **Invariant for anyone editing hooks, the launcher, or install-cli —
+> updates must never break existing installs.** A plugin update rotates
+> the versioned cache directory under `~/.claude/plugins/cache/...`, so
+> any resolution that pins to a specific version path (a PATH symlink
+> into a cache dir, a hard-coded version, a stored absolute path) WILL
+> dangle on the next update. Always:
+> 1. resolve the launcher via `$CLAUDE_PLUGIN_ROOT` first (Claude Code
+> re-reads `hooks.json` from the active version each session, so a
+> correct command shape here repairs an already-broken install on the
+> next update);
+> 2. keep hooks fail-soft — `exit 0` on every internal error, never
+> `exit 2`, never a hard `command not found` trace as the only path;
+> 3. keep symlink resolution self-healing and conservative (never hijack
+> a stable-dir or foreign symlink).
+>
+> These three properties are locked by `tests/hooks/o2b-hook.test.ts`,
+> `tests/hooks/hooks-json-shape.test.ts`, and
+> `tests/cli/install-cli.test.ts`. See [`docs/updating.md`](../docs/updating.md).
## Local dev loop
diff --git a/hooks/active-inject.ts b/hooks/active-inject.ts
index 895f4cbc..f23368f6 100644
--- a/hooks/active-inject.ts
+++ b/hooks/active-inject.ts
@@ -31,6 +31,7 @@ import { existsSync, readFileSync } from "node:fs";
import { resolveVault } from "../src/core/config.ts";
import { brainActivePath } from "../src/core/brain/paths.ts";
+import { healCliSymlinks } from "../src/cli/install-cli.ts";
import { asHookPayload, readHookInput } from "./lib/stdin.ts";
async function main(): Promise<void> {
@@ -54,6 +55,19 @@ async function main(): Promise<void> {
? payload.hook_event_name
: "SessionStart";
+ // Self-heal the ~/.local/bin CLI symlinks on SessionStart only: a plugin
+ // update can leave them dangling or pointing at an old version. Runs from
+ // the current checkout (resolved via $CLAUDE_PLUGIN_ROOT); strictly
+ // best-effort, and gated to SessionStart so PostCompact does not trigger
+ // avoidable filesystem side effects. Never affects the injection below.
+ if (hookEventName === "SessionStart") {
+ try {
+ healCliSymlinks();
+ } catch {
+ // ignore — opportunistic; must never disrupt the session
+ }
+ }
+
const vault = resolveVault();
if (vault === null) return;
diff --git a/hooks/hooks.json b/hooks/hooks.json
index e1488500..8ecadf46 100644
--- a/hooks/hooks.json
+++ b/hooks/hooks.json
@@ -6,7 +6,7 @@
"hooks": [
{
"type": "command",
- "command": "o2b-hook session-capture",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
"timeout": 10,
"statusMessage": "OSB: capturing brain_feedback lifecycle event"
}
@@ -17,7 +17,7 @@
"hooks": [
{
"type": "command",
- "command": "o2b-hook post-write-reminder",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" post-write-reminder; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook post-write-reminder; exit 0",
"timeout": 10,
"statusMessage": "OSB: reminding to log signals/evidence"
}
@@ -30,13 +30,13 @@
"hooks": [
{
"type": "command",
- "command": "o2b-hook active-inject",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" active-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook active-inject; exit 0",
"timeout": 10,
"statusMessage": "OSB: injecting active preferences"
},
{
"type": "command",
- "command": "o2b-hook session-capture",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
"timeout": 10,
"statusMessage": "OSB: capturing session start"
}
@@ -49,7 +49,7 @@
"hooks": [
{
"type": "command",
- "command": "o2b-hook session-capture",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
"timeout": 10,
"statusMessage": "OSB: capturing prompt markers"
}
@@ -62,13 +62,13 @@
"hooks": [
{
"type": "command",
- "command": "o2b-hook session-capture",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
"timeout": 10,
"statusMessage": "OSB: capturing session stop"
},
{
"type": "command",
- "command": "o2b-hook stop-log-guardrail",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" stop-log-guardrail; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook stop-log-guardrail; exit 0",
"timeout": 10,
"statusMessage": "OSB: checking stop log guardrail"
}
@@ -81,7 +81,7 @@
"hooks": [
{
"type": "command",
- "command": "o2b-hook session-capture",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
"timeout": 10,
"statusMessage": "OSB: capturing session end"
}
@@ -94,13 +94,13 @@
"hooks": [
{
"type": "command",
- "command": "o2b-hook active-inject",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" active-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook active-inject; exit 0",
"timeout": 10,
"statusMessage": "OSB: re-injecting active preferences after compact"
},
{
"type": "command",
- "command": "o2b-hook session-capture",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
"timeout": 10,
"statusMessage": "OSB: capturing post-compact lifecycle event"
}
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index b86c0d34..83efad13 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": "0.31.0",
+ "version": "0.31.1",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 4c3d2457..26e415d9 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.31.0",
+ "version": "0.31.1",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
@@ -44,7 +44,9 @@
"validate": "bun run typecheck && bun run lint && bun run test",
"validate:fix": "bun run lint:fix && bun run fmt",
"sync-version": "bun run scripts/sync-version.ts",
- "sync-version:check": "bun run scripts/sync-version.ts --check"
+ "sync-version:check": "bun run scripts/sync-version.ts --check",
+ "hooks:install": "git config core.hooksPath .githooks && echo 'git hooks enabled (core.hooksPath=.githooks)'",
+ "prepare": "git rev-parse --git-dir >/dev/null 2>&1 && git config core.hooksPath .githooks || true"
},
"dependencies": {
"proper-lockfile": "^4.1.2"
diff --git a/plugin.yaml b/plugin.yaml
index a050c9e7..d17085fe 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.31.0"
+version: "0.31.1"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 82e1dc4c..c3d1ef5e 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.31.0",
+ "version": "0.31.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/plugin.yaml b/plugins/hermes/plugin.yaml
index 2fd83e81..aa83eea2 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.31.0"
+version: "0.31.1"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index 59b95b85..fe4dd7c3 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 = "0.31.0"
+version = "0.31.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/scripts/o2b-hook b/scripts/o2b-hook
index 1f2713de..159b8410 100755
--- a/scripts/o2b-hook
+++ b/scripts/o2b-hook
@@ -1,40 +1,79 @@
#!/usr/bin/env bash
-# Entry point Claude Code and Codex call from `hooks/hooks.json`. The
-# only reason this exists separately from `o2b` is path resolution:
-# both runtimes spawn the hook command through /bin/sh with the user's
-# session cwd, and neither one substitutes a `${PLUGIN_ROOT}`-style
-# env var that we could rely on cross-runtime. Putting a thin wrapper
-# on PATH (via `o2b install-cli`) lets `hooks/hooks.json` invoke
-# `o2b-hook <name>` and have it always find the right plugin checkout.
+# Entry point Claude Code and Codex call from `hooks/hooks.json`.
#
-# The wrapper follows its own symlink back to whichever runtime's
-# checkout `install-cli` pointed it at, then execs the requested hook
-# under Bun. Bun precheck mirrors `scripts/o2b` so the failure modes
-# stay consistent.
+# Resilience contract (see docs/updating.md):
+# 1. FAIL-SOFT. This wrapper must NEVER exit 2 (the only hook exit code
+# that blocks the agent in Claude Code) and never abort the runtime.
+# Any internal problem -> warn on stderr and exit 0 (no-op).
+# 2. VERSION-CURRENT RESOLUTION. The plugin checkout root is resolved in
+# priority order, so a stale ~/.local/bin symlink can never strand the
+# hook on an old plugin version:
+# a. $CLAUDE_PLUGIN_ROOT (Claude Code; always the active version)
+# b. this wrapper's own realpath dir/.. (Codex / stable dir install)
+# c. $OSB_PLUGIN_ROOT (explicit override)
+# First candidate that actually contains hooks/<name>.ts wins.
+#
+# Because Claude Code reads hooks.json fresh from the active version and
+# substitutes $CLAUDE_PLUGIN_ROOT, shipping (1)+(2) means the NEXT update
+# repairs an already-broken install with no user action.
#
# Usage: o2b-hook <hook-basename> [args...]
-# e.g. o2b-hook stop-log-guardrail
-
-set -euo pipefail
-SELF=$(realpath -- "${BASH_SOURCE[0]}")
-SCRIPT_DIR=$(cd -- "$(dirname -- "$SELF")" && pwd)
-REPO_ROOT=$(cd -- "$SCRIPT_DIR/.." && pwd)
+# NOTE: deliberately no `-e`. We handle every failure explicitly so we can
+# always exit 0; `set -e` could abort before our soft-exit runs.
+set -uo pipefail
-# shellcheck source=./_bun-precheck.sh
-. "$SCRIPT_DIR/_bun-precheck.sh"
+warn() { printf 'o2b-hook: %s\n' "$1" >&2; }
HOOK_NAME=${1:-}
if [[ -z $HOOK_NAME ]]; then
- echo "usage: o2b-hook <hook-name> [args...]" >&2
- exit 2
+ warn "missing hook name; skipping"
+ exit 0
fi
shift
-HOOK_FILE="$REPO_ROOT/hooks/$HOOK_NAME.ts"
-if [[ ! -f "$HOOK_FILE" ]]; then
- echo "o2b-hook: $HOOK_FILE not found" >&2
- exit 2
+# Resolve the checkout root that actually contains this hook.
+resolve_root() {
+ local cand
+ # a. Claude Code's active plugin dir.
+ if [[ -n ${CLAUDE_PLUGIN_ROOT:-} && -f "${CLAUDE_PLUGIN_ROOT}/hooks/${HOOK_NAME}.ts" ]]; then
+ printf '%s\n' "$CLAUDE_PLUGIN_ROOT"
+ return 0
+ fi
+ # b. This wrapper's own location (follows the symlink to the real checkout).
+ local self
+ if self=$(realpath -- "${BASH_SOURCE[0]}" 2>/dev/null); then
+ cand=$(cd -- "$(dirname -- "$self")/.." 2>/dev/null && pwd || true)
+ if [[ -n $cand && -f "${cand}/hooks/${HOOK_NAME}.ts" ]]; then
+ printf '%s\n' "$cand"
+ return 0
+ fi
+ fi
+ # c. Explicit override.
+ if [[ -n ${OSB_PLUGIN_ROOT:-} && -f "${OSB_PLUGIN_ROOT}/hooks/${HOOK_NAME}.ts" ]]; then
+ printf '%s\n' "$OSB_PLUGIN_ROOT"
+ return 0
+ fi
+ return 1
+}
+
+ROOT=$(resolve_root) || {
+ warn "could not locate hooks/${HOOK_NAME}.ts (plugin root unresolved); skipping"
+ exit 0
+}
+
+if ! command -v bun >/dev/null 2>&1; then
+ warn "bun not on PATH; skipping ${HOOK_NAME}"
+ exit 0
fi
-exec bun run "$HOOK_FILE" "$@"
+# Do NOT exec: capture the hook's exit so a hook that itself exits non-zero
+# (e.g. 2) can never bubble out and block the agent. Stdout still passes
+# through (hooks that emit JSON decisions on stdout keep working). The
+# wrapper always exits 0 - the fail-soft contract.
+bun run "${ROOT}/hooks/${HOOK_NAME}.ts" "$@"
+status=$?
+if [[ $status -ne 0 ]]; then
+ warn "hook ${HOOK_NAME} exited ${status}; suppressed to keep the runtime unblocked"
+fi
+exit 0
diff --git a/src/cli/brain/verbs/attention-flows.ts b/src/cli/brain/verbs/attention-flows.ts
index d24b4509..bf7f8d07 100644
--- a/src/cli/brain/verbs/attention-flows.ts
+++ b/src/cli/brain/verbs/attention-flows.ts
@@ -12,9 +12,7 @@ export async function cmdBrainAttentionFlows(argv: string[]): Promise<number> {
if (sub === "list") return list(rest);
if (sub === "evaluate") return evaluate(rest);
if (sub === "render") return render(rest);
- throw new CliError(
- "brain attention-flows: expected list, evaluate, or render",
- );
+ throw new CliError("brain attention-flows: expected list, evaluate, or render");
}
function list(argv: string[]): number {
@@ -22,22 +20,15 @@ function list(argv: string[]): number {
vault: { type: "string" },
json: { type: "boolean" },
});
- const vault = resolveBrainVault(
- flags["vault"] as string | undefined,
- defaultConfigPath(),
- );
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
const flows = listAttentionFlows(vault);
if (flags["json"]) {
- process.stdout.write(
- JSON.stringify({ total: flows.length, flows }, null, 2) + "\n",
- );
+ process.stdout.write(JSON.stringify({ total: flows.length, flows }, null, 2) + "\n");
return 0;
}
process.stdout.write(`${flows.length} attention flow(s):\n`);
for (const flow of flows) {
- process.stdout.write(
- ` ${flow.id} actions=${flow.actions.join(",") || "-"}\n`,
- );
+ process.stdout.write(` ${flow.id} actions=${flow.actions.join(",") || "-"}\n`);
}
return 0;
}
@@ -48,12 +39,8 @@ function evaluate(argv: string[]): number {
json: { type: "boolean" },
});
const flowId = positional[0];
- if (!flowId)
- throw new CliError("brain attention-flows evaluate: flow id is required");
- const vault = resolveBrainVault(
- flags["vault"] as string | undefined,
- defaultConfigPath(),
- );
+ if (!flowId) throw new CliError("brain attention-flows evaluate: flow id is required");
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
let report;
try {
report = evaluateAttentionFlow(vault, flowId);
@@ -77,12 +64,8 @@ function render(argv: string[]): number {
json: { type: "boolean" },
});
const flowId = positional[0];
- if (!flowId)
- throw new CliError("brain attention-flows render: flow id is required");
- const vault = resolveBrainVault(
- flags["vault"] as string | undefined,
- defaultConfigPath(),
- );
+ if (!flowId) throw new CliError("brain attention-flows render: flow id is required");
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
let text: string;
try {
text = renderAttentionFlow(vault, flowId);
@@ -90,9 +73,7 @@ function render(argv: string[]): number {
throw mapAttentionFlowError(error, flowId);
}
if (flags["json"]) {
- process.stdout.write(
- JSON.stringify({ flow_id: flowId, text }, null, 2) + "\n",
- );
+ process.stdout.write(JSON.stringify({ flow_id: flowId, text }, null, 2) + "\n");
return 0;
}
process.stdout.write(text.endsWith("\n") ? text : text + "\n");
diff --git a/src/cli/install-cli.ts b/src/cli/install-cli.ts
index b1dd0a24..cc05021e 100644
--- a/src/cli/install-cli.ts
+++ b/src/cli/install-cli.ts
@@ -67,6 +67,60 @@ function isValidSymlink(link: string, target: string): boolean {
}
}
+/** Raw (possibly relative) target stored in the symlink, or null. */
+function rawLinkTarget(link: string): string | null {
+ try {
+ return readlinkSync(link);
+ } catch {
+ return null;
+ }
+}
+
+/** True when the symlink resolves to an existing file (i.e. is not dangling). */
+function linkResolves(link: string): boolean {
+ try {
+ return existsSync(realpathSync(link));
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Does an absolute path look like one of OUR CLI scripts from some Open Second
+ * Brain checkout, i.e. `<anything>/scripts/<name>`? Used to decide whether a
+ * non-current symlink is safe to reclaim (ours, just stale) vs. owned by an
+ * unrelated tool (leave it alone).
+ */
+function looksLikeOsbScript(absTarget: string, name: string): boolean {
+ const parts = absTarget.split(sep);
+ return parts[parts.length - 1] === name && parts[parts.length - 2] === "scripts";
+}
+
+/** Heuristic: the target lives inside a Claude Code plugin cache, which rotates
+ * version directories on update (so the symlink is expected to go stale). */
+function underPluginCache(absTarget: string): boolean {
+ return absTarget.includes(`${sep}plugins${sep}cache${sep}`);
+}
+
+/** Absolute form of a symlink's stored target (resolved against the link dir). */
+function absoluteTarget(link: string): string | null {
+ const raw = rawLinkTarget(link);
+ if (raw === null) return null;
+ return resolve(dirname(link), raw);
+}
+
+/**
+ * Explicit `install-cli` may reclaim a symlink that is dangling or that points
+ * at any OSB checkout's `scripts/<name>` (the user ran install-cli on purpose,
+ * so re-pointing to the running checkout is the intent). It must NOT clobber a
+ * symlink owned by an unrelated tool or a real file.
+ */
+function canReclaimOnInstall(link: string, name: string): boolean {
+ if (!linkResolves(link)) return true; // dangling
+ const abs = absoluteTarget(link);
+ return abs !== null && looksLikeOsbScript(abs, name);
+}
+
export function installCli(bindir?: string): InstallResult {
const dir = bindir ?? join(homedir(), ".local", "bin");
mkdirSync(dir, { recursive: true });
@@ -87,6 +141,19 @@ export function installCli(bindir?: string): InstallResult {
if (isLink(link)) {
if (isValidSymlink(link, source)) {
outcomes.push([name, `exists: ${link} → ${source}`]);
+ } else if (canReclaimOnInstall(link, name)) {
+ // Stale OSB symlink (e.g. pointing at a removed/old plugin version) or
+ // a dangling link: re-point it to the current checkout instead of
+ // forcing the user to delete it by hand. Idempotent across updates.
+ try {
+ unlinkSync(link);
+ symlinkSync(source, link);
+ outcomes.push([name, `repointed: ${link} → ${source}`]);
+ } catch (exc) {
+ const msg = `error: could not repoint symlink ${link}: ${(exc as Error).message ?? exc}`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ }
} else {
let existing = "unknown";
try {
@@ -94,10 +161,9 @@ export function installCli(bindir?: string): InstallResult {
} catch {
// ignore
}
- // Conflict: report as an error so cmdInstallCli exits non-zero.
- // Otherwise the user thinks install succeeded but their CLI still
- // points at the old checkout.
- const msg = `error: ${link} already points to ${existing}, not overwriting`;
+ // Conflict with a symlink owned by an unrelated tool: refuse, and
+ // report as an error so cmdInstallCli exits non-zero.
+ const msg = `error: ${link} already points to ${existing} (not an Open Second Brain script), not overwriting`;
outcomes.push([name, msg]);
errors.push(msg);
}
@@ -119,6 +185,50 @@ export function installCli(bindir?: string): InstallResult {
return { bindir: dir, outcomes, errors };
}
+/**
+ * Best-effort, non-interactive repair of the `~/.local/bin` CLI symlinks,
+ * meant to run from a SessionStart hook. Unlike `installCli`, this is automatic
+ * and therefore conservative: it only touches a symlink that is
+ * - dangling (its target was removed by a plugin update), or
+ * - an OSB `scripts/<name>` link that lives inside a Claude Code plugin cache
+ * (which rotates version dirs on update) and is not already current.
+ * It NEVER repoints a stable-directory install (e.g. `/srv/projects/...` used by
+ * Hermes/Codex on a server), never touches a foreign symlink, and never touches
+ * a real file. Resolves the current checkout from this module's own location,
+ * so it heals even when the on-PATH `o2b` is the stale one.
+ */
+export function healCliSymlinks(bindir?: string): InstallResult {
+ const dir = bindir ?? join(homedir(), ".local", "bin");
+ const outcomes: Array<readonly [string, string]> = [];
+ const errors: string[] = [];
+
+ for (const name of CLI_SCRIPTS) {
+ const link = join(dir, name);
+ const source = findScript(name);
+ if (source === null) continue; // cannot heal what we cannot source
+ if (!isLink(link)) continue; // absent, or a real file we must not touch
+ if (isValidSymlink(link, source)) continue; // already current
+
+ // Only auto-heal a link whose stored target is clearly OURS and lives in a
+ // version-rotating plugin cache (works for dangling links too, since the
+ // stored target is read via readlink). A dangling link that points at a
+ // stable-dir or foreign install is left alone - automatic repair must not
+ // hijack installs it does not own.
+ const abs = absoluteTarget(link);
+ const reclaimable = abs !== null && looksLikeOsbScript(abs, name) && underPluginCache(abs);
+ if (!reclaimable) continue;
+
+ try {
+ unlinkSync(link);
+ symlinkSync(source, link);
+ outcomes.push([name, `healed: ${link} → ${source}`]);
+ } catch (exc) {
+ errors.push(`could not heal ${link}: ${(exc as Error).message ?? exc}`);
+ }
+ }
+ return { bindir: dir, outcomes, errors };
+}
+
export function uninstallCli(bindir?: string): UninstallResult {
const dir = bindir ?? join(homedir(), ".local", "bin");
const repoScripts = scriptsDir();
diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.ts
index 71969a47..c72dc28b 100644
--- a/src/core/brain/context-pack.ts
+++ b/src/core/brain/context-pack.ts
@@ -27,14 +27,8 @@ import { PAGE_TIER, readTier, type PageTier } from "./page-meta/tier.ts";
import { estimateTokens } from "./text/tokenizer.ts";
import { normalizeForDedup } from "./text/normalize.ts";
import { applyCharBudget } from "./recall-budget.ts";
-import {
- emitContextReceipt,
- type ContextReceiptOptions,
-} from "./context-receipts.ts";
-import {
- emitRecallTelemetry,
- type RecallTelemetryOptions,
-} from "./recall-telemetry.ts";
+import { emitContextReceipt, type ContextReceiptOptions } from "./context-receipts.ts";
+import { emitRecallTelemetry, type RecallTelemetryOptions } from "./recall-telemetry.ts";
import {
applyContextTransforms,
type ContextTransformOptions,
@@ -71,11 +65,7 @@ export interface ContextPackItem extends ContextTransformAnnotations {
export interface ContextPackSkipped {
readonly id: string;
readonly tokens: number;
- readonly reason:
- | "over-budget"
- | "filter-miss"
- | "guard-blocked"
- | "over-char-budget";
+ readonly reason: "over-budget" | "filter-miss" | "guard-blocked" | "over-char-budget";
}
export interface ContextPackReport {
@@ -166,11 +156,9 @@ function collectCandidates(vault: string): Candidate[] {
} catch {
continue;
}
- const id =
- typeof meta["id"] === "string" ? meta["id"] : name.replace(/\.md$/, "");
+ const id = typeof meta["id"] === "string" ? meta["id"] : name.replace(/\.md$/, "");
const tier = readTier(meta);
- const created =
- typeof meta["created_at"] === "string" ? meta["created_at"] : "";
+ const created = typeof meta["created_at"] === "string" ? meta["created_at"] : "";
let fallbackMtimeMs = 0;
if (!created) {
try {
@@ -181,8 +169,7 @@ function collectCandidates(vault: string): Candidate[] {
}
const createdAtMs = created ? Date.parse(created) : fallbackMtimeMs;
const topic = typeof meta["topic"] === "string" ? meta["topic"] : "";
- const principle =
- typeof meta["principle"] === "string" ? meta["principle"] : "";
+ const principle = typeof meta["principle"] === "string" ? meta["principle"] : "";
const contextLane = normalizeContextLane(meta["context_lane"]);
const guarded = guardBrainContextSnippet(body, {
source: { id, path: full, metadata: meta },
@@ -205,19 +192,14 @@ function collectCandidates(vault: string): Candidate[] {
contextLane,
body: guarded.safeText,
tokens: estimateTokens(guarded.safeText),
- ...(contextSafetyReport(guarded)
- ? { safety: contextSafetyReport(guarded) }
- : {}),
+ ...(contextSafetyReport(guarded) ? { safety: contextSafetyReport(guarded) } : {}),
});
}
}
return out;
}
-export function packContext(
- vault: string,
- opts: ContextPackOptions,
-): ContextPackReport {
+export function packContext(vault: string, opts: ContextPackOptions): ContextPackReport {
const startedAtMs = Date.now();
if (!Number.isFinite(opts.maxTokens) || opts.maxTokens <= 0) {
return finalizeContextPackReport(
@@ -284,44 +266,37 @@ export function packContext(
}
if (opts.attentionFlowIds && opts.attentionFlowIds.length > 0) {
- const attentionBody = buildAttentionContextBlock(
- vault,
- opts.attentionFlowIds,
- );
+ const attentionBody = buildAttentionContextBlock(vault, opts.attentionFlowIds);
if (attentionBody && attentionBody.trim()) {
const guarded = guardBrainContextSnippet(attentionBody, {
- path: join(vault, "Brain", "attention", "flows"),
- contextLane: "directive",
+ source: { id: "attention-flows", path: join(vault, "Brain", "attention", "flows") },
});
- if (!guarded.allowed) {
- skipped.push({
+ const safeAttentionBody = guarded.safeText;
+ const tokens = estimateTokens(safeAttentionBody);
+ const safetyReport = contextSafetyReport(guarded);
+ if (!safeAttentionBody.trim()) {
+ // The guard reduced the whole block to nothing - surface nothing
+ // rather than an empty attention-flows item.
+ skipped.push({ id: "attention-flows", tokens: 0, reason: "filter-miss" });
+ } else if (used + tokens <= opts.maxTokens) {
+ items.unshift({
id: "attention-flows",
- tokens: estimateTokens(attentionBody),
- reason: "guard-blocked",
+ path: join(vault, "Brain", "attention", "flows"),
+ tier: PAGE_TIER.core,
+ tokens,
+ body: safeAttentionBody,
+ principle: "Declarative attention flow output",
+ contextLane: "directives",
+ trimmed: false,
+ ...(safetyReport ? { safety: safetyReport } : {}),
});
+ used += tokens;
} else {
- const safeAttentionBody = guarded.sanitized;
- const tokens = estimateTokens(safeAttentionBody);
- if (used + tokens <= opts.maxTokens) {
- items.unshift({
- id: "attention-flows",
- path: join(vault, "Brain", "attention", "flows"),
- tier: PAGE_TIER.core,
- tokens,
- body: safeAttentionBody,
- principle: "Declarative attention flow output",
- contextLane: "directive",
- trimmed: false,
- ...(guarded.report ? { safety: guarded.report } : {}),
- });
- used += tokens;
- } else {
- skipped.push({
- id: "attention-flows",
- tokens,
- reason: "over-budget",
- });
- }
+ skipped.push({
+ id: "attention-flows",
+ tokens,
+ reason: "over-budget",
+ });
}
}
}
@@ -368,10 +343,7 @@ export function packContext(
}
const finalItems = applyContextTransforms(items, opts.transforms);
- const finalTokensUsed = finalItems.reduce(
- (sum, item) => sum + item.tokens,
- 0,
- );
+ const finalTokensUsed = finalItems.reduce((sum, item) => sum + item.tokens, 0);
return finalizeContextPackReport(
vault,
opts,
@@ -424,9 +396,7 @@ function finalizeContextPackReport(
status: report.items.length > 0 ? "ok" : "empty",
durationMs: Date.now() - startedAtMs,
resultCount: report.items.length,
- topArtifacts: report.items
- .slice(0, 10)
- .map((item) => ({ id: item.id, path: item.path })),
+ topArtifacts: report.items.slice(0, 10).map((item) => ({ id: item.id, path: item.path })),
gaps: contextPackGaps(report),
metadata: {
...(opts.telemetry.metadata ?? {}),
@@ -451,17 +421,13 @@ function contextPackBudgetMetadata(
...(opts.maxCharsPerMemory !== undefined
? { max_chars_per_memory: opts.maxCharsPerMemory }
: {}),
- ...(opts.maxTotalChars !== undefined
- ? { max_total_chars: opts.maxTotalChars }
- : {}),
+ ...(opts.maxTotalChars !== undefined ? { max_total_chars: opts.maxTotalChars } : {}),
};
}
function contextPackGaps(report: ContextPackReport): ReadonlyArray<string> {
const gaps = new Set<string>();
- if (report.items.length === 0 && report.skipped.length === 0)
- gaps.add("no_matching_context");
- for (const skipped of report.skipped)
- gaps.add(skipped.reason.replace(/-/g, "_"));
+ if (report.items.length === 0 && report.skipped.length === 0) gaps.add("no_matching_context");
+ for (const skipped of report.skipped) gaps.add(skipped.reason.replace(/-/g, "_"));
return [...gaps];
}
diff --git a/src/core/brain/procedural-graph.ts b/src/core/brain/procedural-graph.ts
index 736de8fa..a786b87d 100644
--- a/src/core/brain/procedural-graph.ts
+++ b/src/core/brain/procedural-graph.ts
@@ -13,12 +13,7 @@ import {
} from "./paths.ts";
import type { ProceduralMemoryEntry } from "./procedural-memory.ts";
-export type ProceduralGraphNodeKind =
- | "procedure"
- | "skill"
- | "runbook"
- | "proposal"
- | "entity";
+export type ProceduralGraphNodeKind = "procedure" | "skill" | "runbook" | "proposal" | "entity";
export type ProceduralGraphEdgeKind =
| "derived_from_proposal"
| "trigger_matches"
@@ -147,18 +142,13 @@ export function rebuildProceduralGraph(
return projection;
}
-export function readProceduralGraph(
- vault: string,
-): ProceduralGraphProjection | null {
+export function readProceduralGraph(vault: string): ProceduralGraphProjection | null {
const path = proceduralGraphPath(vault);
if (!existsSync(path)) return null;
try {
- const parsed = JSON.parse(
- readFileSync(path, "utf8"),
- ) as ProceduralGraphProjection;
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as ProceduralGraphProjection;
if (parsed.schema_version !== 1) return null;
- if (!Array.isArray(parsed.nodes) || !Array.isArray(parsed.edges))
- return null;
+ if (!Array.isArray(parsed.nodes) || !Array.isArray(parsed.edges)) return null;
return parsed;
} catch {
return null;
@@ -181,10 +171,7 @@ function readProceduralIndex(vault: string): ProceduralMemoryEntry[] {
}
}
-function detectProcedureSourceProposal(
- vault: string,
- sourcePath: string,
-): string | null {
+function detectProcedureSourceProposal(vault: string, sourcePath: string): string | null {
if (!sourcePath.startsWith("Brain/procedures/")) return null;
let absPath: string;
try {
@@ -195,10 +182,7 @@ function detectProcedureSourceProposal(
if (!existsSync(absPath)) return null;
try {
const [fm] = parseFrontmatter(absPath);
- if (
- typeof fm["source_proposal"] === "string" &&
- fm["source_proposal"].trim()
- ) {
+ if (typeof fm["source_proposal"] === "string" && fm["source_proposal"].trim()) {
return fm["source_proposal"].trim();
}
return null;
@@ -223,10 +207,7 @@ function listProposals(vault: string): ProceduralGraphNode[] {
try {
const [fm] = parseFrontmatter(absPath);
if (fm["kind"] !== "brain-skill-proposal") continue;
- const id =
- typeof fm["id"] === "string"
- ? fm["id"]
- : `proposal-${basename(name, ".md")}`;
+ const id = typeof fm["id"] === "string" ? fm["id"] : `proposal-${basename(name, ".md")}`;
out.push({
id,
kind: "proposal",
@@ -288,9 +269,7 @@ function entityNodeId(raw: string): string {
.replace(/^-+|-+$/g, "")}`;
}
-function dedupeEdges(
- edges: ReadonlyArray<ProceduralGraphEdge>,
-): ProceduralGraphEdge[] {
+function dedupeEdges(edges: ReadonlyArray<ProceduralGraphEdge>): ProceduralGraphEdge[] {
const out: ProceduralGraphEdge[] = [];
const seen = new Set<string>();
for (const edge of edges) {
diff --git a/src/core/brain/procedural-hints.ts b/src/core/brain/procedural-hints.ts
index ae70cc83..a329fb98 100644
--- a/src/core/brain/procedural-hints.ts
+++ b/src/core/brain/procedural-hints.ts
@@ -3,10 +3,7 @@ import { dirname } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { proceduralHintsPath } from "./paths.ts";
-import {
- readProceduralGraph,
- type ProceduralGraphProjection,
-} from "./procedural-graph.ts";
+import { readProceduralGraph, type ProceduralGraphProjection } from "./procedural-graph.ts";
export interface ProceduralHintEntry {
readonly node_id: string;
@@ -47,9 +44,7 @@ export function rebuildProceduralHints(
}
entries.push({
node_id: node.id,
- cues: Object.freeze(
- [...cues].filter((item) => item.length >= 3).toSorted(),
- ),
+ cues: Object.freeze([...cues].filter((item) => item.length >= 3).toSorted()),
});
}
}
@@ -57,9 +52,7 @@ export function rebuildProceduralHints(
const projection: ProceduralHintsProjection = {
schema_version: 1,
generated_at: now.toISOString(),
- entries: Object.freeze(
- entries.toSorted((l, r) => l.node_id.localeCompare(r.node_id)),
- ),
+ entries: Object.freeze(entries.toSorted((l, r) => l.node_id.localeCompare(r.node_id))),
};
const path = proceduralHintsPath(vault);
@@ -68,15 +61,11 @@ export function rebuildProceduralHints(
return projection;
}
-export function readProceduralHints(
- vault: string,
-): ProceduralHintsProjection | null {
+export function readProceduralHints(vault: string): ProceduralHintsProjection | null {
const path = proceduralHintsPath(vault);
if (!existsSync(path)) return null;
try {
- const parsed = JSON.parse(
- readFileSync(path, "utf8"),
- ) as ProceduralHintsProjection;
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as ProceduralHintsProjection;
if (parsed.schema_version !== 1) return null;
if (!Array.isArray(parsed.entries)) return null;
return parsed;
diff --git a/src/core/brain/skill-proposals.ts b/src/core/brain/skill-proposals.ts
index a8bca46e..2af93732 100644
--- a/src/core/brain/skill-proposals.ts
+++ b/src/core/brain/skill-proposals.ts
@@ -1,11 +1,5 @@
import { createHash } from "node:crypto";
-import {
- existsSync,
- mkdirSync,
- readdirSync,
- readFileSync,
- unlinkSync,
-} from "node:fs";
+import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import { parseFrontmatter, slugify, writeFrontmatterAtomic } from "../vault.ts";
@@ -22,10 +16,7 @@ import {
skillProposalPendingPath,
skillProposalRejectedPath,
} from "./paths.ts";
-import {
- listContinuityRecords,
- type ContinuityRecord,
-} from "./continuity/store.ts";
+import { listContinuityRecords, type ContinuityRecord } from "./continuity/store.ts";
export type SkillProposalPatternKind =
| "repeated_action"
@@ -88,8 +79,7 @@ export function learnSkillProposals(
})
.toSorted(
(left, right) =>
- left.createdAt.localeCompare(right.createdAt) ||
- left.id.localeCompare(right.id),
+ left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
);
if (records.length === 0) {
@@ -115,11 +105,7 @@ export function learnSkillProposals(
const acceptedPath = skillProposalAcceptedPath(vault, slug);
const rejectedPath = skillProposalRejectedPath(vault, slug);
- if (
- existsSync(pendingPath) ||
- existsSync(acceptedPath) ||
- existsSync(rejectedPath)
- ) {
+ if (existsSync(pendingPath) || existsSync(acceptedPath) || existsSync(rejectedPath)) {
suppressed.push(proposalId);
continue;
}
@@ -179,10 +165,7 @@ export function listPendingSkillProposals(vault: string): ReadonlyArray<{
status: string;
patternKind: string;
}> {
- const dir = ensureInsideVault(
- join(vault, BRAIN_SKILL_PROPOSALS_REL, "pending"),
- vault,
- );
+ const dir = ensureInsideVault(join(vault, BRAIN_SKILL_PROPOSALS_REL, "pending"), vault);
if (!existsSync(dir)) return Object.freeze([]);
const out: Array<{
@@ -199,13 +182,9 @@ export function listPendingSkillProposals(vault: string): ReadonlyArray<{
if (typeof fm["id"] !== "string") continue;
out.push({
id: fm["id"],
- slug:
- typeof fm["slug"] === "string"
- ? fm["slug"]
- : fm["id"].replace(/^prop-/, ""),
+ slug: typeof fm["slug"] === "string" ? fm["slug"] : fm["id"].replace(/^prop-/, ""),
status: typeof fm["status"] === "string" ? fm["status"] : "pending",
- patternKind:
- typeof fm["pattern_kind"] === "string" ? fm["pattern_kind"] : "unknown",
+ patternKind: typeof fm["pattern_kind"] === "string" ? fm["pattern_kind"] : "unknown",
});
}
return Object.freeze(out);
@@ -339,15 +318,9 @@ function readWatermark(vault: string): WatermarkState {
const path = watermarkPath(vault);
if (!existsSync(path)) return { lastCreatedAt: null, lastId: null };
try {
- const parsed = JSON.parse(readFileSync(path, "utf8")) as Record<
- string,
- unknown
- >;
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
return {
- lastCreatedAt:
- typeof parsed["lastCreatedAt"] === "string"
- ? parsed["lastCreatedAt"]
- : null,
+ lastCreatedAt: typeof parsed["lastCreatedAt"] === "string" ? parsed["lastCreatedAt"] : null,
lastId: typeof parsed["lastId"] === "string" ? parsed["lastId"] : null,
};
} catch {
@@ -445,9 +418,7 @@ function detectCandidates(
temporalMap.set(key, bucket);
}
for (const [key, bucket] of temporalMap) {
- const daySet = new Set(
- bucket.map((record) => record.createdAt.slice(0, 10)),
- );
+ const daySet = new Set(bucket.map((record) => record.createdAt.slice(0, 10)));
if (daySet.size < minSupport) continue;
out.push({
patternKind: "temporal_routine",
@@ -460,8 +431,7 @@ function detectCandidates(
return out.toSorted(
(left, right) =>
- left.patternKind.localeCompare(right.patternKind) ||
- left.key.localeCompare(right.key),
+ left.patternKind.localeCompare(right.patternKind) || left.key.localeCompare(right.key),
);
}
@@ -528,10 +498,7 @@ function evidenceSnippet(record: ContinuityRecord): string {
return "";
}
-function proposalSlug(
- candidate: ProposalCandidate,
- payloadHash: string,
-): string {
+function proposalSlug(candidate: ProposalCandidate, payloadHash: string): string {
const keySlug = slugify(candidate.key).slice(0, 40);
return `${candidate.patternKind}-${keySlug}-${payloadHash.slice(0, 8)}`;
}
@@ -549,16 +516,10 @@ function candidateHash(candidate: ProposalCandidate): string {
.digest("hex");
}
-function renderAcceptedProcedureBody(
- proposalId: string,
- proposalBody: string,
-): string {
+function renderAcceptedProcedureBody(proposalId: string, proposalBody: string): string {
const marker = "## Suggested skill body";
const idx = proposalBody.indexOf(marker);
- const suggested =
- idx >= 0
- ? proposalBody.slice(idx + marker.length).trim()
- : proposalBody.trim();
+ const suggested = idx >= 0 ? proposalBody.slice(idx + marker.length).trim() : proposalBody.trim();
return [
"# Procedure",
"",
diff --git a/src/core/partner/codegraph.ts b/src/core/partner/codegraph.ts
index beb48be5..1f50d1e6 100644
--- a/src/core/partner/codegraph.ts
+++ b/src/core/partner/codegraph.ts
@@ -30,7 +30,6 @@ const CODE_MANIFESTS: ReadonlyArray<string> = [
];
const DEFAULT_LIMIT = 50;
-const CODEGRAPH_REPO = "https://github.com/colbymchenry/codegraph";
function isDir(path: string): boolean {
try {
@@ -171,12 +170,14 @@ function defaultRunStatusJson(projectPath: string): CodegraphStatusResult {
}
/**
- * Doctor-grade check for codegraph partnership. Returns `null` when
- * the current scope is not a code project (so the doctor printer can
- * stay quiet) or when the user has explicitly disabled the check.
+ * Doctor-grade check for codegraph partnership. Returns `null` (skip,
+ * no doctor output) when the current scope is not a code project, when the
+ * user has explicitly disabled the check, or when the codegraph CLI is not
+ * installed — codegraph is an optional partner OSB never installs, so its
+ * absence must not fail doctor.
*
* Non-null results carry a single `code_graph` `CheckResult` describing
- * one of four states: `missing`, `not_indexed`, `ok`, or `error`.
+ * one of three states: `not_indexed`, `ok`, or `error`.
*/
export function checkCodegraph(
opts: CodegraphCheckOptions,
@@ -192,11 +193,10 @@ export function checkCodegraph(
const cliPath = whichFn();
if (!cliPath) {
- return {
- name: "code_graph",
- ok: false,
- message: `code project at ${project}: codegraph not installed (install: ${CODEGRAPH_REPO})`,
- };
+ // codegraph is an optional partner OSB never installs. If the CLI is not
+ // on PATH there is nothing to check — skip silently rather than failing
+ // doctor, so `o2b doctor` stays green for users (and CI) without codegraph.
+ return null;
}
const indexDir = join(project, ".codegraph");
diff --git a/tests/cli/install-cli.test.ts b/tests/cli/install-cli.test.ts
index dac46e01..0703302a 100644
--- a/tests/cli/install-cli.test.ts
+++ b/tests/cli/install-cli.test.ts
@@ -2,8 +2,10 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import {
existsSync,
lstatSync,
+ mkdirSync,
mkdtempSync,
readlinkSync,
+ realpathSync,
rmSync,
symlinkSync,
writeFileSync,
@@ -11,7 +13,7 @@ import {
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { installCli, uninstallCli } from "../../src/cli/install-cli.ts";
+import { healCliSymlinks, installCli, uninstallCli } from "../../src/cli/install-cli.ts";
let tmp: string;
@@ -82,3 +84,109 @@ describe("uninstallCli", () => {
expect(result.outcomes.every(([_, msg]) => msg.startsWith("skipped:"))).toBe(true);
});
});
+
+function fakeOsbScript(root: string, name: string): string {
+ const dir = join(root, "scripts");
+ mkdirSync(dir, { recursive: true });
+ const file = join(dir, name);
+ writeFileSync(file, "#!/bin/sh\n");
+ return file;
+}
+
+describe("installCli (idempotent reclaim, no manual rm)", () => {
+ test("reclaims a dangling symlink", () => {
+ symlinkSync(join(tmp, "gone", "scripts", "o2b"), join(tmp, "o2b"));
+ const result = installCli(tmp);
+ expect(result.errors).toEqual([]);
+ expect(result.outcomes.some(([n, m]) => n === "o2b" && m.startsWith("repointed:"))).toBe(true);
+ expect(existsSync(realpathSync(join(tmp, "o2b")))).toBe(true);
+ expect(readlinkSync(join(tmp, "o2b"))).toContain(`scripts${"/"}o2b`);
+ });
+
+ test("reclaims a stale symlink pointing at another OSB checkout", () => {
+ const stale = fakeOsbScript(join(tmp, "old-version"), "o2b");
+ symlinkSync(stale, join(tmp, "o2b"));
+ const result = installCli(tmp);
+ expect(result.errors).toEqual([]);
+ expect(result.outcomes.some(([n, m]) => n === "o2b" && m.startsWith("repointed:"))).toBe(true);
+ expect(readlinkSync(join(tmp, "o2b"))).not.toBe(stale);
+ });
+});
+
+describe("healCliSymlinks", () => {
+ test("heals a dangling symlink that points into a plugin cache", () => {
+ const cacheTarget = join(
+ tmp,
+ "home",
+ ".claude",
+ "plugins",
+ "cache",
+ "open-second-brain",
+ "open-second-brain",
+ "0.0.9",
+ "scripts",
+ "o2b",
+ );
+ symlinkSync(cacheTarget, join(tmp, "o2b")); // target does not exist (dangling)
+ const r = healCliSymlinks(tmp);
+ expect(r.outcomes.some(([n, m]) => n === "o2b" && m.startsWith("healed:"))).toBe(true);
+ expect(existsSync(realpathSync(join(tmp, "o2b")))).toBe(true);
+ });
+
+ test("leaves a dangling symlink that is not under a plugin cache alone", () => {
+ // Could be a broken stable-dir install; automatic repair must not hijack it.
+ symlinkSync(join(tmp, "gone", "scripts", "o2b"), join(tmp, "o2b"));
+ const r = healCliSymlinks(tmp);
+ expect(r.outcomes.length).toBe(0);
+ expect(lstatSync(join(tmp, "o2b")).isSymbolicLink()).toBe(true);
+ });
+
+ test("heals an OSB symlink that lives inside a plugin cache", () => {
+ const cacheRoot = join(
+ tmp,
+ "home",
+ ".claude",
+ "plugins",
+ "cache",
+ "open-second-brain",
+ "open-second-brain",
+ "0.1.0",
+ );
+ const stale = fakeOsbScript(cacheRoot, "o2b");
+ symlinkSync(stale, join(tmp, "o2b"));
+ const r = healCliSymlinks(tmp);
+ expect(r.outcomes.some(([n, m]) => n === "o2b" && m.startsWith("healed:"))).toBe(true);
+ expect(readlinkSync(join(tmp, "o2b"))).not.toBe(stale);
+ });
+
+ test("leaves a stable-directory install alone (not under a plugin cache)", () => {
+ const stableTarget = fakeOsbScript(join(tmp, "srv", "open-second-brain"), "o2b");
+ symlinkSync(stableTarget, join(tmp, "o2b"));
+ const r = healCliSymlinks(tmp);
+ expect(r.outcomes.length).toBe(0);
+ expect(readlinkSync(join(tmp, "o2b"))).toBe(stableTarget);
+ });
+
+ test("leaves a foreign symlink alone", () => {
+ const foreign = join(tmp, "foreign.sh");
+ writeFileSync(foreign, "#!/bin/sh\n");
+ symlinkSync(foreign, join(tmp, "o2b"));
+ const r = healCliSymlinks(tmp);
+ expect(r.outcomes.length).toBe(0);
+ expect(readlinkSync(join(tmp, "o2b"))).toBe(foreign);
+ });
+
+ test("never touches a real (non-symlink) file", () => {
+ const real = join(tmp, "o2b");
+ writeFileSync(real, "i am not a symlink\n");
+ const r = healCliSymlinks(tmp);
+ expect(r.outcomes.length).toBe(0);
+ expect(lstatSync(real).isSymbolicLink()).toBe(false);
+ });
+
+ test("is a no-op when links are already current", () => {
+ installCli(tmp);
+ const r = healCliSymlinks(tmp);
+ expect(r.outcomes.length).toBe(0);
+ });
+});
diff --git a/tests/core/doctor.test.ts b/tests/core/doctor.test.ts
index 070dfaf3..920e9361 100644
--- a/tests/core/doctor.test.ts
+++ b/tests/core/doctor.test.ts
@@ -148,13 +148,18 @@ describe("doctor aggregator", () => {
expect(results.some((r) => r.name === "code_graph")).toBe(false);
});
- test("includes code_graph when cwd is a code project", () => {
+ test("includes code_graph for a code project only when codegraph is installed", () => {
const repo = join(tmp, "myrepo");
mkdirSync(join(repo, ".git"), { recursive: true });
writeFileSync(join(repo, "package.json"), "{}\n");
const vaultDir = join(tmp, "vault");
mkdirSync(vaultDir);
const results = doctor({ vault: vaultDir, cwd: repo });
- expect(results.some((r) => r.name === "code_graph")).toBe(true);
+ // codegraph is an optional partner: the check appears for a code project
+ // only when the CLI is actually installed (it is skipped otherwise), so
+ // this stays hermetic whether or not the runner has codegraph.
+ const codegraphInstalled =
+ (Bun as unknown as { which: (c: string) => string | null }).which("codegraph") !== null;
+ expect(results.some((r) => r.name === "code_graph")).toBe(codegraphInstalled);
});
});
diff --git a/tests/core/partner/codegraph.test.ts b/tests/core/partner/codegraph.test.ts
index a97665a8..820b7a7d 100644
--- a/tests/core/partner/codegraph.test.ts
+++ b/tests/core/partner/codegraph.test.ts
@@ -157,16 +157,16 @@ describe("checkCodegraph", () => {
expect(r).toBeNull();
});
- test("code project + no CLI -> missing", () => {
+ test("code project + no CLI -> skipped (codegraph is optional)", () => {
+ // OSB never installs codegraph; its absence is normal, not a doctor
+ // failure. When the CLI is not on PATH the check is skipped entirely so
+ // `o2b doctor` stays green for the many users without codegraph.
const repo = makeRepo(join(tmp, "repo"));
const r = checkCodegraph(
{ cwd: repo, vault: join(tmp, "vault") },
{ whichCodegraph: () => null },
);
- expect(r).not.toBeNull();
- expect(r!.name).toBe("code_graph");
- expect(r!.ok).toBe(false);
- expect(r!.message.toLowerCase()).toContain("not installed");
+ expect(r).toBeNull();
});
test("code project + CLI + no .codegraph/ -> not_indexed", () => {
@@ -228,8 +228,11 @@ describe("checkCodegraph", () => {
test("falls back to real PATH lookup when no whichCodegraph dep provided", () => {
const repo = makeRepo(join(tmp, "repo"));
+ // No injected dep -> real PATH lookup. The result is environment-dependent
+ // (null when codegraph is not installed, a code_graph result when it is),
+ // so assert only that the fallback wiring runs without throwing and yields
+ // a well-formed value either way.
const r = checkCodegraph({ cwd: repo, vault: join(tmp, "vault") });
- expect(r).not.toBeNull();
- expect(r!.name).toBe("code_graph");
+ expect(r === null || r.name === "code_graph").toBe(true);
});
});
diff --git a/tests/hooks/hooks-json-shape.test.ts b/tests/hooks/hooks-json-shape.test.ts
new file mode 100644
index 00000000..9a1cb1a4
--- /dev/null
+++ b/tests/hooks/hooks-json-shape.test.ts
@@ -0,0 +1,67 @@
+/**
+ * Lock the resilient shape of every hook command in hooks/hooks.json.
+ *
+ * Each command must resolve the wrapper via $CLAUDE_PLUGIN_ROOT (Claude Code,
+ * current version) with a PATH fallback (Codex / stable dir) and must end with
+ * `exit 0` so a hook can never block the agent. The bare `o2b-hook <name>`
+ * form is forbidden because it relies solely on a PATH symlink that goes stale
+ * across plugin updates.
+ */
+import { describe, expect, test } from "bun:test";
+import { spawnSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+const HOOKS_JSON = join(REPO, "hooks", "hooks.json");
+
+interface HookEntry {
+ type: string;
+ command: string;
+}
+function allCommands(): string[] {
+ const parsed = JSON.parse(readFileSync(HOOKS_JSON, "utf8")) as {
+ hooks: Record<string, Array<{ hooks: HookEntry[] }>>;
+ };
+ const cmds: string[] = [];
+ for (const groups of Object.values(parsed.hooks)) {
+ for (const group of groups) {
+ for (const h of group.hooks) {
+ if (h.type === "command") cmds.push(h.command);
+ }
+ }
+ }
+ return cmds;
+}
+
+describe("hooks.json command shape", () => {
+ const cmds = allCommands();
+
+ test("is valid JSON with at least one command", () => {
+ expect(cmds.length).toBeGreaterThan(0);
+ });
+
+ test("every command is version-current, has a PATH fallback, and never blocks", () => {
+ for (const cmd of cmds) {
+ expect(cmd).toContain("$CLAUDE_PLUGIN_ROOT");
+ expect(cmd).toContain("/scripts/o2b-hook");
+ expect(cmd).toContain("command -v o2b-hook");
+ expect(cmd.trimEnd().endsWith("exit 0")).toBe(true);
+ // Must NOT be the bare PATH-only form.
+ expect(/^o2b-hook\s/.test(cmd.trim())).toBe(false);
+ }
+ });
+
+ test("a command never blocks when nothing resolves (exit 0)", () => {
+ const cmd = cmds[0]!;
+ const env = { ...process.env } as Record<string, string | undefined>;
+ delete env["CLAUDE_PLUGIN_ROOT"];
+ delete env["OSB_PLUGIN_ROOT"];
+ // Minimal PATH: sh + coreutils resolve, but the `o2b-hook` fallback
+ // (installed under ~/.local/bin) does not.
+ env["PATH"] = "/usr/bin:/bin";
+ const r = spawnSync("sh", ["-c", cmd], { env, encoding: "utf8" });
+ expect(r.status).toBe(0);
+ });
+});
diff --git a/tests/hooks/o2b-hook.test.ts b/tests/hooks/o2b-hook.test.ts
new file mode 100644
index 00000000..e06ca4ca
--- /dev/null
+++ b/tests/hooks/o2b-hook.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Resilience contract for the `scripts/o2b-hook` wrapper.
+ *
+ * These guard the two guarantees that keep plugin updates from bricking the
+ * agent (see docs/updating.md):
+ * 1. fail-soft: a missing/unresolvable hook exits 0, never 2.
+ * 2. version-current resolution: $CLAUDE_PLUGIN_ROOT wins over the wrapper's
+ * own (possibly stale-symlinked) location, so a stale ~/.local/bin link
+ * cannot strand the hook on an old plugin version.
+ */
+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 { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+const WRAPPER = join(REPO, "scripts", "o2b-hook");
+
+const tmps: string[] = [];
+function freshRoot(withHook: string | null): string {
+ const root = mkdtempSync(join(tmpdir(), "o2bhook-"));
+ tmps.push(root);
+ mkdirSync(join(root, "hooks"), { recursive: true });
+ mkdirSync(join(root, "scripts"), { recursive: true });
+ cpSync(WRAPPER, join(root, "scripts", "o2b-hook"));
+ if (withHook !== null) {
+ writeFileSync(join(root, "hooks", `${withHook}.ts`), `console.log("PROBE_OK:${withHook}");\n`);
+ }
+ return root;
+}
+
+// Run the wrapper with a controlled env. CLAUDE_PLUGIN_ROOT is cleared unless given.
+function runHook(wrapperPath: string, args: string[], env: Record<string, string | undefined>) {
+ const baseEnv = { ...process.env };
+ delete baseEnv["CLAUDE_PLUGIN_ROOT"];
+ delete baseEnv["OSB_PLUGIN_ROOT"];
+ return spawnSync("bash", [wrapperPath, ...args], {
+ env: { ...baseEnv, ...env },
+ encoding: "utf8",
+ });
+}
+
+afterEach(() => {
+ while (tmps.length) {
+ try {
+ rmSync(tmps.pop()!, { recursive: true, force: true });
+ } catch {
+ // ignore
+ }
+ }
+});
+
+describe("o2b-hook resilience", () => {
+ test("resolves the hook via CLAUDE_PLUGIN_ROOT and runs it", () => {
+ const root = freshRoot("probe");
+ const r = runHook(WRAPPER, ["probe"], { CLAUDE_PLUGIN_ROOT: root });
+ expect(r.status).toBe(0);
+ expect(r.stdout).toContain("PROBE_OK:probe");
+ });
+
+ test("missing hook fails soft: exit 0, never 2, with a warning", () => {
+ // No CLAUDE_PLUGIN_ROOT, and the repo checkout has no such hook file.
+ const r = runHook(WRAPPER, ["definitely-not-a-real-hook"], {});
+ expect(r.status).toBe(0);
+ expect(r.status).not.toBe(2);
+ expect(r.stderr).toContain("could not locate");
+ });
+
+ test("a hook that exits 2 is suppressed to exit 0 (never blocks)", () => {
+ const root = freshRoot(null);
+ writeFileSync(join(root, "hooks", "boom.ts"), `process.exit(2);\n`);
+ const r = runHook(WRAPPER, ["boom"], { CLAUDE_PLUGIN_ROOT: root });
+ expect(r.status).toBe(0);
+ expect(r.status).not.toBe(2);
+ });
+
+ 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.
+ const oldRoot = freshRoot(null); // old version: wrapper present, hook absent
+ const newRoot = freshRoot("probe"); // active version: has the hook
+ const linkDir = mkdtempSync(join(tmpdir(), "o2bbin-"));
+ tmps.push(linkDir);
+ const link = join(linkDir, "o2b-hook");
+ symlinkSync(join(oldRoot, "scripts", "o2b-hook"), link);
+
+ const r = runHook(link, ["probe"], { CLAUDE_PLUGIN_ROOT: newRoot });
+ expect(r.status).toBe(0);
+ expect(r.stdout).toContain("PROBE_OK:probe");
+ });
+});
diff --git a/tests/mcp/procedural-learning-tools.test.ts b/tests/mcp/procedural-learning-tools.test.ts
index 112921eb..11b33cf6 100644
--- a/tests/mcp/procedural-learning-tools.test.ts
+++ b/tests/mcp/procedural-learning-tools.test.ts
@@ -4,11 +4,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";
-import {
- JSONRPC_VERSION,
- MCPServer,
- PROTOCOL_VERSION,
-} from "../../src/mcp/index.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { buildToolTable } from "../../src/mcp/tools.ts";
let vault: string;
@@ -78,12 +74,8 @@ describe("procedural learning tool registration", () => {
"brain_recurrence",
"brain_attention_flows",
] as const) {
- expect(
- buildToolTable("full").find((tool) => tool.name === name),
- ).toBeDefined();
- expect(
- buildToolTable("writer").find((tool) => tool.name === name),
- ).toBeUndefined();
+ expect(buildToolTable("full").find((tool) => tool.name === name)).toBeDefined();
+ expect(buildToolTable("writer").find((tool) => tool.name === name)).toBeUndefined();
}
});
});
@@ -135,9 +127,7 @@ describe("procedural learning MCP tools", () => {
operation: "rebuild",
});
expect(graphRebuild.operation).toBe("rebuild");
- expect(
- (graphRebuild.graph as Record<string, unknown>).nodes as number,
- ).toBeGreaterThan(0);
+ expect((graphRebuild.graph as Record<string, unknown>).nodes as number).toBeGreaterThan(0);
const graphShow = await callTool(server, "brain_procedural_graph", {
operation: "show",
@@ -153,9 +143,7 @@ describe("procedural learning MCP tools", () => {
operation: "list",
});
expect(flowsList.total).toBeGreaterThan(0);
- const flowId = (flowsList.flows as Array<Record<string, unknown>>)[0]![
- "id"
- ] as string;
+ const flowId = (flowsList.flows as Array<Record<string, unknown>>)[0]!["id"] as string;
const flowsEval = await callTool(server, "brain_attention_flows", {
operation: "evaluate",
diff --git a/tests/setup.ts b/tests/setup.ts
new file mode 100644
index 00000000..10d35445
--- /dev/null
+++ b/tests/setup.ts
@@ -0,0 +1,30 @@
+/**
+ * Global bun:test preload (registered in bunfig.toml).
+ *
+ * Makes the whole suite hermetic: unless a test or the environment already
+ * points `OPEN_SECOND_BRAIN_CONFIG` somewhere explicit, every test resolves an
+ * isolated throwaway vault + config instead of the developer's real
+ * `~/.config/open-second-brain/config.yaml`.
+ *
+ * Two problems this fixes:
+ * 1. On a bare CI runner there is no `o2b init` config, so any test that
+ * resolved the config threw "plugin config not found" - ~136 failures
+ * that only passed on a machine with a pre-initialised config.
+ * 2. On a configured machine those same tests read (and could write) the
+ * operator's REAL vault. A throwaway default keeps tests off it.
+ *
+ * Tests that need their own vault still set `OPEN_SECOND_BRAIN_CONFIG` /
+ * `XDG_CONFIG_HOME` themselves; this only provides a safe default.
+ */
+import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+if (!process.env["OPEN_SECOND_BRAIN_CONFIG"]) {
+ const root = mkdtempSync(join(tmpdir(), "osb-test-default-"));
+ const vault = join(root, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ const configPath = join(root, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\n`);
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+}