Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

fix(codex): real plugin files and a truthful install check (v1.57.1) (#193)

Serg Eroshea4d3ecf8f871
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 3e7e20d1..8dc4ec7a 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.57.0",
+ "version": "1.57.1",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 78ee64d3..54a57be9 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.57.0",
+ "version": "1.57.1",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/.githooks/pre-commit b/.githooks/pre-commit
index c6db3415..794fad94 100755
--- a/.githooks/pre-commit
+++ b/.githooks/pre-commit
@@ -23,5 +23,11 @@ if ! bun run fmt:check; then
exit 1
fi
+echo "pre-commit: bun run sync-plugin-mirrors:check" >&2
+if ! bun run sync-plugin-mirrors:check; then
+ echo "pre-commit: plugins/codex mirrors drifted - run 'bun run sync-plugin-mirrors' and re-stage." >&2
+ exit 1
+fi
+
echo "pre-commit: bun run lint" >&2
bun run lint
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 45e37d30..e571ce1b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -43,6 +43,11 @@ jobs:
- name: Verify manifest version sync
run: bun run sync-version:check
+ # Codex caches only `plugins/codex/` and drops symlinks, so the Codex
+ # plugin carries real copies of `skills/` and `hooks/hooks.json`.
+ - name: Codex plugin mirrors are in sync
+ run: bun run sync-plugin-mirrors:check
+
- name: OpenClaw bundle is in sync with sources
shell: bash
run: |
@@ -145,6 +150,13 @@ jobs:
- name: Install JS dependencies
run: bun install --frozen-lockfile
+ # The one validate-job check repeated here, because it is about the
+ # checkout: the mirrors must come out of a Windows clone as the same
+ # bytes (LF, per .gitattributes) and as real files, not as symlinks
+ # materialised as text.
+ - name: Codex plugin mirrors are in sync
+ run: bun run sync-plugin-mirrors:check
+
- name: Typecheck
run: bun run typecheck
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e48d4cd8..4f386ea4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,26 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.57.1] - 2026-09-25
+
+Two faults that surfaced while wiring Codex CLI 0.157.0 to this plugin. Neither was visible from inside the repository. Codex installs a plugin by copying its marketplace source, `plugins/codex/`, into `~/.codex/plugins/cache/`, and that copy drops symlinks. `plugins/codex/hooks` and `plugins/codex/skills` were both symlinks into the repository root, so every Codex install had no hooks and no skills. Every Codex run also warned `failed to read plugin hooks config .../hooks/hooks.json: No such file or directory`. Separately, `o2b install --check` reported a correctly registered Codex as `mcp-unreachable`, because the host probe discarded every successful answer.
+
+### Fixed
+
+- **The Codex plugin ships real files.**
+ - `plugins/codex/skills/` is a byte copy of `skills/`.
+ - `plugins/codex/hooks/hooks.json` is generated from `hooks/hooks.json`. SessionEnd timeouts are capped at the 3 s that Codex enforces anyway, and that it otherwise warns about on every run.
+ - Only `hooks.json` is mirrored, never the `hooks/*.ts` scripts. Codex exports `CLAUDE_PLUGIN_ROOT` as its cache dir. A cached script there would win `o2b-hook`'s resolution and then fail on its `../src` imports. Without one, resolution falls through to the real checkout, as before.
+ - Every mirrored hook also carries a `commandWindows`. On Windows Codex runs a hook as `%COMSPEC% /C "<command>"`, which cannot parse the POSIX form. The Windows form runs the PATH `o2b-hook.cmd` that `o2b install-cli` writes, sets `NoDefaultCurrentDirectoryInExePath` first and asks `where /q $PATH:o2b-hook` rather than a bare `where`, so a launcher planted in the project Codex opened never runs. It always exits 0. The sync refuses a hook command that does not end in the `o2b-hook <name>` fallback, rather than ship one that cmd.exe cannot run.
+ - The same change retires the only symlinks in the tree. A Windows checkout without Developer Mode or `core.symlinks` materialised them as text files holding the target path.
+ - Verified against Codex 0.157.0 in a throwaway `CODEX_HOME`: `codex plugin marketplace add` plus `codex plugin add` put `hooks/hooks.json` and all five skills in the cache. `hooks/list` reports 16 plugin hooks with no warnings or errors, and `skills/list` reports the five `open-second-brain:*` skills. Once trusted, the SessionStart, UserPromptSubmit and SessionEnd hooks fire through `o2b-hook`.
+- **`install/codex.md` looks for the launcher under `CODEX_HOME`.** Step 2 searched `~/.codex` whatever `CODEX_HOME` said, so a relocated Codex home stopped the install or picked a stale launcher. It now searches the marketplace clone in `${CODEX_HOME:-$HOME/.codex}/.tmp/marketplaces`.
+- **`o2b install --check` stops calling a working Codex `mcp-unreachable`.** The host probe tested `signalCode !== null` to detect a killed child. Bun leaves `signalCode` undefined, not null, on a normal exit, so every successful `codex mcp list` was treated as killed and its stdout was thrown away. The check is now `!= null`, and a test drives a real child that exits normally, since a stubbed runner cannot reproduce a runtime quirk. No other spawn site has the pattern: the `node:child_process` call sites get `null` from Bun, as Node documents.
+
+### Added
+
+- **`bun run sync-plugin-mirrors`** rebuilds the Codex mirrors. `bun run sync-plugin-mirrors:check` is gated in the pre-commit hook and in two CI jobs: `validate`, and `windows`, whose checkout is where a line-ending rewrite or a symlink materialised as a text file would show. It reports a missing, changed or extra mirrored file, and any symlink, by name. A test also asserts that the git index tracks no symlink under `plugins/` or `.agents/`.
+
## [1.57.0] - 2026-09-25
Open Second Brain now runs natively on Windows 10 and 11. Until this release the resolver refused `win32` by name, and the refusal was the honest part: every entry point was a bash script, every durable path assumed `$HOME/.config`, and the code underneath had habits that POSIX forgives and Windows does not. A SQLite connection closed without finalizing its statements keeps its file locked. A rename onto a file another process holds fails. A tar walk follows `readdir` order, and that order differs between filesystems. A path split on `/` misses `\`. The first full test run under Windows Bun failed 2127 of 12,388 tests. This release closes those gaps, gives the platform its own layout, and ends with the same suite at 0 failures on Windows and on Linux. 162 tests are skipped on Windows, each with a stated reason; they assert something Windows cannot express, such as a chmod that denies reading. Several of the fixes were never Windows bugs. They are nondeterminism and leaks that every platform had, which a second platform happened to expose.
@@ -7574,6 +7594,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.57.1]: https://github.com/itechmeat/open-second-brain/compare/v1.57.0...v1.57.1
[1.57.0]: https://github.com/itechmeat/open-second-brain/compare/v1.56.0...v1.57.0
[1.56.0]: https://github.com/itechmeat/open-second-brain/compare/v1.55.0...v1.56.0
[1.55.0]: https://github.com/itechmeat/open-second-brain/compare/v1.54.0...v1.55.0
diff --git a/CLAUDE.md b/CLAUDE.md
index 33fe7560..74c41c2b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -48,3 +48,21 @@ maintainer can push the bump straight to `main` at release time; this repo
cannot, so the bump belongs in the feature PR. The GitHub release
(`gh release create vX.Y.Z`) is published AFTER that PR merges and only tags
the already-bumped commit - it never changes the version.
+
+## Codex plugin mirrors
+
+Codex installs the plugin from `./plugins/codex` only, and its cache copy
+drops symlinks. So `plugins/codex/skills/` is a real, byte-identical copy of
+`skills/`, and `plugins/codex/hooks/hooks.json` is generated from
+`hooks/hooks.json` (SessionEnd timeouts capped at Codex's 3 s limit, and a
+`commandWindows` cmd.exe form added to every hook). Every hook command must
+end in the `o2b-hook <name>` fallback, or the sync refuses it. Never
+edit the copies and never turn them back into symlinks. After changing a
+skill or `hooks/hooks.json`, run:
+
+```
+bun run sync-plugin-mirrors
+```
+
+CI gates on `bun run sync-plugin-mirrors:check` (the `validate` and
+`windows` jobs), and the pre-commit hook runs the same check.
diff --git a/hooks/README.md b/hooks/README.md
index f392fcaf..c4752249 100644
--- a/hooks/README.md
+++ b/hooks/README.md
@@ -65,16 +65,18 @@ call would.
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).
+ Layout: Codex's marketplace source is `./plugins/codex/`, and
+ `codex plugin add` copies only that subtree into its plugin cache,
+ dropping symlinks on the way. So `plugins/codex/hooks/hooks.json` is a
+ real file generated from this one by `bun run sync-plugin-mirrors`, and
+ CI gates it with `bun run sync-plugin-mirrors:check` (the same goes for
+ `plugins/codex/skills/`, which is a byte copy of `skills/`). The one
+ difference: SessionEnd timeouts are capped at Codex's 3 s limit, which
+ Codex enforces anyway and warns about on every run otherwise. Only
+ `hooks.json` is mirrored, never the `*.ts` scripts: Codex exports
+ `CLAUDE_PLUGIN_ROOT` as the cache dir, and `o2b-hook` would pick a
+ cached script there whose `../src` imports do not exist. Edit
+ `hooks/hooks.json`, then run the sync.
- `session-capture.ts` β€” Bun entry script that handles lifecycle
observations and immediate marker/tool-feedback capture. It emits
@@ -106,11 +108,20 @@ r="$CLAUDE_PLUGIN_ROOT"; if [ -n "$r" ] && [ -x "$r/scripts/o2b-hook" ]; then ex
- **Claude Code** sets `CLAUDE_PLUGIN_ROOT` to the *active* plugin
version directory, so the command runs `scripts/o2b-hook` from the
version Claude Code just loaded β€” never a stale copy.
-- **Codex** does not export a plugin-root env var, so it falls through
- to the PATH `o2b-hook` shim (`o2b install-cli` puts it on PATH; on a
- server it points at the stable checkout, which never rotates).
+- **Codex** exports `CLAUDE_PLUGIN_ROOT` too, but as its plugin cache
+ dir, which holds only the Codex plugin subtree (`hooks.json` and the
+ skills) and no `scripts/o2b-hook`. So the command falls through to the
+ PATH `o2b-hook` shim (`o2b install-cli` puts it on PATH; on a server it
+ points at the stable checkout, which never rotates).
- If neither resolves, the command `exit 0`s β€” a missing launcher is a
no-op, never a blocked turn.
+- **Codex on Windows** runs a hook as `%COMSPEC% /C "<command>"`, which
+ cannot parse the POSIX form, so the Codex mirror
+ (`plugins/codex/hooks/hooks.json`, generated by
+ `bun run sync-plugin-mirrors`) gives every hook a `commandWindows`:
+ `set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook <name> & exit /b 0`.
+ It runs the PATH `o2b-hook.cmd` that `o2b install-cli` writes, never
+ one in the project Codex opened, and always exits `0`.
`scripts/o2b-hook` itself resolves the checkout root in the same order
(`$CLAUDE_PLUGIN_ROOT` β†’ its own realpath β†’ `$OSB_PLUGIN_ROOT`) and is
diff --git a/install/codex.md b/install/codex.md
index a263f169..f13f862c 100644
--- a/install/codex.md
+++ b/install/codex.md
@@ -19,12 +19,17 @@ enabled = true
## 2. Publish the `o2b` CLI on PATH
-Codex caches the plugin at a version-hashed path; locate the
-script:
+`codex plugin marketplace add` clones the whole repository into
+`$CODEX_HOME/.tmp/marketplaces/open-second-brain/`, and that clone holds
+the launcher. The installed plugin in `$CODEX_HOME/plugins/cache/` holds
+only the `plugins/codex` subtree (manifest, `hooks/hooks.json`, skills),
+not `scripts/`. The hooks run `o2b-hook` from PATH, so this step is also
+what turns them on. Locate the script in the clone (under `CODEX_HOME`
+when it is set):
```bash
-O2B_SCRIPT="$(find ~/.codex -path '*open-second-brain*/scripts/o2b' -type f 2>/dev/null | head -1)"
-[ -n "$O2B_SCRIPT" ] || { echo "o2b installer not found in Codex plugin cache" >&2; exit 1; }
+O2B_SCRIPT="$(find "${CODEX_HOME:-$HOME/.codex}/.tmp/marketplaces" -path '*open-second-brain*/scripts/o2b' -type f 2>/dev/null | head -1)"
+[ -n "$O2B_SCRIPT" ] || { echo "o2b launcher not found in the Codex marketplace clone" >&2; exit 1; }
"$O2B_SCRIPT" install-cli
```
diff --git a/install/windows.md b/install/windows.md
index dc4b6633..128211aa 100644
--- a/install/windows.md
+++ b/install/windows.md
@@ -85,6 +85,11 @@ carries the host.
`.cmd` launchers set the same variable for their `bun` lookup. The
install refuses a vault path containing `& | < > ^ % " !`, which cmd
would split, expand or execute.
+- **Codex** runs plugin hooks through `cmd.exe`, so every hook in the Codex
+ plugin carries a `commandWindows` form that calls the `o2b-hook.cmd`
+ launcher `o2b install-cli` puts on PATH, never one from the current
+ directory. Git for Windows is not needed for them. Codex marks plugin
+ hooks untrusted until you approve them in `/hooks`.
- **Grok Build** gets absolute `bun.exe run <repo>\src\cli\main.ts` MCP
entries and hook commands. Unverified on Windows: xAI does not document
which shell runs hook commands there (reports say PowerShell), and the
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 9faec2eb..c05ed07c 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "1.57.0",
+ "version": "1.57.1",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index dfc32a8d..2a75b1ee 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.57.0",
+ "version": "1.57.1",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
@@ -46,6 +46,8 @@
"validate:fix": "bun run lint:fix && bun run fmt",
"sync-version": "bun run scripts/sync-version.ts",
"sync-version:check": "bun run scripts/sync-version.ts --check",
+ "sync-plugin-mirrors": "bun run scripts/sync-plugin-mirrors.ts",
+ "sync-plugin-mirrors:check": "bun run scripts/sync-plugin-mirrors.ts --check",
"link-ratchet": "bun run scripts/link-ratchet.ts",
"link-ratchet:check": "bun run scripts/link-ratchet.ts --check",
"check:paths": "bun run scripts/check-hardcoded-paths.ts",
diff --git a/plugin.yaml b/plugin.yaml
index 4eb02453..bda5bd59 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.57.0"
+version: "1.57.1"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 92fc6156..d7eaadbb 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.57.0",
+ "version": "1.57.1",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/codex/hooks b/plugins/codex/hooks
deleted file mode 120000
index 2777e158..00000000
--- a/plugins/codex/hooks
+++ /dev/null
@@ -1 +0,0 @@
-../../hooks
\ No newline at end of file
diff --git a/plugins/codex/hooks/hooks.json b/plugins/codex/hooks/hooks.json
new file mode 100644
index 00000000..6e35de71
--- /dev/null
+++ b/plugins/codex/hooks/hooks.json
@@ -0,0 +1,177 @@
+{
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "brain_feedback",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook session-capture & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: capturing brain_feedback lifecycle event"
+ }
+ ]
+ },
+ {
+ "matcher": "Write|Edit|MultiEdit|apply_patch",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" post-write-reminder; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook post-write-reminder; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook post-write-reminder & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: reminding to log signals/evidence"
+ }
+ ]
+ }
+ ],
+ "SessionStart": [
+ {
+ "matcher": "startup|resume|clear|compact",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" active-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook active-inject; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook active-inject & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: injecting active preferences"
+ },
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" gap-agenda; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook gap-agenda; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook gap-agenda & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: injecting open recall-gap agenda (opt-in)"
+ },
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook session-capture & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: capturing session start"
+ }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook session-capture & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: capturing prompt markers"
+ },
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" recall-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook recall-inject; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook recall-inject & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: recalling bounded prompt context (opt-in)"
+ },
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" nav-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook nav-inject; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook nav-inject & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: injecting structural navmap tier (opt-in)"
+ }
+ ]
+ }
+ ],
+ "PreToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" pretool-orient; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook pretool-orient; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook pretool-orient & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: strict read-block orientation gate (opt-in)"
+ }
+ ]
+ }
+ ],
+ "Stop": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook session-capture & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: capturing session stop"
+ },
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" stop-log-guardrail; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook stop-log-guardrail; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook stop-log-guardrail & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: checking stop log guardrail"
+ }
+ ]
+ }
+ ],
+ "SubagentStop": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook session-capture & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: capturing delegated sub-agent stop"
+ }
+ ]
+ }
+ ],
+ "SessionEnd": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook session-capture & exit /b 0",
+ "timeout": 3,
+ "statusMessage": "OSB: capturing session end"
+ },
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" gap-promote; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook gap-promote; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook gap-promote & exit /b 0",
+ "timeout": 3,
+ "statusMessage": "OSB: promoting recurring recall gaps (opt-in)"
+ }
+ ]
+ }
+ ],
+ "PostCompact": [
+ {
+ "matcher": "manual|auto",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" active-inject; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook active-inject; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook active-inject & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: re-injecting active preferences after compact"
+ },
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook session-capture & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: capturing post-compact lifecycle event"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/codex/skills b/plugins/codex/skills
deleted file mode 120000
index 5dcab58e..00000000
--- a/plugins/codex/skills
+++ /dev/null
@@ -1 +0,0 @@
-../../skills
\ No newline at end of file
diff --git a/plugins/codex/skills/brain-memory/SKILL.md b/plugins/codex/skills/brain-memory/SKILL.md
new file mode 100644
index 00000000..a8291ad3
--- /dev/null
+++ b/plugins/codex/skills/brain-memory/SKILL.md
@@ -0,0 +1,170 @@
+---
+name: brain-memory
+description: Record taste signals and apply-evidence events into the Brain observing-memory layer of Open Second Brain. INVOKE this skill (and call `brain_feedback`) the moment the user expresses a preference, dislike, correction, or rule in dialogue β€” "don't do X", "use A instead of B", "I prefer Y", "X is wrong here", or any explicit imperative that should outlive the current turn. SEPARATELY invoke (and call `brain_apply_evidence`) right after you produce a durable artifact (code shipped, file written, content drafted, config change) and at least one preference in `Brain/preferences/` has a `scope` that plausibly applies β€” record whether you `applied` or `violated` it. SKIP only for casual chat, exploration without a stated rule, read-only inspection, and trivial edits. When a preference plausibly applies but you are unsure, RECORD with `note: "speculative; <reason>"` rather than skipping β€” the dream pass discards single-event speculative entries that do not recur, so coverage costs less than missing the signal. WRITE the `principle` and `note` fields in the same natural language the user has been speaking in this session; technical identifiers (`topic` slug, `pref_id`, `scope`) stay English.
+---
+
+# Brain Memory
+
+Brain is the agent-writable observing-memory layer of Open Second Brain. It accumulates user preferences from real signals and learns from real applications. Your job is to (a) record taste signals as they arrive in conversation, and (b) record whether you applied or violated active preferences each time you produce a durable artifact in a relevant scope. The deterministic `dream` pass turns repeat signals into rules and retires what stops being applied.
+
+## When to call `brain_feedback`
+
+Call **once per taste signal** the user (or a teammate agent) expresses. Concrete triggers:
+
+- Explicit corrections: "don't do X", "stop doing Y", "use A instead of B".
+- Stated preferences with outlasting reach: "I prefer X over Y", "expand acronyms on first use", "always include a CHANGELOG entry".
+- Pushback on a specific artifact you produced that targets a *rule*, not a one-off ("this commit message is wrong β€” use imperative voice").
+- A teammate agent or human describing a process rule in chat that should survive future sessions.
+
+Parameters:
+
+- `topic`: stable kebab-slug for the rule (`no-internal-abbrev`, `imperative-prompts`, `prefer-typed-errors`). Reuse existing slugs β€” call `brain_query --topic <slug>` first if you are unsure. New slugs only when no existing one fits.
+- `signal`: `positive` when the principle stated is the rule to follow, `negative` when the principle stated is what to avoid.
+- `principle`: one-line, imperative-voice agent-readable formulation. "Do not use internal abbreviations in user-facing copy unless explained first."
+- `agent`: your runtime identity (`claude`, `codex`, `hermes`, OpenClaw plugin name, or the human's name if you are recording on their behalf).
+
+Optional but **strongly recommended**:
+
+- `raw`: the verbatim quote that triggered the signal. Without it the
+ signal file lands without a `## Raw` body β€” counters keep working,
+ but the audit trail loses the original phrasing. Pass the exact
+ sentence the user said (or the exact line of the artifact the
+ signal is about). v0.10.1 dropped the `_(not provided)_` placeholder
+ precisely so an absent `raw` is now visible: the file simply has no
+ body, which should be the rare case, not the norm.
+
+Optional:
+
+- `scope`: soft category for later application-scope matching β€” `writing`, `coding`, `process`, `design`, `infra`, `docs`. Pick the narrowest accurate one.
+- `source`: array of wikilinks to the artifacts or notes that triggered the signal β€” `[[src/cli/main.ts]]`, `[[docs/release-notes/v0.11.0]]`. Improves later auditability.
+
+The server creates `Brain/inbox/sig-<date>-<slug>.md` and resolves collisions deterministically.
+
+## When to call `brain_apply_evidence`
+
+Call **once per (preference, artifact) pair**, right after a durable artifact lands. A durable artifact is anything the user would re-find by searching the vault tomorrow: code shipped, config change, deployment touched, content drafted, instruction-file edit, design decision recorded. Trivial edits (typo fix, pure formatting) do not qualify.
+
+Discover applicable preferences first. Options:
+
+- Read `Brain/preferences/` directly β€” files `pref-*.md` are tiny.
+- Call `brain_query --topic <slug>` to fetch a topic-scoped slice.
+- Call `brain_query --preference <id>` for a single preference plus its evidence trail.
+
+Parameters:
+
+- `pref_id`: id of the preference you are recording against (`pref-no-internal-abbrev`).
+- `artifact`: wikilink identifying what you produced β€” `[[src/cli/main.ts]]`, `[[docs/release-notes/v0.11.0.md]]`, `[[Brain/preferences/pref-no-internal-abbrev]]`. The wikilink resolves in Obsidian; use `#anchor` to point at a specific section when relevant.
+- `result`: `applied` if the rule held in this artifact, `violated` if you (or another agent) broke it. Recording a `violated` event is not a failure β€” it is what trains the system.
+- `agent`: your runtime identity.
+
+Optional:
+
+- `note`: one-line context if useful ("expanded 'OSB' to 'Open Second Brain' on first use", "README diff still contained unexplained 'FT'").
+- `note: "speculative; <reason>"` when the preference's `scope` plausibly applies but you are unsure (e.g. a `writing` rule against a docstring inside a source file). The dream pass filters single-event speculative records that do not recur β€” recording the uncertainty costs less than missing the signal.
+
+`applied_count` and `violated_count` on the preference are recomputed by `dream`; you write only the per-event evidence record.
+
+## When NOT to call
+
+- Casual chat, banter, acknowledgements ("ok", "got it").
+- Brainstorming, idea exploration, design discussion that has not concluded in a rule.
+- Read-only inspection (running `git log`, `o2b status`, `vault_health`).
+- Trivial edits (typo, whitespace, formatting only).
+
+When a preference *might* apply but you are unsure, do not skip β€” record the event with `note: "speculative; <reason>"` so the dream pass sees the signal. A one-off speculative entry that does not recur is filtered out by dream; the cost of writing is one MCP call, the cost of missing is a silent gap in the evidence trail. The "do not call" list above is exhaustive on purpose: outside those four bullets, record.
+
+## Language
+
+The `principle` and `note` fields must match the **natural language the user has been speaking in this session**. Technical identifiers stay English regardless: `topic` slug, `scope`, `pref_id`, `result`, `agent` name, file paths, library names, error messages quoted from logs. This mirrors the policy from the `agent-event-log` skill.
+
+Mixed-language session β†’ match the most recent user message at the time the artifact landed.
+
+## Self-discovery
+
+- `brain_query --preference pref-foo` β€” full preference frontmatter + every evidence record in `Brain/log/*` referencing it.
+- `brain_query --topic <slug>` β€” all artifacts (signals, current preference, retired ones) by topic.
+- `brain_query --since <ISO>` β€” recent log events of any type.
+- `brain_brief` (`view="digest"`) β€” daily summary of what `dream` did: new unconfirmed, confirmations, retirements, confidence shifts, contradictions.
+
+## CLI fallback
+
+When MCP is unavailable:
+
+```bash
+o2b brain feedback \
+ --topic no-internal-abbrev \
+ --signal negative \
+ --principle "Do not use internal abbreviations in user-facing copy unless explained first" \
+ --agent claude
+
+o2b brain apply-evidence \
+ --pref pref-no-internal-abbrev \
+ --artifact "[[src/cli/main.ts#L120]]" \
+ --result applied \
+ --agent claude
+```
+
+## Rules
+
+- One call per signal, one call per (preference, artifact) pair.
+- Imperative voice in `principle`. Specific over generic.
+- Never include secrets, tokens, API keys, or credentials in `principle`, `note`, or `source`.
+- Do not edit historical signals, preferences, or log entries by hand β€” the `dream` pass is the only writer for transitions.
+- Do not write into `Brain/.snapshots/` or `Brain/retired/` directly β€” those are managed by `dream` and `o2b brain reject` only.
+- `o2b brain reject` requires `--reason <text>` from v0.10.1 onward. The reason is persisted on the retired file as `user_rejected_reason`. The next dream pass will mark any future signal on the same `(topic, scope)` as `signal-suppressed` and move it straight to `processed/` β€” do not re-record the same signal hoping it will re-grow into a preference. If you genuinely disagree with a past reject, raise it with the user; do not route around it via `brain_feedback`.
+
+## Examples β€” good vs bad
+
+These four pairs calibrate what makes a recorded signal useful versus
+noise. The form of the entry matters as much as the timing β€” a vague
+`principle` clogs the dream pass; a precise one trains it.
+
+**Bad:** `principle: "Write good commits"`
+**Good:** `principle: "Use imperative voice in commit subjects; describe what the commit does, not what was done"`
+*Why:* the bad form is unenforceable β€” no future signal can reasonably mark an artifact as "applied" or "violated" against it. The good form names a checkable behaviour.
+
+**Bad:** `principle: "Be careful with secrets"`
+**Good:** `principle: "Do not commit .env, credentials, or API keys; route them through environment variables"`
+*Why:* the bad form is a vibe. The good form gives the agent a concrete list of patterns to spot in a diff.
+
+**Bad:** `topic: "stuff"`
+**Good:** `topic: "no-internal-abbrev"`
+*Why:* topic is the stable bucket future signals join. A generic slug collects unrelated rules; a precise one keeps the cluster meaningful and lets `brain_query --topic <slug>` return a focused slice.
+
+**Bad:** `note: "fixed it"`
+**Good:** `note: "expanded 'OSB' to 'Open Second Brain' on first use β€” README diff still carried the abbreviation, would have confused a new reader"`
+*Why:* notes survive the artifact. Without the "why" line you cannot tell in three months whether a violation was a regression or a deliberate change.
+
+## Fallback capture surfaces
+
+When no agent is in the loop at the moment the rule is formed, the
+user can write an `@osb` marker directly into any vault markdown
+file β€” a Daily note, a project plan, a self-chat scratchpad. The
+operator runs `o2b brain scan-inline` later to capture every marker
+into `Brain/inbox/`. Two shapes are recognised:
+
+```text
+@osb feedback negative topic=mocking principle="don't mock DB in integration tests" scope=testing
+```
+
+````markdown
+```osb
+kind: feedback
+signal: negative
+topic: mocking
+principle: don't mock DB in integration tests
+scope: testing
+```
+````
+
+This is a fallback path, not the default. When you (the agent) hear
+a preference live, call `brain_feedback` directly β€” the inline
+marker exists for situations where MCP is unavailable. After scan,
+the source line becomes `@osbβœ“ [[sig-...]]` so a second run is
+idempotent.
+
+For session JSONLs (Claude / Codex / Hermes exports) the equivalent
+operator command is `o2b brain import-session <path>` β€” it replays
+both `@osb` markers in message text and live `brain_feedback`
+tool_use calls. Useful for back-filling sessions where the agent
+didn't make the call.
diff --git a/plugins/codex/skills/codegraph-partner/SKILL.md b/plugins/codex/skills/codegraph-partner/SKILL.md
new file mode 100644
index 00000000..09d81746
--- /dev/null
+++ b/plugins/codex/skills/codegraph-partner/SKILL.md
@@ -0,0 +1,130 @@
+---
+name: codegraph-partner
+description: Use when the user explicitly mentions codegraph, asks structural code questions such as callers/callees/impact, asks where a symbol is defined, asks what breaks if a symbol changes, or asks for an architectural overview of a code repository. Skip for prose-only or vault-only questions.
+---
+
+# Codegraph partner
+
+OSB and codegraph are complementary, not overlapping. OSB owns the vault
+(Markdown prose, the Brain layer, preferences, paid-action audit). The
+codegraph CLI and its MCP server own the code-symbol graph of a
+repository - callers, callees, impact radius, AST. This skill teaches the
+agent to detect codegraph in the current scope and to use, recommend, or
+stay quiet about it, depending on what is actually nearby.
+
+This skill never installs, initializes, or writes data for codegraph
+itself. Those actions stay in the user's hands or in codegraph's own
+installer.
+
+## Step 1 - detect
+
+Run these checks in order. Stop at the first state that matches.
+
+1. CLI presence: `which codegraph` (or, in Bun runtimes, `Bun.which("codegraph")`).
+2. Code-project signal in the current working directory: a `.git/`
+ directory plus at least one of `package.json`, `pyproject.toml`,
+ `Cargo.toml`, `go.mod`, `tsconfig.json`, `Gemfile`, `composer.json`,
+ `build.gradle`, `pom.xml`.
+3. If neither cwd nor the user's named project is a code project, look
+ at the vault's parent directory and inspect the top-level entries
+ (one level only). Many users keep their repos as siblings of the
+ vault. All discovered code projects are candidates, not just the first.
+4. Index state: a `.codegraph/` directory inside the code project root.
+5. Confirmed index: `codegraph status -j <project_path>` returns
+ `{"initialized": true, ...}`. The same command on an uninitialized
+ project returns `{"initialized": false, ...}` rather than failing.
+
+The structured way to ask is `o2b doctor`. When OSB is installed in the
+workspace, the doctor report carries a `code_graph` line that summarises
+the detection result with node count and file count.
+
+Multi-project workspaces: when more than one code project is discovered,
+the `code_graph` line covers EVERY project. Status is threaded per project
+by passing each project's path to `codegraph status`, and the line
+aggregates one entry per project (`N code projects:` followed by a bullet
+per project naming its path and index state/health). This per-query
+project-path threading is feature-detected: if the installed codegraph CLI
+does not document a positional `[path]` argument for `status`, OSB cannot
+trust per-project queries, so it degrades to reporting the first project
+only and appends an explicit `note: codegraph CLI has no per-query
+project_path support - reported 1 of N discovered projects only`. A
+single-project workspace is unaffected and its line is unchanged.
+
+## Step 2 - branch on result
+
+| State | Agent behaviour |
+|-------|-----------------|
+| ok (CLI present, indexed) | Use codegraph for AST and graph queries. No install talk. |
+| not_indexed (CLI present, no `.codegraph/` or `initialized: false`) | Offer one line: "run `codegraph init <path>` to index this repo". Do not run it yourself unless the user asks. |
+| missing + code project | Argued recommendation (Step 5). |
+| missing + no code project in scope | Stay quiet. |
+| error (CLI present, `status -j` errors with a lock or schema issue) | Suggest `codegraph unlock <path>` or a rebuild, but do not run it. |
+
+In a multi-project workspace the aggregate `code_graph` line can mix these
+states across projects (one indexed, one not); read each bullet and act per
+project. When the line ends with the `note: ... project_path support` marker,
+only the first project was checked - query the others explicitly with
+`codegraph status <their_path>` before trusting a single-project verdict.
+
+## Step 3 - hard rule after `codegraph init`
+
+Whenever you run `codegraph init` in any repository on the user's
+behalf, immediately read that repo's `.gitignore` and append a
+`.codegraph/` line if one is not already present. The append must be
+atomic, must preserve the existing trailing newline policy, and must
+not touch any other line.
+
+If the repo does not have a `.gitignore`, do not create one yourself.
+Tell the user the file is missing and that they should decide whether
+to add it.
+
+This rule exists so the local codegraph index never lands in a commit.
+
+## Step 4 - tool-vs-tool disambiguation
+
+Use this table to pick the right tool for each kind of question. Do not
+duplicate a codegraph answer by also running a grep; treat its output
+as authoritative.
+
+| Question shape | Tool |
+|----------------|------|
+| Where is symbol X defined? | `codegraph_search` |
+| Who calls function Y? | `codegraph_callers` |
+| What does Y call? | `codegraph_callees` |
+| What would break if I change Z? | `codegraph_impact` |
+| Show Y's signature or body. | `codegraph_node` |
+| Survey several related symbols at once. | `codegraph_explore` |
+| What files exist under path P? | `codegraph_files` |
+| Prose, page bodies, MOC content, daily notes. | `brain_search` |
+| Confirmed preferences, taste rules. | `brain_query` |
+| Free-text fallback when neither index helps. | Plain grep, last resort. |
+
+## Step 5 - argued install recommendation
+
+Trigger only when both conditions hold: there is a code project in the
+current scope, and `codegraph` is not on the user's PATH.
+
+Show the user a short paragraph that uses real numbers from their
+project, with no emoji and no marketing voice. Template:
+
+> Found a code project at `<path>` with N source files. Without an
+> index, every structural question (callers, impact, "where is X")
+> spawns a grep+read loop that burns several thousand tokens per
+> answer. codegraph keeps a SQLite knowledge graph and serves the
+> same question in sub-millisecond time. Installer:
+> `curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh`
+> (or `npm i -g @colbymchenry/codegraph`). After install: `codegraph
+> init <path>` from inside the repo.
+
+If the user says no, drop the topic for the rest of the session. Do
+not nag.
+
+## Out of scope
+
+- Do not call `codegraph install`, `codegraph init`, or `codegraph
+ index` automatically.
+- Do not read or write `.codegraph/codegraph.db`.
+- Do not mirror codegraph data into the Brain or the vault search
+ index.
+- Do not modify `~/.claude.json`, `.cursor/rules/`, or any other agent
+ config on behalf of codegraph.
diff --git a/plugins/codex/skills/embeddings-setup/SKILL.md b/plugins/codex/skills/embeddings-setup/SKILL.md
new file mode 100644
index 00000000..0fe0ba70
--- /dev/null
+++ b/plugins/codex/skills/embeddings-setup/SKILL.md
@@ -0,0 +1,153 @@
+---
+name: embeddings-setup
+description: Bring Open Second Brain semantic search online β€” embedding API key, sqlite-vec extension, first reindex, optional periodic refresh. INVOKE when the user mentions "embeddings", "semantic search", "vector index", or after `o2b search check` reports `vec_extension: unavailable`, `embedding_key: missing`, or any line in its `recommendations:` block. SKIP when the user is asking conceptual questions about embeddings or comparing providers without intent to set up β€” answer those directly.
+---
+
+# Embeddings setup
+
+Open Second Brain ships with two search paths: keyword-only (always
+on, no credentials) and semantic via embedded vectors (opt-in). This
+SKILL walks the activation flow for the semantic path. The flow is
+proactive β€” when the user mentions semantic search or `o2b search
+check` surfaces missing pieces, take the user through this list
+rather than waiting for explicit instruction.
+
+## Step 1 β€” Always start with `o2b search check`
+
+```bash
+o2b search check
+```
+
+The output names every missing piece and ends with a
+`recommendations:` block listing the exact commands to fix each.
+Read both before suggesting next steps. The `recommendations` field
+is also present in the `--json` output for headless callers.
+
+Branch on what the report shows:
+
+- `embedding_key: MISSING` β†’ go to step 2.
+- `vec_extension: unavailable` on macOS β†’ go to step 3.
+- `vec_extension: unavailable` on Linux β†’ go to step 4.
+- Everything OK but `semantic_enabled: false` (no embeddings yet) β†’
+ go to step 5.
+
+## Step 2 β€” Provider and API key
+
+Ask the user which provider they want. The default is
+`text-embedding-3-small` from OpenAI (about $0.02 per 1M tokens,
+which covers tens of thousands of vault pages). Any OpenAI-compatible
+endpoint works β€” Groq, Together, a local LM Studio server, etc.
+
+Required env vars (write to `~/.hermes/.env` or the configured env
+file, never to a tracked file):
+
+```bash
+OPEN_SECOND_BRAIN_EMBEDDING_PROVIDER=openai-compat
+OPEN_SECOND_BRAIN_EMBEDDING_MODEL=text-embedding-3-small
+OPEN_SECOND_BRAIN_EMBEDDING_KEY=<placeholder; user pastes the key>
+# Optional β€” only when not using OpenAI:
+# OPEN_SECOND_BRAIN_EMBEDDING_BASE_URL=https://api.together.xyz/v1
+```
+
+**Never invent or echo the key.** Write a placeholder, then ask the
+user to paste their key in place of it. Recheck with `o2b search
+check` after the user confirms.
+
+## Step 3 β€” macOS: install Homebrew SQLite
+
+Apple ships `/usr/lib/libsqlite3.dylib` with
+`SQLITE_OMIT_LOAD_EXTENSION`, so the optional `sqlite-vec` extension
+cannot load against the system SQLite. Homebrew's `sqlite` formula
+is built with extension loading enabled.
+
+```bash
+brew install sqlite
+```
+
+The `o2b` wrapper auto-detects Homebrew SQLite on Darwin and exports
+`DYLD_LIBRARY_PATH` for `bun:sqlite` on the next invocation. No
+manual patching of the wrapper script is needed (the v0.10.5 shim
+`scripts/_macos-sqlite.sh` handles it). Verify with:
+
+```bash
+o2b search check
+```
+
+Expect `vec_extension: loaded`.
+
+## Step 4 β€” Linux: reconfirm the optional dependency
+
+`sqlite-vec` ships as an optional dependency. If the install path
+missed it, force a rebuild:
+
+```bash
+bun pm ls | grep sqlite-vec
+bun install --force
+```
+
+If the package is present but still does not load, the Linux build
+of `libsqlite3` may have been compiled without `LOAD_EXTENSION`.
+Capture `sqlite3 :memory: "PRAGMA compile_options;"` and surface it
+to the user β€” they will know whether their distro's SQLite is
+unusual.
+
+## Step 5 β€” Compute the first vectors
+
+```bash
+o2b search reindex --embeddings
+```
+
+This walks the vault, chunks every Markdown file, and computes
+embeddings. Cost scales linearly with vault size β€” a 150-file vault
+typically lands in a few seconds.
+
+Verify semantic search works:
+
+```bash
+o2b search "preferences for code review"
+```
+
+The output rows carry `(semantic)` in the source column when the
+match came from the vector index.
+
+## Step 6 β€” Offer periodic reindex
+
+The vault keeps changing β€” other agents add notes, the user edits
+existing ones. Without periodic refresh the embeddings drift behind
+the keyword index.
+
+```bash
+o2b search reindex --cron-template
+```
+
+Prints a watchdog script (a heredoc that, when the operator runs
+the printed block, lands at `~/.local/bin/osb-reindex.sh`), a
+native crontab line, and a `hermes cron create` command. Pure
+stdout β€” the verb writes nothing on its own; pick the path that
+matches the host and paste the relevant section into your
+shell / crontab. Recommended cadence:
+
+- 30 minutes when the vault sees active multi-agent work.
+- 6 hours when changes are sporadic.
+
+Override with `--interval 6h` (or any `<N>m|h|d` value below 60m / 24h
+/ unlimited days).
+
+## Multi-agent note
+
+Only the agent that runs `reindex` needs
+`OPEN_SECOND_BRAIN_EMBEDDING_KEY`. Read-only consumers (sibling
+Claude Code / Codex / OpenClaw sessions on the same vault) query
+the already-computed vectors and never see the key. When designating
+the reindex owner, the canonical choice is Hermes (it carries the
+cron infrastructure); the others stay credential-free.
+
+## What this SKILL does NOT do
+
+- Does not invoke `brew install` on the user's behalf. The SKILL
+ prints the command; the user runs it.
+- Does not paste an API key into the env file silently. Always use
+ a placeholder, then ask the user to substitute.
+- Does not commit env files. They live outside the tracked tree.
+- Does not launch a long-running watcher inside OSB β€” the
+ `--cron-template` recipe is the endorsed automation path.
diff --git a/plugins/codex/skills/open-second-brain/SKILL.md b/plugins/codex/skills/open-second-brain/SKILL.md
new file mode 100644
index 00000000..5d3f14de
--- /dev/null
+++ b/plugins/codex/skills/open-second-brain/SKILL.md
@@ -0,0 +1,49 @@
+---
+name: open-second-brain
+description: Use Open Second Brain to read, write, and maintain an agent-owned second brain in an Obsidian-compatible Markdown vault. The agent owns one top-level directory (`Brain/`). User-authored notes live wherever the operator names them and are read-only inputs when listed in `notes.read_paths`.
+---
+
+# Open Second Brain
+
+Use this skill when a user asks an agent to use, configure, inspect, or maintain Open Second Brain.
+
+## Layout
+
+Open Second Brain owns one top-level directory in the vault: `Brain/`. Everything the agent generates on its own lives under it. The exception is the note-lifecycle family (`brain_note_lifecycle`, `brain_scaffold_stub`), which acts on a user-note path the caller names and can move a note to a second top-level directory, `Archive/`.
+
+- **`Brain/`** - agent-writable observing memory. Taste signals, accreted preferences (unconfirmed β†’ confirmed β†’ retired), evidence log, snapshots. Operations go through MCP tools `brain_feedback`, `brain_apply_evidence`, `brain_dream`, `brain_brief`, `brain_query`, `brain_doctor` - see the `brain-memory` skill for the calling protocol. CLI counterparts: `o2b brain *`.
+- **User-authored notes** - the operator's daily journal, weekly notes, project notes, etc. Folder names are operator-chosen. The agent reads these paths only when they appear under `notes.read_paths` in `Brain/_brain.yaml`; the agent never writes to them.
+
+## Core principles
+
+- Treat the vault as user-owned durable knowledge.
+- Write only into `Brain/`. Never write to user-authored note folders.
+- Keep raw operational evidence separate from synthesized knowledge: per-event records go to `Brain/log/`, preferences live in `Brain/preferences/`.
+- Never write secrets, tokens, passwords, private keys, or credential-bearing connection strings.
+- Prefer deterministic CLI commands (`o2b brain ...`, `o2b doctor`, `o2b status`) over guessing file paths.
+
+## Default workflow
+
+1. Check whether Open Second Brain is configured: `o2b status` or `second_brain_status` MCP tool.
+2. Read the machine-local config if available (vault path, agent identity, timezone).
+3. Read the vault-local operating manual `Brain/_BRAIN.md` - this is the per-vault contract for agents.
+4. Record taste signals as they arrive in dialogue via `brain_feedback` (see the `brain-memory` skill).
+5. After producing a durable artifact, check applicable preferences and record evidence via `brain_apply_evidence` (see the `brain-memory` skill).
+6. For read access to vault pages by title, use `second_brain_query`.
+
+## Search surfaces
+
+Name the surface a question is shaped for, and route to it explicitly:
+
+- **Generic recall** - `brain_search` runs hybrid keyword + semantic search over raw chunks. Use it for open-ended, topical, or exploratory questions.
+- **Summary surface** - for a question that targets a specific source or an artifact kind (a summary, digest, or other declared `schema.page_types` type), reach for the summary surface: search by source or filter by artifact kind rather than running a generic search over raw chunks. `brain_search` detects this structurally and returns `surface: "summary"` on the response as an advisory route hint; a source-targeted query uses a `source:<path>` token and an artifact-kind query uses a `kind:<type>`/`type:<type>` token whose value is a declared page type. The hint never changes ranking - it names the intended surface so the agent asks the right way.
+
+## Safety
+
+If a write operation might affect anything outside the `Brain/` directory, ask for explicit confirmation. When in doubt, prefer `Brain/`.
+
+## See also
+
+- `brain-memory` skill β€” when and how to call `brain_feedback` / `brain_apply_evidence`.
+- `Brain/_BRAIN.md` (in each vault) β€” operating manual for that vault, generated by `o2b brain init`.
+- `docs/plans/2026-05-15-brain-observing-memory.md` (in the repo) β€” full design.
diff --git a/plugins/codex/skills/schema-author/SKILL.md b/plugins/codex/skills/schema-author/SKILL.md
new file mode 100644
index 00000000..05665171
--- /dev/null
+++ b/plugins/codex/skills/schema-author/SKILL.md
@@ -0,0 +1,23 @@
+---
+name: schema-author
+description: Use when adding, renaming, reviewing, or explaining Brain schema tokens, aliases, prefixes, link types, extractability, or expert routing in Open Second Brain vaults.
+---
+
+# Schema Author
+
+Use this skill when a task changes the active Brain schema pack in `Brain/_brain.yaml` or reviews content against that schema.
+
+## Workflow
+
+1. Inspect the active schema pack with `schema_inspect` (`view="active_pack"`) or `o2b brain schema --json`.
+2. Check current usage and findings with `schema_inspect` views `stats`, `lint`, and `orphans`.
+3. Explain candidate tokens with `schema_inspect` (`view="explain_type"`) before renaming or deleting them.
+4. Preview the batch first with `schema_apply_mutations` (`dry_run=true`) or `o2b brain schema apply --dry-run --mutation ...`: it returns the pack that would result and its diff and writes nothing at all - no config write, no audit record, no lock file. It runs the same pack validator the apply runs, so a batch that validator rejects raises identically in both. It does not run the two checks that exist only because the apply writes: the vault-identity write guard, and the atomic writer's re-parse of the rendered YAML. A batch that renders to unparseable YAML previews clean and fails on apply, so treat a clean preview as "the mutations are valid", not as "the apply will succeed".
+5. Apply schema changes only through `schema_apply_mutations` or `o2b brain schema apply --mutation ...` so writes are locked, atomic, and audited.
+6. Re-run lint/stats after mutation and report changed tokens plus any remaining findings.
+
+## Mutation Notes
+
+Supported operations are `add_type`, `remove_type`, `update_type`, `add_alias`, `remove_alias`, `add_prefix`, `remove_prefix`, `add_link_type`, `remove_link_type`, `set_extractable`, and `set_expert_routing`.
+
+Schema tokens must be lowercase normalized tokens accepted by Open Second Brain schema validation. Prefer small, durable tokens over project-specific phrasing unless the schema pack is explicitly project-scoped.
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 4eb02453..bda5bd59 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.57.0"
+version: "1.57.1"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index 96c9b4bc..560f121b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.57.0"
+version = "1.57.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/sync-plugin-mirrors.ts b/scripts/sync-plugin-mirrors.ts
new file mode 100644
index 00000000..3836ea94
--- /dev/null
+++ b/scripts/sync-plugin-mirrors.ts
@@ -0,0 +1,284 @@
+#!/usr/bin/env bun
+/**
+ * Mirror the shared plugin assets into the Codex plugin subtree.
+ *
+ * Codex's marketplace source is `./plugins/codex` (`.agents/plugins/
+ * marketplace.json`), and `codex plugin add` copies only that subtree into
+ * `~/.codex/plugins/cache/<marketplace>/<plugin>/<version>/`. The copy
+ * DROPS symlinks. `plugins/codex/hooks` and `plugins/codex/skills` used to
+ * be symlinks into the repo root, so every installed Codex plugin had no
+ * hooks and no skills. Every Codex run also warned `failed to read plugin
+ * hooks config .../hooks/hooks.json`. Symlinks are fragile on Windows too:
+ * without Developer Mode or `core.symlinks`, git checks one out as a plain
+ * text file that holds the target path.
+ *
+ * So the Codex plugin ships real files, and this script keeps them in step
+ * with their source. It follows the shape of `scripts/sync-version.ts`: the
+ * write form and the `--check` form are the same code path, so what CI
+ * detects and what the write form produces cannot diverge.
+ *
+ * What is mirrored, and what is deliberately NOT:
+ * - `skills/**` -> `plugins/codex/skills/**`, every file, byte for byte.
+ * - `hooks/hooks.json` -> `plugins/codex/hooks/hooks.json`, with two
+ * Codex-specific changes. SessionEnd timeouts are capped at
+ * {@link CODEX_SESSION_END_TIMEOUT_CAP_SEC}: Codex clamps them there
+ * anyway, and warns on every run while the file asks for more. And every
+ * hook gets a `commandWindows` ({@link codexWindowsHookCommand}): on
+ * Windows Codex runs a hook as `%COMSPEC% /C "<command>"`, where the
+ * POSIX `command` cannot parse.
+ * - NOT `hooks/*.ts`. The hook commands run `o2b-hook <name>`, which
+ * resolves the checkout that holds `hooks/<name>.ts` (see
+ * `scripts/o2b-hook`). Codex exports `CLAUDE_PLUGIN_ROOT` as the cache
+ * dir, so a copied script there would win that resolution and then
+ * fail on its `../src` imports, which the cache does not have. Without
+ * the scripts, resolution falls through to the real checkout.
+ *
+ * Usage:
+ * bun run scripts/sync-plugin-mirrors.ts # rewrite the mirrors
+ * bun run scripts/sync-plugin-mirrors.ts --check # exit 1 on drift, no writes
+ */
+
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { dirname, join, relative, resolve, sep } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+
+/**
+ * The longest SessionEnd hook timeout Codex honours, in seconds. Codex
+ * 0.157.0 clamps a longer one and warns `clamping SessionEnd hook timeout
+ * to 3s` on every run.
+ */
+export const CODEX_SESSION_END_TIMEOUT_CAP_SEC = 3;
+
+export interface MirrorSpec {
+ /** Source, relative to the repo root: a directory or a single file. */
+ readonly source: string;
+ /** Destination, relative to the repo root. */
+ readonly target: string;
+ /** Derives the mirrored bytes from the source bytes. Absent: a byte copy. */
+ readonly transform?: (source: string) => string;
+}
+
+interface HookGroup {
+ hooks?: Array<{ command?: string; commandWindows?: string; timeout?: number }>;
+}
+
+/**
+ * The POSIX hook command, which ends by running the PATH `o2b-hook` shim
+ * with the hook's name. The name is the one thing the Windows form needs.
+ */
+const POSIX_HOOK_COMMAND =
+ /command -v o2b-hook >\/dev\/null 2>&1 && exec o2b-hook ([a-z][a-z0-9-]*); exit 0$/;
+
+/**
+ * The `commandWindows` form of a hook, which Codex runs through cmd.exe.
+ *
+ * It calls the PATH `o2b-hook` shim only, the same fallback the POSIX command
+ * reaches under Codex (`CLAUDE_PLUGIN_ROOT` is Codex's cache dir, which holds
+ * no scripts). `o2b install-cli` writes that shim as `o2b-hook.cmd`.
+ * - `NoDefaultCurrentDirectoryInExePath` is set first: cmd.exe otherwise
+ * looks for `where` and `o2b-hook` in the current directory before PATH,
+ * and Codex runs hooks in the project it opened, so a repository could
+ * ship its own `o2b-hook.cmd`.
+ * - `where /q $PATH:o2b-hook` keeps a missing shim silent. The `$PATH:`
+ * scope matters: a bare `where` searches the current directory too, and
+ * would pass for a planted file that cmd.exe then refuses to run.
+ * - `exit /b 0` keeps any outcome non-blocking, as `exit 0` does in the
+ * POSIX form.
+ * - No double quotes: cmd.exe then strips only the pair Codex wraps the
+ * line in.
+ */
+export function codexWindowsHookCommand(hook: string): string {
+ return `set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook ${hook} & exit /b 0`;
+}
+
+/** `hooks/hooks.json` as Codex should read it. Formatting matches the source (oxfmt). */
+export function codexHooksJson(source: string): string {
+ const doc = JSON.parse(source) as { hooks?: Record<string, HookGroup[]> };
+ for (const [event, groups] of Object.entries(doc.hooks ?? {})) {
+ for (const group of groups) {
+ group.hooks = (group.hooks ?? []).map((hook) => {
+ if (
+ event === "SessionEnd" &&
+ typeof hook.timeout === "number" &&
+ hook.timeout > CODEX_SESSION_END_TIMEOUT_CAP_SEC
+ ) {
+ hook.timeout = CODEX_SESSION_END_TIMEOUT_CAP_SEC;
+ }
+ if (hook.command === undefined) return hook;
+ const name = POSIX_HOOK_COMMAND.exec(hook.command)?.[1];
+ if (name === undefined) {
+ // Fail the sync rather than ship a hook that cmd.exe cannot run.
+ throw new Error(
+ `${event} hook command does not end in the o2b-hook fallback; ` +
+ `cannot derive its Windows form: ${hook.command}`,
+ );
+ }
+ // Rebuilt key by key, so that commandWindows sits right after command.
+ const out: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(hook)) {
+ if (key === "commandWindows") continue;
+ out[key] = value;
+ if (key === "command") out["commandWindows"] = codexWindowsHookCommand(name);
+ }
+ return out;
+ });
+ }
+ }
+ return `${JSON.stringify(doc, null, 2)}\n`;
+}
+
+export const MIRRORS: ReadonlyArray<MirrorSpec> = [
+ { source: "skills", target: "plugins/codex/skills" },
+ {
+ source: "hooks/hooks.json",
+ target: "plugins/codex/hooks/hooks.json",
+ transform: codexHooksJson,
+ },
+];
+
+/** Directories the mirrors own outright: a file in them that no spec produces is drift. */
+export const MIRROR_DIRS: ReadonlyArray<string> = ["plugins/codex/skills", "plugins/codex/hooks"];
+
+export interface Drift {
+ readonly path: string;
+ readonly reason: "missing" | "differs" | "extra" | "symlink";
+}
+
+interface Pair {
+ readonly source: string;
+ readonly target: string;
+ readonly transform?: (source: string) => string;
+}
+
+function toPosix(p: string): string {
+ return p.split(sep).join("/");
+}
+
+function isSymlink(path: string): boolean {
+ try {
+ return lstatSync(path).isSymbolicLink();
+ } catch {
+ return false;
+ }
+}
+
+/** Every regular file under `dir`, relative to it, sorted. Symlinks are collected, not followed. */
+function listFiles(dir: string, symlinks: string[], base = dir): string[] {
+ const out: string[] = [];
+ for (const name of readdirSync(dir).toSorted()) {
+ const full = join(dir, name);
+ const st = lstatSync(full);
+ if (st.isSymbolicLink()) symlinks.push(full);
+ else if (st.isDirectory()) out.push(...listFiles(full, symlinks, base));
+ else if (st.isFile()) out.push(toPosix(relative(base, full)));
+ }
+ return out;
+}
+
+/** The (source, target) file pairs every mirror spec expands to. */
+function expectedPairs(root: string): Pair[] {
+ const pairs: Pair[] = [];
+ for (const spec of MIRRORS) {
+ const src = join(root, spec.source);
+ if (!lstatSync(src).isDirectory()) {
+ pairs.push(spec);
+ continue;
+ }
+ const symlinks: string[] = [];
+ for (const rel of listFiles(src, symlinks)) {
+ pairs.push({ source: `${spec.source}/${rel}`, target: `${spec.target}/${rel}` });
+ }
+ if (symlinks.length > 0) {
+ const names = symlinks.map((s) => toPosix(relative(root, s))).join(", ");
+ throw new Error(
+ `mirror source ${spec.source} contains symlinks (${names}); Codex drops them`,
+ );
+ }
+ }
+ return pairs;
+}
+
+/** The bytes a mirrored file must hold. */
+function expectedBytes(root: string, pair: Pair): Buffer {
+ const raw = readFileSync(join(root, pair.source));
+ return pair.transform === undefined
+ ? raw
+ : Buffer.from(pair.transform(raw.toString("utf8")), "utf8");
+}
+
+/** Compare the mirrors against their sources without writing. */
+export function findDrift(root: string = ROOT): Drift[] {
+ const drift: Drift[] = [];
+ const pairs = expectedPairs(root);
+ const expectedTargets = new Set(pairs.map((p) => p.target));
+ const linkedDirs: string[] = [];
+
+ for (const dir of MIRROR_DIRS) {
+ const full = join(root, dir);
+ if (isSymlink(full)) {
+ drift.push({ path: dir, reason: "symlink" });
+ linkedDirs.push(dir);
+ continue;
+ }
+ if (!existsSync(full)) continue;
+ const symlinks: string[] = [];
+ for (const rel of listFiles(full, symlinks)) {
+ const path = `${dir}/${rel}`;
+ if (!expectedTargets.has(path)) drift.push({ path, reason: "extra" });
+ }
+ for (const s of symlinks) drift.push({ path: toPosix(relative(root, s)), reason: "symlink" });
+ }
+
+ for (const pair of pairs) {
+ if (linkedDirs.some((d) => pair.target.startsWith(`${d}/`))) continue;
+ const dst = join(root, pair.target);
+ if (!existsSync(dst)) drift.push({ path: pair.target, reason: "missing" });
+ else if (!expectedBytes(root, pair).equals(readFileSync(dst))) {
+ drift.push({ path: pair.target, reason: "differs" });
+ }
+ }
+ return drift;
+}
+
+/** Rebuild every mirror from its source. Returns the number of files written. */
+export function writeMirrors(root: string = ROOT): number {
+ const pairs = expectedPairs(root);
+ const contents = pairs.map((pair) => expectedBytes(root, pair));
+ for (const dir of MIRROR_DIRS) rmSync(join(root, dir), { recursive: true, force: true });
+ pairs.forEach((pair, i) => {
+ const dst = join(root, pair.target);
+ mkdirSync(dirname(dst), { recursive: true });
+ writeFileSync(dst, contents[i]!);
+ });
+ return pairs.length;
+}
+
+function main(argv: ReadonlyArray<string>): number {
+ if (!argv.includes("--check")) {
+ const n = writeMirrors();
+ process.stdout.write(`wrote ${n} mirrored file(s) into plugins/codex\n`);
+ return 0;
+ }
+ const drift = findDrift();
+ if (drift.length === 0) {
+ process.stdout.write("plugin mirrors: ok\n");
+ return 0;
+ }
+ for (const d of drift) process.stderr.write(` DRIFT (${d.reason}): ${d.path}\n`);
+ process.stderr.write(`\n${drift.length} drifted path(s); run: bun run sync-plugin-mirrors\n`);
+ return 1;
+}
+
+if (import.meta.main) {
+ process.exit(main(process.argv.slice(2)));
+}
diff --git a/src/core/install/host-probe.ts b/src/core/install/host-probe.ts
index b3d65876..359e6f98 100644
--- a/src/core/install/host-probe.ts
+++ b/src/core/install/host-probe.ts
@@ -197,7 +197,11 @@ export function createHostProbeRunner(timeoutMs: number): HostProbeRunner {
stderr: "pipe",
timeout: timeoutMs,
});
- if (r.signalCode !== null) {
+ // `!= null`, not `!== null`: Bun leaves `signalCode` UNDEFINED on a
+ // normal exit, so the strict form read every successful probe as a
+ // kill and threw its stdout away - `o2b install --check` then called
+ // a correctly registered Codex `mcp-unreachable`.
+ if (r.signalCode != null) {
// A killed child has no answer to report, and its partial stdout
// must not be parsed as one. The signal is named because the
// timeout kill and a host that crashed arrive the same way, and
diff --git a/src/core/install/ownership.ts b/src/core/install/ownership.ts
index 91b7b8f8..ac7dede5 100644
--- a/src/core/install/ownership.ts
+++ b/src/core/install/ownership.ts
@@ -231,7 +231,7 @@ export const OUT_OF_VAULT_STATE: ReadonlyArray<OutOfVaultState> = Object.freeze(
note:
"One empty file per session id. It records that a reminder was shown; it records nothing " +
"that was said.",
- sources: ["hooks/post-write-reminder.ts", "plugins/codex/hooks/post-write-reminder.ts"],
+ sources: ["hooks/post-write-reminder.ts"],
},
{
id: "cron_recipe_artifacts",
diff --git a/tests/core/install/host-probe.test.ts b/tests/core/install/host-probe.test.ts
index f294ca44..cbb788b7 100644
--- a/tests/core/install/host-probe.test.ts
+++ b/tests/core/install/host-probe.test.ts
@@ -190,6 +190,22 @@ describe("the wait is bounded", () => {
expect(result.stderr).toContain("200 ms");
});
+ test("a host that answers in time keeps its answer", () => {
+ // The regression this pins: Bun leaves `signalCode` undefined, not
+ // null, on a normal exit, and a strict `!== null` check read every
+ // successful probe as killed and discarded its stdout. Driven against a
+ // real child because a stubbed runner cannot reproduce a runtime quirk.
+ const runner = createHostProbeRunner(HOST_PROBE_TIMEOUT_MS);
+ const result = runner.run(
+ process.execPath,
+ ["-e", `process.stdout.write(${JSON.stringify(realCodexListing())})`],
+ { PATH: process.env["PATH"] ?? "/usr/bin" },
+ );
+ expect(result.stderr).toBe("");
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toBe(realCodexListing());
+ });
+
test("a killed probe becomes a named skip, never an assumed answer", () => {
setHostProbeRunner({
available: () => true,
diff --git a/tests/core/install/ownership.test.ts b/tests/core/install/ownership.test.ts
index fc36141e..046fba45 100644
--- a/tests/core/install/ownership.test.ts
+++ b/tests/core/install/ownership.test.ts
@@ -536,8 +536,8 @@ function walk(dir: string, out: string[]): string[] {
} catch {
// A dangling symlink is not a module, and a census that throws on one
// reports nothing at all - which is strictly worse than reporting the
- // rest of the tree. `plugins/codex/skills` is a symlink; a checkout
- // that has not materialised it must not take the sweep down with it.
+ // rest of the tree. A symlink a checkout has not materialised (a
+ // Windows clone without `core.symlinks`) must not take the sweep down.
continue;
}
if (isDir) walk(full, out);
diff --git a/tests/scripts/sync-plugin-mirrors.test.ts b/tests/scripts/sync-plugin-mirrors.test.ts
new file mode 100644
index 00000000..14a64462
--- /dev/null
+++ b/tests/scripts/sync-plugin-mirrors.test.ts
@@ -0,0 +1,204 @@
+/**
+ * `scripts/sync-plugin-mirrors.ts` - the Codex plugin ships real files, not
+ * symlinks, and they stay byte-identical to their sources.
+ *
+ * Codex copies only `plugins/codex/` into its plugin cache and drops
+ * symlinks on the way, so a symlinked `hooks` or `skills` dir there reached
+ * users as nothing at all.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { spawnSync } from "node:child_process";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import {
+ CODEX_SESSION_END_TIMEOUT_CAP_SEC,
+ codexHooksJson,
+ codexWindowsHookCommand,
+ findDrift,
+ writeMirrors,
+} from "../../scripts/sync-plugin-mirrors.ts";
+
+const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+
+type HookGroups = Array<{ hooks: Array<{ command: string; commandWindows?: string }> }>;
+
+describe("the repository", () => {
+ test("the Codex plugin mirrors are in sync with their sources", () => {
+ expect(findDrift(REPO_ROOT)).toEqual([]);
+ });
+
+ test("no plugin directory tracks a symlink", () => {
+ // Mode 120000 is a symlink in the git index. Checked in the index rather
+ // than on disk because a Windows checkout without `core.symlinks`
+ // materialises one as a plain file, which the disk check cannot tell apart.
+ const r = spawnSync("git", ["ls-files", "-s", "--", "plugins", ".agents"], {
+ cwd: REPO_ROOT,
+ encoding: "utf8",
+ });
+ if (r.status !== 0) return; // not a git checkout (a packed tarball)
+ const links = r.stdout.split("\n").filter((line) => line.startsWith("120000 "));
+ expect(links).toEqual([]);
+ });
+
+ test("the Codex hooks mirror carries hooks.json only, never the hook scripts", () => {
+ // Codex exports CLAUDE_PLUGIN_ROOT as its cache dir; a `.ts` hook there
+ // would win `o2b-hook`'s resolution and then fail on `../src` imports.
+ const hooksJson = join(REPO_ROOT, "plugins/codex/hooks/hooks.json");
+ expect(existsSync(hooksJson)).toBe(true);
+ expect(existsSync(join(REPO_ROOT, "plugins/codex/hooks/active-inject.ts"))).toBe(false);
+ });
+});
+
+describe("the Codex hooks.json", () => {
+ test("caps SessionEnd timeouts at the Codex limit and leaves everything else alone", () => {
+ const source = readFileSync(join(REPO_ROOT, "hooks/hooks.json"), "utf8");
+ const src = JSON.parse(source);
+ const out = JSON.parse(codexHooksJson(source));
+
+ const sessionEnd = out.hooks.SessionEnd.flatMap((g: { hooks: unknown[] }) => g.hooks);
+ expect(sessionEnd.length).toBeGreaterThan(0);
+ for (const hook of sessionEnd) {
+ expect(hook.timeout).toBeLessThanOrEqual(CODEX_SESSION_END_TIMEOUT_CAP_SEC);
+ }
+
+ // Apart from those timeouts and the added Windows commands, the Codex
+ // copy is the shared file.
+ for (const group of src.hooks.SessionEnd) {
+ for (const hook of group.hooks)
+ hook.timeout = Math.min(hook.timeout, CODEX_SESSION_END_TIMEOUT_CAP_SEC);
+ }
+ for (const groups of Object.values(out.hooks) as HookGroups[]) {
+ for (const group of groups) {
+ for (const hook of group.hooks) delete hook.commandWindows;
+ }
+ }
+ expect(out).toEqual(src);
+ });
+
+ test("gives every hook a cmd.exe form that runs the same o2b-hook", () => {
+ // On Windows Codex runs `%COMSPEC% /C "<command>"`, which cannot parse
+ // the POSIX command, unless the hook carries `commandWindows`.
+ const source = readFileSync(join(REPO_ROOT, "hooks/hooks.json"), "utf8");
+ const out = JSON.parse(codexHooksJson(source));
+ let count = 0;
+ for (const groups of Object.values(out.hooks) as HookGroups[]) {
+ for (const group of groups) {
+ for (const hook of group.hooks) {
+ const name = /exec o2b-hook ([a-z0-9-]+); exit 0$/.exec(hook.command)?.[1];
+ expect(name).toBeDefined();
+ expect(hook.commandWindows).toBe(codexWindowsHookCommand(name!));
+ const keys = Object.keys(hook);
+ expect(keys.indexOf("commandWindows")).toBe(keys.indexOf("command") + 1);
+ count++;
+ }
+ }
+ }
+ expect(count).toBeGreaterThan(0);
+ });
+
+ test("the cmd.exe form never looks in the current directory and never blocks", () => {
+ const cmd = codexWindowsHookCommand("session-capture");
+ // Set before the first bare command name, so neither `where` nor
+ // `o2b-hook` resolves from the project Codex opened.
+ expect(cmd.startsWith("set NoDefaultCurrentDirectoryInExePath=1&")).toBe(true);
+ // A bare `where` searches the current directory; `$PATH:` does not.
+ expect(cmd).toContain("where /q $PATH:o2b-hook && o2b-hook session-capture");
+ expect(cmd.endsWith("& exit /b 0")).toBe(true);
+ // Codex wraps the line in one pair of quotes, which cmd.exe strips
+ // cleanly only while the line holds no other quote; a `%` would expand.
+ expect(cmd).not.toMatch(/["%]/);
+ });
+
+ test("refuses a hook command whose Windows form it cannot derive", () => {
+ const source = JSON.stringify({
+ hooks: { Stop: [{ hooks: [{ type: "command", command: "echo hi", timeout: 5 }] }] },
+ });
+ expect(() => codexHooksJson(source)).toThrow(/cannot derive its Windows form/);
+ });
+
+ test("keeps the source's formatting, so the mirror passes fmt:check", () => {
+ // With the timeouts already within the cap, everything but the added
+ // commandWindows lines is the source, byte for byte.
+ const source = readFileSync(join(REPO_ROOT, "hooks/hooks.json"), "utf8").replace(
+ /"timeout": 10/g,
+ '"timeout": 2',
+ );
+ const out = codexHooksJson(source)
+ .split("\n")
+ .filter((line) => !line.trimStart().startsWith('"commandWindows": '))
+ .join("\n");
+ expect(out).toBe(source);
+ });
+});
+
+describe("drift detection", () => {
+ let root: string;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "osb-plugin-mirrors-"));
+ mkdirSync(join(root, "skills/alpha"), { recursive: true });
+ writeFileSync(join(root, "skills/alpha/SKILL.md"), "alpha\n");
+ mkdirSync(join(root, "hooks"), { recursive: true });
+ writeFileSync(join(root, "hooks/hooks.json"), '{"hooks":{}}\n');
+ writeFileSync(join(root, "hooks/active-inject.ts"), "// not mirrored\n");
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ test("a fresh write is clean, and copies only what the specs name", () => {
+ expect(writeMirrors(root)).toBe(2);
+ expect(findDrift(root)).toEqual([]);
+ expect(readFileSync(join(root, "plugins/codex/skills/alpha/SKILL.md"), "utf8")).toBe("alpha\n");
+ expect(existsSync(join(root, "plugins/codex/hooks/active-inject.ts"))).toBe(false);
+ });
+
+ test("a missing, a changed and an extra file are each reported", () => {
+ writeMirrors(root);
+ writeFileSync(join(root, "skills/alpha/SKILL.md"), "alpha, edited\n");
+ mkdirSync(join(root, "skills/beta"));
+ writeFileSync(join(root, "skills/beta/SKILL.md"), "beta\n");
+ writeFileSync(join(root, "plugins/codex/skills/stale.md"), "gone upstream\n");
+
+ expect(findDrift(root)).toEqual([
+ { path: "plugins/codex/skills/stale.md", reason: "extra" },
+ { path: "plugins/codex/skills/alpha/SKILL.md", reason: "differs" },
+ { path: "plugins/codex/skills/beta/SKILL.md", reason: "missing" },
+ ]);
+
+ writeMirrors(root);
+ expect(findDrift(root)).toEqual([]);
+ expect(existsSync(join(root, "plugins/codex/skills/stale.md"))).toBe(false);
+ });
+
+ test.skipIf(process.platform === "win32")(
+ "a symlinked mirror dir is drift, and a write replaces it with real files",
+ () => {
+ mkdirSync(join(root, "plugins/codex"), { recursive: true });
+ symlinkSync("../../skills", join(root, "plugins/codex/skills"));
+ symlinkSync("../../hooks", join(root, "plugins/codex/hooks"));
+
+ expect(findDrift(root)).toEqual([
+ { path: "plugins/codex/skills", reason: "symlink" },
+ { path: "plugins/codex/hooks", reason: "symlink" },
+ ]);
+
+ writeMirrors(root);
+ expect(findDrift(root)).toEqual([]);
+ expect(existsSync(join(root, "hooks/active-inject.ts"))).toBe(true);
+ },
+ );
+});