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
v0.8.1: Lifecycle hooks β fix silent event_log_append skips
Sol Aitkenb939f2eb4798
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 87521468..be86d3e1 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.8.0",+ "version": "0.8.1","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 3a52c089..dc884072 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,7 +1,8 @@{"name": "open-second-brain",- "version": "0.8.0",+ "version": "0.8.1","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills",+ "hooks": "./hooks/hooks.json","keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"]}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3e8322f9..ce6ebfaa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,88 @@ 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.8.1] - 2026-05-14++Plugin-bundled lifecycle hooks for Claude Code and Codex that close a+real silent-skip bug: the MCP server's `instructions` reminder to call+`event_log_append` after a durable artifact was being dropped under+load with no visible signal β agent finished the turn, the vault's+Daily log stayed empty, no stderr trail. This release moves the+reminder out of soft instructions and into a runtime-side guardrail.++Hermes and OpenClaw are unaffected: Hermes already injects the+equivalent reminder through its `pre_llm_call` shim, and OpenClaw's+native JS plugin format predates the hook schema. The new hooks are+loaded only by Claude Code and Codex.++### Added++- **Lifecycle hooks** (`hooks/`):+ - `PostToolUse` (matcher `Write|Edit|MultiEdit|apply_patch`) β emits+ a developer-context reminder right after the file-mutating tool+ returns. Skipped when `tool_response` reports `is_error: true` or+ `success: false` so failed edits do not generate noise.+ - `Stop` β parses the runtime's transcript JSONL, decides whether+ the turn produced a durable artifact AND whether+ `event_log_append` was called (recognising both the bare Codex+ name `event_log_append` and the Claude-decorated+ `mcp__plugin_open-second-brain_open-second-brain__event_log_append`,+ matched via `/(?:^|__)event_log_append$/` so future prefix+ renames keep working). Emits `{"decision":"block","reason":β¦}`+ once per turn; respects `stop_hook_active === true` so the next+ Stop passes unconditionally β the agent decides whether to log+ or just finish, no deadlocks.+ - Bash logging counts: if the agent ran `o2b append-event β¦` or+ `vault-log β¦` through `Bash` (Claude) or `exec_command` /+ `shell` (Codex), the parser pulls the command string out of the+ transcript and the guardrail treats it as a valid log call.+- **`scripts/o2b-hook`** β PATH-deployed shim that both runtimes+ invoke from `hooks/hooks.json`. Resolves its own location, runs+ the Bun precheck, and execs `hooks/<name>.ts`. `o2b install-cli`+ now symlinks `o2b-hook` alongside `o2b` and `vault-log`. One+ PATH-discoverable entry point works in both runtimes without a+ per-runtime `${PLUGIN_ROOT}` env var (Codex 0.129 exposes none).+- **Codex manifest wiring**: `"hooks": "./hooks/hooks.json"` added to+ both `.codex-plugin/plugin.json` and+ `plugins/codex/.codex-plugin/plugin.json`; `plugins/codex/hooks`+ symlinked to `../../hooks` (mirrors the existing+ `plugins/codex/skills` pattern).+- **Tests** (`tests/hooks/`): 52 new bun:test cases covering format+ detection, Claude / Codex transcript shapes, artifact / log+ classification (including the prefix-decorated MCP names),+ Bash-as-log paths, the trailing-newline JSON contract, malformed+ JSONL, empty transcripts, missing `transcript_path`,+ `stop_hook_active`, failed-edit suppression.+- **Documentation**:+ - `hooks/README.md` β full design notes (cross-runtime detection,+ PATH-based shim rationale, symlink caveat for Codex marketplace+ staging, cwd contract for test subprocesses).+ - `install.md` branches C (Codex) and D (Claude Code) β new+ `### 6b. Lifecycle hooks (auto-enabled)` sections; step 3 in+ every branch now mentions the `o2b-hook` symlink.+ - `install.md` readiness checklist β split the `VAULT_AGENT_NAME`+ line so it requires the env var for Hermes / Codex only;+ Claude Code derives identity from the persisted plugin config+ that `o2b init --agent-name` writes.+ - `README.md` rewritten to be runtime-neutral β removed Hermes-first+ framing and duplication with `install.md`, added a+ Supported-runtimes table and a Lifecycle-hooks section.++### Fixed++- Silent `event_log_append` skips after a durable artifact landed,+ visible in real Claude Code sessions where a Write or Edit was+ followed by no log call and no warning. The `Stop` guardrail now+ blocks the turn once with a clear reason; the agent must either+ log or explicitly skip by sending its final reply a second time.++### Changed++- `sync-version` now also updates `plugins/codex/.codex-plugin/plugin.json`+ (it was stuck at 0.7.0). All seven manifests stay in lockstep with+ `package.json`.+- `tsconfig.json` `include` extended to cover `hooks/**/*.ts`.+## [0.8.0] - 2026-05-10Pay Memory: a memory and audit layer for paid agent actions. Hermes (or anydiff --git a/README.md b/README.mdindex 6d9dedda..8f9ce7f8 100644--- a/README.md+++ b/README.md@@ -1,176 +1,154 @@-# OpenSecondBrain--OpenSecondBrain gives Hermes Agent a small, filesystem-first second brain for Obsidian-compatible Markdown vaults.--It is built for Hermes first: install it as a Hermes plugin, point it at a vault, and let Hermes use deterministic commands for the parts that should not depend on model reasoning β setup checks, vault bootstrap, daily event logging, safe config export, and wiki indexing.--Claude Code, OpenAI Codex, and OpenClaw are supported through lightweight adapter manifests and the MCP tool server. Hermes is the primary runtime.--## What it does today--- Bootstraps an agent-owned area inside your vault: `AI Wiki/` plus `_OPEN_SECOND_BRAIN.md`.-- Appends agent events to daily Markdown notes without editing your manual notes above `## Raw events`.-- Regenerates a simple Markdown page index from frontmatter and wikilinks.+# Open Second Brain++A filesystem-first, agent-owned second brain for Obsidian-compatible+Markdown vaults. Plugs into the agent runtime you already use β Hermes+Agent, Claude Code, OpenAI Codex, OpenClaw, or any MCP-aware client β+and gives it deterministic CLI / MCP / hook surfaces for vault setup,+daily event logging, wiki indexing, paid-action audit, and health+checks. The model never has to guess at any of that.++Open Second Brain is **not** a daemon, **not** a vault replacement, and+never writes hidden state outside the configured vault and config+directory.++## Supported runtimes++| Runtime | Integration | Notes |+| --------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |+| Hermes Agent | Hermes plugin (`plugin.yaml`) + MCP server | Adds a per-turn identity reminder via the `pre_llm_call` hook. |+| Claude Code | Marketplace plugin + bundled `.mcp.json` + lifecycle hooks | `hooks/hooks.json` registers `PostToolUse` reminder + `Stop` guardrail (see [`hooks/`](hooks/)). |+| OpenAI Codex | Marketplace plugin + MCP server + lifecycle hooks | Same hook bundle as Claude Code. |+| OpenClaw | Native JS plugin (`openclaw.extensions`) β no MCP needed | The five core tools are registered directly inside OpenClaw's Node.js process. |+| Other MCP hosts | Generic adapter (stdio MCP server, persisted plugin config) | See `install.md` branch E for the contract. |++## What it does++- Bootstraps an agent-owned area inside your vault β `AI Wiki/`+ plus `_OPEN_SECOND_BRAIN.md`.+- Appends agent events to daily Markdown notes+ (`Daily/YYYY.MM.DD.md`, append-only below `## Raw events`).+- Regenerates a Markdown page index from frontmatter and wikilinks.- Exports config snapshots with secret-like values redacted.-- Runs health checks for the vault, config file, Hermes plugin, and Claude/Codex manifests.-- Ships with dependency-free CLI wrappers: `scripts/o2b` and `scripts/vault-log`.--OpenSecondBrain does not run a daemon, replace your vault, or write hidden background state outside the configured vault/config paths.--## Installation--> **Agent-assisted install (recommended):** The easiest way to install this plugin is to send your agent the following prompt with a link to the installation guide. <ins>Replace `[your_agent_name, Hermes for example]` with the runtime you are installing into</ins> β for example `Hermes`, `Claude Code`, `Codex`, or `OpenClaw`. The agent uses that name to pick the correct branch in the install guide.->-> ```-> Install the open-second-brain plugin for [your_agent_name, Hermes for example] following the instructions at https://raw.githubusercontent.com/itechmeat/open-second-brain/main/install.md-> ```->-> The guide at `install.md` contains exact commands for both Hermes and OpenClaw runtimes. Below are the same instructions for manual installation.--### Install in Hermes+- Runs vault + adapter health checks (`o2b doctor`).+- (Optional) Records paid agent actions through **Pay Memory**:+ receipts, generated assets, spending policy decisions, human+ approval state, and per-day reports β all as plain Markdown inside+ the vault.-In the Hermes Dashboard:+## Install-1. Open Plugins.-2. Choose Install from GitHub / Git URL.-3. Paste this repository URL:+`install.md` is the canonical install guide. It is written so an+agent can read it directly and pick the right branch by runtime+name. The recommended way to install is to send your agent the+prompt below β replace `[runtime]` with `Hermes`, `Claude Code`,+`Codex`, or `OpenClaw`:```text-https://github.com/itechmeat/open-second-brain-```--4. Install and enable the plugin.-5. Restart Hermes or start a fresh session if the plugin list was already loaded.--Hermes also supports the same flow from the CLI:--```bash-hermes plugins install itechmeat/open-second-brain --enable-hermes gateway restart-```--Then publish the CLI commands to PATH, initialize the vault, register the MCP server, and verify:--```bash-~/.hermes/plugins/open-second-brain/scripts/o2b install-cli-o2b init --vault /path/to/vault --name "My Second Brain"-hermes mcp add open-second-brain --command o2b --args mcp --vault /path/to/vault-hermes gateway restart-o2b doctor --vault /path/to/vault --repo .+Install the open-second-brain plugin for [runtime] following the+instructions at+https://raw.githubusercontent.com/itechmeat/open-second-brain/main/install.md```-### Install in OpenClaw+For manual installs, follow the matching branch in+[`install.md`](install.md) directly:-OpenClaw supports this project through the **Native plugin format**: a root `package.json` with `openclaw.extensions` pointing to a JS entry that registers tools natively inside OpenClaw's Node.js process. The JS entry spawns the Python CLI as a subprocess, so no MCP server is needed for basic operation.+- Branch A β Hermes+- Branch B β OpenClaw+- Branch C β Codex+- Branch D β Claude Code+- Branch E β generic adapter (other runtimes)-Install from Git (always installs the latest from `main`; do not append `@v...`):+Each branch covers the same six steps: collect vault path, install+plugin, publish CLI to PATH (`o2b install-cli`), initialise the+vault (`o2b init`), register the MCP server (where needed), and+verify with `o2b doctor` + a daily-identity check.-```bash-openclaw plugins install git:github.com/itechmeat/open-second-brain-```+## CLI-Or from a local checkout:--```bash-openclaw plugins install ./open-second-brain-```--After installing, configure the vault path, instance name, and agent identity:--```bash-openclaw config set plugins.entries.open-second-brain.config.vault '"/path/to/vault"'-openclaw config set plugins.entries.open-second-brain.config.instanceName '"My Second Brain"'-openclaw config set plugins.entries.open-second-brain.config.agentName '"openclaw-main"'-```--`agentName` is the identity used in `Daily/*.md` event log entries-(`- HH:MM β @openclaw-main β message`). Pick a name that makes the host-or runtime obvious β `openclaw-main`, `openclaw-server`,-`<hostname>-openclaw`, etc.--Tools are registered natively by the JS plugin entry β no MCP registration is needed. The five tools (`second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`) are available immediately after install and gateway restart. The optional MCP server (`o2b mcp`) can still be enabled for runtimes that prefer the MCP protocol.--## First run--Create or update the OpenSecondBrain profile inside a vault. Pass-`--agent-name` to register the identity used in Daily event log entries:--```bash-scripts/o2b init --vault /path/to/vault --name "My Second Brain" --agent-name "openclaw-main"-```--Check that the vault and runtime adapters are healthy:--```bash-scripts/o2b doctor --vault /path/to/vault --repo .-```--Append an agent event:--```bash-scripts/o2b append-event --vault /path/to/vault --as hermes "initialized OpenSecondBrain"-```--Refresh the Markdown page index:--```bash-scripts/o2b index --vault /path/to/vault-```--## CLI commands+After `o2b install-cli` the following commands are on PATH:```text-o2b status Show config/vault status-o2b init Bootstrap the vault profile-o2b install-cli Symlink o2b and vault-log into ~/.local/bin-o2b doctor Run vault and adapter checks+o2b status Show config / vault status+o2b init Bootstrap the vault profile (idempotent)+o2b install-cli Symlink o2b, vault-log, o2b-hook into ~/.local/bin+o2b doctor Run vault + adapter checkso2b append-event Append one daily event-log entryo2b index Rebuild the Markdown page indexo2b export-config Write a redacted config snapshoto2b mcp Run the optional MCP tool server (stdio)-o2b uninstall Print an uninstall plan; --apply-local removes config; --remove-cli removes symlinks+o2b tool-call Invoke an MCP tool handler from the CLI+o2b uninstall Print uninstall plan; --apply-local cleans config; --remove-cli removes symlinks++# Pay Memoryo2b init-pay-memory Bootstrap AI Wiki/{policies,payments,assets,drafts,reports}/o2b append-payment-receipt Save a Markdown receipt for a paid API callo2b capture-asset Save a Markdown note for a generated asseto2b payment-report Aggregate a date's receipts into a Markdown reporto2b check-payment-policy Evaluate a paid call against policies/spending.jsono2b request-payment-approval Create a pending payment request (human must approve)-o2b approve-payment-request Mark a pending request as approved (human action)-o2b reject-payment-request Mark a pending request as rejected (human action)+o2b approve-payment-request Mark a pending request as approved+o2b reject-payment-request Mark a pending request as rejectedo2b consume-payment-request Link an approved request to its resulting receipt-o2b list-pending-payments List pending/approved/etc. requests-o2b payment-digest Render a 4-line digest for a date (Hermes cron-friendly)-vault-log Compatibility wrapper around append-event-```--After running `o2b install-cli`, the bare `o2b` and `vault-log` commands are available on PATH. The local checkout can also be used without installing the Python package β run commands through `scripts/o2b` and `scripts/vault-log`, or set `PYTHONPATH=src` for module execution.--## Optional MCP tool server+o2b list-pending-payments List pending / approved / etc. requests+o2b payment-digest Render a 4-line digest for a date-OpenSecondBrain ships an optional Model Context Protocol server that exposes the same deterministic operations as MCP tools. Register it through Hermes from the CLI:--```bash-hermes mcp add open-second-brain --command o2b --args mcp --vault /path/to/vault-```--Or edit `~/.hermes/config.yaml` directly:--```yaml-mcp_servers:- open-second-brain:- command: o2b- args: ["mcp", "--vault", "/path/to/vault"]+# Helpers+vault-log Compatibility wrapper around `o2b append-event`+o2b-hook Internal launcher invoked by hooks/hooks.json (Claude Code & Codex)```-Tools: `second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`, plus the eight Pay Memory tools (`payment_memory_init`, `payment_receipt_append`, `asset_capture`, `payment_report_generate`, `payment_policy_check`, `payment_request_approval`, `payment_request_status`, `payment_request_consume`). See `docs/mcp.md` for full setup, tool schemas, and Claude Code/Codex notes. The CLI remains the supported baseline; the MCP server is opt-in.+The local checkout can also be used without installing the symlinks+β run commands through `scripts/o2b` and `scripts/vault-log`.++## MCP tool server++The plugin ships an optional stdio MCP server (`o2b mcp`) that+exposes the same deterministic operations as MCP tools:++- **Core (5):** `second_brain_status`, `second_brain_query`,+ `second_brain_capture`, `event_log_append`, `vault_health`.+- **Pay Memory (8):** `payment_memory_init`,+ `payment_receipt_append`, `asset_capture`,+ `payment_report_generate`, `payment_policy_check`,+ `payment_request_approval`, `payment_request_status`,+ `payment_request_consume`.++Each runtime registers the server differently β Hermes via+`mcp_servers:` in `~/.hermes/config.yaml`, Codex via `codex mcp add`+(written to `~/.codex/config.toml`), Claude Code automatically through+the plugin-bundled `.mcp.json`, OpenClaw not at all (tools registered+natively). The exact wiring is in `install.md`; the protocol,+schemas, and lifecycle details are in [`docs/mcp.md`](docs/mcp.md).++## Lifecycle hooks (Claude Code & Codex)++The plugin bundles a `hooks/hooks.json` that both runtimes auto-load.+Two hooks fire per turn:++- **PostToolUse** (matcher `Write|Edit|MultiEdit|apply_patch`) β+ after a file-mutating tool succeeds, injects a short reminder that+ the agent should call `event_log_append` if the change is a+ durable artifact.+- **Stop** β when the runtime is about to end the turn, parses the+ transcript JSONL, and if a durable-looking artifact was produced+ without a matching log call, blocks the Stop **once** with+ `decision: "block"`. The next Stop passes unconditionally, so the+ agent can deliberately skip logging on trivial edits by just+ finishing again. No deadlocks.++This was added to close the gap exposed by a real bug where soft+MCP-server instructions were silently dropped under load.+Hermes and OpenClaw don't load these hooks β they have their own+per-turn channels. Full design notes: [`hooks/README.md`](hooks/README.md).## Pay Memory-Pay Memory is an audit layer for paid agent actions. The agent makes the-paid API call itself (typically through `pay` from-[solana-foundation/pay](https://github.com/solana-foundation/pay)); Open-Second Brain records the reason, the policy check, the receipt, and any-generated asset as plain Markdown inside the vault.+Pay Memory is an audit layer for paid agent actions. The agent makes+the paid API call itself (typically through `pay` from+[solana-foundation/pay](https://github.com/solana-foundation/pay));+Open Second Brain records the reason, the policy check, the receipt,+and any generated asset as plain Markdown inside the vault. It never+executes payments and never holds wallet keys.```basho2b init-pay-memory --vault /path/to/vault@@ -197,22 +175,19 @@ o2b capture-asset \o2b payment-report --vault /path/to/vault --date 2026-05-10```-Open Second Brain never executes payments and never holds wallet keys. The-spending policy at `AI Wiki/policies/spending.md` is read by the agent-before each paid call; this MVP does not enforce policy at runtime.--`--raw-output-file` is run through a redactor that masks values for-`api_key` / `token` / `secret` / `bearer` / `authorization` / `private_key` /-`password` / `passwd` / `pwd` / `credential` / `session_token` in env, YAML,-JSON, and HTTP-header shapes. Best-effort only β verify the saved receipt+The spending policy at `AI Wiki/policies/spending.md` is read by the+agent before each paid call; this MVP does not enforce policy at+runtime. The `--raw-output-file` of a receipt is run through a+redactor that masks values for `api_key` / `token` / `secret` /+`bearer` / `authorization` / `private_key` / `password` / `passwd` /+`pwd` / `credential` / `session_token` in env, YAML, JSON, and+HTTP-header shapes. Best-effort only β verify the saved receiptbefore sharing it externally.### Optional: machine-readable spending policy-Pay Memory's default policy is the Markdown document at-`AI Wiki/policies/spending.md` β read by the agent before each paid call,-enforced by convention. To enable runtime enforcement, drop a JSON-companion at `AI Wiki/policies/spending.json`:+To enable runtime enforcement, drop a JSON companion at+`AI Wiki/policies/spending.json`:```json{@@ -232,18 +207,18 @@ Then have the agent (or the user) run:o2b check-payment-policy --service paysponge/fal --expected-amount 0.05```-Exit codes are `0` (allowed), `1` (denied), `3` (approval required) so a-shell script can branch. The MCP tool `payment_policy_check` returns the-same structured decision.--If `spending.json` is absent, the check fails open (`has_policy: false`)-β existing flows that rely on the Markdown-only policy keep working.+Exit codes are `0` (allowed), `1` (denied), `3` (approval required)+so a shell script can branch. The MCP tool `payment_policy_check`+returns the same structured decision. If `spending.json` is absent,+the check fails open (`has_policy: false`) β existing flows that+rely on the Markdown-only policy keep working.### Optional: approval workflow-For paid calls that should not happen until a human signs off, Pay Memory-ships a pending-payment-request artifact under `AI Wiki/payments/_pending/`-with a `pending β approved/rejected β consumed` state machine.+For paid calls that should not happen until a human signs off, Pay+Memory ships a pending-payment-request artifact under+`AI Wiki/payments/_pending/` with a+`pending β approved/rejected β consumed` state machine.Agent side:@@ -263,8 +238,8 @@ o2b approve-payment-request --id <id> --approved-by <name>o2b reject-payment-request --id <id> --rejected-by <name> --reason "..."```-Agent side, after the approved paid call succeeded and the receipt was-saved:+Agent side, after the approved paid call succeeded and the receipt+was saved:```basho2b consume-payment-request --id <id> \@@ -272,21 +247,25 @@ o2b consume-payment-request --id <id> \```The MCP-server side mirrors `payment_request_approval`,-`payment_request_status` (poll for approval), and `payment_request_consume`.+`payment_request_status` (poll for approval), and+`payment_request_consume`.### Optional: daily Telegram digest via Hermes cron-`o2b payment-digest --vault <vault> --date <YYYY-MM-DD>` renders a 4-line-Russian summary suitable for delivery via Hermes cron `--script --no-agent`-jobs. See [`docs/hermes-cron.md`](docs/hermes-cron.md) for the-ready-to-paste `hermes cron create` command.+`o2b payment-digest --vault <vault> --date <YYYY-MM-DD>` renders a+4-line Russian summary suitable for delivery via Hermes cron+`--script --no-agent` jobs. See+[`docs/hermes-cron.md`](docs/hermes-cron.md) for the ready-to-paste+`hermes cron create` command. The same command can be wrapped by+any other scheduler that can pipe its stdout to a chat+destination β the digest itself is runtime-neutral.### Installing the `pay` CLI on a Linux VPS-`pay` is the Solana-Foundation payment wrapper that turns a regular HTTP-client into one that handles HTTP 402 payment challenges. It is published-as a prebuilt static binary on GitHub Releases β no Rust toolchain or-Node.js is needed on the host:+`pay` is the Solana-Foundation payment wrapper that turns a regular+HTTP client into one that handles HTTP 402 payment challenges. It is+published as a prebuilt static binary on GitHub Releases β no Rust+toolchain or Node.js is needed on the host:```bashTAG=pay-v0.16.0 # pin a specific release@@ -298,37 +277,44 @@ sudo install -m 0755 pay /usr/local/bin/paypay --version```-Sandbox mode (`pay --sandbox curl <url>`) does **not** require running-`pay setup` first β it generates an ephemeral Solana keypair and funds it-locally via the Surfpool sandbox RPC. That makes it safe to wire into a-CI / e2e test that exercises the full Pay Memory pipeline without spending-real funds. See `tests/e2e/pay-memory-sandbox.sh` for a reference run.+Sandbox mode (`pay --sandbox curl <url>`) does **not** require+running `pay setup` first β it generates an ephemeral Solana keypair+and funds it locally via the Surfpool sandbox RPC. That makes it+safe to wire into a CI / e2e test that exercises the full Pay Memory+pipeline without spending real funds. See+`tests/e2e/pay-memory-sandbox.sh` for a reference run.-For non-sandbox use the local secure storage helper (macOS Keychain, GNOME-Keyring, Windows Hello, 1Password) is configured by `pay setup`. Open-Second Brain itself never holds wallet keys.+For non-sandbox use the local secure storage helper (macOS Keychain,+GNOME Keyring, Windows Hello, 1Password) is configured by+`pay setup`. Open Second Brain itself never holds wallet keys.## Updating-OpenSecondBrain follows the standard Hermes plugin update flow.--```bash-hermes plugins update open-second-brain-hermes gateway restart-```+Each runtime's CLI is authoritative for refreshing the plugin β+follow the matching `## 7. Update` section in `install.md`:-`hermes plugins update` runs `git pull` inside the installed plugin directory; it does not rewrite your `~/.hermes/config.yaml` MCP registration. After an update:+- Hermes: `hermes plugins update open-second-brain && hermes gateway restart`+- Claude Code: `claude plugin marketplace update open-second-brain && claude plugin update open-second-brain@open-second-brain`+- Codex (Git source): `codex plugin marketplace upgrade open-second-brain`+- Codex (local source): re-add the marketplace; there is no+ `upgrade` for local sources.+- OpenClaw: `openclaw plugins update open-second-brain && openclaw gateway restart`-- The `o2b` CLI is upgraded automatically.-- The MCP entrypoint stays registered, so no `hermes mcp add` is needed for an in-place upgrade.-- Restart the gateway (or open a fresh Hermes session) so cached plugin metadata and the MCP subprocess are reloaded.-- Run `o2b doctor --vault /path/to/vault --repo .` to confirm the new manifest still validates.+The CLI symlinks created by `o2b install-cli` point into the cached+plugin checkout and survive in-place updates β no need to re-run+`install-cli`. After an update, run+`o2b doctor --vault /path/to/vault --repo .` to confirm the new+manifest still validates.-The `version` field in `plugin.yaml` is informational β Hermes installs whatever the current `main` branch contains. Pin to a specific release by checking out a tag inside the plugin directory if you want stricter control.+The `version` field in each runtime manifest is informational; the+canonical version lives in `package.json` and is mirrored by+`bun run sync-version`.## Uninstalling-OpenSecondBrain treats your vault as the source of truth and never removes Markdown notes, `Daily/`, or `AI Wiki/`. Uninstalling has three independent layers; do them in this order.+Open Second Brain treats your vault as the source of truth and never+removes Markdown notes, `Daily/`, or `AI Wiki/`. Uninstalling has+three independent layers; do them in this order:1. Print a plan and review the leftovers (read-only):@@ -336,39 +322,39 @@ OpenSecondBrain treats your vault as the source of truth and never removes Markdo2b uninstall```- The plan tells you which Hermes commands to run yourself, where the machine-local config directory lives, and reminds you that the vault is untouched. The dry-run never modifies the filesystem.--2. Deregister the MCP server, clean up CLI symlinks, and remove the Hermes plugin (Hermes-owned state):+2. Run your runtime's plugin-remove command (see the matching+ `## 8. Uninstall` section in `install.md`), then clean local+ state:```bash- hermes mcp remove open-second-braino2b uninstall --apply-local --remove-cli- hermes plugins remove open-second-brain- hermes gateway restart- ```-- `hermes mcp remove` deletes the MCP registration and any OAuth tokens. `o2b uninstall --remove-cli` removes the CLI symlinks β run it *before* `hermes plugins remove` so the plugin directory still exists for symlink verification. `hermes plugins remove` deletes the installed plugin directory. OpenSecondBrain itself never edits `~/.hermes/config.yaml` β these commands are run by you against Hermes.--3. Optionally remove the machine-local config directory (typically `~/.config/open-second-brain` or `$OPEN_SECOND_BRAIN_CONFIG`'s parent):-- ```bash- o2b uninstall --apply-local```- `--apply-local` only removes that one config directory. It refuses to act outside its intended scope β it never touches the vault, Hermes config, or anything else.+3. Optionally delete the machine-local config directory (typically+ `~/.config/open-second-brain` or `$OPEN_SECOND_BRAIN_CONFIG`'s+ parent) β `--apply-local` handles this and refuses to touch+ anything outside that directory.-To delete the vault you must do that yourself with normal filesystem tools β OpenSecondBrain will not do it for you, even with `--apply-local`.+The vault is never deleted by the uninstall flow, even with+`--apply-local`. Delete it yourself with normal filesystem tools if+you want to.## Safety model- Your notes stay as plain Markdown.-- Secrets are not meant to be stored in the vault.-- Config export redacts secret-like keys and values.+- Secrets are not meant to be stored in the vault. Daily logs and+ config exports go through a best-effort redactor that masks+ common secret-name patterns.- Daily logs are append-only below `## Raw events`.-- The current Hermes plugin only registers lightweight health checks; it does not start background jobs.+- The plugin never starts background processes or daemons. The+ optional MCP server is a stdio subprocess that exits when its+ parent runtime exits.+- Hooks (Claude Code, Codex) only inject text into the agent's+ context. They never write to the vault directly β every log+ entry still goes through `event_log_append` or the equivalent CLI.## Repository-GitHub: https://github.com/itechmeat/open-second-brain+GitHub: <https://github.com/itechmeat/open-second-brain>License: MIT.diff --git a/hooks/README.md b/hooks/README.mdnew file mode 100644index 00000000..3b624bfd--- /dev/null+++ b/hooks/README.md@@ -0,0 +1,141 @@+# Open Second Brain β runtime hooks++Plugin-bundled lifecycle hooks for Claude Code and Codex. The hooks+exist to close the gap exposed by the Claude Code bug report at+`Projects/OpenSecondBrain/Plan/1. claude-bug.md`: a soft MCP-server+instruction is not enough to make `event_log_append` reliably fire+after a durable artifact, and the agent had no visible signal that+the log was skipped.++Hermes and OpenClaw deliberately do **not** load these hooks. Hermes+already injects an identity / log reminder via its `pre_llm_call`+plugin shim, so the same nudge arrives through a different channel+without duplicating subsystems. OpenClaw's native JS plugin format+predates these hooks. If either runtime grows a Claude-style hook+schema later, point its config at `hooks/hooks.json` and the same+scripts will work β they only depend on the documented hook payload+shape, not on the runtime.++## What the hooks do++| Event | Matcher | Behaviour |+|---------------|--------------------------------------|----------------------------------------------------------------------------------------|+| `PostToolUse` | `Write\|Edit\|MultiEdit\|apply_patch` | Emits `additionalContext` reminding the agent to call `event_log_append` if the edit is durable. |+| `Stop` | (every Stop) | If the turn produced a durable artifact but no `event_log_append` call, returns `decision: "block"` once, then lets the second Stop pass. |++The Stop guardrail respects the runtime-provided `stop_hook_active`+flag: it fires at most once per turn, so the agent can deliberately+decide that an edit was trivial and skip logging by just finishing+again. No deadlocks.++## Files++- `hooks.json` β lifecycle config picked up by both runtimes. Claude+ Code looks for `hooks/hooks.json` at the plugin root by convention;+ Codex auto-loads the same file when the plugin manifest's `"hooks"`+ field points at it (set in both `.codex-plugin/plugin.json` and+ `plugins/codex/.codex-plugin/plugin.json`).++ Layout caveat: Codex's marketplace source is+ `./plugins/codex/`, so the Codex side only sees what lives under+ that subdirectory. The repo exposes the hooks tree there via a+ `plugins/codex/hooks β ../../hooks` symlink (same pattern as+ `plugins/codex/skills`). The symlink target is relative, so it+ resolves correctly inside a cloned repo too β but it does assume+ the consumer copies the whole repo, not just `plugins/codex/`. If+ Codex ever switches to a "ship subtree only" extraction model, the+ symlink will dangle and the hooks tree will need to move+ physically under `plugins/codex/hooks/` (or be duplicated).+- `post-write-reminder.ts` / `stop-log-guardrail.ts` β Bun entry+ scripts. They are tiny by design: they parse stdin, query+ `lib/transcript.ts` and `lib/detect.ts`, and emit the hook's JSON+ response on stdout. Never block on errors.+- `lib/stdin.ts` β read the single JSON object both runtimes send on+ stdin.+- `lib/transcript.ts` β JSONL parser that recognises both the+ Claude Code shape (top-level `{type:"user"|"assistant", message:+ {content:[...]}}`) and the Codex shape (`{type:"response_item",+ payload:{type:"function_call"|"custom_tool_call", name}}`).+- `lib/detect.ts` β canonical lists of artifact / log tool names.+- `lib/messages.ts` β reminder + block text. Kept here so it can be+ unit-tested without a hook subprocess.++## 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.++## Local dev loop++The plugin lives at `/srv/projects/open-second-brain/` and Claude+Code / Codex are wired to that directory via local marketplaces+(`extraKnownMarketplaces` in `~/.claude/settings.json`,+`[marketplaces.open-second-brain] source_type = "local"` in+`~/.codex/config.toml`). Both runtimes cache the installed plugin,+so edits to `hooks/*.ts` don't auto-propagate.++After changing a hook script:++```bash+# Claude Code: refresh the local-marketplace cache and reinstall.+claude plugin marketplace update open-second-brain+claude plugin update open-second-brain@open-second-brain++# Codex: re-add the marketplace (there is no "upgrade" for local+# marketplaces; remove + add wipes the cache and re-stages the+# plugin tree from /srv/projects/open-second-brain/plugins/codex/).+codex plugin marketplace remove open-second-brain+codex plugin marketplace add /srv/projects/open-second-brain+```++Then exercise the hook end-to-end:++```bash+# Claude Code+claude -p 'create a tiny note.md in /tmp/x with content hello' \+ --output-format=stream-json --verbose --include-hook-events \+ --allowedTools 'Write Read' --add-dir /tmp/x++# Codex+codex exec --skip-git-repo-check 'create a tiny /tmp/x/note.md ...'+```++Expect the stream to show `hook_started` / `hook_response` events+around each Write and around the Stop event; the agent's first reply+gets `decision: "block"` and it has to either log or send a second+finishing message.++## Unit tests++`tests/hooks/*.test.ts` exercises the library and spawns the two+hook entry scripts as subprocesses with synthetic stdin / JSONL+transcripts. Run with:++```bash+bun test tests/hooks/+```++The subprocess tests inherit the test runner's cwd, not the+plugin's, which matches production behaviour: Claude Code and Codex+both spawn the hook in the user's session cwd, not in the plugin+checkout. The scripts therefore must NEVER use `process.cwd()` to+locate plugin files β resolve paths via `import.meta.url` or+relative imports, as the current code does. If you ever need to+read a vault path, take it from the hook payload or the persisted+plugin config.diff --git a/hooks/hooks.json b/hooks/hooks.jsonnew file mode 100644index 00000000..4f1a68f5--- /dev/null+++ b/hooks/hooks.json@@ -0,0 +1,29 @@+{+ "hooks": {+ "PostToolUse": [+ {+ "matcher": "Write|Edit|MultiEdit|apply_patch",+ "hooks": [+ {+ "type": "command",+ "command": "o2b-hook post-write-reminder",+ "timeout": 10,+ "statusMessage": "OSB: reminding to log"+ }+ ]+ }+ ],+ "Stop": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "o2b-hook stop-log-guardrail",+ "timeout": 15,+ "statusMessage": "OSB: checking event log"+ }+ ]+ }+ ]+ }+}diff --git a/hooks/lib/detect.ts b/hooks/lib/detect.tsnew file mode 100644index 00000000..6b5de4d3--- /dev/null+++ b/hooks/lib/detect.ts@@ -0,0 +1,89 @@+/**+ * Tool-name classifiers shared by the PostToolUse reminder and the Stop+ * guardrail. Names match what Claude Code and Codex actually put on the+ * wire (verified against live transcripts under `~/.claude/projects/**`+ * and `~/.codex/sessions/**`).+ *+ * Why a single shared module: the guardrail's correctness rests on+ * counting the same set of names that the PostToolUse reminder fires+ * for, and the same set of names that count as logging. Drifting these+ * lists into separate hook scripts would let the guardrail block on a+ * tool the reminder never warned about, or skip a log call the user+ * actually made.+ */++import type { ToolCall } from "./transcript.ts";++// Canonical tool names that mutate files in either runtime.+// Claude Code: `Write`, `Edit`, `MultiEdit` (native tools β no+// `mcp__β¦__` prefix in transcripts).+// Codex: `apply_patch` (custom_tool_call wrapping diffs).+//+// Codex also supports Edit/Write *aliases* in matchers, but the actual+// `name` field in the transcript is always `apply_patch` for file+// edits done through it; we still accept Edit/Write to defend against+// a future runtime that mirrors the matcher alias into the call name.+const NATIVE_ARTIFACT_NAMES = new Set<string>([+ "Write",+ "Edit",+ "MultiEdit",+ "apply_patch",+]);++// Tool-name suffixes that mean "the agent logged this turn", regardless+// of any runtime-injected MCP prefix:+// Codex: `event_log_append` (bare; verified live).+// Claude Code: `mcp__plugin_open-second-brain_open-second-brain__event_log_append`+// (the runtime decorates plugin-provided MCP tools with+// `mcp__plugin_<plugin>_<server>__` β verified live in+// `~/.claude/projects/-root/*.jsonl`).+//+// We match the trailing `event_log_append` token after either the start+// of the name or a `__` separator so any future prefix change (Claude+// has rebranded this twice in two months) keeps working without an+// emergency patch.+const LOG_NAME_SUFFIX = /(?:^|__)event_log_append$/;++// Bash command substrings that indicate the agent called the CLI+// equivalent of `event_log_append`. We deliberately keep this list+// narrow: anything matched here suppresses the guardrail. Spawning+// the MCP server (`o2b mcp β¦`) does NOT log on its own, so it is not+// in the list β only the explicit append commands are.+const LOG_BASH_NEEDLES = [+ "o2b append-event",+ "vault-log ", // trailing space distinguishes the CLI from a literal log path+];++export function isArtifactToolName(name: string): boolean {+ return NATIVE_ARTIFACT_NAMES.has(name);+}++export function isLogToolName(name: string): boolean {+ return LOG_NAME_SUFFIX.test(name);+}++export interface TurnSummary {+ readonly hadArtifact: boolean;+ readonly hadLog: boolean;+}++export function summarizeTurn(+ toolCalls: readonly ToolCall[],+ bashCommandsThisTurn: readonly string[] = [],+): TurnSummary {+ let hadArtifact = false;+ let hadLog = false;+ for (const tc of toolCalls) {+ if (isArtifactToolName(tc.name)) hadArtifact = true;+ if (isLogToolName(tc.name)) hadLog = true;+ }+ if (!hadLog) {+ for (const cmd of bashCommandsThisTurn) {+ if (LOG_BASH_NEEDLES.some((n) => cmd.includes(n))) {+ hadLog = true;+ break;+ }+ }+ }+ return { hadArtifact, hadLog };+}diff --git a/hooks/lib/messages.ts b/hooks/lib/messages.tsnew file mode 100644index 00000000..de6040fa--- /dev/null+++ b/hooks/lib/messages.ts@@ -0,0 +1,51 @@+/**+ * Hook-side reminder texts. Kept in one module so the wording stays+ * consistent across the PostToolUse reminder and the Stop guardrail,+ * and so it can be tested without spinning up a hook process.+ *+ * The text is deliberately written for the LLM consumer (a coding+ * agent), not the human user β the human only ever sees a status+ * line. Tone: factual, terse, no exclamation marks, no apology.+ *+ * These messages are emitted in English because the hooks run in the+ * agent's runtime, not in a conversation context β the language+ * choice for the *event log entry itself* still follows the+ * conversation locale per the `agent-event-log` skill.+ */++export interface PostWriteReminderInput {+ readonly toolName: string;+ readonly filePath: string | null;+}++export function postWriteReminder({ toolName, filePath }: PostWriteReminderInput): string {+ const target = filePath ? `\`${filePath}\`` : "a file";+ return [+ `Open Second Brain hook: you just ran \`${toolName}\` against ${target}.`,+ "",+ "If this change is a durable artifact (code shipped, config or",+ "deployment change, instruction-file edit, content artifact,",+ "research / investigation finding, or external-fact discovery),",+ "call `event_log_append` before you finish this turn.",+ "",+ "If it is trivial (typo fix, formatting, intermediate scratch),",+ "no log is needed β just finish your reply and the Stop guardrail",+ "will not block you a second time.",+ ].join("\n");+}++export function stopGuardrailReason(): string {+ return [+ "Open Second Brain hook: this turn touched files",+ "(Write / Edit / MultiEdit / apply_patch) but did not call",+ "`event_log_append`.",+ "",+ "If the change is a durable artifact you want future sessions to",+ "be able to search for, call `event_log_append` with a one-line",+ "message describing what landed, then finish.",+ "",+ "If the change is trivial and not worth logging, just send your",+ "reply again β this guardrail fires at most once per turn and",+ "will let the second Stop through.",+ ].join("\n");+}diff --git a/hooks/lib/stdin.ts b/hooks/lib/stdin.tsnew file mode 100644index 00000000..43e74c94--- /dev/null+++ b/hooks/lib/stdin.ts@@ -0,0 +1,34 @@+/**+ * Read the full stdin payload Claude Code / Codex hand to a hook as one+ * JSON object. Both runtimes pass a single JSON document on stdin and+ * close the pipe; we read until EOF, parse once, and return the parsed+ * value. Empty payload returns `null` so the caller can short-circuit.+ */++export async function readHookInput(): Promise<unknown> {+ const chunks: Buffer[] = [];+ for await (const chunk of process.stdin) {+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array));+ }+ const raw = Buffer.concat(chunks).toString("utf8").trim();+ if (raw.length === 0) return null;+ return JSON.parse(raw);+}++export interface HookPayloadBase {+ readonly session_id?: string;+ readonly transcript_path?: string | null;+ readonly cwd?: string;+ readonly hook_event_name?: string;+ readonly stop_hook_active?: boolean;+ readonly tool_name?: string;+ readonly tool_input?: unknown;+ readonly tool_response?: unknown;+}++export function asHookPayload(value: unknown): HookPayloadBase {+ if (value !== null && typeof value === "object") {+ return value as HookPayloadBase;+ }+ return {};+}diff --git a/hooks/lib/transcript.ts b/hooks/lib/transcript.tsnew file mode 100644index 00000000..812a266d--- /dev/null+++ b/hooks/lib/transcript.ts@@ -0,0 +1,270 @@+/**+ * Transcript parser shared by the Stop hook. Reads the JSONL transcript+ * pointed at by `transcript_path` and extracts the turn's signal:+ * which tool calls happened since the last user message, and what their+ * canonical tool_name is.+ *+ * Both Claude Code and Codex pass `transcript_path` in the hook stdin+ * payload but each runtime uses a different on-disk shape:+ *+ * Claude Code: one line per message, top-level `type: "user" | "assistant"`,+ * tool calls inside `message.content[*]` as `{type:"tool_use", name, ...}`.+ *+ * Codex: one line per record, top-level `{type: "response_item" |+ * "event_msg" | "session_meta" | "turn_context", payload: ...}`. Tool+ * calls land as `payload.type === "function_call"` (shell, MCP) or+ * `payload.type === "custom_tool_call"` (apply_patch). The+ * `payload.name` is the canonical tool name.+ *+ * We detect the format from the first non-empty line and apply the+ * right reader. The output is a normalized list of `ToolCall` records+ * since the last user-turn boundary.+ */++import { readFileSync, existsSync } from "node:fs";++export interface ToolCall {+ readonly name: string;+}++export interface TurnSignal {+ readonly toolCalls: readonly ToolCall[];+ /**+ * Plain-text shell commands the agent ran this turn. Surfaced+ * separately from `toolCalls` because the Stop guardrail wants to+ * treat `o2b append-event β¦` or `vault-log β¦` invoked through+ * Bash / `exec_command` as a valid log call.+ */+ readonly bashCommands: readonly string[];+}++type Format = "claude" | "codex" | "unknown";++// Strong signals to distinguish the two transcript shapes:+// - Codex always wraps records as `{type, payload: {...}}`.+// - Claude Code emits records with a `message` object that has a+// `role` field. (Bookkeeping records like `queue-operation` /+// `attachment` / `permission-mode` also use `type` + `sessionId`+// but they DON'T carry `message.role`, so we can't anchor on+// `sessionId` alone β we'd flip detection to "claude" off a+// bookkeeping line and the actual format check below would still+// work, but in a brittle way. Anchoring on `message.role` is the+// stable signal.)+//+// Returns "unknown" when neither signal is present so the caller can+// scan more lines (real transcripts have many bookkeeping records+// before the first proper message).+export function detectFormat(firstLine: string): Format {+ if (firstLine.length === 0) return "unknown";+ let obj: unknown;+ try {+ obj = JSON.parse(firstLine);+ } catch {+ return "unknown";+ }+ if (obj === null || typeof obj !== "object") return "unknown";+ const o = obj as Record<string, unknown>;+ const payload = o.payload;+ if (+ "type" in o &&+ payload !== null &&+ typeof payload === "object" &&+ "type" in (payload as Record<string, unknown>)+ ) {+ return "codex";+ }+ const message = o.message;+ if (+ "type" in o &&+ message !== null &&+ typeof message === "object" &&+ "role" in (message as Record<string, unknown>)+ ) {+ return "claude";+ }+ return "unknown";+}++const EMPTY_SIGNAL: TurnSignal = { toolCalls: [], bashCommands: [] };++export function parseTranscript(jsonl: string): TurnSignal {+ const lines = jsonl.split(/\r?\n/).filter((l) => l.length > 0);+ if (lines.length === 0) return EMPTY_SIGNAL;+ // Scan until we find a line that parses to a recognisable shape. A+ // malformed leading line (rare in practice β only seen during disk+ // races where the writer crashed mid-line) must not flip the whole+ // transcript to "unknown".+ let format: Format = "unknown";+ for (const line of lines) {+ format = detectFormat(line);+ if (format !== "unknown") break;+ }+ if (format === "claude") return parseClaude(lines);+ if (format === "codex") return parseCodex(lines);+ return EMPTY_SIGNAL;+}++export function readTranscript(transcriptPath: string): TurnSignal {+ if (!existsSync(transcriptPath)) return EMPTY_SIGNAL;+ const text = readFileSync(transcriptPath, "utf8");+ return parseTranscript(text);+}++interface ClaudeContentBlock {+ readonly type?: string;+ readonly name?: string;+ readonly input?: Record<string, unknown>;+ readonly text?: string;+}++interface ClaudeRecord {+ readonly type?: string;+ readonly message?: {+ readonly role?: string;+ readonly content?: ClaudeContentBlock[] | string;+ };+}++function parseClaude(lines: readonly string[]): TurnSignal {+ // Walk from the end backward to find the boundary index of the last+ // user message. Then collect tool_use entries from records strictly+ // after that index.+ const records: ClaudeRecord[] = [];+ for (const line of lines) {+ try {+ records.push(JSON.parse(line) as ClaudeRecord);+ } catch {+ // skip malformed lines+ }+ }+ let boundary = -1;+ for (let i = records.length - 1; i >= 0; i--) {+ const r = records[i]!;+ if (r.type === "user" && r.message?.role === "user" && !isToolResultOnly(r)) {+ boundary = i;+ break;+ }+ }+ // No real user prompt in this transcript yet β there is no "current+ // turn" to evaluate. Return empty so the guardrail stays silent.+ if (boundary === -1) return EMPTY_SIGNAL;+ const toolCalls: ToolCall[] = [];+ const bashCommands: string[] = [];+ for (let i = boundary + 1; i < records.length; i++) {+ const r = records[i]!;+ const content = r.message?.content;+ if (!Array.isArray(content)) continue;+ for (const block of content) {+ if (block?.type !== "tool_use" || typeof block.name !== "string") continue;+ toolCalls.push({ name: block.name });+ if (block.name === "Bash") {+ const cmd = block.input?.command;+ if (typeof cmd === "string") bashCommands.push(cmd);+ }+ }+ }+ return { toolCalls, bashCommands };+}++// Claude marks tool-results as `type: "user"` records that carry a+// `tool_result` content block β those are *not* real user turn+// boundaries; only treat plain user messages as boundaries.+function isToolResultOnly(r: ClaudeRecord): boolean {+ const content = r.message?.content;+ if (!Array.isArray(content)) return false;+ if (content.length === 0) return false;+ return content.every((b) => b?.type === "tool_result");+}++interface CodexRecord {+ readonly type?: string;+ readonly payload?: {+ readonly type?: string;+ readonly role?: string;+ readonly name?: string;+ readonly arguments?: string;+ readonly content?: ReadonlyArray<{ readonly type?: string; readonly text?: string }>;+ };+}++function parseCodex(lines: readonly string[]): TurnSignal {+ const records: CodexRecord[] = [];+ for (const line of lines) {+ try {+ records.push(JSON.parse(line) as CodexRecord);+ } catch {+ // skip+ }+ }+ let boundary = -1;+ for (let i = records.length - 1; i >= 0; i--) {+ const r = records[i]!;+ const p = r.payload;+ if (+ r.type === "response_item" &&+ p?.type === "message" &&+ p?.role === "user" &&+ !isCodexEnvelope(p)+ ) {+ boundary = i;+ break;+ }+ }+ if (boundary === -1) return EMPTY_SIGNAL;+ const toolCalls: ToolCall[] = [];+ const bashCommands: string[] = [];+ for (let i = boundary + 1; i < records.length; i++) {+ const r = records[i]!;+ const p = r.payload;+ if (!p) continue;+ if (+ (p.type === "function_call" || p.type === "custom_tool_call") &&+ typeof p.name === "string"+ ) {+ toolCalls.push({ name: p.name });+ if (p.name === "exec_command" || p.name === "shell") {+ const cmd = extractCodexShellCommand(p.arguments);+ if (cmd !== null) bashCommands.push(cmd);+ }+ }+ }+ return { toolCalls, bashCommands };+}++// Codex serialises function_call `arguments` as a JSON string. Pull+// out the `cmd` (older Codex) / `command` (newer) field if present.+// Returns null when the shape is anything else so the caller can+// fall through silently.+function extractCodexShellCommand(serialized: string | undefined): string | null {+ if (typeof serialized !== "string") return null;+ let args: unknown;+ try {+ args = JSON.parse(serialized);+ } catch {+ return null;+ }+ if (args === null || typeof args !== "object") return null;+ const a = args as Record<string, unknown>;+ if (typeof a.cmd === "string") return a.cmd;+ if (typeof a.command === "string") return a.command;+ // exec_command sometimes uses argv-array form.+ if (Array.isArray(a.command)) {+ return a.command.filter((x) => typeof x === "string").join(" ");+ }+ return null;+}++// Codex prepends a synthetic `<environment_context>` user message at the+// start of every turn. We want to anchor at the *real* user prompt, not+// that envelope. Same for `<user_instructions>` blocks.+function isCodexEnvelope(p: NonNullable<CodexRecord["payload"]>): boolean {+ const content = p.content;+ if (!Array.isArray(content)) return false;+ const text = content+ .map((c) => (typeof c?.text === "string" ? c.text : ""))+ .join("");+ return (+ text.startsWith("<environment_context>") ||+ text.startsWith("<user_instructions>")+ );+}diff --git a/hooks/post-write-reminder.ts b/hooks/post-write-reminder.tsnew file mode 100755index 00000000..86955d56--- /dev/null+++ b/hooks/post-write-reminder.ts@@ -0,0 +1,83 @@+#!/usr/bin/env -S bun+/**+ * PostToolUse hook: emits a soft reminder after Write / Edit /+ * MultiEdit / apply_patch so the agent considers calling+ * `event_log_append` before its final reply.+ *+ * Contract (identical for Claude Code and Codex):+ * stdin: hook payload JSON with `tool_name`, `tool_input`.+ * stdout: JSON of the shape+ * {+ * "hookSpecificOutput": {+ * "hookEventName": "PostToolUse",+ * "additionalContext": "<reminder text>"+ * }+ * }+ * Both runtimes inject `additionalContext` as developer-side+ * context for the next model call.+ *+ * Quiet on unrelated tools: if the tool name isn't in the artifact+ * set, exit 0 with no output. The matcher in `hooks.json` should+ * already filter most of those out β this is belt-and-suspenders.+ *+ * Quiet on failures: we never block the agent here. If we crash, we+ * exit 0 so the turn proceeds; the Stop guardrail is the gating hook.+ */++import { asHookPayload, readHookInput } from "./lib/stdin.ts";+import { isArtifactToolName } from "./lib/detect.ts";+import { postWriteReminder } from "./lib/messages.ts";++async function main(): Promise<void> {+ let payload;+ try {+ payload = asHookPayload(await readHookInput());+ } catch {+ return;+ }++ const toolName = payload.tool_name;+ if (typeof toolName !== "string" || !isArtifactToolName(toolName)) return;++ // Skip on failed edits: the spec is "after a file-mutating tool+ // SUCCEEDS, remind about logging". Claude Code's `tool_response`+ // carries `is_error: true` on a failed Write/Edit; Codex's+ // `function_call_output` records success differently and is not+ // surfaced here, so we only gate on the Claude shape.+ if (isToolResponseError(payload.tool_response)) return;++ const filePath = extractFilePath(payload.tool_input);+ const text = postWriteReminder({ toolName, filePath });++ const out = {+ hookSpecificOutput: {+ hookEventName: "PostToolUse",+ additionalContext: text,+ },+ };+ process.stdout.write(JSON.stringify(out) + "\n");+}++function isToolResponseError(response: unknown): boolean {+ if (response === null || typeof response !== "object") return false;+ const r = response as Record<string, unknown>;+ return r.is_error === true || r.success === false;+}++function extractFilePath(input: unknown): string | null {+ if (input === null || typeof input !== "object") return null;+ const o = input as Record<string, unknown>;+ // Claude Code: Write / Edit / MultiEdit all carry `file_path`.+ if (typeof o.file_path === "string") return o.file_path;+ // Codex apply_patch: the patch body is in `input` as a string; we+ // can extract the first `*** Update File:` or `*** Add File:` line.+ if (typeof o.input === "string") {+ const m = /\*\*\* (?:Update File|Add File|Delete File): ([^\n]+)/.exec(o.input);+ if (m && m[1]) return m[1].trim();+ }+ return null;+}++main().catch(() => {+ // Never block on hook crash.+});diff --git a/hooks/stop-log-guardrail.ts b/hooks/stop-log-guardrail.tsnew file mode 100755index 00000000..bbdd3971--- /dev/null+++ b/hooks/stop-log-guardrail.ts@@ -0,0 +1,65 @@+#!/usr/bin/env -S bun+/**+ * Stop hook: blocks the turn at most once when the agent produced a+ * durable-looking artifact (Write / Edit / MultiEdit / apply_patch) but+ * never called `event_log_append`. Lets the agent decide whether to log+ * or finish β but forces the decision to be conscious.+ *+ * Decision shape (identical for Claude Code and Codex):+ *+ * - On the first Stop of a turn (`stop_hook_active === false` and the+ * artifact-without-log condition holds): emit+ * {"decision": "block", "reason": "<text>"}+ * so the runtime continues the agent loop with that reason injected+ * as a developer message. The agent can then either call+ * `event_log_append` or just finish; either way the next Stop sees+ * `stop_hook_active === true` and passes through.+ *+ * - On any Stop where the guardrail already fired+ * (`stop_hook_active === true`): exit 0 silently. No deadlocks.+ *+ * - On any Stop where there was no artifact or a log was made: exit 0+ * silently.+ *+ * The guardrail never blocks twice in a row by design β that matches+ * the user's "agent decides what to log" requirement.+ */++import { asHookPayload, readHookInput } from "./lib/stdin.ts";+import { readTranscript } from "./lib/transcript.ts";+import { summarizeTurn } from "./lib/detect.ts";+import { stopGuardrailReason } from "./lib/messages.ts";++async function main(): Promise<void> {+ let payload;+ try {+ payload = asHookPayload(await readHookInput());+ } catch {+ return;+ }++ if (payload.stop_hook_active === true) return;++ const transcriptPath = payload.transcript_path;+ if (typeof transcriptPath !== "string" || transcriptPath.length === 0) return;++ let signal;+ try {+ signal = readTranscript(transcriptPath);+ } catch {+ return;+ }++ const summary = summarizeTurn(signal.toolCalls, signal.bashCommands);+ if (!summary.hadArtifact || summary.hadLog) return;++ const out = {+ decision: "block",+ reason: stopGuardrailReason(),+ };+ process.stdout.write(JSON.stringify(out) + "\n");+}++main().catch(() => {+ // Never deadlock on a hook crash.+});diff --git a/install.md b/install.mdindex c5deaa2b..bb0eed7a 100644--- a/install.md+++ b/install.md@@ -153,15 +153,21 @@ hermes gateway restart### 3. Publish CLI commands to PATH-`hermes plugins install` clones the repository but does not pip-install the package, so the `o2b` and `vault-log` commands are not on PATH yet. Run this step to create symlinks:+`hermes plugins install` clones the repository but does not pip-install the package, so the `o2b`, `vault-log`, and `o2b-hook` commands are not on PATH yet. Run this step to create symlinks:```bash~/.hermes/plugins/open-second-brain/scripts/o2b install-cli```-This creates symlinks in `~/.local/bin` pointing to `scripts/o2b` and `scripts/vault-log` inside the plugin checkout. The symlinks survive `hermes plugins update` because they point into the git-managed checkout.+This creates symlinks in `~/.local/bin` pointing to `scripts/o2b`,+`scripts/vault-log`, and `scripts/o2b-hook` inside the plugin+checkout. The symlinks survive `hermes plugins update` because they+point into the git-managed checkout.-After this step, the bare commands `o2b` and `vault-log` will be available on PATH.+After this step, the bare commands `o2b`, `vault-log`, and+`o2b-hook` will be available on PATH. (`o2b-hook` is the launcher+that Claude Code and Codex use for lifecycle hooks; it is not used+by Hermes itself but installing it costs nothing.)### 4. Initialize the vault@@ -383,14 +389,15 @@ openclaw gateway restart### 3. Publish CLI commands to PATHThe `o2b` and `vault-log` commands are not on PATH after OpenClaw plugin-install. Run this step to create symlinks:+install (and `o2b-hook`, even though OpenClaw doesn't use it).+Run this step to create symlinks:```bash./scripts/o2b install-cli```-This creates symlinks in `~/.local/bin`. After this, bare `o2b` and-`vault-log` work on PATH.+This creates symlinks in `~/.local/bin` for `o2b`, `vault-log`, and+`o2b-hook`. After this, the bare commands work on PATH.### 4. Initialize the vault@@ -607,8 +614,10 @@ enablement.### 3. Publish CLI commands to PATH-The `o2b` and `vault-log` scripts ship inside the plugin checkout; this-step symlinks them into `~/.local/bin` so they are usable on PATH.+The `o2b`, `vault-log`, and `o2b-hook` scripts ship inside the plugin+checkout; this step symlinks them into `~/.local/bin` so they are+usable on PATH. (`o2b-hook` is the launcher that lifecycle hooks+invoke β see step 6b.)The cached path differs across Codex versions (see step 2), so locatethe script by searching under `~/.codex/`:@@ -678,6 +687,22 @@ The `codex mcp list` output must show `open-second-brain` withΒ§ Verification β daily identity below). Installation is incompleteuntil that check passes.+### 6b. Lifecycle hooks (auto-enabled)++The plugin ships a `hooks/hooks.json` that Codex loads automatically+from the bundled plugin tree. Two hooks fire per turn:++- `PostToolUse` (matcher `Write|Edit|MultiEdit|apply_patch`) β reminds+ the agent to call `event_log_append` when a durable artifact landed.+- `Stop` β blocks the turn at most once if the agent produced an+ artifact but did not log. The next Stop passes through, so the agent+ decides whether to log or just finish.++Both hooks invoke `o2b-hook` from PATH. That CLI was symlinked into+`~/.local/bin` by step 3, so no extra wiring is needed. If+`o2b-hook` is missing from PATH the hooks fail closed (turn proceeds+normally with a stderr trace) β re-run step 3 to fix.+### 7. Update```bash@@ -821,8 +846,10 @@ step 4 below (vault init), `claude mcp list` will show### 3. Publish CLI commands to PATH-The `o2b` and `vault-log` scripts ship inside the plugin checkout; this-step symlinks them into `~/.local/bin` so they are usable on PATH.+The `o2b`, `vault-log`, and `o2b-hook` scripts ship inside the plugin+checkout; this step symlinks them into `~/.local/bin` so they are+usable on PATH. (`o2b-hook` is the launcher that lifecycle hooks+invoke β see step 6b.)The cached path includes the plugin version segment, so locate thescript by searching under the cache:@@ -870,6 +897,23 @@ with `Status: β enabled`. `claude mcp list` must showrun the **daily identity** check (see Β§ Verification β daily identitybelow). Installation is incomplete until that check passes.+### 6b. Lifecycle hooks (auto-enabled)++The plugin ships a `hooks/hooks.json` that Claude Code loads+automatically from the cached plugin tree. Two hooks fire per turn:++- `PostToolUse` (matcher `Write|Edit|MultiEdit|apply_patch`) β reminds+ the agent to call `event_log_append` when a durable artifact landed.+- `Stop` β blocks the turn at most once if the agent produced an+ artifact but did not log. The next Stop passes through, so the agent+ decides whether to log or just finish.++Both hooks invoke `o2b-hook` from PATH. That CLI was symlinked into+`~/.local/bin` by step 3, so no extra wiring is needed. To watch the+hooks fire end-to-end use `--output-format=stream-json --verbose+--include-hook-events`; you should see `hook_started` /+`hook_response` events around each `Write` / `Edit` and around `Stop`.+### 7. Update```bash@@ -1124,8 +1168,13 @@ The installation is complete **only** when **all** of the following hold:- [ ] `vault_health` (or `o2b doctor`) reports OK;- [ ] for OpenClaw: `plugins.entries.open-second-brain.config.agentName` isset to the chosen name;-- [ ] for Hermes / Codex / Claude: `VAULT_AGENT_NAME` is exported in the- environment that launches the MCP server;+- [ ] for Hermes / Codex: `VAULT_AGENT_NAME` is exported in the+ environment that launches the MCP server (or set in the runtime's+ MCP-config stanza);+- [ ] for Claude Code: `agent_name` is persisted in+ `~/.config/open-second-brain/config.yaml` by `o2b init --agent-name`.+ Claude Code's bundled `.mcp.json` reads from that config at server+ spawn, so no `VAULT_AGENT_NAME` env var is required;- [ ] `AI Wiki/identity/agents.md` contains the chosen agent name and nolonger contains the `(add your agents here, β¦)` templateplaceholder;diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 99cc1d85..565c7edf 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.8.0",+ "version": "0.8.1","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 68707325..8b231172 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.8.0",+ "version": "0.8.1","type": "module","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",diff --git a/plugin.yaml b/plugin.yamlindex 65d0b4a3..760fb92b 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.8.0"+version: "0.8.1"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex d8851dfc..58780d34 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.7.0",+ "version": "0.8.1","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",@@ -11,6 +11,7 @@"license": "MIT","keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"],"skills": "./skills",+ "hooks": "./hooks/hooks.json","interface": {"displayName": "Open Second Brain","shortDescription": "Per-vault second brain for AI agents using Obsidian-compatible Markdown",diff --git a/plugins/codex/hooks b/plugins/codex/hooksnew file mode 120000index 00000000..2777e158--- /dev/null+++ b/plugins/codex/hooks@@ -0,0 +1 @@+../../hooks\ No newline at end of filediff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 03456a63..41592461 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.8.0"+version: "0.8.1"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex 788dbc47..cc84ed90 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.8.0"+version = "0.8.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-hooknew file mode 100755index 00000000..1f2713de--- /dev/null+++ b/scripts/o2b-hook@@ -0,0 +1,40 @@+#!/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.+#+# 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.+#+# 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)++# shellcheck source=./_bun-precheck.sh+. "$SCRIPT_DIR/_bun-precheck.sh"++HOOK_NAME=${1:-}+if [[ -z $HOOK_NAME ]]; then+ echo "usage: o2b-hook <hook-name> [args...]" >&2+ exit 2+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+fi++exec bun run "$HOOK_FILE" "$@"diff --git a/scripts/sync-version.ts b/scripts/sync-version.tsindex 6b71c2fc..7d7c16e1 100644--- a/scripts/sync-version.ts+++ b/scripts/sync-version.ts@@ -27,6 +27,7 @@ const YAML_TARGETS = ["plugin.yaml", "plugins/hermes/plugin.yaml"] as const;const JSON_TARGETS = [".claude-plugin/plugin.json",".codex-plugin/plugin.json",+ "plugins/codex/.codex-plugin/plugin.json","openclaw.plugin.json",] as const;const PYPROJECT = "pyproject.toml";diff --git a/src/cli/install-cli.ts b/src/cli/install-cli.tsindex 3c77110e..b1dd0a24 100644--- a/src/cli/install-cli.ts+++ b/src/cli/install-cli.ts@@ -22,7 +22,7 @@ import { fileURLToPath } from "node:url";import type { InstallResult, UninstallResult } from "../core/types.ts";-const CLI_SCRIPTS = ["o2b", "vault-log"] as const;+const CLI_SCRIPTS = ["o2b", "vault-log", "o2b-hook"] as const;function repoRoot(): string {// src/cli/install-cli.ts β repo/diff --git a/tests/cli/install-cli.test.ts b/tests/cli/install-cli.test.tsindex b0acff00..1b0c5e89 100644--- a/tests/cli/install-cli.test.ts+++ b/tests/cli/install-cli.test.ts@@ -16,10 +16,10 @@ afterEach(() => {});describe("installCli", () => {- test("creates symlinks for o2b and vault-log", () => {+ test("creates symlinks for o2b, vault-log, and o2b-hook", () => {const result = installCli(tmp);expect(result.errors).toEqual([]);- for (const name of ["o2b", "vault-log"]) {+ for (const name of ["o2b", "vault-log", "o2b-hook"]) {const link = join(tmp, name);expect(lstatSync(link).isSymbolicLink()).toBe(true);expect(readlinkSync(link)).toContain(`scripts/${name}`);diff --git a/tests/hooks/detect.test.ts b/tests/hooks/detect.test.tsnew file mode 100644index 00000000..de8f9b09--- /dev/null+++ b/tests/hooks/detect.test.ts@@ -0,0 +1,115 @@+import { describe, expect, test } from "bun:test";++import {+ isArtifactToolName,+ isLogToolName,+ summarizeTurn,+} from "../../hooks/lib/detect.ts";++describe("isArtifactToolName", () => {+ test.each([["Write"], ["Edit"], ["MultiEdit"], ["apply_patch"]])(+ "%s is an artifact",+ (name) => {+ expect(isArtifactToolName(name)).toBe(true);+ },+ );++ test.each([["Bash"], ["Read"], ["Grep"], ["event_log_append"], ["second_brain_status"]])(+ "%s is NOT an artifact",+ (name) => {+ expect(isArtifactToolName(name)).toBe(false);+ },+ );+});++describe("isLogToolName", () => {+ test("recognises the bare name used in Codex transcripts", () => {+ expect(isLogToolName("event_log_append")).toBe(true);+ });++ test("recognises the Claude Code plugin-decorated MCP name", () => {+ // Verified live against /root/.claude/projects/-root/*.jsonl β+ // Claude prefixes plugin-supplied MCP tools with+ // `mcp__plugin_<plugin>_<server>__`.+ expect(+ isLogToolName("mcp__plugin_open-second-brain_open-second-brain__event_log_append"),+ ).toBe(true);+ });++ test("recognises the legacy short MCP name", () => {+ // Older Claude builds (and some forks) used a shorter prefix.+ expect(isLogToolName("mcp__open-second-brain__event_log_append")).toBe(true);+ });++ test("rejects unrelated names", () => {+ expect(isLogToolName("second_brain_capture")).toBe(false);+ expect(isLogToolName("Write")).toBe(false);+ expect(isLogToolName("event_log_append_other")).toBe(false);+ expect(isLogToolName("not_event_log_append")).toBe(false);+ });++ test("rejects names that contain the suffix but not as a `__`-bounded token", () => {+ expect(isLogToolName("xevent_log_append")).toBe(false);+ });+});++describe("summarizeTurn", () => {+ test("artifact without log β hadArtifact && !hadLog", () => {+ const s = summarizeTurn([{ name: "Write" }, { name: "Bash" }]);+ expect(s).toEqual({ hadArtifact: true, hadLog: false });+ });++ test("artifact AND MCP log β hadLog wins", () => {+ const s = summarizeTurn([{ name: "Write" }, { name: "event_log_append" }]);+ expect(s).toEqual({ hadArtifact: true, hadLog: true });+ });++ test("artifact + bash that runs `o2b append-event` counts as log", () => {+ const s = summarizeTurn(+ [{ name: "apply_patch" }, { name: "Bash" }],+ ["o2b append-event 'fixed bug'"],+ );+ expect(s).toEqual({ hadArtifact: true, hadLog: true });+ });++ test("artifact + bash that runs the legacy `vault-log` wrapper counts as log", () => {+ const s = summarizeTurn(+ [{ name: "Write" }, { name: "Bash" }],+ ["vault-log 'noted finding'"],+ );+ expect(s).toEqual({ hadArtifact: true, hadLog: true });+ });++ test("the trailing space in the `vault-log ` needle prevents false matches on paths", () => {+ // A path like `/srv/audit/vault-log.json` must NOT be misread as+ // an `o2b vault-log` invocation. The needle's trailing space (the+ // CLI is always followed by an argument) makes the match precise.+ const s = summarizeTurn(+ [{ name: "Write" }, { name: "Bash" }],+ ["cat /srv/audit/vault-log.json"],+ );+ expect(s).toEqual({ hadArtifact: true, hadLog: false });+ });++ test("starting the MCP server (`o2b mcp β¦`) does NOT count as log", () => {+ // Spawning `o2b mcp` only launches the server subprocess β it+ // does not append anything to the daily log. Regression guard+ // against an earlier, looser needle list that incorrectly+ // treated `o2b mcp` as a log call.+ const s = summarizeTurn(+ [{ name: "Write" }, { name: "Bash" }],+ ["o2b mcp --vault /tmp/vault"],+ );+ expect(s).toEqual({ hadArtifact: true, hadLog: false });+ });++ test("bash without an OSB log command does NOT count as log", () => {+ const s = summarizeTurn([{ name: "Write" }, { name: "Bash" }], ["echo hello"]);+ expect(s).toEqual({ hadArtifact: true, hadLog: false });+ });++ test("read-only tools yield no artifact", () => {+ const s = summarizeTurn([{ name: "Read" }, { name: "Grep" }]);+ expect(s).toEqual({ hadArtifact: false, hadLog: false });+ });+});diff --git a/tests/hooks/post-write-reminder.test.ts b/tests/hooks/post-write-reminder.test.tsnew file mode 100644index 00000000..147759b3--- /dev/null+++ b/tests/hooks/post-write-reminder.test.ts@@ -0,0 +1,119 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const HOOK = resolve(+ dirname(fileURLToPath(import.meta.url)),+ "..",+ "..",+ "hooks",+ "post-write-reminder.ts",+);++let tmp: string;+beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-hook-post-"));+});+afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++interface RunResult {+ readonly stdout: string;+ readonly exit: number;+}++async function runHook(payload: unknown): Promise<RunResult> {+ const proc = Bun.spawn(["bun", "run", HOOK], {+ stdin: "pipe",+ stdout: "pipe",+ stderr: "pipe",+ });+ proc.stdin.write(JSON.stringify(payload));+ await proc.stdin.end();+ const stdout = await new Response(proc.stdout).text();+ const exit = await proc.exited;+ return { stdout, exit };+}++describe("post-write-reminder hook", () => {+ test("emits additionalContext for Claude Code Write", async () => {+ const r = await runHook({+ hook_event_name: "PostToolUse",+ tool_name: "Write",+ tool_input: { file_path: "/tmp/foo.md", content: "hello" },+ });+ expect(r.exit).toBe(0);+ // Line-oriented runtimes (stream-json on Claude Code) parse hook+ // stdout line-by-line, so the terminator is part of the contract.+ expect(r.stdout.endsWith("\n")).toBe(true);+ const out = JSON.parse(r.stdout);+ expect(out.hookSpecificOutput.hookEventName).toBe("PostToolUse");+ expect(out.hookSpecificOutput.additionalContext).toContain("`Write`");+ expect(out.hookSpecificOutput.additionalContext).toContain("/tmp/foo.md");+ expect(out.hookSpecificOutput.additionalContext).toContain("event_log_append");+ });++ test("emits additionalContext for Codex apply_patch with patch body", async () => {+ const patch =+ "*** Begin Patch\n*** Update File: /srv/projects/x/src/index.ts\n@@\n-foo\n+bar\n*** End Patch\n";+ const r = await runHook({+ hook_event_name: "PostToolUse",+ tool_name: "apply_patch",+ tool_input: { input: patch },+ });+ expect(r.exit).toBe(0);+ const out = JSON.parse(r.stdout);+ expect(out.hookSpecificOutput.additionalContext).toContain("apply_patch");+ expect(out.hookSpecificOutput.additionalContext).toContain(+ "/srv/projects/x/src/index.ts",+ );+ });++ test("stays silent when Claude's tool_response reports an error", async () => {+ const r = await runHook({+ hook_event_name: "PostToolUse",+ tool_name: "Edit",+ tool_input: { file_path: "/tmp/foo.md", old_string: "x", new_string: "y" },+ tool_response: { is_error: true, error: "old_string not found" },+ });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("stays silent when tool_response.success === false", async () => {+ const r = await runHook({+ hook_event_name: "PostToolUse",+ tool_name: "Write",+ tool_input: { file_path: "/tmp/foo.md", content: "hi" },+ tool_response: { success: false },+ });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("stays silent for non-artifact tools", async () => {+ const r = await runHook({+ hook_event_name: "PostToolUse",+ tool_name: "Bash",+ tool_input: { command: "ls" },+ });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("stays silent on empty payload", async () => {+ const proc = Bun.spawn(["bun", "run", HOOK], {+ stdin: "pipe",+ stdout: "pipe",+ stderr: "pipe",+ });+ await proc.stdin.end();+ const stdout = await new Response(proc.stdout).text();+ const exit = await proc.exited;+ expect(exit).toBe(0);+ expect(stdout).toBe("");+ });+});diff --git a/tests/hooks/stop-log-guardrail.test.ts b/tests/hooks/stop-log-guardrail.test.tsnew file mode 100644index 00000000..ac8efc94--- /dev/null+++ b/tests/hooks/stop-log-guardrail.test.ts@@ -0,0 +1,212 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const HOOK = resolve(+ dirname(fileURLToPath(import.meta.url)),+ "..",+ "..",+ "hooks",+ "stop-log-guardrail.ts",+);++let tmp: string;+beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-hook-stop-"));+});+afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function ccUser(text: string): string {+ return JSON.stringify({+ type: "user",+ message: { role: "user", content: [{ type: "text", text }] },+ });+}++function ccAssistantToolUse(name: string, input: Record<string, unknown> = {}): string {+ return JSON.stringify({+ type: "assistant",+ message: {+ role: "assistant",+ content: [{ type: "tool_use", id: "toolu_" + name, name, input }],+ },+ });+}++function writeTranscript(lines: readonly string[]): string {+ const path = join(tmp, "transcript.jsonl");+ writeFileSync(path, lines.join("\n") + "\n");+ return path;+}++interface RunResult {+ readonly stdout: string;+ readonly exit: number;+}++async function runHook(payload: unknown): Promise<RunResult> {+ const proc = Bun.spawn(["bun", "run", HOOK], {+ stdin: "pipe",+ stdout: "pipe",+ stderr: "pipe",+ });+ proc.stdin.write(JSON.stringify(payload));+ await proc.stdin.end();+ const stdout = await new Response(proc.stdout).text();+ const exit = await proc.exited;+ return { stdout, exit };+}++describe("stop-log-guardrail hook", () => {+ test("blocks once when artifact was produced and no log was called", async () => {+ const transcript_path = writeTranscript([+ ccUser("please add a file"),+ ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),+ ]);+ const r = await runHook({+ hook_event_name: "Stop",+ transcript_path,+ stop_hook_active: false,+ });+ expect(r.exit).toBe(0);+ expect(r.stdout.endsWith("\n")).toBe(true);+ const out = JSON.parse(r.stdout);+ expect(out.decision).toBe("block");+ expect(out.reason).toContain("event_log_append");+ });++ test("passes through when log was called this turn", async () => {+ const transcript_path = writeTranscript([+ ccUser("please add a file"),+ ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),+ ccAssistantToolUse("event_log_append", { message: "added /tmp/x.md" }),+ ]);+ const r = await runHook({+ hook_event_name: "Stop",+ transcript_path,+ stop_hook_active: false,+ });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("passes through when no artifact was produced", async () => {+ const transcript_path = writeTranscript([+ ccUser("what's in the README?"),+ ccAssistantToolUse("Read", { file_path: "/tmp/README.md" }),+ ]);+ const r = await runHook({+ hook_event_name: "Stop",+ transcript_path,+ stop_hook_active: false,+ });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("never blocks twice in a row (stop_hook_active === true)", async () => {+ const transcript_path = writeTranscript([+ ccUser("please add a file"),+ ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),+ ]);+ const r = await runHook({+ hook_event_name: "Stop",+ transcript_path,+ stop_hook_active: true,+ });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("stays silent when transcript_path is missing", async () => {+ const r = await runHook({+ hook_event_name: "Stop",+ stop_hook_active: false,+ });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("stays silent when transcript_path does not exist on disk", async () => {+ const r = await runHook({+ hook_event_name: "Stop",+ transcript_path: join(tmp, "missing.jsonl"),+ stop_hook_active: false,+ });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("passes through when the agent logged via Bash (`o2b append-event`)", async () => {+ const transcript_path = writeTranscript([+ ccUser("add a file and log it via bash"),+ ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),+ JSON.stringify({+ type: "assistant",+ message: {+ role: "assistant",+ content: [+ {+ type: "tool_use",+ id: "toolu_b",+ name: "Bash",+ input: { command: "o2b append-event 'added /tmp/x.md'" },+ },+ ],+ },+ }),+ ]);+ const r = await runHook({+ hook_event_name: "Stop",+ transcript_path,+ stop_hook_active: false,+ });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("passes through when the Claude MCP-prefixed event_log_append is called", async () => {+ const transcript_path = writeTranscript([+ ccUser("add a file"),+ ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),+ ccAssistantToolUse("mcp__plugin_open-second-brain_open-second-brain__event_log_append", {+ message: "added /tmp/x.md",+ }),+ ]);+ const r = await runHook({+ hook_event_name: "Stop",+ transcript_path,+ stop_hook_active: false,+ });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("blocks for Codex apply_patch with no logging", async () => {+ const transcript_path = writeTranscript([+ JSON.stringify({+ type: "response_item",+ payload: {+ type: "message",+ role: "user",+ content: [{ type: "input_text", text: "patch the file" }],+ },+ }),+ JSON.stringify({+ type: "response_item",+ payload: { type: "custom_tool_call", name: "apply_patch", call_id: "c1", input: "" },+ }),+ ]);+ const r = await runHook({+ hook_event_name: "Stop",+ transcript_path,+ stop_hook_active: false,+ });+ const out = JSON.parse(r.stdout);+ expect(out.decision).toBe("block");+ });+});diff --git a/tests/hooks/transcript.test.ts b/tests/hooks/transcript.test.tsnew file mode 100644index 00000000..aa2c8465--- /dev/null+++ b/tests/hooks/transcript.test.ts@@ -0,0 +1,248 @@+import { describe, expect, test } from "bun:test";++import { detectFormat, parseTranscript } from "../../hooks/lib/transcript.ts";++// Minimal builders that mirror the on-disk shapes verified against+// live `~/.claude/projects/**/*.jsonl` and `~/.codex/sessions/**/*.jsonl`+// rollouts. Each helper produces ONE JSONL line; tests join them.++function ccUser(text: string): string {+ return JSON.stringify({+ type: "user",+ message: { role: "user", content: [{ type: "text", text }] },+ });+}++function ccToolResult(toolUseId: string, text = "ok"): string {+ return JSON.stringify({+ type: "user",+ message: {+ role: "user",+ content: [{ type: "tool_result", tool_use_id: toolUseId, content: text }],+ },+ });+}++function ccAssistantToolUse(name: string, input: Record<string, unknown> = {}): string {+ return JSON.stringify({+ type: "assistant",+ message: {+ role: "assistant",+ content: [{ type: "tool_use", id: "toolu_" + name, name, input }],+ },+ });+}++function ccAssistantText(text: string): string {+ return JSON.stringify({+ type: "assistant",+ message: { role: "assistant", content: [{ type: "text", text }] },+ });+}++function cxUserEnvelope(text = "<environment_context>"): string {+ return JSON.stringify({+ type: "response_item",+ payload: { type: "message", role: "user", content: [{ type: "input_text", text }] },+ });+}++function cxUser(text: string): string {+ return JSON.stringify({+ type: "response_item",+ payload: { type: "message", role: "user", content: [{ type: "input_text", text }] },+ });+}++function cxFunctionCall(name: string): string {+ return JSON.stringify({+ type: "response_item",+ payload: { type: "function_call", name, call_id: "call_" + name, arguments: "{}" },+ });+}++function cxCustomToolCall(name: string): string {+ return JSON.stringify({+ type: "response_item",+ payload: { type: "custom_tool_call", name, call_id: "call_" + name, input: "" },+ });+}++describe("detectFormat", () => {+ test("recognises Claude transcript", () => {+ expect(detectFormat(ccUser("hi"))).toBe("claude");+ });++ test("recognises Codex transcript", () => {+ expect(detectFormat(cxUser("hi"))).toBe("codex");+ });++ test("treats empty and malformed input as unknown", () => {+ expect(detectFormat("")).toBe("unknown");+ expect(detectFormat("not-json")).toBe("unknown");+ expect(detectFormat("[]")).toBe("unknown");+ });++ test("returns unknown for Claude bookkeeping records (no message.role)", () => {+ // Real Claude transcripts start with records like queue-operation,+ // permission-mode, attachment. They have `type` and `sessionId`+ // but no `message.role`. Detection must keep scanning so a real+ // user/assistant line drives the decision.+ expect(+ detectFormat(JSON.stringify({ type: "queue-operation", sessionId: "abc" })),+ ).toBe("unknown");+ expect(+ detectFormat(JSON.stringify({ type: "permission-mode", permissionMode: "default" })),+ ).toBe("unknown");+ });+});++describe("parseTranscript β Claude", () => {+ test("collects tool_use calls after the last user message", () => {+ const jsonl = [+ ccUser("first user message"),+ ccAssistantToolUse("Read"),+ ccUser("second user message"),+ ccAssistantToolUse("Write", { file_path: "/tmp/a.md" }),+ ccAssistantToolUse("Edit", { file_path: "/tmp/a.md" }),+ ccAssistantText("done"),+ ].join("\n");+ const sig = parseTranscript(jsonl);+ expect(sig.toolCalls.map((t) => t.name)).toEqual(["Write", "Edit"]);+ });++ test("does NOT treat tool_result records as user-turn boundaries", () => {+ // A `tool_result` is sent as `type:"user"` by the runtime but it is+ // NOT a real user prompt. The boundary must stay at the actual user+ // message, so tool_uses *before* the tool_result still count.+ const jsonl = [+ ccUser("real user prompt"),+ ccAssistantToolUse("Write", { file_path: "/tmp/a.md" }),+ ccToolResult("toolu_Write"),+ ccAssistantText("finished"),+ ].join("\n");+ const sig = parseTranscript(jsonl);+ expect(sig.toolCalls.map((t) => t.name)).toEqual(["Write"]);+ });++ test("returns empty for sessions with no user message yet", () => {+ const jsonl = [ccAssistantText("system init")].join("\n");+ const sig = parseTranscript(jsonl);+ expect(sig.toolCalls).toEqual([]);+ });+});++describe("parseTranscript β Codex", () => {+ test("collects function_call and custom_tool_call after last user message", () => {+ const jsonl = [+ cxUserEnvelope(),+ cxUser("real user prompt"),+ cxFunctionCall("event_log_append"),+ cxCustomToolCall("apply_patch"),+ cxFunctionCall("exec_command"),+ ].join("\n");+ const sig = parseTranscript(jsonl);+ expect(sig.toolCalls.map((t) => t.name)).toEqual([+ "event_log_append",+ "apply_patch",+ "exec_command",+ ]);+ });++ test("skips synthetic <environment_context> envelopes when finding the boundary", () => {+ // If we anchored at the envelope, we'd include tool calls from prior+ // turns. The real user prompt is the anchor.+ const jsonl = [+ cxUserEnvelope("<environment_context>\n <cwd>/tmp</cwd>\n</environment_context>"),+ cxUser("real user prompt"),+ cxCustomToolCall("apply_patch"),+ ].join("\n");+ const sig = parseTranscript(jsonl);+ expect(sig.toolCalls.map((t) => t.name)).toEqual(["apply_patch"]);+ });++ test("returns empty when there is no user prompt yet", () => {+ const jsonl = [cxUserEnvelope(), cxFunctionCall("exec_command")].join("\n");+ const sig = parseTranscript(jsonl);+ expect(sig.toolCalls).toEqual([]);+ });+});++describe("parseTranscript β robustness", () => {+ test("skips malformed lines silently", () => {+ const jsonl = ["not-json", ccUser("hi"), "{broken", ccAssistantToolUse("Write")].join("\n");+ const sig = parseTranscript(jsonl);+ expect(sig.toolCalls.map((t) => t.name)).toEqual(["Write"]);+ });++ test("scans past Claude bookkeeping records before the first proper message", () => {+ const jsonl = [+ JSON.stringify({ type: "queue-operation", sessionId: "abc" }),+ JSON.stringify({ type: "permission-mode", permissionMode: "default" }),+ ccUser("hi"),+ ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),+ ].join("\n");+ const sig = parseTranscript(jsonl);+ expect(sig.toolCalls.map((t) => t.name)).toEqual(["Write"]);+ });+});++describe("parseTranscript β Bash commands", () => {+ test("Claude: collects Bash tool_use commands this turn", () => {+ const jsonl = [+ ccUser("log this"),+ JSON.stringify({+ type: "assistant",+ message: {+ role: "assistant",+ content: [+ {+ type: "tool_use",+ id: "toolu_b",+ name: "Bash",+ input: { command: "o2b append-event 'fixed bug'" },+ },+ ],+ },+ }),+ ].join("\n");+ const sig = parseTranscript(jsonl);+ expect(sig.bashCommands).toEqual(["o2b append-event 'fixed bug'"]);+ });++ test("Codex: collects exec_command arguments this turn", () => {+ const jsonl = [+ cxUserEnvelope(),+ cxUser("log this"),+ JSON.stringify({+ type: "response_item",+ payload: {+ type: "function_call",+ name: "exec_command",+ call_id: "c1",+ arguments: JSON.stringify({ cmd: "vault-log 'noted finding'" }),+ },+ }),+ ].join("\n");+ const sig = parseTranscript(jsonl);+ expect(sig.bashCommands).toEqual(["vault-log 'noted finding'"]);+ });++ test("Codex: handles `command` field as fallback", () => {+ const jsonl = [+ cxUserEnvelope(),+ cxUser("log this"),+ JSON.stringify({+ type: "response_item",+ payload: {+ type: "function_call",+ name: "exec_command",+ call_id: "c2",+ arguments: JSON.stringify({ command: ["o2b", "append-event", "x"] }),+ },+ }),+ ].join("\n");+ const sig = parseTranscript(jsonl);+ expect(sig.bashCommands).toEqual(["o2b append-event x"]);+ });+});diff --git a/tsconfig.json b/tsconfig.jsonindex c15eadbc..f0c2c872 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -19,5 +19,11 @@"forceConsistentCasingInFileNames": true,"types": ["bun"]},- "include": ["src/**/*.ts", "src/**/*.d.ts", "tests/**/*.ts", "scripts/**/*.ts"]+ "include": [+ "src/**/*.ts",+ "src/**/*.d.ts",+ "tests/**/*.ts",+ "scripts/**/*.ts",+ "hooks/**/*.ts"+ ]}