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

v0.7.0: TypeScript on Bun, single core across Hermes / Claude / Codex / OpenClaw (#10)

Sol Aitken214df8c407ca
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json
index 61b17977..746338e6 100644
--- a/.agents/plugins/marketplace.json
+++ b/.agents/plugins/marketplace.json
@@ -8,7 +8,7 @@
"name": "open-second-brain",
"source": {
"source": "local",
- "path": "."
+ "path": "./plugins/codex"
},
"policy": {
"installation": "AVAILABLE"
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 4bef338a..8524a508 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.6.2",
+ "version": "0.7.0",
"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 a4ab53c5..f1fb96bd 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.6.2",
+ "version": "0.7.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"]
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 1e9e8912..e06e327b 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -7,7 +7,7 @@ on:
workflow_dispatch:
inputs:
version:
- description: "Release version (with or without leading v). Defaults to pyproject.toml version."
+ description: "Release version (with or without leading v). Defaults to package.json version."
required: false
type: string
prerelease:
@@ -24,78 +24,127 @@ concurrency:
cancel-in-progress: false
jobs:
- release:
- name: Build and publish GitHub release
+ verify:
+ name: Verify (bun ${{ matrix.bun-version }})
runs-on: ubuntu-latest
- env:
- VERSION_INPUT: ${{ github.event.inputs.version || '' }}
- PRERELEASE_INPUT: ${{ github.event.inputs.prerelease || 'false' }}
+ strategy:
+ fail-fast: true
+ matrix:
+ # Floor matches `engines.bun` in package.json. Bumping that floor MUST
+ # also bump this matrix so CI never silently ships green at "latest"
+ # while the declared minimum no longer compiles.
+ bun-version: ["1.1.0", "latest"]
steps:
- name: Check out repository
uses: actions/checkout@v4
+
+ - name: Set up Bun ${{ matrix.bun-version }}
+ uses: oven-sh/setup-bun@v2
with:
- fetch-depth: 0
+ bun-version: ${{ matrix.bun-version }}
- - name: Set up Python
+ - name: Set up Python (Hermes shim test only)
uses: actions/setup-python@v5
with:
python-version: "3.11"
- - name: Resolve release version
- id: version
- shell: bash
- run: |
- set -euo pipefail
- pyproject_version=$(python -c 'import pathlib, tomllib; data = tomllib.loads(pathlib.Path("pyproject.toml").read_text(encoding="utf-8")); print(data["project"]["version"])')
+ - name: Install JS dependencies
+ run: bun install --frozen-lockfile
- if [ "${GITHUB_REF_TYPE}" = "tag" ]; then
- tag="${GITHUB_REF_NAME}"
- version="${tag#v}"
- elif [ -n "${VERSION_INPUT}" ]; then
- version="${VERSION_INPUT#v}"
- tag="v${version}"
- else
- version="${pyproject_version}"
- tag="v${version}"
- fi
+ - name: Verify manifest version sync
+ run: bun run sync-version:check
- if [ "${version}" != "${pyproject_version}" ]; then
- echo "Release version ${version} does not match pyproject.toml version ${pyproject_version}" >&2
- exit 1
- fi
+ - name: Run TypeScript typecheck
+ run: bun run typecheck
- echo "version=${version}" >> "$GITHUB_OUTPUT"
- echo "tag=${tag}" >> "$GITHUB_OUTPUT"
+ - name: Run TypeScript test suite (bun:test)
+ run: bun test
- - name: Run test suite
- run: PYTHONPATH=src python -m unittest discover -s tests -v
+ - name: Run Python shim tests
+ run: python -m unittest discover -s tests/python -v
- - name: Run packaging and manifest checks
+ - name: Validate manifests and CLI scripts
shell: bash
run: |
set -euo pipefail
python -m json.tool .claude-plugin/plugin.json >/dev/null
python -m json.tool .codex-plugin/plugin.json >/dev/null
python -m json.tool openclaw.plugin.json >/dev/null
+ python -m json.tool package.json >/dev/null
python -m py_compile plugins/hermes/__init__.py
bash -n scripts/o2b
bash -n scripts/vault-log
- scripts/o2b doctor --vault . --repo .
+ bash -n scripts/_bun-precheck.sh
+ ./scripts/o2b doctor --vault . --repo .
+
+ - name: Validate OpenClaw bundle is in sync with sources
+ shell: bash
+ run: |
+ set -euo pipefail
+ # Re-build into a temp file and diff against the committed bundle
+ # so a stale `openclaw/index.js` fails CI rather than ships silently.
+ bun build src/openclaw/index.ts \
+ --outfile /tmp/openclaw-rebuild.js \
+ --target=node --format=esm \
+ --external openclaw/plugin-sdk/plugin-entry
+ diff -q /tmp/openclaw-rebuild.js openclaw/index.js \
+ || { echo "openclaw/index.js is out of date; run: bun run build:openclaw" >&2; exit 1; }
- name: Validate OpenClaw packaging
shell: bash
run: |
set -euo pipefail
- python -m json.tool package.json >/dev/null
node -e "const pkg = require('./package.json'); if (!pkg.openclaw?.extensions?.length) throw new Error('missing openclaw.extensions')"
for entry in $(node -e "console.log(require('./package.json').openclaw.extensions.join(' '))"); do
[ -f "$entry" ] || { echo "Missing entry: $entry"; exit 1; }
done
- - name: Build source and wheel distributions
+ release:
+ name: Build and publish GitHub release
+ needs: verify
+ runs-on: ubuntu-latest
+ # Only fire on actual release events β€” every push triggers `verify`,
+ # but only tag pushes / workflow_dispatch should publish.
+ if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
+ env:
+ VERSION_INPUT: ${{ github.event.inputs.version || '' }}
+ PRERELEASE_INPUT: ${{ github.event.inputs.prerelease || 'false' }}
+ steps:
+ - name: Check out repository
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Set up Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: latest
+
+ - name: Resolve release version
+ id: version
+ shell: bash
run: |
- python -m pip install --upgrade pip build
- python -m build
+ set -euo pipefail
+ pkg_version=$(node -p "require('./package.json').version")
+
+ if [ "${GITHUB_REF_TYPE}" = "tag" ]; then
+ tag="${GITHUB_REF_NAME}"
+ version="${tag#v}"
+ elif [ -n "${VERSION_INPUT}" ]; then
+ version="${VERSION_INPUT#v}"
+ tag="v${version}"
+ else
+ version="${pkg_version}"
+ tag="v${version}"
+ fi
+
+ if [ "${version}" != "${pkg_version}" ]; then
+ echo "Release version ${version} does not match package.json version ${pkg_version}" >&2
+ exit 1
+ fi
+
+ echo "version=${version}" >> "$GITHUB_OUTPUT"
+ echo "tag=${tag}" >> "$GITHUB_OUTPUT"
- name: Publish GitHub release
env:
@@ -115,7 +164,7 @@ jobs:
exit 1
fi
- gh release create "${TAG}" dist/* \
+ gh release create "${TAG}" \
--target "${GITHUB_SHA}" \
--title "open-second-brain ${TAG}" \
--generate-notes \
diff --git a/.gitignore b/.gitignore
index 93bac306..29ae0138 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,8 +12,9 @@ build/
dist/
*.egg-info/
-# Node
+# Node / Bun
node_modules/
+.bun/
# Local config and sandbox data
.env
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9c81f3de..d3c93b1c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,7 +5,77 @@ 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).
-## [Unreleased]
+## [0.7.0] - 2026-05-09
+
+Single TypeScript source of truth on the [Bun](https://bun.sh) runtime.
+Hermes, Claude Code, Codex, and OpenClaw all consume the same `src/core/`
+modules; the duplicate JavaScript copy under `openclaw/*.js` and the
+parallel Python implementation under `src/open_second_brain/*.py` are gone.
+
+### Added
+
+- TypeScript core (`src/core/`) for config, event-log, vault, init, doctor.
+- `bun:test` suite (176 cases) + Python shim tests (13 cases). Includes a
+ 12-worker multi-process append-event lock test.
+- Per-runtime install flows for local marketplaces (Claude `claude plugin
+ marketplace add <path>`, Codex `codex plugin marketplace add <path>`,
+ Hermes via plugin-dir symlink, OpenClaw `openclaw plugins install <path>`).
+- `agent-event-log` skill: stronger trigger description and a language
+ policy that follows the user's session language.
+- `scripts/sync-version.ts` and `bun run sync-version:check` to keep all
+ manifests aligned with `package.json`.
+- `bun.lock` for reproducible dependency resolution.
+
+### Changed (BREAKING)
+
+- **Runtime:** `o2b` CLI requires [Bun](https://bun.sh) (>=1.1.0). The
+ wrapper script aborts with an install hint if `bun` is not on PATH.
+- **Source layout:** Python `src/open_second_brain/*` replaced by TypeScript
+ `src/core/*`, `src/cli/*`, `src/mcp/*`.
+- **OpenClaw plugin:** `openclaw/index.js` is now a `bun build` bundle
+ (target=node) of `src/openclaw/index.ts`; no more hand-translated JS.
+ CI rebuilds and diffs the committed bundle.
+- **Hermes plugin:** `plugins/hermes/__init__.py` slimmed to a thin shim
+ (`pre_llm_call` + minimal health). Identity reminder template lives in
+ `templates/identity-reminder.txt`, shared with the OpenClaw
+ `before_prompt_build` hook.
+- **Version source of truth:** `package.json`. `pyproject.toml` and the
+ five plugin manifests carry synced copies.
+- **CI:** `oven-sh/setup-bun@v2`, `bun test`, `bun run typecheck`,
+ Python-shim tests, manifest + bundle freshness checks.
+
+### Fixed
+
+- **Security β€” path traversal in `event_log_append`:** `date` parameter is
+ now validated against `^\d{4}\.\d{2}\.\d{2}$` and rejects non-existent
+ calendar dates and `..` segments. Previously `date: "../AI Wiki/notes/pwn"`
+ could write outside `Daily/`.
+- **Identity hallucination:** placeholder blacklist extended to include
+ `codex`, `codex-cli`, `codex-exec`, `claude-code`, `hermes`, `openclaw`.
+ When the model echoes its runtime name as the `agent` argument the server
+ now falls back to the persisted `agent_name` instead of writing
+ `@codex` / `@hermes` / etc.
+- **Cross-platform paths:** `fs-atomic`, `install-cli`, `uninstall` use
+ `node:path` `basename` / `sep` instead of hard-coded `/`.
+- **Test reliability:** `expect(Bun.file(...).text()).resolves` now awaited
+ β€” assertion was silently dropped.
+- **Hermes shim:** `__init__.py` tolerates both relative and absolute
+ `plugins.hermes` import paths (Hermes loads it as a file directly).
+
+### Removed (BREAKING)
+
+- Python `open_second_brain` package and its pip entry points
+ (`o2b`, `vault-log`, `o2b-mcp`).
+- `openclaw/event-log.js` and `openclaw/vault.js` (rolled into the bundle).
+
+### Migration
+
+1. Install Bun (`curl -fsSL https://bun.sh/install | bash`).
+2. `git pull` the plugin checkout.
+3. Re-run `o2b install-cli` to refresh symlinks.
+4. `o2b doctor --vault <path> --repo <repo>` to verify.
+
+Hermes / Claude Code / Codex / OpenClaw configurations do not change.
## [0.6.2] - 2026-05-08
@@ -558,7 +628,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
-[unreleased]: https://github.com/itechmeat/open-second-brain/compare/v0.6.2...HEAD
+[0.7.0]: https://github.com/itechmeat/open-second-brain/compare/v0.6.2...v0.7.0
[0.6.2]: https://github.com/itechmeat/open-second-brain/compare/v0.6.1...v0.6.2
[0.6.1]: https://github.com/itechmeat/open-second-brain/compare/v0.6.0...v0.6.1
[0.6.0]: https://github.com/itechmeat/open-second-brain/compare/v0.5.5...v0.6.0
diff --git a/__init__.py b/__init__.py
index c95c6bd2..60f39f04 100644
--- a/__init__.py
+++ b/__init__.py
@@ -7,6 +7,9 @@ it can also be used directly by runtimes that expect an adapter subdirectory.
from __future__ import annotations
-from .plugins.hermes import check_health, health, register
+try:
+ from .plugins.hermes import check_health, health, register
+except ImportError:
+ from plugins.hermes import check_health, health, register
__all__ = ["check_health", "health", "register"]
diff --git a/bun.lock b/bun.lock
new file mode 100644
index 00000000..0a7d3740
--- /dev/null
+++ b/bun.lock
@@ -0,0 +1,41 @@
+{
+ "lockfileVersion": 1,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "open-second-brain",
+ "dependencies": {
+ "proper-lockfile": "^4.1.2",
+ },
+ "devDependencies": {
+ "@types/bun": "^1.1.0",
+ "@types/node": "^22.0.0",
+ "@types/proper-lockfile": "^4.1.4",
+ "typescript": "^5.5.0",
+ },
+ },
+ },
+ "packages": {
+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.13" } }, "sha512-9fqXWk5YIHGGnUau9TEi+qdlTYDAnOj+xLCmSTwXfAIqXr2x4tytJb43E9uCvt09zJURKXwAtkoH4nLQfzeTXw=="],
+
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-9v00a+dn2yWVsYDEunWC4g/TcRKVq3r8N5FuZp7u0SGrPvdN9c2yXI9bBuf5Fl0hNCb+QTIePTn5pJs2pwBOQQ=="],
+
+ "@types/proper-lockfile": ["@types/[email protected]", "", { "dependencies": { "@types/retry": "*" } }, "sha512-uo2ABllncSqg9F1D4nugVl9v93RmjxF6LJzQLMLDdPaXCUIDPeOJ21Gbqi43xNKzBi/WQ0Q0dICqufzQbMjipQ=="],
+
+ "@types/retry": ["@types/[email protected]", "", {}, "sha512-3xSjTp3v03X/lSQLkczaN9UIEwJMoMCA1+Nb5HfbJEQWogdeQIyVtTvxPXDQjZ5zws8rFQfVfRdz03ARihPJgw=="],
+
+ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-QXKeHLlOLqQX9LgYaHJfzdBaV21T63HhFJnvuRCcjZiaUDpbs5ED1MgxbMra71CsryN/1dAoXuJJJwIv/2drVA=="],
+
+ "graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
+
+ "proper-lockfile": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "retry": "^0.12.0", "signal-exit": "^3.0.2" } }, "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA=="],
+
+ "retry": ["[email protected]", "", {}, "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow=="],
+
+ "signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
+ }
+}
diff --git a/install.md b/install.md
index c47a3569..c5deaa2b 100644
--- a/install.md
+++ b/install.md
@@ -14,6 +14,29 @@ If at any point you are missing information β€” for example, the vault path is u
---
+## Prerequisites β€” Bun runtime (all branches)
+
+**Open Second Brain v0.7+ runs on the [Bun](https://bun.sh) JavaScript runtime.** The `o2b` CLI, the MCP server (`o2b mcp`), and the OpenClaw native plugin all execute under Bun. Hermes still loads a small Python shim for the per-turn `pre_llm_call` hook, but every other runtime path is Bun-only.
+
+**Before running any branch below, verify Bun is on PATH:**
+
+```bash
+command -v bun >/dev/null 2>&1 || curl -fsSL https://bun.sh/install | bash
+```
+
+If the install runs, re-source your shell so `~/.bun/bin` lands on PATH:
+
+```bash
+export PATH="$HOME/.bun/bin:$PATH"
+bun --version
+```
+
+`bun --version` must report **1.1.0 or newer**. If it does not, stop and ask the user to upgrade Bun before continuing β€” older versions miss APIs the plugin relies on.
+
+If the user is on a system where they cannot install Bun (locked-down environment, unsupported architecture), abort the install and tell them so explicitly. Do **not** try to work around the missing runtime by re-exporting Python sources β€” those were removed in v0.7.0 and there is no Python fallback for the CLI.
+
+---
+
## Branch A β€” Hermes
### 1. Collect installation parameters (vault path + agent name + timezone)
@@ -86,7 +109,7 @@ answer (city name, country, "my time", etc.) and translate it to a
canonical IANA name yourself before passing it to `o2b init` β€” the
plugin only accepts IANA. Examples of the translation you should do:
-- `Belgrade` / `БСрбия` β†’ `Europe/Belgrade`
+- `Belgrade` / `Serbia` β†’ `Europe/Belgrade`
- `New York` / `EST` / `eastern` β†’ `America/New_York`
- `UTC` / `none` / `server time` β†’ `UTC`
- `Tokyo` / `JST` β†’ `Asia/Tokyo`
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 4ad199f3..cdcfa0cc 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.6.2",
+ "version": "0.7.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/event-log.js b/openclaw/event-log.js
deleted file mode 100644
index 3ce77091..00000000
--- a/openclaw/event-log.js
+++ /dev/null
@@ -1,199 +0,0 @@
-/**
- * Pure JavaScript event log operations for Open Second Brain.
- *
- * All filesystem operations use `node:fs/promises` and `node:path`.
- * No native process module, no subprocess calls β€” passes the OpenClaw security scanner.
- *
- * Logic mirrors the Python implementation in `src/open_second_brain/event_log.py`.
- *
- * Daily note format:
- * File: vault/Daily/YYYY.MM.DD.md
- * Sections separated by ---
- * Events under ## Raw events (lowercase 'events' to match Python)
- * Entries: - HH:MM β€” @agent β€” message
- * Chronologically sorted within the section
- */
-
-import { readFile, writeFile, mkdir } from "node:fs/promises";
-import { join, dirname } from "node:path";
-import { existsSync } from "node:fs";
-import { randomUUID } from "node:crypto";
-
-// ── Constants ──────────────────────────────────────────────────────────────
-
-const SECRET_ASSIGNMENT_RE =
- /\b(api[_-]?key|token|secret|password|credential)(\s*[:=]\s*)([^\s]+)/gi;
-
-const EVENT_RE = /^- (\d{2}:\d{2}) β€” @/;
-const TIME_RE = /^(\d{2}):(\d{2})$/;
-
-// ── Helpers ────────────────────────────────────────────────────────────────
-
-/**
- * Redact secret-like values from text.
- */
-function redactText(text) {
- return text.replace(SECRET_ASSIGNMENT_RE, "$1$2[REDACTED]");
-}
-
-/**
- * Get current date in YYYY.MM.DD format.
- *
- * When ``tz`` is an IANA timezone name, the date is computed in that
- * zone rather than the host's local clock. Mirrors the Python
- * ``current_date(tz)`` helper. Around midnight this matters: an event
- * taken at 23:30 host-local UTC may be 01:30 the next day in the
- * user's local timezone, so the entry must land in the next day's
- * Daily file.
- */
-function currentDate(tz) {
- const parts = new Intl.DateTimeFormat("en-US", {
- timeZone: tz || undefined,
- year: "numeric",
- month: "2-digit",
- day: "2-digit",
- }).formatToParts(new Date());
- const get = (type) => parts.find((p) => p.type === type).value;
- return `${get("year")}.${get("month")}.${get("day")}`;
-}
-
-/**
- * Get current time in HH:MM 24-hour format, optionally in ``tz``.
- */
-function currentTime(tz) {
- const parts = new Intl.DateTimeFormat("en-US", {
- timeZone: tz || undefined,
- hour: "2-digit",
- minute: "2-digit",
- hourCycle: "h23",
- }).formatToParts(new Date());
- const get = (type) => parts.find((p) => p.type === type).value;
- return `${get("hour")}:${get("minute")}`;
-}
-
-/**
- * Validate a time string in HH:MM 24-hour format.
- * Returns the validated time string or throws.
- */
-function validateEventTime(value) {
- const match = TIME_RE.exec(value);
- if (!match) {
- throw new Error("event time must use HH:MM 24-hour format");
- }
- const hour = parseInt(match[1], 10);
- const minute = parseInt(match[2], 10);
- if (hour > 23 || minute > 59) {
- throw new Error("event time must use HH:MM 24-hour format");
- }
- return value;
-}
-
-/**
- * Build a new empty daily note.
- */
-function newDailyNote(date) {
- return `---\nformatted: false\n---\n\n# ${date}\n\n## Raw events\n\n`;
-}
-
-/**
- * Insert an event entry into the daily note content, maintaining chronological order.
- * Uses the "## Raw events" heading (lowercase, matching Python).
- */
-function insertEventEntry(content, entry) {
- const marker = "## Raw events";
- const idx = content.indexOf(marker);
- if (idx === -1) {
- // Shouldn't happen since we ensure it exists, but handle gracefully
- return content + "\n\n" + marker + "\n\n" + entry + "\n";
- }
-
- const before = content.slice(0, idx);
- const after = content.slice(idx + marker.length);
-
- // Strip leading newlines from after section
- const afterStripped = after.replace(/^\n+/, "");
- const lines = afterStripped.split("\n").filter((line) => line.trim());
-
- // Extract time from entry: "- HH:MM β€” @..."
- const entryTime = entry.slice(2, 7);
-
- let inserted = false;
- const output = [];
- for (const line of lines) {
- const match = EVENT_RE.exec(line);
- if (!inserted && match && match[1] > entryTime) {
- output.push(entry);
- inserted = true;
- }
- output.push(line);
- }
- if (!inserted) {
- output.push(entry);
- }
-
- let rawEvents = output.join("\n");
- if (rawEvents) {
- rawEvents += "\n";
- }
-
- return before + marker + "\n\n" + rawEvents;
-}
-
-// ── Public API ─────────────────────────────────────────────────────────────
-
-/**
- * Append an event to the daily event log.
- *
- * @param {string} vaultPath - Absolute path to the vault directory.
- * @param {string} agent - Agent name (e.g., "hermes-agent").
- * @param {string} message - Event message text.
- * @param {string|null} date - Optional date in YYYY.MM.DD format.
- * @param {string|null} time - Optional time in HH:MM format.
- * @param {string|null} tz - Optional IANA timezone (e.g. "Europe/Belgrade")
- * used when ``date`` / ``time`` are not provided. Default: host local.
- * @returns {Promise<{path: string, relativePath: string, agent: string, date: string|null, time: string|null}>}
- */
-export async function appendEvent(vaultPath, agent, message, date = null, time = null, tz = null) {
- const eventDate = date || currentDate(tz);
- const eventTime = validateEventTime(time || currentTime(tz));
-
- const dailyDir = join(vaultPath, "Daily");
- const filePath = join(dailyDir, `${eventDate}.md`);
-
- await mkdir(dailyDir, { recursive: true });
-
- // Build the event line (replace newlines in message with spaces)
- const cleanMessage = redactText(message).replace(/\n/g, " ");
- const entry = `- ${eventTime} β€” @${agent} β€” ${cleanMessage}`;
-
- let content;
- if (existsSync(filePath)) {
- content = await readFile(filePath, "utf8");
- } else {
- content = newDailyNote(eventDate);
- }
-
- // Ensure the Raw events section exists
- if (!content.includes("## Raw events")) {
- content = content.trimEnd() + "\n\n## Raw events\n\n";
- }
-
- const updated = insertEventEntry(content, entry);
-
- // Atomic write using a temp file in the same directory
- const tmpPath = join(dailyDir, `.${eventDate}.tmp-${randomUUID()}`);
- await writeFile(tmpPath, updated, "utf8");
-
- // Rename is atomic on same filesystem
- const { rename } = await import("node:fs/promises");
- await rename(tmpPath, filePath);
-
- const relativePath = `Daily${require("node:path").sep}${eventDate}.md`;
- return {
- path: filePath,
- relativePath,
- agent,
- date: date || null,
- time: time || null,
- };
-}
diff --git a/openclaw/index.js b/openclaw/index.js
index 776dfe2f..c1f40d38 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -1,92 +1,1675 @@
-/**
- * OpenClaw native plugin entry for Open Second Brain.
- *
- * Pure JavaScript implementation β€” all five tools operate directly on the
- * vault filesystem using `node:fs/promises` and `node:path`. No
- * subprocess creation, no native process module. Passes the OpenClaw security scanner.
- *
- * Tool parameter schemas match `src/open_second_brain/mcp.py` exactly.
- */
+import { createRequire } from "node:module";
+var __create = Object.create;
+var __getProtoOf = Object.getPrototypeOf;
+var __defProp = Object.defineProperty;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+function __accessProp(key) {
+ return this[key];
+}
+var __toESMCache_node;
+var __toESMCache_esm;
+var __toESM = (mod, isNodeMode, target) => {
+ var canCache = mod != null && typeof mod === "object";
+ if (canCache) {
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
+ var cached = cache.get(mod);
+ if (cached)
+ return cached;
+ }
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
+ for (let key of __getOwnPropNames(mod))
+ if (!__hasOwnProp.call(to, key))
+ __defProp(to, key, {
+ get: __accessProp.bind(mod, key),
+ enumerable: true
+ });
+ if (canCache)
+ cache.set(mod, to);
+ return to;
+};
+var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
+var __require = /* @__PURE__ */ createRequire(import.meta.url);
-import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
-import {
- listVaultPages,
- writeFrontmatter,
- slugify,
-} from "./vault.js";
-import { appendEvent } from "./event-log.js";
-import {
- readFile,
- writeFile,
- mkdir,
- access,
- readdir,
- stat,
- unlink,
-} from "node:fs/promises";
-import {
- join,
- resolve,
- relative,
- dirname,
- basename,
- sep,
-} from "node:path";
-import { existsSync } from "node:fs";
+// node_modules/graceful-fs/polyfills.js
+var require_polyfills = __commonJS((exports, module) => {
+ var constants = __require("constants");
+ var origCwd = process.cwd;
+ var cwd = null;
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
+ process.cwd = function() {
+ if (!cwd)
+ cwd = origCwd.call(process);
+ return cwd;
+ };
+ try {
+ process.cwd();
+ } catch (er) {}
+ if (typeof process.chdir === "function") {
+ chdir = process.chdir;
+ process.chdir = function(d) {
+ cwd = null;
+ chdir.call(process, d);
+ };
+ if (Object.setPrototypeOf)
+ Object.setPrototypeOf(process.chdir, chdir);
+ }
+ var chdir;
+ module.exports = patch;
+ function patch(fs) {
+ if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
+ patchLchmod(fs);
+ }
+ if (!fs.lutimes) {
+ patchLutimes(fs);
+ }
+ fs.chown = chownFix(fs.chown);
+ fs.fchown = chownFix(fs.fchown);
+ fs.lchown = chownFix(fs.lchown);
+ fs.chmod = chmodFix(fs.chmod);
+ fs.fchmod = chmodFix(fs.fchmod);
+ fs.lchmod = chmodFix(fs.lchmod);
+ fs.chownSync = chownFixSync(fs.chownSync);
+ fs.fchownSync = chownFixSync(fs.fchownSync);
+ fs.lchownSync = chownFixSync(fs.lchownSync);
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
+ fs.stat = statFix(fs.stat);
+ fs.fstat = statFix(fs.fstat);
+ fs.lstat = statFix(fs.lstat);
+ fs.statSync = statFixSync(fs.statSync);
+ fs.fstatSync = statFixSync(fs.fstatSync);
+ fs.lstatSync = statFixSync(fs.lstatSync);
+ if (fs.chmod && !fs.lchmod) {
+ fs.lchmod = function(path, mode, cb) {
+ if (cb)
+ process.nextTick(cb);
+ };
+ fs.lchmodSync = function() {};
+ }
+ if (fs.chown && !fs.lchown) {
+ fs.lchown = function(path, uid, gid, cb) {
+ if (cb)
+ process.nextTick(cb);
+ };
+ fs.lchownSync = function() {};
+ }
+ if (platform === "win32") {
+ fs.rename = typeof fs.rename !== "function" ? fs.rename : function(fs$rename) {
+ function rename(from, to, cb) {
+ var start = Date.now();
+ var backoff = 0;
+ fs$rename(from, to, function CB(er) {
+ if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 60000) {
+ setTimeout(function() {
+ fs.stat(to, function(stater, st) {
+ if (stater && stater.code === "ENOENT")
+ fs$rename(from, to, CB);
+ else
+ cb(er);
+ });
+ }, backoff);
+ if (backoff < 100)
+ backoff += 10;
+ return;
+ }
+ if (cb)
+ cb(er);
+ });
+ }
+ if (Object.setPrototypeOf)
+ Object.setPrototypeOf(rename, fs$rename);
+ return rename;
+ }(fs.rename);
+ }
+ fs.read = typeof fs.read !== "function" ? fs.read : function(fs$read) {
+ function read(fd, buffer, offset, length, position, callback_) {
+ var callback;
+ if (callback_ && typeof callback_ === "function") {
+ var eagCounter = 0;
+ callback = function(er, _, __) {
+ if (er && er.code === "EAGAIN" && eagCounter < 10) {
+ eagCounter++;
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
+ }
+ callback_.apply(this, arguments);
+ };
+ }
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
+ }
+ if (Object.setPrototypeOf)
+ Object.setPrototypeOf(read, fs$read);
+ return read;
+ }(fs.read);
+ fs.readSync = typeof fs.readSync !== "function" ? fs.readSync : function(fs$readSync) {
+ return function(fd, buffer, offset, length, position) {
+ var eagCounter = 0;
+ while (true) {
+ try {
+ return fs$readSync.call(fs, fd, buffer, offset, length, position);
+ } catch (er) {
+ if (er.code === "EAGAIN" && eagCounter < 10) {
+ eagCounter++;
+ continue;
+ }
+ throw er;
+ }
+ }
+ };
+ }(fs.readSync);
+ function patchLchmod(fs2) {
+ fs2.lchmod = function(path, mode, callback) {
+ fs2.open(path, constants.O_WRONLY | constants.O_SYMLINK, mode, function(err, fd) {
+ if (err) {
+ if (callback)
+ callback(err);
+ return;
+ }
+ fs2.fchmod(fd, mode, function(err2) {
+ fs2.close(fd, function(err22) {
+ if (callback)
+ callback(err2 || err22);
+ });
+ });
+ });
+ };
+ fs2.lchmodSync = function(path, mode) {
+ var fd = fs2.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
+ var threw = true;
+ var ret;
+ try {
+ ret = fs2.fchmodSync(fd, mode);
+ threw = false;
+ } finally {
+ if (threw) {
+ try {
+ fs2.closeSync(fd);
+ } catch (er) {}
+ } else {
+ fs2.closeSync(fd);
+ }
+ }
+ return ret;
+ };
+ }
+ function patchLutimes(fs2) {
+ if (constants.hasOwnProperty("O_SYMLINK") && fs2.futimes) {
+ fs2.lutimes = function(path, at, mt, cb) {
+ fs2.open(path, constants.O_SYMLINK, function(er, fd) {
+ if (er) {
+ if (cb)
+ cb(er);
+ return;
+ }
+ fs2.futimes(fd, at, mt, function(er2) {
+ fs2.close(fd, function(er22) {
+ if (cb)
+ cb(er2 || er22);
+ });
+ });
+ });
+ };
+ fs2.lutimesSync = function(path, at, mt) {
+ var fd = fs2.openSync(path, constants.O_SYMLINK);
+ var ret;
+ var threw = true;
+ try {
+ ret = fs2.futimesSync(fd, at, mt);
+ threw = false;
+ } finally {
+ if (threw) {
+ try {
+ fs2.closeSync(fd);
+ } catch (er) {}
+ } else {
+ fs2.closeSync(fd);
+ }
+ }
+ return ret;
+ };
+ } else if (fs2.futimes) {
+ fs2.lutimes = function(_a, _b, _c, cb) {
+ if (cb)
+ process.nextTick(cb);
+ };
+ fs2.lutimesSync = function() {};
+ }
+ }
+ function chmodFix(orig) {
+ if (!orig)
+ return orig;
+ return function(target, mode, cb) {
+ return orig.call(fs, target, mode, function(er) {
+ if (chownErOk(er))
+ er = null;
+ if (cb)
+ cb.apply(this, arguments);
+ });
+ };
+ }
+ function chmodFixSync(orig) {
+ if (!orig)
+ return orig;
+ return function(target, mode) {
+ try {
+ return orig.call(fs, target, mode);
+ } catch (er) {
+ if (!chownErOk(er))
+ throw er;
+ }
+ };
+ }
+ function chownFix(orig) {
+ if (!orig)
+ return orig;
+ return function(target, uid, gid, cb) {
+ return orig.call(fs, target, uid, gid, function(er) {
+ if (chownErOk(er))
+ er = null;
+ if (cb)
+ cb.apply(this, arguments);
+ });
+ };
+ }
+ function chownFixSync(orig) {
+ if (!orig)
+ return orig;
+ return function(target, uid, gid) {
+ try {
+ return orig.call(fs, target, uid, gid);
+ } catch (er) {
+ if (!chownErOk(er))
+ throw er;
+ }
+ };
+ }
+ function statFix(orig) {
+ if (!orig)
+ return orig;
+ return function(target, options, cb) {
+ if (typeof options === "function") {
+ cb = options;
+ options = null;
+ }
+ function callback(er, stats) {
+ if (stats) {
+ if (stats.uid < 0)
+ stats.uid += 4294967296;
+ if (stats.gid < 0)
+ stats.gid += 4294967296;
+ }
+ if (cb)
+ cb.apply(this, arguments);
+ }
+ return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback);
+ };
+ }
+ function statFixSync(orig) {
+ if (!orig)
+ return orig;
+ return function(target, options) {
+ var stats = options ? orig.call(fs, target, options) : orig.call(fs, target);
+ if (stats) {
+ if (stats.uid < 0)
+ stats.uid += 4294967296;
+ if (stats.gid < 0)
+ stats.gid += 4294967296;
+ }
+ return stats;
+ };
+ }
+ function chownErOk(er) {
+ if (!er)
+ return true;
+ if (er.code === "ENOSYS")
+ return true;
+ var nonroot = !process.getuid || process.getuid() !== 0;
+ if (nonroot) {
+ if (er.code === "EINVAL" || er.code === "EPERM")
+ return true;
+ }
+ return false;
+ }
+ }
+});
-// ── Constants ──────────────────────────────────────────────────────────────
+// node_modules/graceful-fs/legacy-streams.js
+var require_legacy_streams = __commonJS((exports, module) => {
+ var Stream = __require("stream").Stream;
+ module.exports = legacy;
+ function legacy(fs) {
+ return {
+ ReadStream,
+ WriteStream
+ };
+ function ReadStream(path, options) {
+ if (!(this instanceof ReadStream))
+ return new ReadStream(path, options);
+ Stream.call(this);
+ var self = this;
+ this.path = path;
+ this.fd = null;
+ this.readable = true;
+ this.paused = false;
+ this.flags = "r";
+ this.mode = 438;
+ this.bufferSize = 64 * 1024;
+ options = options || {};
+ var keys = Object.keys(options);
+ for (var index = 0, length = keys.length;index < length; index++) {
+ var key = keys[index];
+ this[key] = options[key];
+ }
+ if (this.encoding)
+ this.setEncoding(this.encoding);
+ if (this.start !== undefined) {
+ if (typeof this.start !== "number") {
+ throw TypeError("start must be a Number");
+ }
+ if (this.end === undefined) {
+ this.end = Infinity;
+ } else if (typeof this.end !== "number") {
+ throw TypeError("end must be a Number");
+ }
+ if (this.start > this.end) {
+ throw new Error("start must be <= end");
+ }
+ this.pos = this.start;
+ }
+ if (this.fd !== null) {
+ process.nextTick(function() {
+ self._read();
+ });
+ return;
+ }
+ fs.open(this.path, this.flags, this.mode, function(err, fd) {
+ if (err) {
+ self.emit("error", err);
+ self.readable = false;
+ return;
+ }
+ self.fd = fd;
+ self.emit("open", fd);
+ self._read();
+ });
+ }
+ function WriteStream(path, options) {
+ if (!(this instanceof WriteStream))
+ return new WriteStream(path, options);
+ Stream.call(this);
+ this.path = path;
+ this.fd = null;
+ this.writable = true;
+ this.flags = "w";
+ this.encoding = "binary";
+ this.mode = 438;
+ this.bytesWritten = 0;
+ options = options || {};
+ var keys = Object.keys(options);
+ for (var index = 0, length = keys.length;index < length; index++) {
+ var key = keys[index];
+ this[key] = options[key];
+ }
+ if (this.start !== undefined) {
+ if (typeof this.start !== "number") {
+ throw TypeError("start must be a Number");
+ }
+ if (this.start < 0) {
+ throw new Error("start must be >= zero");
+ }
+ this.pos = this.start;
+ }
+ this.busy = false;
+ this._queue = [];
+ if (this.fd === null) {
+ this._open = fs.open;
+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
+ this.flush();
+ }
+ }
+ }
+});
-const SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"];
+// node_modules/graceful-fs/clone.js
+var require_clone = __commonJS((exports, module) => {
+ module.exports = clone;
+ var getPrototypeOf = Object.getPrototypeOf || function(obj) {
+ return obj.__proto__;
+ };
+ function clone(obj) {
+ if (obj === null || typeof obj !== "object")
+ return obj;
+ if (obj instanceof Object)
+ var copy = { __proto__: getPrototypeOf(obj) };
+ else
+ var copy = Object.create(null);
+ Object.getOwnPropertyNames(obj).forEach(function(key) {
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
+ });
+ return copy;
+ }
+});
-// Strings the LLM is most likely to emit as a guess for the ``agent``
-// argument when it doesn't actually know its identity. Compared
-// case-insensitively, after a leading ``@`` is stripped. Mirrors the
-// Python ``_PLACEHOLDER_AGENT_VALUES`` set in ``mcp.py`` so all
-// runtimes filter the same hallucination shapes out of Daily.
-const PLACEHOLDER_AGENTS = new Set([
- "agent",
- "assistant",
- "ai",
- "ai-assistant",
- "bot",
- "chatbot",
- "claude",
- "copilot",
- "gemini",
- "gpt",
- "gpt-4",
- "gpt-5",
- "llm",
- "model",
- "openai",
- "user",
-]);
+// node_modules/graceful-fs/graceful-fs.js
+var require_graceful_fs = __commonJS((exports, module) => {
+ var fs = __require("fs");
+ var polyfills = require_polyfills();
+ var legacy = require_legacy_streams();
+ var clone = require_clone();
+ var util = __require("util");
+ var gracefulQueue;
+ var previousSymbol;
+ if (typeof Symbol === "function" && typeof Symbol.for === "function") {
+ gracefulQueue = Symbol.for("graceful-fs.queue");
+ previousSymbol = Symbol.for("graceful-fs.previous");
+ } else {
+ gracefulQueue = "___graceful-fs.queue";
+ previousSymbol = "___graceful-fs.previous";
+ }
+ function noop() {}
+ function publishQueue(context, queue2) {
+ Object.defineProperty(context, gracefulQueue, {
+ get: function() {
+ return queue2;
+ }
+ });
+ }
+ var debug = noop;
+ if (util.debuglog)
+ debug = util.debuglog("gfs4");
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
+ debug = function() {
+ var m = util.format.apply(util, arguments);
+ m = "GFS4: " + m.split(/\n/).join(`
+GFS4: `);
+ console.error(m);
+ };
+ if (!fs[gracefulQueue]) {
+ queue = global[gracefulQueue] || [];
+ publishQueue(fs, queue);
+ fs.close = function(fs$close) {
+ function close(fd, cb) {
+ return fs$close.call(fs, fd, function(err) {
+ if (!err) {
+ resetQueue();
+ }
+ if (typeof cb === "function")
+ cb.apply(this, arguments);
+ });
+ }
+ Object.defineProperty(close, previousSymbol, {
+ value: fs$close
+ });
+ return close;
+ }(fs.close);
+ fs.closeSync = function(fs$closeSync) {
+ function closeSync3(fd) {
+ fs$closeSync.apply(fs, arguments);
+ resetQueue();
+ }
+ Object.defineProperty(closeSync3, previousSymbol, {
+ value: fs$closeSync
+ });
+ return closeSync3;
+ }(fs.closeSync);
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
+ process.on("exit", function() {
+ debug(fs[gracefulQueue]);
+ __require("assert").equal(fs[gracefulQueue].length, 0);
+ });
+ }
+ }
+ var queue;
+ if (!global[gracefulQueue]) {
+ publishQueue(global, fs[gracefulQueue]);
+ }
+ module.exports = patch(clone(fs));
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
+ module.exports = patch(fs);
+ fs.__patched = true;
+ }
+ function patch(fs2) {
+ polyfills(fs2);
+ fs2.gracefulify = patch;
+ fs2.createReadStream = createReadStream;
+ fs2.createWriteStream = createWriteStream;
+ var fs$readFile = fs2.readFile;
+ fs2.readFile = readFile;
+ function readFile(path, options, cb) {
+ if (typeof options === "function")
+ cb = options, options = null;
+ return go$readFile(path, options, cb);
+ function go$readFile(path2, options2, cb2, startTime) {
+ return fs$readFile(path2, options2, function(err) {
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
+ enqueue([go$readFile, [path2, options2, cb2], err, startTime || Date.now(), Date.now()]);
+ else {
+ if (typeof cb2 === "function")
+ cb2.apply(this, arguments);
+ }
+ });
+ }
+ }
+ var fs$writeFile = fs2.writeFile;
+ fs2.writeFile = writeFile;
+ function writeFile(path, data, options, cb) {
+ if (typeof options === "function")
+ cb = options, options = null;
+ return go$writeFile(path, data, options, cb);
+ function go$writeFile(path2, data2, options2, cb2, startTime) {
+ return fs$writeFile(path2, data2, options2, function(err) {
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
+ enqueue([go$writeFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
+ else {
+ if (typeof cb2 === "function")
+ cb2.apply(this, arguments);
+ }
+ });
+ }
+ }
+ var fs$appendFile = fs2.appendFile;
+ if (fs$appendFile)
+ fs2.appendFile = appendFile;
+ function appendFile(path, data, options, cb) {
+ if (typeof options === "function")
+ cb = options, options = null;
+ return go$appendFile(path, data, options, cb);
+ function go$appendFile(path2, data2, options2, cb2, startTime) {
+ return fs$appendFile(path2, data2, options2, function(err) {
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
+ enqueue([go$appendFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
+ else {
+ if (typeof cb2 === "function")
+ cb2.apply(this, arguments);
+ }
+ });
+ }
+ }
+ var fs$copyFile = fs2.copyFile;
+ if (fs$copyFile)
+ fs2.copyFile = copyFile;
+ function copyFile(src, dest, flags, cb) {
+ if (typeof flags === "function") {
+ cb = flags;
+ flags = 0;
+ }
+ return go$copyFile(src, dest, flags, cb);
+ function go$copyFile(src2, dest2, flags2, cb2, startTime) {
+ return fs$copyFile(src2, dest2, flags2, function(err) {
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
+ enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
+ else {
+ if (typeof cb2 === "function")
+ cb2.apply(this, arguments);
+ }
+ });
+ }
+ }
+ var fs$readdir = fs2.readdir;
+ fs2.readdir = readdir;
+ var noReaddirOptionVersions = /^v[0-5]\./;
+ function readdir(path, options, cb) {
+ if (typeof options === "function")
+ cb = options, options = null;
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path2, options2, cb2, startTime) {
+ return fs$readdir(path2, fs$readdirCallback(path2, options2, cb2, startTime));
+ } : function go$readdir2(path2, options2, cb2, startTime) {
+ return fs$readdir(path2, options2, fs$readdirCallback(path2, options2, cb2, startTime));
+ };
+ return go$readdir(path, options, cb);
+ function fs$readdirCallback(path2, options2, cb2, startTime) {
+ return function(err, files) {
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
+ enqueue([
+ go$readdir,
+ [path2, options2, cb2],
+ err,
+ startTime || Date.now(),
+ Date.now()
+ ]);
+ else {
+ if (files && files.sort)
+ files.sort();
+ if (typeof cb2 === "function")
+ cb2.call(this, err, files);
+ }
+ };
+ }
+ }
+ if (process.version.substr(0, 4) === "v0.8") {
+ var legStreams = legacy(fs2);
+ ReadStream = legStreams.ReadStream;
+ WriteStream = legStreams.WriteStream;
+ }
+ var fs$ReadStream = fs2.ReadStream;
+ if (fs$ReadStream) {
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
+ ReadStream.prototype.open = ReadStream$open;
+ }
+ var fs$WriteStream = fs2.WriteStream;
+ if (fs$WriteStream) {
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
+ WriteStream.prototype.open = WriteStream$open;
+ }
+ Object.defineProperty(fs2, "ReadStream", {
+ get: function() {
+ return ReadStream;
+ },
+ set: function(val) {
+ ReadStream = val;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(fs2, "WriteStream", {
+ get: function() {
+ return WriteStream;
+ },
+ set: function(val) {
+ WriteStream = val;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ var FileReadStream = ReadStream;
+ Object.defineProperty(fs2, "FileReadStream", {
+ get: function() {
+ return FileReadStream;
+ },
+ set: function(val) {
+ FileReadStream = val;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ var FileWriteStream = WriteStream;
+ Object.defineProperty(fs2, "FileWriteStream", {
+ get: function() {
+ return FileWriteStream;
+ },
+ set: function(val) {
+ FileWriteStream = val;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ function ReadStream(path, options) {
+ if (this instanceof ReadStream)
+ return fs$ReadStream.apply(this, arguments), this;
+ else
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
+ }
+ function ReadStream$open() {
+ var that = this;
+ open(that.path, that.flags, that.mode, function(err, fd) {
+ if (err) {
+ if (that.autoClose)
+ that.destroy();
+ that.emit("error", err);
+ } else {
+ that.fd = fd;
+ that.emit("open", fd);
+ that.read();
+ }
+ });
+ }
+ function WriteStream(path, options) {
+ if (this instanceof WriteStream)
+ return fs$WriteStream.apply(this, arguments), this;
+ else
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
+ }
+ function WriteStream$open() {
+ var that = this;
+ open(that.path, that.flags, that.mode, function(err, fd) {
+ if (err) {
+ that.destroy();
+ that.emit("error", err);
+ } else {
+ that.fd = fd;
+ that.emit("open", fd);
+ }
+ });
+ }
+ function createReadStream(path, options) {
+ return new fs2.ReadStream(path, options);
+ }
+ function createWriteStream(path, options) {
+ return new fs2.WriteStream(path, options);
+ }
+ var fs$open = fs2.open;
+ fs2.open = open;
+ function open(path, flags, mode, cb) {
+ if (typeof mode === "function")
+ cb = mode, mode = null;
+ return go$open(path, flags, mode, cb);
+ function go$open(path2, flags2, mode2, cb2, startTime) {
+ return fs$open(path2, flags2, mode2, function(err, fd) {
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
+ enqueue([go$open, [path2, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
+ else {
+ if (typeof cb2 === "function")
+ cb2.apply(this, arguments);
+ }
+ });
+ }
+ }
+ return fs2;
+ }
+ function enqueue(elem) {
+ debug("ENQUEUE", elem[0].name, elem[1]);
+ fs[gracefulQueue].push(elem);
+ retry();
+ }
+ var retryTimer;
+ function resetQueue() {
+ var now = Date.now();
+ for (var i = 0;i < fs[gracefulQueue].length; ++i) {
+ if (fs[gracefulQueue][i].length > 2) {
+ fs[gracefulQueue][i][3] = now;
+ fs[gracefulQueue][i][4] = now;
+ }
+ }
+ retry();
+ }
+ function retry() {
+ clearTimeout(retryTimer);
+ retryTimer = undefined;
+ if (fs[gracefulQueue].length === 0)
+ return;
+ var elem = fs[gracefulQueue].shift();
+ var fn = elem[0];
+ var args = elem[1];
+ var err = elem[2];
+ var startTime = elem[3];
+ var lastTime = elem[4];
+ if (startTime === undefined) {
+ debug("RETRY", fn.name, args);
+ fn.apply(null, args);
+ } else if (Date.now() - startTime >= 60000) {
+ debug("TIMEOUT", fn.name, args);
+ var cb = args.pop();
+ if (typeof cb === "function")
+ cb.call(null, err);
+ } else {
+ var sinceAttempt = Date.now() - lastTime;
+ var sinceStart = Math.max(lastTime - startTime, 1);
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
+ if (sinceAttempt >= desiredDelay) {
+ debug("RETRY", fn.name, args);
+ fn.apply(null, args.concat([startTime]));
+ } else {
+ fs[gracefulQueue].push(elem);
+ }
+ }
+ if (retryTimer === undefined) {
+ retryTimer = setTimeout(retry, 0);
+ }
+ }
+});
-// ── Config helpers ─────────────────────────────────────────────────────────
+// node_modules/retry/lib/retry_operation.js
+var require_retry_operation = __commonJS((exports, module) => {
+ function RetryOperation(timeouts, options) {
+ if (typeof options === "boolean") {
+ options = { forever: options };
+ }
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
+ this._timeouts = timeouts;
+ this._options = options || {};
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
+ this._fn = null;
+ this._errors = [];
+ this._attempts = 1;
+ this._operationTimeout = null;
+ this._operationTimeoutCb = null;
+ this._timeout = null;
+ this._operationStart = null;
+ if (this._options.forever) {
+ this._cachedTimeouts = this._timeouts.slice(0);
+ }
+ }
+ module.exports = RetryOperation;
+ RetryOperation.prototype.reset = function() {
+ this._attempts = 1;
+ this._timeouts = this._originalTimeouts;
+ };
+ RetryOperation.prototype.stop = function() {
+ if (this._timeout) {
+ clearTimeout(this._timeout);
+ }
+ this._timeouts = [];
+ this._cachedTimeouts = null;
+ };
+ RetryOperation.prototype.retry = function(err) {
+ if (this._timeout) {
+ clearTimeout(this._timeout);
+ }
+ if (!err) {
+ return false;
+ }
+ var currentTime = new Date().getTime();
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
+ return false;
+ }
+ this._errors.push(err);
+ var timeout = this._timeouts.shift();
+ if (timeout === undefined) {
+ if (this._cachedTimeouts) {
+ this._errors.splice(this._errors.length - 1, this._errors.length);
+ this._timeouts = this._cachedTimeouts.slice(0);
+ timeout = this._timeouts.shift();
+ } else {
+ return false;
+ }
+ }
+ var self = this;
+ var timer = setTimeout(function() {
+ self._attempts++;
+ if (self._operationTimeoutCb) {
+ self._timeout = setTimeout(function() {
+ self._operationTimeoutCb(self._attempts);
+ }, self._operationTimeout);
+ if (self._options.unref) {
+ self._timeout.unref();
+ }
+ }
+ self._fn(self._attempts);
+ }, timeout);
+ if (this._options.unref) {
+ timer.unref();
+ }
+ return true;
+ };
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
+ this._fn = fn;
+ if (timeoutOps) {
+ if (timeoutOps.timeout) {
+ this._operationTimeout = timeoutOps.timeout;
+ }
+ if (timeoutOps.cb) {
+ this._operationTimeoutCb = timeoutOps.cb;
+ }
+ }
+ var self = this;
+ if (this._operationTimeoutCb) {
+ this._timeout = setTimeout(function() {
+ self._operationTimeoutCb();
+ }, self._operationTimeout);
+ }
+ this._operationStart = new Date().getTime();
+ this._fn(this._attempts);
+ };
+ RetryOperation.prototype.try = function(fn) {
+ console.log("Using RetryOperation.try() is deprecated");
+ this.attempt(fn);
+ };
+ RetryOperation.prototype.start = function(fn) {
+ console.log("Using RetryOperation.start() is deprecated");
+ this.attempt(fn);
+ };
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
+ RetryOperation.prototype.errors = function() {
+ return this._errors;
+ };
+ RetryOperation.prototype.attempts = function() {
+ return this._attempts;
+ };
+ RetryOperation.prototype.mainError = function() {
+ if (this._errors.length === 0) {
+ return null;
+ }
+ var counts = {};
+ var mainError = null;
+ var mainErrorCount = 0;
+ for (var i = 0;i < this._errors.length; i++) {
+ var error = this._errors[i];
+ var message = error.message;
+ var count = (counts[message] || 0) + 1;
+ counts[message] = count;
+ if (count >= mainErrorCount) {
+ mainError = error;
+ mainErrorCount = count;
+ }
+ }
+ return mainError;
+ };
+});
+
+// node_modules/retry/lib/retry.js
+var require_retry = __commonJS((exports) => {
+ var RetryOperation = require_retry_operation();
+ exports.operation = function(options) {
+ var timeouts = exports.timeouts(options);
+ return new RetryOperation(timeouts, {
+ forever: options && options.forever,
+ unref: options && options.unref,
+ maxRetryTime: options && options.maxRetryTime
+ });
+ };
+ exports.timeouts = function(options) {
+ if (options instanceof Array) {
+ return [].concat(options);
+ }
+ var opts = {
+ retries: 10,
+ factor: 2,
+ minTimeout: 1 * 1000,
+ maxTimeout: Infinity,
+ randomize: false
+ };
+ for (var key in options) {
+ opts[key] = options[key];
+ }
+ if (opts.minTimeout > opts.maxTimeout) {
+ throw new Error("minTimeout is greater than maxTimeout");
+ }
+ var timeouts = [];
+ for (var i = 0;i < opts.retries; i++) {
+ timeouts.push(this.createTimeout(i, opts));
+ }
+ if (options && options.forever && !timeouts.length) {
+ timeouts.push(this.createTimeout(i, opts));
+ }
+ timeouts.sort(function(a, b) {
+ return a - b;
+ });
+ return timeouts;
+ };
+ exports.createTimeout = function(attempt, opts) {
+ var random = opts.randomize ? Math.random() + 1 : 1;
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
+ timeout = Math.min(timeout, opts.maxTimeout);
+ return timeout;
+ };
+ exports.wrap = function(obj, options, methods) {
+ if (options instanceof Array) {
+ methods = options;
+ options = null;
+ }
+ if (!methods) {
+ methods = [];
+ for (var key in obj) {
+ if (typeof obj[key] === "function") {
+ methods.push(key);
+ }
+ }
+ }
+ for (var i = 0;i < methods.length; i++) {
+ var method = methods[i];
+ var original = obj[method];
+ obj[method] = function retryWrapper(original2) {
+ var op = exports.operation(options);
+ var args = Array.prototype.slice.call(arguments, 1);
+ var callback = args.pop();
+ args.push(function(err) {
+ if (op.retry(err)) {
+ return;
+ }
+ if (err) {
+ arguments[0] = op.mainError();
+ }
+ callback.apply(this, arguments);
+ });
+ op.attempt(function() {
+ original2.apply(obj, args);
+ });
+ }.bind(obj, original);
+ obj[method].options = options;
+ }
+ };
+});
+
+// node_modules/signal-exit/signals.js
+var require_signals = __commonJS((exports, module) => {
+ module.exports = [
+ "SIGABRT",
+ "SIGALRM",
+ "SIGHUP",
+ "SIGINT",
+ "SIGTERM"
+ ];
+ if (process.platform !== "win32") {
+ module.exports.push("SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
+ }
+ if (process.platform === "linux") {
+ module.exports.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT", "SIGUNUSED");
+ }
+});
+
+// node_modules/signal-exit/index.js
+var require_signal_exit = __commonJS((exports, module) => {
+ var process2 = global.process;
+ var processOk = function(process3) {
+ return process3 && typeof process3 === "object" && typeof process3.removeListener === "function" && typeof process3.emit === "function" && typeof process3.reallyExit === "function" && typeof process3.listeners === "function" && typeof process3.kill === "function" && typeof process3.pid === "number" && typeof process3.on === "function";
+ };
+ if (!processOk(process2)) {
+ module.exports = function() {
+ return function() {};
+ };
+ } else {
+ assert = __require("assert");
+ signals = require_signals();
+ isWin = /^win/i.test(process2.platform);
+ EE = __require("events");
+ if (typeof EE !== "function") {
+ EE = EE.EventEmitter;
+ }
+ if (process2.__signal_exit_emitter__) {
+ emitter = process2.__signal_exit_emitter__;
+ } else {
+ emitter = process2.__signal_exit_emitter__ = new EE;
+ emitter.count = 0;
+ emitter.emitted = {};
+ }
+ if (!emitter.infinite) {
+ emitter.setMaxListeners(Infinity);
+ emitter.infinite = true;
+ }
+ module.exports = function(cb, opts) {
+ if (!processOk(global.process)) {
+ return function() {};
+ }
+ assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
+ if (loaded === false) {
+ load();
+ }
+ var ev = "exit";
+ if (opts && opts.alwaysLast) {
+ ev = "afterexit";
+ }
+ var remove = function() {
+ emitter.removeListener(ev, cb);
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
+ unload();
+ }
+ };
+ emitter.on(ev, cb);
+ return remove;
+ };
+ unload = function unload2() {
+ if (!loaded || !processOk(global.process)) {
+ return;
+ }
+ loaded = false;
+ signals.forEach(function(sig) {
+ try {
+ process2.removeListener(sig, sigListeners[sig]);
+ } catch (er) {}
+ });
+ process2.emit = originalProcessEmit;
+ process2.reallyExit = originalProcessReallyExit;
+ emitter.count -= 1;
+ };
+ module.exports.unload = unload;
+ emit = function emit2(event, code, signal) {
+ if (emitter.emitted[event]) {
+ return;
+ }
+ emitter.emitted[event] = true;
+ emitter.emit(event, code, signal);
+ };
+ sigListeners = {};
+ signals.forEach(function(sig) {
+ sigListeners[sig] = function listener() {
+ if (!processOk(global.process)) {
+ return;
+ }
+ var listeners = process2.listeners(sig);
+ if (listeners.length === emitter.count) {
+ unload();
+ emit("exit", null, sig);
+ emit("afterexit", null, sig);
+ if (isWin && sig === "SIGHUP") {
+ sig = "SIGINT";
+ }
+ process2.kill(process2.pid, sig);
+ }
+ };
+ });
+ module.exports.signals = function() {
+ return signals;
+ };
+ loaded = false;
+ load = function load2() {
+ if (loaded || !processOk(global.process)) {
+ return;
+ }
+ loaded = true;
+ emitter.count += 1;
+ signals = signals.filter(function(sig) {
+ try {
+ process2.on(sig, sigListeners[sig]);
+ return true;
+ } catch (er) {
+ return false;
+ }
+ });
+ process2.emit = processEmit;
+ process2.reallyExit = processReallyExit;
+ };
+ module.exports.load = load;
+ originalProcessReallyExit = process2.reallyExit;
+ processReallyExit = function processReallyExit2(code) {
+ if (!processOk(global.process)) {
+ return;
+ }
+ process2.exitCode = code || 0;
+ emit("exit", process2.exitCode, null);
+ emit("afterexit", process2.exitCode, null);
+ originalProcessReallyExit.call(process2, process2.exitCode);
+ };
+ originalProcessEmit = process2.emit;
+ processEmit = function processEmit2(ev, arg) {
+ if (ev === "exit" && processOk(global.process)) {
+ if (arg !== undefined) {
+ process2.exitCode = arg;
+ }
+ var ret = originalProcessEmit.apply(this, arguments);
+ emit("exit", process2.exitCode, null);
+ emit("afterexit", process2.exitCode, null);
+ return ret;
+ } else {
+ return originalProcessEmit.apply(this, arguments);
+ }
+ };
+ }
+ var assert;
+ var signals;
+ var isWin;
+ var EE;
+ var emitter;
+ var unload;
+ var emit;
+ var sigListeners;
+ var loaded;
+ var load;
+ var originalProcessReallyExit;
+ var processReallyExit;
+ var originalProcessEmit;
+ var processEmit;
+});
+
+// node_modules/proper-lockfile/lib/mtime-precision.js
+var require_mtime_precision = __commonJS((exports, module) => {
+ var cacheSymbol = Symbol();
+ function probe(file, fs, callback) {
+ const cachedPrecision = fs[cacheSymbol];
+ if (cachedPrecision) {
+ return fs.stat(file, (err, stat) => {
+ if (err) {
+ return callback(err);
+ }
+ callback(null, stat.mtime, cachedPrecision);
+ });
+ }
+ const mtime = new Date(Math.ceil(Date.now() / 1000) * 1000 + 5);
+ fs.utimes(file, mtime, mtime, (err) => {
+ if (err) {
+ return callback(err);
+ }
+ fs.stat(file, (err2, stat) => {
+ if (err2) {
+ return callback(err2);
+ }
+ const precision = stat.mtime.getTime() % 1000 === 0 ? "s" : "ms";
+ Object.defineProperty(fs, cacheSymbol, { value: precision });
+ callback(null, stat.mtime, precision);
+ });
+ });
+ }
+ function getMtime(precision) {
+ let now = Date.now();
+ if (precision === "s") {
+ now = Math.ceil(now / 1000) * 1000;
+ }
+ return new Date(now);
+ }
+ exports.probe = probe;
+ exports.getMtime = getMtime;
+});
+
+// node_modules/proper-lockfile/lib/lockfile.js
+var require_lockfile = __commonJS((exports, module) => {
+ var path = __require("path");
+ var fs = require_graceful_fs();
+ var retry = require_retry();
+ var onExit = require_signal_exit();
+ var mtimePrecision = require_mtime_precision();
+ var locks = {};
+ function getLockFile(file, options) {
+ return options.lockfilePath || `${file}.lock`;
+ }
+ function resolveCanonicalPath(file, options, callback) {
+ if (!options.realpath) {
+ return callback(null, path.resolve(file));
+ }
+ options.fs.realpath(file, callback);
+ }
+ function acquireLock(file, options, callback) {
+ const lockfilePath = getLockFile(file, options);
+ options.fs.mkdir(lockfilePath, (err) => {
+ if (!err) {
+ return mtimePrecision.probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision2) => {
+ if (err2) {
+ options.fs.rmdir(lockfilePath, () => {});
+ return callback(err2);
+ }
+ callback(null, mtime, mtimePrecision2);
+ });
+ }
+ if (err.code !== "EEXIST") {
+ return callback(err);
+ }
+ if (options.stale <= 0) {
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
+ }
+ options.fs.stat(lockfilePath, (err2, stat) => {
+ if (err2) {
+ if (err2.code === "ENOENT") {
+ return acquireLock(file, { ...options, stale: 0 }, callback);
+ }
+ return callback(err2);
+ }
+ if (!isLockStale(stat, options)) {
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
+ }
+ removeLock(file, options, (err3) => {
+ if (err3) {
+ return callback(err3);
+ }
+ acquireLock(file, { ...options, stale: 0 }, callback);
+ });
+ });
+ });
+ }
+ function isLockStale(stat, options) {
+ return stat.mtime.getTime() < Date.now() - options.stale;
+ }
+ function removeLock(file, options, callback) {
+ options.fs.rmdir(getLockFile(file, options), (err) => {
+ if (err && err.code !== "ENOENT") {
+ return callback(err);
+ }
+ callback();
+ });
+ }
+ function updateLock(file, options) {
+ const lock2 = locks[file];
+ if (lock2.updateTimeout) {
+ return;
+ }
+ lock2.updateDelay = lock2.updateDelay || options.update;
+ lock2.updateTimeout = setTimeout(() => {
+ lock2.updateTimeout = null;
+ options.fs.stat(lock2.lockfilePath, (err, stat) => {
+ const isOverThreshold = lock2.lastUpdate + options.stale < Date.now();
+ if (err) {
+ if (err.code === "ENOENT" || isOverThreshold) {
+ return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" }));
+ }
+ lock2.updateDelay = 1000;
+ return updateLock(file, options);
+ }
+ const isMtimeOurs = lock2.mtime.getTime() === stat.mtime.getTime();
+ if (!isMtimeOurs) {
+ return setLockAsCompromised(file, lock2, Object.assign(new Error("Unable to update lock within the stale threshold"), { code: "ECOMPROMISED" }));
+ }
+ const mtime = mtimePrecision.getMtime(lock2.mtimePrecision);
+ options.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => {
+ const isOverThreshold2 = lock2.lastUpdate + options.stale < Date.now();
+ if (lock2.released) {
+ return;
+ }
+ if (err2) {
+ if (err2.code === "ENOENT" || isOverThreshold2) {
+ return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" }));
+ }
+ lock2.updateDelay = 1000;
+ return updateLock(file, options);
+ }
+ lock2.mtime = mtime;
+ lock2.lastUpdate = Date.now();
+ lock2.updateDelay = null;
+ updateLock(file, options);
+ });
+ });
+ }, lock2.updateDelay);
+ if (lock2.updateTimeout.unref) {
+ lock2.updateTimeout.unref();
+ }
+ }
+ function setLockAsCompromised(file, lock2, err) {
+ lock2.released = true;
+ if (lock2.updateTimeout) {
+ clearTimeout(lock2.updateTimeout);
+ }
+ if (locks[file] === lock2) {
+ delete locks[file];
+ }
+ lock2.options.onCompromised(err);
+ }
+ function lock(file, options, callback) {
+ options = {
+ stale: 1e4,
+ update: null,
+ realpath: true,
+ retries: 0,
+ fs,
+ onCompromised: (err) => {
+ throw err;
+ },
+ ...options
+ };
+ options.retries = options.retries || 0;
+ options.retries = typeof options.retries === "number" ? { retries: options.retries } : options.retries;
+ options.stale = Math.max(options.stale || 0, 2000);
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1000);
+ resolveCanonicalPath(file, options, (err, file2) => {
+ if (err) {
+ return callback(err);
+ }
+ const operation = retry.operation(options.retries);
+ operation.attempt(() => {
+ acquireLock(file2, options, (err2, mtime, mtimePrecision2) => {
+ if (operation.retry(err2)) {
+ return;
+ }
+ if (err2) {
+ return callback(operation.mainError());
+ }
+ const lock2 = locks[file2] = {
+ lockfilePath: getLockFile(file2, options),
+ mtime,
+ mtimePrecision: mtimePrecision2,
+ options,
+ lastUpdate: Date.now()
+ };
+ updateLock(file2, options);
+ callback(null, (releasedCallback) => {
+ if (lock2.released) {
+ return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
+ }
+ unlock(file2, { ...options, realpath: false }, releasedCallback);
+ });
+ });
+ });
+ });
+ }
+ function unlock(file, options, callback) {
+ options = {
+ fs,
+ realpath: true,
+ ...options
+ };
+ resolveCanonicalPath(file, options, (err, file2) => {
+ if (err) {
+ return callback(err);
+ }
+ const lock2 = locks[file2];
+ if (!lock2) {
+ return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
+ }
+ lock2.updateTimeout && clearTimeout(lock2.updateTimeout);
+ lock2.released = true;
+ delete locks[file2];
+ removeLock(file2, options, callback);
+ });
+ }
+ function check(file, options, callback) {
+ options = {
+ stale: 1e4,
+ realpath: true,
+ fs,
+ ...options
+ };
+ options.stale = Math.max(options.stale || 0, 2000);
+ resolveCanonicalPath(file, options, (err, file2) => {
+ if (err) {
+ return callback(err);
+ }
+ options.fs.stat(getLockFile(file2, options), (err2, stat) => {
+ if (err2) {
+ return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
+ }
+ return callback(null, !isLockStale(stat, options));
+ });
+ });
+ }
+ function getLocks() {
+ return locks;
+ }
+ onExit(() => {
+ for (const file in locks) {
+ const options = locks[file].options;
+ try {
+ options.fs.rmdirSync(getLockFile(file, options));
+ } catch (e) {}
+ }
+ });
+ exports.lock = lock;
+ exports.unlock = unlock;
+ exports.check = check;
+ exports.getLocks = getLocks;
+});
+
+// node_modules/proper-lockfile/lib/adapter.js
+var require_adapter = __commonJS((exports, module) => {
+ var fs = require_graceful_fs();
+ function createSyncFs(fs2) {
+ const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
+ const newFs = { ...fs2 };
+ methods.forEach((method) => {
+ newFs[method] = (...args) => {
+ const callback = args.pop();
+ let ret;
+ try {
+ ret = fs2[`${method}Sync`](...args);
+ } catch (err) {
+ return callback(err);
+ }
+ callback(null, ret);
+ };
+ });
+ return newFs;
+ }
+ function toPromise(method) {
+ return (...args) => new Promise((resolve, reject) => {
+ args.push((err, result) => {
+ if (err) {
+ reject(err);
+ } else {
+ resolve(result);
+ }
+ });
+ method(...args);
+ });
+ }
+ function toSync(method) {
+ return (...args) => {
+ let err;
+ let result;
+ args.push((_err, _result) => {
+ err = _err;
+ result = _result;
+ });
+ method(...args);
+ if (err) {
+ throw err;
+ }
+ return result;
+ };
+ }
+ function toSyncOptions(options) {
+ options = { ...options };
+ options.fs = createSyncFs(options.fs || fs);
+ if (typeof options.retries === "number" && options.retries > 0 || options.retries && typeof options.retries.retries === "number" && options.retries.retries > 0) {
+ throw Object.assign(new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
+ }
+ return options;
+ }
+ module.exports = {
+ toPromise,
+ toSync,
+ toSyncOptions
+ };
+});
-/**
- * Parse a simple YAML key: value file into an object.
- */
+// node_modules/proper-lockfile/index.js
+var require_proper_lockfile = __commonJS((exports, module) => {
+ var lockfile = require_lockfile();
+ var { toPromise, toSync, toSyncOptions } = require_adapter();
+ async function lock(file, options) {
+ const release = await toPromise(lockfile.lock)(file, options);
+ return toPromise(release);
+ }
+ function lockSync(file, options) {
+ const release = toSync(lockfile.lock)(file, toSyncOptions(options));
+ return toSync(release);
+ }
+ function unlock(file, options) {
+ return toPromise(lockfile.unlock)(file, options);
+ }
+ function unlockSync(file, options) {
+ return toSync(lockfile.unlock)(file, toSyncOptions(options));
+ }
+ function check(file, options) {
+ return toPromise(lockfile.check)(file, options);
+ }
+ function checkSync(file, options) {
+ return toSync(lockfile.check)(file, toSyncOptions(options));
+ }
+ module.exports = lock;
+ module.exports.lock = lock;
+ module.exports.unlock = unlock;
+ module.exports.lockSync = lockSync;
+ module.exports.unlockSync = unlockSync;
+ module.exports.check = check;
+ module.exports.checkSync = checkSync;
+});
+
+// src/openclaw/index.ts
+import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
+import { existsSync as existsSync5 } from "node:fs";
+import { join as join6 } from "node:path";
+
+// src/core/config.ts
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { join as join2 } from "node:path";
+
+// src/core/fs-atomic.ts
+import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from "node:fs";
+import { basename, dirname, join } from "node:path";
+function atomicWriteFileSync(target, contents) {
+ const dir = dirname(target);
+ mkdirSync(dir, { recursive: true });
+ const tmpName = `.${basename(target)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;
+ const tmpPath = join(dir, tmpName);
+ let fd = null;
+ try {
+ fd = openSync(tmpPath, "wx", 420);
+ const buf = Buffer.from(contents, "utf8");
+ let written = 0;
+ while (written < buf.byteLength) {
+ written += writeSync(fd, buf, written, buf.byteLength - written);
+ }
+ fsyncSync(fd);
+ closeSync(fd);
+ fd = null;
+ renameSync(tmpPath, target);
+ try {
+ const dfd = openSync(dir, "r");
+ try {
+ fsyncSync(dfd);
+ } finally {
+ closeSync(dfd);
+ }
+ } catch {}
+ } catch (err) {
+ if (fd !== null) {
+ try {
+ closeSync(fd);
+ } catch {}
+ }
+ try {
+ unlinkSync(tmpPath);
+ } catch {}
+ throw err;
+ }
+}
+
+// src/core/config.ts
+var SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"];
+function defaultConfigPath() {
+ const override = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ if (override)
+ return expandTilde(override);
+ const xdg = process.env["XDG_CONFIG_HOME"];
+ if (xdg)
+ return join2(expandTilde(xdg), "open-second-brain", "config.yaml");
+ return join2(homedir(), ".config", "open-second-brain", "config.yaml");
+}
function parseSimpleYaml(text) {
const data = {};
- for (const rawLine of text.split("\n")) {
+ for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
- if (!line || line.startsWith("#")) continue;
- if (!line.includes(":")) continue;
+ if (!line || line.startsWith("#"))
+ continue;
const idx = line.indexOf(":");
- let key = line.slice(0, idx).trim();
+ if (idx === -1)
+ continue;
+ const key = line.slice(0, idx).trim();
+ if (!key)
+ continue;
let value = line.slice(idx + 1).trim();
- // Strip surrounding quotes
- if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
- if (value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
- if (key) data[key] = value;
+ if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) {
+ value = value.slice(1, -1);
+ }
+ data[key] = value;
}
return data;
}
-
-/**
- * Redact values for keys that look like secrets.
- */
+function discoverConfig(path) {
+ const resolved = path ?? defaultConfigPath();
+ if (!isRegularFile(resolved)) {
+ return { path: resolved, exists: false, data: {} };
+ }
+ try {
+ const text = readFileSync(resolved, "utf8");
+ return { path: resolved, exists: true, data: parseSimpleYaml(text) };
+ } catch {
+ return { path: resolved, exists: false, data: {} };
+ }
+}
+function resolveTimezone(configPath) {
+ let name = process.env["VAULT_TIMEZONE"];
+ if (!name) {
+ name = discoverConfig(configPath).data["timezone"];
+ }
+ if (!name)
+ return null;
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: name });
+ return name;
+ } catch {
+ return null;
+ }
+}
+function resolveAgentName(configPath) {
+ const env = process.env["VAULT_AGENT_NAME"];
+ if (env)
+ return env;
+ const data = discoverConfig(configPath).data;
+ const value = data["agent_name"] ?? data["agentName"];
+ if (value)
+ return value;
+ return "agent";
+}
function redactMapping(data) {
const redacted = {};
for (const [key, value] of Object.entries(data)) {
@@ -99,540 +1682,966 @@ function redactMapping(data) {
}
return redacted;
}
-
-/**
- * Discover config from the vault or the default path.
- */
-function resolveVaultPath(api) {
- const config = api.pluginConfig || {};
- return config.vault || process.env.VAULT_DIR || ".";
+function expandTilde(p) {
+ if (p === "~")
+ return homedir();
+ if (p.startsWith("~/"))
+ return join2(homedir(), p.slice(2));
+ return p;
}
-
-/**
- * Resolve the IANA timezone the OpenClaw plugin should stamp Daily
- * entries in.
- *
- * Resolution order (first hit wins):
- * 1. ``api.pluginConfig.timezone`` β€” set by ``openclaw config set
- * plugins.entries.open-second-brain.config.timezone "..."``.
- * 2. ``VAULT_TIMEZONE`` env var (legacy, parity with the Python
- * side's resolver).
- * 3. ``null`` β€” caller falls back to the host's local clock.
- *
- * Whatever value comes out is validated against ``Intl.DateTimeFormat``
- * before being returned: an invalid IANA name (e.g. user typo) would
- * otherwise crash every ``event_log_append`` call inside
- * ``Intl.DateTimeFormat`` with ``RangeError``. Mirrors the Python
- * ``resolve_timezone`` helper, which also silently falls back when
- * ``ZoneInfo(name)`` raises β€” agents shouldn't lose entries because
- * of a typo in plugin config.
- */
-function resolveTimezone(api) {
- const config = api.pluginConfig || {};
- const candidate = config.timezone || process.env.VAULT_TIMEZONE || null;
- if (!candidate) return null;
+function isRegularFile(p) {
+ if (!existsSync(p))
+ return false;
try {
- new Intl.DateTimeFormat("en-US", { timeZone: candidate });
+ return statSync(p).isFile();
} catch {
- return null;
+ return false;
}
- return candidate;
}
-/**
- * Sanitize an LLM-supplied ``agent`` argument.
- *
- * Strips a leading ``@`` (so ``@hermes-vps-agent`` doesn't end up as
- * ``@@hermes-vps-agent`` once the event entry re-prefixes ``@``).
- * Treats common LLM self-name guesses (``agent``, ``assistant``,
- * ``claude``, ``gpt``, ...) as "no value" so a hallucinated identity
- * falls back to the resolved default instead of being written
- * verbatim into Daily.
- *
- * Returns ``null`` for empty or placeholder inputs. Mirrors
- * ``open_second_brain.mcp._normalize_agent_argument``.
- */
-function normalizeAgentArgument(value) {
- if (value == null) return null;
- const cleaned = String(value).trim().replace(/^@+/, "").trim();
- if (!cleaned) return null;
- if (PLACEHOLDER_AGENTS.has(cleaned.toLowerCase())) return null;
- return cleaned;
+// src/core/doctor.ts
+import {
+ existsSync as existsSync2,
+ mkdirSync as mkdirSync2,
+ openSync as openSync2,
+ readFileSync as readFileSync2,
+ rmSync,
+ statSync as statSync2,
+ writeSync as writeSync2,
+ closeSync as closeSync2
+} from "node:fs";
+import { dirname as dirname2, join as join3 } from "node:path";
+function checkVaultWriteable(vault) {
+ if (!existsSync2(vault)) {
+ return { name: "vault_writeable", ok: false, message: `vault directory missing: ${vault}` };
+ }
+ const probe = join3(vault, ".open-second-brain-doctor-test");
+ try {
+ const fd = openSync2(probe, "w");
+ closeSync2(fd);
+ rmSync(probe);
+ } catch (exc) {
+ return {
+ name: "vault_writeable",
+ ok: false,
+ message: `cannot write to vault: ${exc.message ?? exc}`
+ };
+ }
+ return { name: "vault_writeable", ok: true, message: `vault exists and is writable: ${vault}` };
}
-
-/**
- * Get UTC timestamp for frontmatter.
- */
-function utcTimestamp() {
- return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
+function checkConfigWriteable(config) {
+ let createdForCheck = false;
+ try {
+ mkdirSync2(dirname2(config), { recursive: true });
+ if (!existsSync2(config))
+ createdForCheck = true;
+ const fd = openSync2(config, "a");
+ writeSync2(fd, "");
+ closeSync2(fd);
+ if (createdForCheck)
+ rmSync(config);
+ } catch (exc) {
+ return {
+ name: "config_writeable",
+ ok: false,
+ message: `cannot write config ${config}: ${exc.message ?? exc}`
+ };
+ }
+ return { name: "config_writeable", ok: true, message: `config writable: ${config}` };
}
-
-/**
- * Compute relative path from vault to target.
- */
-function vaultRelpath(target, vault) {
+function loadJsonManifest(path, name) {
+ if (!isFile(path)) {
+ return {
+ result: { name, ok: false, message: `missing: ${path}` },
+ data: null
+ };
+ }
+ let data;
try {
- return relative(resolve(vault), resolve(target));
- } catch {
- return String(target);
+ data = JSON.parse(readFileSync2(path, "utf8"));
+ } catch (exc) {
+ return {
+ result: { name, ok: false, message: `invalid JSON: ${path} (${exc.message})` },
+ data: null
+ };
}
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
+ return {
+ result: { name, ok: false, message: `invalid manifest object: ${path}` },
+ data: null
+ };
+ }
+ return {
+ result: { name, ok: true, message: `valid: ${path}` },
+ data
+ };
}
-
-/**
- * Ensure a target path stays inside the vault.
- */
-function ensureInsideVault(target, vault) {
- const resolvedTarget = resolve(target);
- const resolvedVault = resolve(vault);
- if (!resolvedTarget.startsWith(resolvedVault + sep) && resolvedTarget !== resolvedVault) {
- throw new Error(`path escapes vault: ${target}`);
+function validateRequired(data, required) {
+ const problems = [];
+ for (const [field, expected] of required) {
+ if (!(field in data)) {
+ problems.push(`missing ${field}`);
+ continue;
+ }
+ const v = data[field];
+ const ok = isOfType(v, expected);
+ if (!ok) {
+ problems.push(`${field} must be ${typeName(expected)}`);
+ continue;
+ }
+ if (typeof v === "string" && v.trim() === "") {
+ problems.push(`${field} must not be empty`);
+ } else if (Array.isArray(v) && v.length === 0) {
+ problems.push(`${field} must not be empty`);
+ }
}
- return resolvedTarget;
+ return problems;
}
-
-// ── Health checks (pure JS) ────────────────────────────────────────────────
-
-async function checkVaultWritable(vaultPath) {
- if (!existsSync(vaultPath)) {
- return { name: "vault_writeable", ok: false, message: `vault directory missing: ${vaultPath}` };
+function isOfType(v, expected) {
+ if (expected === "string")
+ return typeof v === "string";
+ if (expected === "list")
+ return Array.isArray(v);
+ return typeof v === "string" || Array.isArray(v);
+}
+function typeName(expected) {
+ if (expected === "string")
+ return "str";
+ if (expected === "list")
+ return "list";
+ return expected.map((t) => t === "string" ? "str" : "list").join("/");
+}
+function checkCodexManifest(path) {
+ const { result, data } = loadJsonManifest(path, "codex_manifest");
+ if (!data)
+ return result;
+ const problems = validateRequired(data, [
+ ["name", "string"],
+ ["version", "string"],
+ ["description", "string"],
+ ["skills", "string"],
+ ["keywords", "list"]
+ ]);
+ if (problems.length > 0) {
+ return { name: "codex_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };
+ }
+ return { name: "codex_manifest", ok: true, message: `valid Codex manifest: ${path}` };
+}
+function checkClaudeManifest(path) {
+ const { result, data } = loadJsonManifest(path, "claude_manifest");
+ if (!data)
+ return result;
+ const problems = validateRequired(data, [
+ ["name", "string"],
+ ["version", "string"],
+ ["description", "string"]
+ ]);
+ for (const field of ["license", "repository", "homepage"]) {
+ if (field in data && typeof data[field] !== "string") {
+ problems.push(`${field} must be string`);
+ }
+ }
+ if ("keywords" in data) {
+ const kw = data["keywords"];
+ if (!Array.isArray(kw) || !kw.every((k) => typeof k === "string")) {
+ problems.push("keywords must be list of strings");
+ }
}
- const testPath = join(vaultPath, ".open-second-brain-doctor-test");
+ if ("author" in data) {
+ const author = data["author"];
+ const authorName = typeof author === "object" && author !== null ? author["name"] : null;
+ if (typeof author !== "object" || author === null || typeof authorName !== "string" || authorName.trim() === "") {
+ problems.push("author must be an object with a non-empty 'name' field " + "(legacy string form is rejected by Claude 2.x)");
+ }
+ }
+ if ("commands" in data) {
+ problems.push("embedded 'commands' array is deprecated β€” author slash commands " + "as Markdown files under commands/ at plugin root instead");
+ }
+ if (problems.length > 0) {
+ return { name: "claude_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };
+ }
+ return { name: "claude_manifest", ok: true, message: `valid Claude manifest: ${path}` };
+}
+function checkHermesManifest(path) {
+ if (!isFile(path)) {
+ return { name: "hermes_manifest", ok: false, message: `missing: ${path}` };
+ }
+ let text;
try {
- await writeFile(testPath, "", "utf8");
- await unlink(testPath);
+ text = readFileSync2(path, "utf8");
} catch (exc) {
- return { name: "vault_writeable", ok: false, message: `cannot write to vault: ${exc}` };
+ return {
+ name: "hermes_manifest",
+ ok: false,
+ message: `invalid text: ${path} (${exc.message ?? exc})`
+ };
+ }
+ const required = ["name", "version", "description"];
+ const missing = [];
+ for (const field of required) {
+ if (!new RegExp(`^${field}\\s*:`, "m").test(text))
+ missing.push(field);
}
- return { name: "vault_writeable", ok: true, message: `vault exists and is writable: ${vaultPath}` };
+ if (missing.length > 0) {
+ return {
+ name: "hermes_manifest",
+ ok: false,
+ message: `schema invalid: ${path} (missing ${missing.join(", ")})`
+ };
+ }
+ return { name: "hermes_manifest", ok: true, message: `readable Hermes manifest: ${path}` };
}
-
-async function checkDailyNotesDir(vaultPath) {
- const dailyDir = join(vaultPath, "Daily");
- if (existsSync(dailyDir)) {
- return { name: "daily_notes_dir", ok: true, message: `Daily notes directory exists: ${dailyDir}` };
+function checkOpenclawManifest(path) {
+ const { result, data } = loadJsonManifest(path, "openclaw_manifest");
+ if (!data)
+ return result;
+ const problems = [];
+ if (typeof data["id"] !== "string" || data["id"].trim() === "") {
+ problems.push("missing or empty field 'id'");
+ }
+ const schema = data["configSchema"];
+ if (typeof schema !== "object" || schema === null || Object.keys(schema).length === 0) {
+ problems.push("missing or empty field 'configSchema'");
+ }
+ if (problems.length > 0) {
+ return { name: "openclaw_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };
}
- return { name: "daily_notes_dir", ok: false, message: `Daily notes directory missing: ${dailyDir}` };
+ return { name: "openclaw_manifest", ok: true, message: `valid OpenClaw manifest: ${path}` };
}
-
-async function checkAIWikiDir(vaultPath) {
- const wikiDir = join(vaultPath, "AI Wiki");
- if (existsSync(wikiDir)) {
- return { name: "ai_wiki_dir", ok: true, message: `AI Wiki directory exists: ${wikiDir}` };
+function checkOpenclawInstallability(repoRoot) {
+ const results = [];
+ const pkgPath = join3(repoRoot, "package.json");
+ const { result, data } = loadJsonManifest(pkgPath, "openclaw_package_json");
+ results.push(result);
+ if (!data)
+ return results;
+ const oc = data["openclaw"] ?? {};
+ const extensions = oc["extensions"];
+ if (!Array.isArray(extensions) || extensions.length === 0) {
+ results.push({
+ name: "openclaw_package_json_extensions",
+ ok: false,
+ message: "package.json missing or empty openclaw.extensions array"
+ });
+ return results;
}
- return { name: "ai_wiki_dir", ok: false, message: `AI Wiki directory missing: ${wikiDir}` };
+ results.push({
+ name: "openclaw_package_json_extensions",
+ ok: true,
+ message: `package.json declares ${extensions.length} extension(s)`
+ });
+ for (const entry of extensions) {
+ if (typeof entry !== "string") {
+ results.push({
+ name: `openclaw_entry_invalid_${typeof entry}`,
+ ok: false,
+ message: `extension entry must be a string, got: ${typeof entry}`
+ });
+ continue;
+ }
+ const entryPath = join3(repoRoot, entry);
+ if (isFile(entryPath)) {
+ results.push({
+ name: `openclaw_entry_${entry}`,
+ ok: true,
+ message: `extension entry exists: ${entry}`
+ });
+ } else {
+ results.push({
+ name: `openclaw_entry_${entry}`,
+ ok: false,
+ message: `missing extension entry: ${entry}`
+ });
+ }
+ }
+ return results;
}
-
-async function checkNotesDir(vaultPath) {
- const notesDir = join(vaultPath, "AI Wiki", "notes");
- if (existsSync(notesDir)) {
- return { name: "notes_dir", ok: true, message: `Notes directory exists: ${notesDir}` };
+function doctor(opts) {
+ const results = [];
+ results.push(checkVaultWriteable(opts.vault));
+ if (opts.config)
+ results.push(checkConfigWriteable(opts.config));
+ if (opts.repoRoot) {
+ const root = opts.repoRoot;
+ results.push(checkClaudeManifest(join3(root, ".claude-plugin", "plugin.json")));
+ results.push(checkCodexManifest(join3(root, ".codex-plugin", "plugin.json")));
+ results.push(checkHermesManifest(join3(root, "plugins", "hermes", "plugin.yaml")));
+ results.push(checkOpenclawManifest(join3(root, "openclaw.plugin.json")));
+ results.push(...checkOpenclawInstallability(root));
+ }
+ return results;
+}
+function isFile(p) {
+ if (!existsSync2(p))
+ return false;
+ try {
+ return statSync2(p).isFile();
+ } catch {
+ return false;
}
- return { name: "notes_dir", ok: false, message: `Notes directory missing: ${notesDir}` };
}
-// ── Plugin entry ───────────────────────────────────────────────────────────
-
-export default definePluginEntry({
- register(api) {
- // ── second_brain_status ────────────────────────────────────────────
- api.registerTool(
- {
- name: "second_brain_status",
- description: "Report Open Second Brain configuration and vault status.",
- parameters: {
- type: "object",
- properties: {},
- additionalProperties: false,
- },
- async execute() {
- const pluginConfig = api.pluginConfig || {};
- const vault = resolveVaultPath(api);
-
- // Try to discover config from default path or env
- let configPath = null;
- let configExists = false;
- let configData = {};
+// src/core/event-log.ts
+var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
+import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3 } from "node:fs";
+import { join as join4 } from "node:path";
+var SECRET_ASSIGNMENT_RE = /\b(api[_-]?key|token|secret|password|credential)(\s*[:=]\s*)\S+/gi;
+var EVENT_RE = /^- (\d{2}:\d{2}) β€” @/;
+var DATE_RE = /^(\d{4})\.(\d{2})\.(\d{2})$/;
+var TIME_RE = /^(\d{2}):(\d{2})$/;
+function redactText(text) {
+ return text.replace(SECRET_ASSIGNMENT_RE, (_match, field, sep) => `${field}${sep}[REDACTED]`);
+}
+function currentDate(tz) {
+ const fmt = new Intl.DateTimeFormat("en-CA", {
+ timeZone: tz ?? undefined,
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit"
+ });
+ return fmt.format(new Date).replace(/-/g, ".");
+}
+function currentTime(tz) {
+ const parts = new Intl.DateTimeFormat("en-US", {
+ timeZone: tz ?? undefined,
+ hour: "2-digit",
+ minute: "2-digit",
+ hourCycle: "h23"
+ }).formatToParts(new Date);
+ const get = (type) => parts.find((p) => p.type === type).value;
+ return `${get("hour")}:${get("minute")}`;
+}
+function dailyNotePath(vaultDir, date) {
+ return join4(vaultDir, "Daily", `${validateEventDate(date)}.md`);
+}
+function newDailyNote(date) {
+ return `---
+formatted: false
+---
- const configOverride = process.env.OPEN_SECOND_BRAIN_CONFIG;
- const xdgHome = process.env.XDG_CONFIG_HOME;
- const defaultConfig = configOverride
- ? resolve(configOverride.replace(/^~/, process.env.HOME || ""))
- : xdgHome
- ? join(xdgHome, "open-second-brain", "config.yaml")
- : join(process.env.HOME || "/root", ".config", "open-second-brain", "config.yaml");
+# ${date}
- configPath = defaultConfig;
- if (existsSync(configPath)) {
- configExists = true;
- try {
- const text = await readFile(configPath, "utf8");
- configData = parseSimpleYaml(text);
- } catch {
- configExists = false;
- }
- }
+## Raw events
- const vaultExists = existsSync(vault);
- const configKeys = Object.keys(configData).sort();
+`;
+}
+function validateEventTime(value) {
+ const m = TIME_RE.exec(value);
+ if (!m) {
+ throw new Error("event time must use HH:MM 24-hour format");
+ }
+ const hour = parseInt(m[1], 10);
+ const minute = parseInt(m[2], 10);
+ if (hour > 23 || minute > 59) {
+ throw new Error("event time must use HH:MM 24-hour format");
+ }
+ return value;
+}
+function validateEventDate(value) {
+ const m = DATE_RE.exec(value);
+ if (!m) {
+ throw new Error("event date must use YYYY.MM.DD format");
+ }
+ const year = parseInt(m[1], 10);
+ const month = parseInt(m[2], 10);
+ const day = parseInt(m[3], 10);
+ const utc = new Date(Date.UTC(year, month - 1, day));
+ if (utc.getUTCFullYear() !== year || utc.getUTCMonth() !== month - 1 || utc.getUTCDate() !== day) {
+ throw new Error("event date must use YYYY.MM.DD format");
+ }
+ return value;
+}
+function insertEventEntry(content, entry) {
+ const marker = "## Raw events";
+ const idx = content.indexOf(marker);
+ if (idx === -1) {
+ return content.trimEnd() + `
- const result = {
- config_path: String(configPath),
- config_exists: configExists,
- config_keys: configKeys,
- config: redactMapping(configData),
- vault_path: vault,
- vault_exists: vaultExists,
- };
+` + marker + `
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
- },
- },
- { name: "second_brain_status" },
- );
+` + entry + `
+`;
+ }
+ const before = content.slice(0, idx);
+ let after = content.slice(idx + marker.length).replace(/^\n+/, "");
+ const lines = after.split(`
+`).filter((line) => line.trim());
+ const entryTime = entry.slice(2, 7);
+ let inserted = false;
+ const output = [];
+ for (const line of lines) {
+ const m = EVENT_RE.exec(line);
+ if (!inserted && m && m[1] > entryTime) {
+ output.push(entry);
+ inserted = true;
+ }
+ output.push(line);
+ }
+ if (!inserted)
+ output.push(entry);
+ let raw = output.join(`
+`);
+ if (raw)
+ raw += `
+`;
+ return before + marker + `
- // ── second_brain_query ─────────────────────────────────────────────
- api.registerTool(
- {
- name: "second_brain_query",
- description: "List vault pages with optional title substring filter.",
- parameters: {
- type: "object",
- properties: {
- pattern: {
- type: "string",
- description: "Optional case-insensitive substring matched against page titles.",
- },
- limit: {
- type: "integer",
- minimum: 1,
- maximum: 500,
- description: "Maximum number of matched pages to return (default 50).",
- },
- },
- additionalProperties: false,
- },
- async execute(_id, params) {
- const vault = resolveVaultPath(api);
- if (!existsSync(vault)) {
- throw new Error(`vault directory missing: ${vault}`);
- }
+` + raw;
+}
+async function appendEvent(vaultDir, agent, message, opts = {}) {
+ const tz = opts.tz ?? null;
+ const eventDate = validateEventDate(opts.date ?? currentDate(tz));
+ const eventTime = validateEventTime(opts.time ?? currentTime(tz));
+ const path = dailyNotePath(vaultDir, eventDate);
+ const cleanMessage = redactText(message).replace(/\r?\n/g, " ");
+ const entry = `- ${eventTime} β€” @${agent} β€” ${cleanMessage}`;
+ const dailyDir = join4(vaultDir, "Daily");
+ mkdirSync3(dailyDir, { recursive: true });
+ const release = await import_proper_lockfile.default.lock(dailyDir, {
+ retries: { retries: 30, factor: 1.2, minTimeout: 30, maxTimeout: 500 },
+ stale: 1e4,
+ realpath: false
+ });
+ try {
+ let content;
+ if (existsSync3(path)) {
+ content = readFileSync3(path, "utf8");
+ } else {
+ content = newDailyNote(eventDate);
+ }
+ if (!content.includes("## Raw events")) {
+ content = content.trimEnd() + `
- const pattern = params.pattern || null;
- const limit = typeof params.limit === "number" ? params.limit : 50;
+## Raw events
- if (limit < 1 || limit > 500) {
- throw new Error("argument 'limit' must be between 1 and 500");
- }
+`;
+ }
+ const updated = insertEventEntry(content, entry);
+ atomicWriteFileSync(path, updated);
+ } finally {
+ await release();
+ }
+ return path;
+}
- const { allPages, matched } = await listVaultPages(vault, pattern, limit);
+// src/core/identity-reminder.ts
+import { readFileSync as readFileSync4 } from "node:fs";
+import { dirname as dirname3, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+var TEMPLATE_PATH = resolve(dirname3(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");
+function loadReminderTemplate() {
+ try {
+ return readFileSync4(TEMPLATE_PATH, "utf8").trimEnd();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ throw new Error(`Failed to load identity reminder template from ${TEMPLATE_PATH}: ${message}`);
+ }
+}
+function buildReminder(agent) {
+ return loadReminderTemplate().replace(/\{agent\}/g, agent);
+}
- const pages = matched.map((p) => ({
- title: p.title,
- path: p.relativePath,
- metadata: p.metadata,
- }));
+// src/core/vault.ts
+import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync, statSync as statSync3, writeFileSync } from "node:fs";
+import { dirname as dirname4, join as join5, relative } from "node:path";
+var FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;
+var KEY_VALUE_RE = /^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$/;
+var PLAIN_SCALAR_RE = /^[A-Za-z0-9_./-](?:[A-Za-z0-9_./ -]*[A-Za-z0-9_./-])?$/;
+var SLUG_INVALID_RE = /[^a-z0-9]+/g;
+var SLUG_MAX_LEN = 64;
+var MEDIA_EXTENSIONS = new Set([
+ ".png",
+ ".jpg",
+ ".jpeg",
+ ".gif",
+ ".svg",
+ ".webp",
+ ".bmp",
+ ".tiff",
+ ".avif",
+ ".mp4",
+ ".webm",
+ ".ogv",
+ ".mov",
+ ".mkv",
+ ".avi",
+ ".mp3",
+ ".wav",
+ ".ogg",
+ ".flac",
+ ".m4a",
+ ".pdf"
+]);
+var DEFAULT_SKIP_DIRS = [".git", ".obsidian", ".trash", ".stversions"];
+var DEFAULT_SKIP_FILES = ["index.md", "log.md"];
+function parseFrontmatter(path) {
+ let text;
+ try {
+ text = readFileSync5(path, "utf8");
+ } catch {
+ return [{}, ""];
+ }
+ const match = FRONTMATTER_RE.exec(text);
+ if (!match) {
+ return [{}, text.trim()];
+ }
+ const fmBlock = match[1];
+ const body = text.slice(match[0].length).trim();
+ const metadata = {};
+ for (const rawLine of fmBlock.split(`
+`)) {
+ const line = rawLine.trim();
+ if (!line || line.startsWith("#"))
+ continue;
+ const kv = KEY_VALUE_RE.exec(line);
+ if (!kv)
+ continue;
+ const key = kv[1];
+ let value = kv[2].trim();
+ if (value.startsWith("[") && value.endsWith("]")) {
+ const inner = value.slice(1, -1).trim();
+ metadata[key] = inner ? splitInlineArray(inner) : [];
+ continue;
+ }
+ metadata[key] = stripQuotes(value);
+ }
+ return [metadata, body];
+}
+function writeFrontmatter(path, metadata, body) {
+ mkdirSync4(dirname4(path), { recursive: true });
+ const lines = ["---"];
+ for (const [key, value] of Object.entries(metadata)) {
+ lines.push(`${key}: ${formatYamlValue(value)}`);
+ }
+ lines.push("---");
+ if (body) {
+ lines.push("");
+ lines.push(body);
+ }
+ writeFileSync(path, lines.join(`
+`) + `
+`, "utf8");
+}
+function slugify(value) {
+ const lowered = value.trim().toLowerCase();
+ let slug = lowered.replace(SLUG_INVALID_RE, "-").replace(/^-+|-+$/g, "");
+ if (!slug)
+ slug = "note";
+ slug = slug.slice(0, SLUG_MAX_LEN).replace(/-+$/, "");
+ return slug || "note";
+}
+function listVaultPages(vaultDir, opts = {}) {
+ const skipDirs = new Set(opts.skipDirs ?? DEFAULT_SKIP_DIRS);
+ const skipFiles = new Set((opts.skipFiles ?? DEFAULT_SKIP_FILES).map((f) => f.toLowerCase()));
+ const pages = [];
+ walk(vaultDir, vaultDir, skipDirs, skipFiles, pages);
+ pages.sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase()));
+ return pages;
+}
+function walk(root, dir, skipDirs, skipFiles, out) {
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const full = join5(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (skipDirs.has(entry.name))
+ continue;
+ walk(root, full, skipDirs, skipFiles, out);
+ continue;
+ }
+ if (!entry.isFile())
+ continue;
+ if (!entry.name.toLowerCase().endsWith(".md"))
+ continue;
+ if (skipFiles.has(entry.name.toLowerCase()))
+ continue;
+ const rel = relative(root, full);
+ const parts = rel.split(/[\\/]/);
+ if (parts.some((p) => skipDirs.has(p)))
+ continue;
+ let meta;
+ try {
+ [meta] = parseFrontmatter(full);
+ } catch {
+ continue;
+ }
+ const titleVal = meta["title"];
+ const title = typeof titleVal === "string" && titleVal ? titleVal : stem(entry.name);
+ out.push({ title, path: full, metadata: meta });
+ }
+}
+function stem(filename) {
+ const dot = filename.lastIndexOf(".");
+ return dot > 0 ? filename.slice(0, dot) : filename;
+}
+function stripQuotes(s) {
+ if (s.length >= 2 && (s.startsWith('"') && s.endsWith('"') || s.startsWith("'") && s.endsWith("'"))) {
+ return s.slice(1, -1);
+ }
+ return s;
+}
+function splitInlineArray(inner) {
+ const out = [];
+ let current = "";
+ let inQuote = false;
+ let quoteChar = "";
+ for (let i = 0;i < inner.length; i++) {
+ const ch = inner[i];
+ if (inQuote) {
+ current += ch;
+ if (ch === quoteChar && inner[i - 1] !== "\\") {
+ inQuote = false;
+ quoteChar = "";
+ }
+ continue;
+ }
+ if (ch === '"' || ch === "'") {
+ inQuote = true;
+ quoteChar = ch;
+ current += ch;
+ continue;
+ }
+ if (ch === ",") {
+ out.push(stripQuotes(current.trim()));
+ current = "";
+ continue;
+ }
+ current += ch;
+ }
+ if (current.trim() !== "") {
+ out.push(stripQuotes(current.trim()));
+ }
+ return out;
+}
+function formatYamlScalar(value) {
+ const text = typeof value === "string" ? value : String(value);
+ if (text && PLAIN_SCALAR_RE.test(text) && !text.includes(": ") && !text.includes(" #")) {
+ return text;
+ }
+ const escaped = text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
+ return `"${escaped}"`;
+}
+function formatYamlValue(value) {
+ if (Array.isArray(value)) {
+ return "[" + value.map((item) => formatYamlScalar(item)).join(", ") + "]";
+ }
+ return formatYamlScalar(value);
+}
+// package.json
+var package_default = {
+ name: "open-second-brain",
+ version: "0.7.0",
+ type: "module",
+ private: false,
+ description: "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
+ license: "MIT",
+ homepage: "https://github.com/itechmeat/open-second-brain",
+ repository: {
+ type: "git",
+ url: "https://github.com/itechmeat/open-second-brain.git"
+ },
+ keywords: ["second-brain", "obsidian", "agents", "openclaw-plugin", "mcp"],
+ engines: {
+ bun: ">=1.1.0"
+ },
+ bin: {
+ o2b: "./scripts/o2b",
+ "vault-log": "./scripts/vault-log"
+ },
+ scripts: {
+ "build:openclaw": "bun build src/openclaw/index.ts --outfile openclaw/index.js --target=node --format=esm --external openclaw/plugin-sdk/plugin-entry",
+ test: "bun test",
+ typecheck: "tsc --noEmit",
+ "sync-version": "bun run scripts/sync-version.ts",
+ "sync-version:check": "bun run scripts/sync-version.ts --check"
+ },
+ files: [
+ "openclaw/",
+ "src/",
+ "skills/",
+ "scripts/",
+ "plugins/",
+ "openclaw.plugin.json",
+ "README.md",
+ "LICENSE",
+ "pyproject.toml"
+ ],
+ dependencies: {
+ "proper-lockfile": "^4.1.2"
+ },
+ devDependencies: {
+ "@types/bun": "^1.1.0",
+ "@types/node": "^22.0.0",
+ "@types/proper-lockfile": "^4.1.4",
+ typescript: "^5.5.0"
+ },
+ openclaw: {
+ extensions: ["./openclaw/index.js"]
+ }
+};
- const result = {
- vault_path: vault,
- total_pages: allPages.length,
- returned: pages.length,
- limit,
- pattern,
- pages,
- };
+// src/mcp/protocol.ts
+var SERVER_VERSION = package_default.version;
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
- },
- },
- { name: "second_brain_query" },
- );
+// src/mcp/tools.ts
+var PLACEHOLDER_AGENT_VALUES = new Set([
+ "agent",
+ "assistant",
+ "ai",
+ "ai-assistant",
+ "bot",
+ "chatbot",
+ "claude",
+ "claude-code",
+ "codex",
+ "codex-cli",
+ "codex-exec",
+ "copilot",
+ "gemini",
+ "gpt",
+ "gpt-4",
+ "gpt-5",
+ "hermes",
+ "llm",
+ "model",
+ "openai",
+ "openclaw",
+ "user"
+]);
- // ── second_brain_capture ───────────────────────────────────────────
- api.registerTool(
- {
- name: "second_brain_capture",
- description: "Write a new Markdown note to AI Wiki/notes/ with frontmatter.",
- parameters: {
- type: "object",
- properties: {
- title: {
- type: "string",
- description: "Human-readable note title.",
- },
- content: {
- type: "string",
- description: "Markdown body of the note.",
- },
- tags: {
- type: "array",
- items: { type: "string" },
- description: "Optional list of tag strings.",
- },
- overwrite: {
- type: "boolean",
- description: "Allow overwriting an existing note with the same slug.",
- },
+// src/openclaw/index.ts
+function resolveVaultPath(api) {
+ const cfg = api.pluginConfig ?? {};
+ return cfg.vault || process.env["VAULT_DIR"] || ".";
+}
+function resolveOpenclawTimezone(api) {
+ const cfg = api.pluginConfig ?? {};
+ const candidate = cfg.timezone || process.env["VAULT_TIMEZONE"] || null;
+ if (!candidate)
+ return null;
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: candidate });
+ return candidate;
+ } catch {
+ return null;
+ }
+}
+function resolveOpenclawAgent(api, argAgent) {
+ const normalized = normalizeAgentArg(argAgent);
+ if (normalized)
+ return normalized;
+ const cfg = api.pluginConfig ?? {};
+ return cfg.agentName ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();
+}
+function normalizeAgentArg(value) {
+ if (value === null || value === undefined)
+ return null;
+ const cleaned = String(value).trim().replace(/^@+/, "").trim();
+ if (!cleaned)
+ return null;
+ if (PLACEHOLDER_AGENT_VALUES.has(cleaned.toLowerCase()))
+ return null;
+ return cleaned;
+}
+function vaultRel(target, vault) {
+ if (target.startsWith(vault + "/"))
+ return target.slice(vault.length + 1);
+ return target;
+}
+var openclaw_default = definePluginEntry({
+ register(api) {
+ api.on("before_prompt_build", () => {
+ const cfg = api.pluginConfig ?? {};
+ const agent = normalizeAgentArg(cfg.agentName ?? null) ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();
+ if (agent === "agent")
+ return;
+ return { prependContext: buildReminder(agent) };
+ });
+ api.registerTool({
+ name: "second_brain_status",
+ description: "Report Open Second Brain configuration and vault status.",
+ parameters: { type: "object", properties: {}, additionalProperties: false },
+ async execute() {
+ const vault = resolveVaultPath(api);
+ const discovery = discoverConfig();
+ const result = {
+ config_path: discovery.path,
+ config_exists: discovery.exists,
+ config_keys: Object.keys(discovery.data).sort(),
+ config: redactMapping(discovery.data),
+ vault_path: vault,
+ vault_exists: existsSync5(vault)
+ };
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ }
+ });
+ api.registerTool({
+ name: "second_brain_query",
+ description: "List vault pages with optional title substring filter.",
+ parameters: {
+ type: "object",
+ properties: {
+ pattern: {
+ type: "string",
+ description: "Optional case-insensitive substring matched against page titles."
},
- required: ["title", "content"],
- additionalProperties: false,
- },
- async execute(_id, params) {
- const vault = resolveVaultPath(api);
- if (!existsSync(vault)) {
- throw new Error(`vault directory missing: ${vault}`);
- }
-
- const title = params.title;
- const content = params.content;
- const tags = params.tags || [];
- const overwrite = !!params.overwrite;
-
- if (!title || !title.trim()) {
- throw new Error("title must not be empty");
- }
- if (!content || !content.trim()) {
- throw new Error("content must not be empty");
- }
-
- const notesDir = join(vault, "AI Wiki", "notes");
- const slug = slugify(title);
- const target = join(notesDir, `${slug}.md`);
- ensureInsideVault(target, vault);
-
- await mkdir(notesDir, { recursive: true });
-
- const noteExisted = existsSync(target);
- if (noteExisted && !overwrite) {
- throw new Error(`note already exists: ${vaultRelpath(target, vault)}`);
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 500,
+ description: "Maximum number of matched pages to return (default 50)."
}
-
- const metadata = {
- title,
- type: "note",
- created: utcTimestamp(),
- };
- if (tags.length > 0) {
- metadata.tags = tags;
- }
-
- await writeFrontmatter(target, metadata, content.trim());
-
- const result = {
- path: vaultRelpath(target, vault),
- absolute_path: resolve(target),
- slug,
- overwritten: noteExisted && overwrite,
- };
-
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
},
+ additionalProperties: false
},
- { name: "second_brain_capture" },
- );
-
- // ── event_log_append ───────────────────────────────────────────────
- api.registerTool(
- {
- name: "event_log_append",
- description: "Append a single-line event to the daily Markdown event log.",
- parameters: {
- type: "object",
- properties: {
- message: {
- type: "string",
- description: "Single-line event message.",
- },
- agent: {
- type: "string",
- description: "Agent name (default 'agent').",
- },
- date: {
- type: "string",
- description: "Optional event date in YYYY.MM.DD format.",
- },
- time: {
- type: "string",
- description: "Optional event time in 24-hour HH:MM format.",
- },
+ async execute(_id, params) {
+ const vault = resolveVaultPath(api);
+ if (!existsSync5(vault))
+ throw new Error(`vault directory missing: ${vault}`);
+ const pattern = params["pattern"] ?? null;
+ const limit = typeof params["limit"] === "number" ? params["limit"] : 50;
+ if (limit < 1 || limit > 500)
+ throw new Error("argument 'limit' must be between 1 and 500");
+ const pages = listVaultPages(vault);
+ const needle = pattern ? pattern.toLowerCase() : null;
+ const matched = (needle === null ? pages : pages.filter((p) => p.title.toLowerCase().includes(needle))).slice(0, limit).map((p) => ({ title: p.title, path: vaultRel(p.path, vault), metadata: p.metadata }));
+ const result = {
+ vault_path: vault,
+ total_pages: pages.length,
+ returned: matched.length,
+ limit,
+ pattern,
+ pages: matched
+ };
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ }
+ });
+ api.registerTool({
+ name: "second_brain_capture",
+ description: "Write a new Markdown note to AI Wiki/notes/ with frontmatter.",
+ parameters: {
+ type: "object",
+ properties: {
+ title: { type: "string", description: "Human-readable note title." },
+ content: { type: "string", description: "Markdown body of the note." },
+ tags: {
+ type: "array",
+ items: { type: "string" },
+ description: "Optional list of tag strings."
},
- required: ["message"],
- additionalProperties: false,
- },
- async execute(_id, params) {
- const vault = resolveVaultPath(api);
- const message = params.message;
- if (!message) {
- throw new Error("missing required argument: message");
+ overwrite: {
+ type: "boolean",
+ description: "Allow overwriting an existing note with the same slug."
}
-
- const pluginConfig = api.pluginConfig || {};
- const configuredAgent = pluginConfig.agentName || null;
- const normalizedAgent = normalizeAgentArgument(params.agent);
- const agent =
- normalizedAgent ||
- process.env.VAULT_AGENT_NAME ||
- configuredAgent ||
- "agent";
- const date = params.date || null;
- const time = params.time || null;
- const tz = resolveTimezone(api);
-
- const result = await appendEvent(vault, agent, message, date, time, tz);
-
- return {
- content: [
- {
- type: "text",
- text: JSON.stringify(
- {
- path: vaultRelpath(result.path, vault),
- absolute_path: resolve(result.path),
- agent: result.agent,
- date: result.date,
- time: result.time,
- },
- null,
- 2,
- ),
- },
- ],
- };
},
+ required: ["title", "content"],
+ additionalProperties: false
},
- { name: "event_log_append" },
- );
-
- // ── vault_health ───────────────────────────────────────────────────
- api.registerTool(
- {
- name: "vault_health",
- description: "Run vault, config, and plugin manifest health checks.",
- parameters: {
- type: "object",
- properties: {
- repo: {
- type: "string",
- description: "Optional repository root to validate plugin manifests.",
- },
- },
- additionalProperties: false,
+ async execute(_id, params) {
+ const vault = resolveVaultPath(api);
+ if (!existsSync5(vault))
+ throw new Error(`vault directory missing: ${vault}`);
+ const title = params["title"] ?? "";
+ const content = params["content"] ?? "";
+ const tags = params["tags"] ?? [];
+ const overwrite = Boolean(params["overwrite"]);
+ if (!title.trim())
+ throw new Error("title must not be empty");
+ if (!content.trim())
+ throw new Error("content must not be empty");
+ const notesDir = join6(vault, "AI Wiki", "notes");
+ const slug = slugify(title);
+ const target = join6(notesDir, `${slug}.md`);
+ const noteExisted = existsSync5(target);
+ if (noteExisted && !overwrite) {
+ throw new Error(`note already exists: ${vaultRel(target, vault)}`);
+ }
+ const metadata = {
+ title,
+ type: "note",
+ created: new Date().toISOString().replace(/\.\d{3}Z$/, "Z")
+ };
+ if (tags.length > 0)
+ metadata["tags"] = tags;
+ writeFrontmatter(target, metadata, content.trim());
+ const result = {
+ path: vaultRel(target, vault),
+ absolute_path: target,
+ slug,
+ overwritten: noteExisted && overwrite
+ };
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ }
+ });
+ api.registerTool({
+ name: "event_log_append",
+ description: "Append a single-line event to the daily Markdown event log.",
+ parameters: {
+ type: "object",
+ properties: {
+ message: { type: "string", description: "Single-line event message." },
+ agent: { type: "string", description: "Agent name (default 'agent')." },
+ date: { type: "string", description: "Optional event date in YYYY.MM.DD format." },
+ time: { type: "string", description: "Optional event time in 24-hour HH:MM format." }
},
- async execute(_id, params) {
- const vault = resolveVaultPath(api);
- const checks = [];
-
- // Vault writable check
- checks.push(await checkVaultWritable(vault));
-
- // Daily notes dir
- checks.push(await checkDailyNotesDir(vault));
-
- // AI Wiki dir
- checks.push(await checkAIWikiDir(vault));
-
- // Notes dir
- checks.push(await checkNotesDir(vault));
-
- // Plugin manifest checks (only if repo provided)
- if (params.repo) {
- const repoRoot = params.repo;
-
- // Check openclaw.plugin.json
- const openclawManifestPath = join(repoRoot, "openclaw.plugin.json");
- if (existsSync(openclawManifestPath)) {
- try {
- const text = await readFile(openclawManifestPath, "utf8");
- const data = JSON.parse(text);
- if (data.id && data.configSchema) {
- checks.push({
- name: "openclaw_manifest",
- ok: true,
- message: `valid OpenClaw manifest: ${openclawManifestPath}`,
- });
- } else {
- checks.push({
- name: "openclaw_manifest",
- ok: false,
- message: `schema invalid: ${openclawManifestPath} (missing id or configSchema)`,
- });
- }
- } catch (exc) {
- checks.push({
- name: "openclaw_manifest",
- ok: false,
- message: `invalid JSON: ${openclawManifestPath} (${exc})`,
- });
- }
- } else {
- checks.push({
- name: "openclaw_manifest",
- ok: false,
- message: `missing: ${openclawManifestPath}`,
- });
- }
-
- // Check package.json
- const pkgPath = join(repoRoot, "package.json");
- if (existsSync(pkgPath)) {
- try {
- const data = JSON.parse(await readFile(pkgPath, "utf8"));
- const extensions = data?.openclaw?.extensions;
- if (Array.isArray(extensions) && extensions.length > 0) {
- checks.push({
- name: "openclaw_package_json_extensions",
- ok: true,
- message: `package.json declares ${extensions.length} extension(s)`,
- });
- // Check each extension file
- for (const entry of extensions) {
- const entryPath = join(repoRoot, entry);
- if (existsSync(entryPath)) {
- checks.push({
- name: `openclaw_entry_${entry}`,
- ok: true,
- message: `extension entry exists: ${entry}`,
- });
- } else {
- checks.push({
- name: `openclaw_entry_${entry}`,
- ok: false,
- message: `missing extension entry: ${entry}`,
- });
- }
- }
- } else {
- checks.push({
- name: "openclaw_package_json_extensions",
- ok: false,
- message: "package.json missing or empty openclaw.extensions array",
- });
- }
- } catch (exc) {
- checks.push({
- name: "openclaw_package_json",
- ok: false,
- message: `invalid JSON: ${pkgPath} (${exc})`,
- });
- }
- } else {
- checks.push({
- name: "openclaw_package_json",
- ok: false,
- message: `missing: ${pkgPath}`,
- });
- }
+ required: ["message"],
+ additionalProperties: false
+ },
+ async execute(_id, params) {
+ const vault = resolveVaultPath(api);
+ const message = params["message"];
+ if (!message || !message.trim()) {
+ throw new Error("missing required argument: message");
+ }
+ const argAgent = params["agent"] ?? null;
+ const date = params["date"] ?? null;
+ const time = params["time"] ?? null;
+ if (time)
+ validateEventTime(time);
+ const agent = resolveOpenclawAgent(api, argAgent);
+ const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();
+ const path = await appendEvent(vault, agent, message, { date, time, tz });
+ const result = {
+ path: vaultRel(path, vault),
+ absolute_path: path,
+ agent,
+ date,
+ time
+ };
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ }
+ });
+ api.registerTool({
+ name: "vault_health",
+ description: "Run vault, config, and plugin manifest health checks.",
+ parameters: {
+ type: "object",
+ properties: {
+ repo: {
+ type: "string",
+ description: "Optional repository root to validate plugin manifests."
}
-
- const result = {
- vault_path: vault,
- ok: checks.every((c) => c.ok),
- checks,
- };
-
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
},
+ additionalProperties: false
},
- { name: "vault_health" },
- );
- },
+ async execute(_id, params) {
+ const vault = resolveVaultPath(api);
+ const repoRoot = params["repo"] ?? null;
+ const results = doctor({ vault, repoRoot });
+ const result = {
+ vault_path: vault,
+ ok: results.every((r) => r.ok),
+ checks: results.map((r) => ({ name: r.name, ok: r.ok, message: r.message }))
+ };
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ }
+ });
+ }
});
+export {
+ openclaw_default as default
+};
diff --git a/openclaw/vault.js b/openclaw/vault.js
deleted file mode 100644
index dc703c80..00000000
--- a/openclaw/vault.js
+++ /dev/null
@@ -1,277 +0,0 @@
-/**
- * Pure JavaScript vault operations for Open Second Brain.
- *
- * All filesystem operations use `node:fs/promises` and `node:path`.
- * No native process module, no subprocess calls β€” passes the OpenClaw security scanner.
- *
- * Logic mirrors the Python implementation in `src/open_second_brain/vault.py`.
- */
-
-import { readdir, readFile, writeFile, mkdir } from "node:fs/promises";
-import { join, relative, sep, extname, basename, dirname, resolve, posix } from "node:path";
-import { existsSync } from "node:fs";
-
-// ── Constants ──────────────────────────────────────────────────────────────
-
-export const EXCLUDED_DIRS = new Set([
- ".git",
- ".obsidian",
- ".trash",
- ".stversions",
- "node_modules",
- "__pycache__",
- ".venv",
- "build",
- "dist",
- ".claude-plugin",
- ".codex-plugin",
-]);
-
-export const EXCLUDED_FILES = new Set([".DS_Store", ".gitkeep"]);
-
-const SKIP_FILE_NAMES = new Set(["index.md", "log.md"]);
-
-const FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;
-const KEY_VALUE_RE = /^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$/;
-const PLAIN_SCALAR_RE = /^[A-Za-z0-9_./-](?:[A-Za-z0-9_./ -]*[A-Za-z0-9_./-])?$/;
-
-const WIKILINK_RE = /\[\[([^\]|#]+)(?:[|#][^\]]*)?\]\]/g;
-const CODE_BLOCK_RE = /```[\s\S]*?```|`[^`]+`/g;
-
-const MEDIA_EXTENSIONS = new Set([
- ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".tiff", ".avif",
- ".mp4", ".webm", ".ogv", ".mov", ".mkv", ".avi",
- ".mp3", ".wav", ".ogg", ".flac", ".m4a",
- ".pdf",
-]);
-
-const SLUG_INVALID_RE = /[^a-z0-9]+/g;
-const SLUG_MAX_LEN = 64;
-
-// ── Frontmatter ────────────────────────────────────────────────────────────
-
-/**
- * Parse YAML-like frontmatter from markdown content.
- * Returns { frontmatter: {...}, body: "..." } or null if no frontmatter found.
- */
-export function parseFrontmatter(content) {
- const match = FRONTMATTER_RE.exec(content);
- if (!match) {
- return null;
- }
-
- const fmBlock = match[1];
- const body = content.slice(match[0].length).trim();
- const frontmatter = {};
-
- for (const rawLine of fmBlock.split("\n")) {
- const line = rawLine.trim();
- if (!line || line.startsWith("#")) continue;
-
- const kv = KEY_VALUE_RE.exec(line);
- if (kv) {
- const key = kv[1];
- let value = kv[2].trim();
- // Strip surrounding quotes
- if (
- (value.startsWith('"') && value.endsWith('"')) ||
- (value.startsWith("'") && value.endsWith("'"))
- ) {
- value = value.slice(1, -1);
- }
- // Parse inline YAML arrays: [a, b, c]
- if (value.startsWith("[") && value.endsWith("]")) {
- const inner = value.slice(1, -1).trim();
- if (inner) {
- frontmatter[key] = inner.split(",").map((s) => {
- s = s.trim();
- if (
- (s.startsWith('"') && s.endsWith('"')) ||
- (s.startsWith("'") && s.endsWith("'"))
- ) {
- s = s.slice(1, -1);
- }
- return s;
- });
- } else {
- frontmatter[key] = [];
- }
- } else {
- frontmatter[key] = value;
- }
- }
- }
-
- return { frontmatter, body };
-}
-
-/**
- * Format a YAML scalar value, quoting if necessary.
- */
-function formatYamlScalar(value) {
- const text = String(value);
- if (
- text &&
- PLAIN_SCALAR_RE.test(text) &&
- !text.includes(": ") &&
- !text.includes(" #")
- ) {
- return text;
- }
- const escaped = text
- .replace(/\\/g, "\\\\")
- .replace(/"/g, '\\"')
- .replace(/\n/g, "\\n")
- .replace(/\r/g, "\\r")
- .replace(/\t/g, "\\t");
- return `"${escaped}"`;
-}
-
-/**
- * Format a YAML value (scalar or array).
- */
-function formatYamlValue(value) {
- if (Array.isArray(value)) {
- return "[" + value.map((item) => formatYamlScalar(item)).join(", ") + "]";
- }
- return formatYamlScalar(value);
-}
-
-/**
- * Write a markdown file with YAML frontmatter and body.
- * Creates parent directories if needed.
- */
-export async function writeFrontmatter(filePath, frontmatter, body) {
- await mkdir(dirname(filePath), { recursive: true });
-
- const lines = ["---"];
- for (const [key, value] of Object.entries(frontmatter)) {
- lines.push(`${key}: ${formatYamlValue(value)}`);
- }
- lines.push("---");
-
- if (body) {
- lines.push("");
- lines.push(body);
- }
-
- await writeFile(filePath, lines.join("\n") + "\n", "utf8");
-}
-
-// ── Slugify ────────────────────────────────────────────────────────────────
-
-/**
- * Convert title to URL-safe slug.
- * Lowercase, replace non-alphanumeric with dashes, trim to max length.
- */
-export function slugify(title) {
- const lowered = title.trim().toLowerCase();
- let slug = lowered.replace(SLUG_INVALID_RE, "-").replace(/^-+|-+$/g, "");
- if (!slug) slug = "note";
- slug = slug.slice(0, SLUG_MAX_LEN).replace(/-+$/, "");
- return slug || "note";
-}
-
-// ── Wikilinks ──────────────────────────────────────────────────────────────
-
-/**
- * Extract [[wikilinks]] from markdown content.
- * Skips links inside code blocks and media file targets.
- * Returns unique targets in order of appearance.
- */
-export function extractWikilinks(content) {
- // Mask code blocks
- const masked = content.replace(CODE_BLOCK_RE, " ");
-
- const seen = new Set();
- const result = [];
-
- // Reset the global regex
- WIKILINK_RE.lastIndex = 0;
- let match;
- while ((match = WIKILINK_RE.exec(masked)) !== null) {
- const target = match[1];
- const ext = extname(target).toLowerCase();
- if (MEDIA_EXTENSIONS.has(ext)) continue;
- if (!seen.has(target)) {
- seen.add(target);
- result.push(target);
- }
- }
-
- return result;
-}
-
-// ── Vault page listing ─────────────────────────────────────────────────────
-
-/**
- * Recursively list all markdown pages in a vault directory.
- * Returns [{ title, path, relativePath, metadata }].
- * Sorted alphabetically by title (case-insensitive).
- */
-export async function listVaultPages(vaultPath, pattern = null, limit = 50) {
- const pages = [];
-
- async function walk(dir) {
- let entries;
- try {
- entries = await readdir(dir, { withFileTypes: true });
- } catch {
- return;
- }
-
- for (const entry of entries) {
- if (entry.isDirectory()) {
- if (EXCLUDED_DIRS.has(entry.name)) continue;
- await walk(join(dir, entry.name));
- } else if (entry.isFile() && entry.name.endsWith(".md")) {
- if (EXCLUDED_FILES.has(entry.name)) continue;
- if (SKIP_FILE_NAMES.has(entry.name.toLowerCase())) continue;
-
- const fullPath = join(dir, entry.name);
- const relPath = relative(vaultPath, fullPath);
- // Skip if any directory component is excluded
- const parts = relPath.split(sep);
- if (parts.some((p) => EXCLUDED_DIRS.has(p))) continue;
-
- let content;
- try {
- content = await readFile(fullPath, "utf8");
- } catch {
- continue;
- }
-
- const parsed = parseFrontmatter(content);
- const metadata = parsed ? parsed.frontmatter : {};
- const title =
- metadata && metadata.title ? metadata.title : basename(entry.name, ".md");
-
- pages.push({
- title,
- path: fullPath,
- relativePath: relPath,
- metadata: metadata || {},
- });
- }
- }
- }
-
- await walk(vaultPath);
-
- // Sort by title case-insensitive
- pages.sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase()));
-
- // Apply pattern filter
- let matched = pages;
- if (pattern) {
- const needle = pattern.toLowerCase();
- matched = pages.filter((p) => p.title.toLowerCase().includes(needle));
- }
-
- // Apply limit
- if (limit && matched.length > limit) {
- matched = matched.slice(0, limit);
- }
-
- return { allPages: pages, matched };
-}
diff --git a/package.json b/package.json
index 12b06986..be9901d1 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.6.2",
+ "version": "0.7.0",
"type": "module",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
@@ -11,6 +11,20 @@
"url": "https://github.com/itechmeat/open-second-brain.git"
},
"keywords": ["second-brain", "obsidian", "agents", "openclaw-plugin", "mcp"],
+ "engines": {
+ "bun": ">=1.1.0"
+ },
+ "bin": {
+ "o2b": "./scripts/o2b",
+ "vault-log": "./scripts/vault-log"
+ },
+ "scripts": {
+ "build:openclaw": "bun build src/openclaw/index.ts --outfile openclaw/index.js --target=node --format=esm --external openclaw/plugin-sdk/plugin-entry",
+ "test": "bun test",
+ "typecheck": "tsc --noEmit",
+ "sync-version": "bun run scripts/sync-version.ts",
+ "sync-version:check": "bun run scripts/sync-version.ts --check"
+ },
"files": [
"openclaw/",
"src/",
@@ -22,6 +36,15 @@
"LICENSE",
"pyproject.toml"
],
+ "dependencies": {
+ "proper-lockfile": "^4.1.2"
+ },
+ "devDependencies": {
+ "@types/bun": "^1.1.0",
+ "@types/node": "^22.0.0",
+ "@types/proper-lockfile": "^4.1.4",
+ "typescript": "^5.5.0"
+ },
"openclaw": {
"extensions": ["./openclaw/index.js"]
}
diff --git a/plugin.yaml b/plugin.yaml
index 3d9b41a6..f5128296 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.6.2"
+version: "0.7.0"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
new file mode 100644
index 00000000..d8851dfc
--- /dev/null
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -0,0 +1,23 @@
+{
+ "name": "open-second-brain",
+ "version": "0.7.0",
+ "description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
+ "author": {
+ "name": "Open Second Brain contributors",
+ "url": "https://github.com/itechmeat/open-second-brain"
+ },
+ "homepage": "https://github.com/itechmeat/open-second-brain",
+ "repository": "https://github.com/itechmeat/open-second-brain",
+ "license": "MIT",
+ "keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"],
+ "skills": "./skills",
+ "interface": {
+ "displayName": "Open Second Brain",
+ "shortDescription": "Per-vault second brain for AI agents using Obsidian-compatible Markdown",
+ "longDescription": "Open Second Brain gives every agent on this machine a shared, append-only event log and a curated AI Wiki space inside a portable Markdown vault. The plugin exposes vault status, query, capture, event-log append, and vault health tools via MCP, and injects a per-turn identity reminder so agents reliably log durable artifacts.",
+ "developerName": "Open Second Brain contributors",
+ "category": "Productivity",
+ "capabilities": ["Read", "Write"],
+ "defaultPrompt": ["Capture this finding to the second brain"]
+ }
+}
diff --git a/plugins/codex/skills b/plugins/codex/skills
new file mode 120000
index 00000000..5dcab58e
--- /dev/null
+++ b/plugins/codex/skills
@@ -0,0 +1 @@
+../../skills
\ No newline at end of file
diff --git a/plugins/hermes/__init__.py b/plugins/hermes/__init__.py
index 6769346d..5ab07aa9 100644
--- a/plugins/hermes/__init__.py
+++ b/plugins/hermes/__init__.py
@@ -1,162 +1,149 @@
-"""Hermes adapter for Open Second Brain runtime health checks.
-
-The adapter intentionally avoids depending on Hermes internals. It exposes small,
-deterministic health helpers that Hermes (or any other runtime) can call directly,
-and ``register(ctx)`` makes a best-effort attempt to attach the health check to
-common plugin context shapes.
+"""Hermes Python shim for Open Second Brain.
+
+Most of Open Second Brain runs as a Bun-based MCP server on stdio (registered
+via ``hermes mcp_servers`` in ``~/.hermes/config.yaml``). The MCP route is the
+only one Hermes needs for the five tools (``second_brain_status``,
+``second_brain_query``, ``second_brain_capture``, ``event_log_append``,
+``vault_health``).
+
+This file exists for one Hermes-specific feature that MCP cannot replicate:
+the per-turn ``pre_llm_call`` hook, which appends a short identity reminder
+to the user message of every turn. Doing it server-side (in MCP
+``initialize.instructions``) only fires once per session, not per turn β€” long
+sessions drift away from the reminder.
+
+The shim has no dependency on the TypeScript core. It reads ``agent_name``
+from the same plugin config the TS code writes (``~/.config/open-second-brain/config.yaml``).
"""
from __future__ import annotations
-import json
import os
import re
from pathlib import Path
-from typing import Any, Callable
+from typing import Any
+PLUGIN_NAME = "open-second-brain"
-HealthReport = dict[str, Any]
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+_TEMPLATE_PATH = _REPO_ROOT / "templates" / "identity-reminder.txt"
+_AGENT_LINE_RE = re.compile(r"^\s*(agent_name|agentName)\s*:\s*['\"]?([^'\"\n]+?)['\"]?\s*$", re.MULTILINE)
-def _repo_root() -> Path:
- return Path(__file__).resolve().parents[2]
+def _load_reminder_template() -> str:
+ """Read the shared reminder template.
-def _check_file(path: Path, *, executable: bool = False) -> HealthReport:
- ok = path.is_file()
- message = "present" if ok else "missing"
- if ok and executable and not os.access(path, os.X_OK):
- ok = False
- message = "not executable"
- return {"ok": ok, "path": str(path), "message": message}
+ The TypeScript core (`src/core/identity-reminder.ts`) reads the same
+ file. Keeping one source on disk avoids manual mirroring of the wording
+ between Python and TS. CI fails the build if the file is missing.
+ """
+ return _TEMPLATE_PATH.read_text(encoding="utf-8").rstrip()
-def _check_json(path: Path) -> HealthReport:
- base = _check_file(path)
- if not base["ok"]:
- return base
- try:
- data = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
- return {"ok": False, "path": str(path), "message": f"invalid JSON: {exc}"}
- if isinstance(data, dict):
- return {"ok": True, "path": str(path), "message": "valid JSON object"}
- return {"ok": False, "path": str(path), "message": "JSON is not an object"}
-
-
-def _check_text_manifest(path: Path) -> HealthReport:
- base = _check_file(path)
- if not base["ok"]:
- return base
+def _config_path() -> Path:
+ override = os.environ.get("OPEN_SECOND_BRAIN_CONFIG")
+ if override:
+ return Path(override).expanduser()
+ xdg = os.environ.get("XDG_CONFIG_HOME")
+ if xdg:
+ return Path(xdg).expanduser() / "open-second-brain" / "config.yaml"
+ return Path.home() / ".config" / "open-second-brain" / "config.yaml"
+
+
+def _resolve_agent_name() -> str:
+ """Resolve the agent identity used by ``pre_llm_call``.
+
+ Order: ``VAULT_AGENT_NAME`` env, ``agent_name``/``agentName`` in plugin
+ config, then the literal placeholder ``"agent"``. Mirrors
+ ``resolveAgentName`` in ``src/core/config.ts``.
+ """
+ env_value = os.environ.get("VAULT_AGENT_NAME")
+ if env_value:
+ return env_value
+ path = _config_path()
+ if not path.is_file():
+ return "agent"
try:
text = path.read_text(encoding="utf-8")
- except (OSError, UnicodeDecodeError) as exc:
- return {"ok": False, "path": str(path), "message": f"unreadable: {exc}"}
- required = ("name", "version", "description")
- missing = [field for field in required if not re.search(rf"^{field}\s*:", text, re.MULTILINE)]
- if missing:
- return {"ok": False, "path": str(path), "message": "missing fields: " + ", ".join(missing)}
- return {"ok": True, "path": str(path), "message": "readable manifest"}
+ except OSError:
+ return "agent"
+ match = _AGENT_LINE_RE.search(text)
+ if match:
+ value = match.group(2).strip()
+ if value:
+ return value
+ return "agent"
+
+
+def on_pre_llm_call(**_kwargs: Any) -> dict[str, str] | None:
+ """Inject identity context into the current turn's user message.
+
+ Hermes ``pre_llm_call`` contract: callbacks receive turn metadata and may
+ return ``{"context": "..."}`` β€” Hermes appends the value to the user
+ message of this turn (system prompt left untouched, so the cache prefix
+ is preserved). Returns ``None`` when no identity is configured, to avoid
+ leaking the literal ``@agent`` placeholder into Daily.
+ """
+ agent = _resolve_agent_name()
+ if agent == "agent":
+ return None
+ template = _load_reminder_template()
+ return {"context": template.replace("{agent}", agent)}
-def health(repo_root: str | Path | None = None) -> HealthReport:
- """Return deterministic Open Second Brain plugin health.
+def health(repo_root: str | Path | None = None) -> dict[str, Any]:
+ """Minimal data-only readiness check.
- The report is data-only so it is safe to serialize in runtimes that do not
- know this package. No background processes are started and no files are
- written.
+ Verifies the artifacts Hermes itself depends on (the runner script and
+ the OpenClaw bundle that the same repo produces). The TypeScript ``o2b
+ doctor`` covers everything else; runtimes that want the full suite
+ should call it via the MCP ``vault_health`` tool.
"""
-
- root = Path(repo_root) if repo_root is not None else _repo_root()
+ root = Path(repo_root) if repo_root is not None else Path(__file__).resolve().parents[2]
checks = {
- "hermes_manifest": _check_text_manifest(root / "plugins" / "hermes" / "plugin.yaml"),
- "claude_manifest": _check_json(root / ".claude-plugin" / "plugin.json"),
- "codex_manifest": _check_json(root / ".codex-plugin" / "plugin.json"),
- "openclaw_manifest": _check_json(root / "openclaw.plugin.json"),
"o2b_script": _check_file(root / "scripts" / "o2b", executable=True),
- "vault_log_script": _check_file(root / "scripts" / "vault-log", executable=True),
+ "openclaw_bundle": _check_file(root / "openclaw" / "index.js"),
+ "package_json": _check_file(root / "package.json"),
}
- ok = all(bool(check["ok"]) for check in checks.values())
- return {"name": "open-second-brain", "ok": ok, "checks": checks}
+ ok = all(c["ok"] for c in checks.values())
+ return {"name": PLUGIN_NAME, "ok": ok, "checks": checks}
-def check_health(repo_root: str | Path | None = None) -> HealthReport:
- """Compatibility alias for runtimes expecting a check_health callable."""
-
+def check_health(repo_root: str | Path | None = None) -> dict[str, Any]:
+ """Compatibility alias for runtimes expecting ``check_health``."""
return health(repo_root=repo_root)
-def _attach_health(ctx: Any, callback: Callable[[], HealthReport]) -> bool:
- for method_name in ("register_health_check", "add_health_check", "register_check"):
- method = getattr(ctx, method_name, None)
- if callable(method):
- try:
- method("open-second-brain", callback)
- except TypeError:
- method(callback)
- return True
-
- health_checks = getattr(ctx, "health_checks", None)
- if isinstance(health_checks, dict):
- health_checks["open-second-brain"] = callback
- return True
- if isinstance(health_checks, list):
- health_checks.append(("open-second-brain", callback))
- return True
-
- try:
- setattr(ctx, "open_second_brain_health", callback)
- except Exception:
- return False
- return True
-
-
-_PRE_LLM_CALL_TEMPLATE = (
- "[open-second-brain] Identity: @{agent}. After producing a durable "
- "artifact β€” code shipped, bug fixed, config or deployment change, "
- "instruction-file edit, content artifact created, research finding "
- "or design decision reached, investigation that surfaced a fact "
- "future sessions should know β€” call the event_log_append tool with "
- "the plain event description as `message`. The server prepends "
- "timestamp and `@{agent}` automatically, do not include them "
- "yourself. Skip pure discussion, exploration, read-only queries, "
- "and planning that hasn't yet produced an artifact."
-)
-
-
-def on_pre_llm_call(**kwargs: Any) -> dict[str, str] | None:
- """Plugin context injected into the current turn's user message.
-
- The Hermes ``pre_llm_call`` hook contract: callbacks receive the turn
- metadata as keyword arguments and may return ``{"context": "..."}`` β€”
- Hermes appends the value to the user message of this turn (system prompt
- is left untouched, so the cache prefix is preserved).
-
- Returns ``None`` (skipping injection) when the agent identity is not
- configured, because the only thing we'd otherwise inject is the literal
- ``@agent`` placeholder, which is worse than silence.
- """
- try:
- from open_second_brain.config import resolve_agent_name
- except ImportError:
- return None
- agent = resolve_agent_name()
- if agent == "agent":
- return None
- return {"context": _PRE_LLM_CALL_TEMPLATE.format(agent=agent)}
+def _check_file(path: Path, *, executable: bool = False) -> dict[str, Any]:
+ ok = path.is_file()
+ message = "present" if ok else "missing"
+ if ok and executable and not os.access(path, os.X_OK):
+ ok = False
+ message = "not executable"
+ return {"ok": ok, "path": str(path), "message": message}
def register(ctx: Any) -> None:
- """Register Hermes-side hooks when the context supports them.
+ """Best-effort registration of the health check and the pre_llm_call hook.
- Best-effort: unsupported context shapes are ignored without raising, so a
- minimal/test ``ctx`` won't break plugin loading.
+ Unsupported context shapes are ignored without raising so a minimal /
+ test ``ctx`` won't break plugin loading.
"""
-
- try:
- _attach_health(ctx, check_health)
- except Exception:
- pass
+ for method_name in ("register_health_check", "add_health_check", "register_check"):
+ method = getattr(ctx, method_name, None)
+ if callable(method):
+ try:
+ method(PLUGIN_NAME, check_health)
+ except TypeError:
+ method(check_health)
+ break
+ else:
+ health_checks = getattr(ctx, "health_checks", None)
+ if isinstance(health_checks, dict):
+ health_checks[PLUGIN_NAME] = check_health
+ elif isinstance(health_checks, list):
+ health_checks.append((PLUGIN_NAME, check_health))
register_hook = getattr(ctx, "register_hook", None)
if callable(register_hook):
@@ -164,4 +151,3 @@ def register(ctx: Any) -> None:
register_hook("pre_llm_call", on_pre_llm_call)
except Exception:
pass
- return None
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index f2e593dc..3c80f1b4 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.6.2"
+version: "0.7.0"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index 47124c71..04206414 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -2,21 +2,22 @@
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"
+# Open Second Brain v0.7+ runs on the Bun TypeScript runtime; the canonical
+# version lives in package.json. This pyproject.toml exists only so the
+# Hermes Python shim (`plugins/hermes/__init__.py`) and the root entry
+# (`__init__.py`) are addressable as a Python package β€” Hermes loads them
+# in-process as part of its plugin lifecycle. No runtime dependencies, no
+# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "0.6.2"
-description = "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw."
+version = "0.7.0"
+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"
license = "MIT"
authors = [{ name = "Open Second Brain contributors" }]
-keywords = ["second-brain", "obsidian", "agents", "skills", "event-log"]
+keywords = ["second-brain", "obsidian", "agents", "hermes-plugin"]
dependencies = []
-[project.scripts]
-o2b = "open_second_brain.cli:main"
-vault-log = "open_second_brain.vault_log:main"
-o2b-mcp = "open_second_brain.mcp:main"
-
-[tool.setuptools.packages.find]
-where = ["src"]
+[tool.setuptools]
+packages = ["plugins.hermes"]
diff --git a/scripts/_bun-precheck.sh b/scripts/_bun-precheck.sh
new file mode 100755
index 00000000..2e2b017f
--- /dev/null
+++ b/scripts/_bun-precheck.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# Sourced by scripts/o2b and scripts/vault-log to verify Bun is present
+# and meets the declared minimum version (>=1.1.0, mirrored against
+# `engines.bun` in package.json).
+#
+# Side effects: writes a clear error to stderr and exits the calling
+# script if Bun is missing, unparseable, or older than the minimum.
+# No-op on success.
+
+# shellcheck shell=bash
+set -euo pipefail
+
+MIN_BUN_MAJOR=1
+MIN_BUN_MINOR=1
+MIN_BUN_PATCH=0
+
+if ! command -v bun >/dev/null 2>&1; then
+ cat >&2 <<EOS
+error: 'bun' is not on PATH.
+
+Open Second Brain v0.7+ runs on the Bun JavaScript runtime (>=${MIN_BUN_MAJOR}.${MIN_BUN_MINOR}.${MIN_BUN_PATCH}). Install it with:
+
+ curl -fsSL https://bun.sh/install | bash
+
+Then re-open your shell, or source the rc file your shell uses
+(e.g. ~/.bashrc, ~/.zshrc) so ~/.bun/bin lands on PATH.
+EOS
+ exit 127
+fi
+
+_BUN_PRECHECK_VERSION=$(bun --version 2>/dev/null | tr -d '\r' | head -n1)
+if ! [[ "$_BUN_PRECHECK_VERSION" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
+ echo "error: could not parse 'bun --version' output: '${_BUN_PRECHECK_VERSION}'" >&2
+ exit 1
+fi
+_BUN_MAJOR="${BASH_REMATCH[1]}"
+_BUN_MINOR="${BASH_REMATCH[2]}"
+_BUN_PATCH="${BASH_REMATCH[3]}"
+
+if (( _BUN_MAJOR < MIN_BUN_MAJOR )) \
+ || ( (( _BUN_MAJOR == MIN_BUN_MAJOR )) && (( _BUN_MINOR < MIN_BUN_MINOR )) ) \
+ || ( (( _BUN_MAJOR == MIN_BUN_MAJOR )) && (( _BUN_MINOR == MIN_BUN_MINOR )) && (( _BUN_PATCH < MIN_BUN_PATCH )) ); then
+ cat >&2 <<EOS
+error: bun ${_BUN_PRECHECK_VERSION} is older than the required ${MIN_BUN_MAJOR}.${MIN_BUN_MINOR}.${MIN_BUN_PATCH}.
+
+Upgrade with:
+
+ bun upgrade
+EOS
+ exit 1
+fi
diff --git a/scripts/o2b b/scripts/o2b
index e9f153f0..6702a972 100755
--- a/scripts/o2b
+++ b/scripts/o2b
@@ -1,10 +1,13 @@
#!/usr/bin/env bash
set -euo pipefail
-# Follow symlink so PYTHONPATH is correct even when invoked through
-# a symlink from ~/.local/bin (created by 'o2b install-cli').
+# Follow symlink so the repo root is correct even when invoked through
+# a symlink in ~/.local/bin (created by 'o2b install-cli').
SELF=$(realpath -- "${BASH_SOURCE[0]}")
SCRIPT_DIR=$(cd -- "$(dirname -- "$SELF")" && pwd)
REPO_ROOT=$(cd -- "$SCRIPT_DIR/.." && pwd)
-export PYTHONPATH="$REPO_ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
-exec python3 -m open_second_brain.cli "$@"
+
+# shellcheck source=./_bun-precheck.sh
+. "$SCRIPT_DIR/_bun-precheck.sh"
+
+exec bun run "$REPO_ROOT/src/cli/main.ts" "$@"
diff --git a/scripts/sync-version.ts b/scripts/sync-version.ts
new file mode 100644
index 00000000..6b71c2fc
--- /dev/null
+++ b/scripts/sync-version.ts
@@ -0,0 +1,110 @@
+#!/usr/bin/env bun
+/**
+ * Propagate the version from `package.json` to the runtime manifests.
+ *
+ * `package.json` is the single source of truth in v0.7+. Manifests
+ * consumed by external runtimes (Hermes, OpenClaw, Claude Code, Codex,
+ * pip) carry a copy on disk for parity with their schemas.
+ *
+ * Files NOT touched (matches the legacy Python script's design):
+ * - `CHANGELOG.md` β€” historical record, edited by hand on release.
+ * - `install.md` / `docs/architecture.md` β€” install commands MUST NOT
+ * pin a specific tag; they always pull the latest.
+ * - `tests/` β€” fixtures may reference specific historical versions.
+ *
+ * Usage:
+ * bun run scripts/sync-version.ts # write changes
+ * bun run scripts/sync-version.ts --check # exit 1 on drift, no writes
+ */
+
+import { readFileSync, writeFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+
+const YAML_TARGETS = ["plugin.yaml", "plugins/hermes/plugin.yaml"] as const;
+const JSON_TARGETS = [
+ ".claude-plugin/plugin.json",
+ ".codex-plugin/plugin.json",
+ "openclaw.plugin.json",
+] as const;
+const PYPROJECT = "pyproject.toml";
+
+const YAML_RE = /^(version:\s*)"[^"]*"/m;
+const JSON_RE = /("version"\s*:\s*)"[^"]*"/;
+const PYPROJECT_RE = /^(version\s*=\s*)"[^"]*"/m;
+
+interface FileSpec {
+ readonly rel: string;
+ readonly regex: RegExp;
+}
+
+const TARGETS: FileSpec[] = [
+ ...YAML_TARGETS.map((rel) => ({ rel, regex: YAML_RE })),
+ ...JSON_TARGETS.map((rel) => ({ rel, regex: JSON_RE })),
+ { rel: PYPROJECT, regex: PYPROJECT_RE },
+];
+
+function canonicalVersion(): string {
+ const pkg = JSON.parse(readFileSync(`${ROOT}/package.json`, "utf8"));
+ if (typeof pkg.version !== "string" || !pkg.version) {
+ throw new Error("package.json is missing a top-level 'version' field");
+ }
+ return pkg.version;
+}
+
+function replace(text: string, regex: RegExp, version: string): string {
+ return text.replace(regex, `$1"${version}"`);
+}
+
+interface UpdateResult {
+ readonly matched: boolean;
+ readonly wouldChange: boolean;
+}
+
+function updateFile(rel: string, regex: RegExp, version: string, write: boolean): UpdateResult {
+ const path = `${ROOT}/${rel}`;
+ const text = readFileSync(path, "utf8");
+ if (!regex.test(text)) return { matched: false, wouldChange: false };
+ const updated = replace(text, regex, version);
+ if (updated === text) return { matched: true, wouldChange: false };
+ if (write) writeFileSync(path, updated, "utf8");
+ return { matched: true, wouldChange: true };
+}
+
+function main(argv: ReadonlyArray<string>): number {
+ const check = argv.includes("--check");
+ const version = canonicalVersion();
+ process.stdout.write(`canonical version: ${version}\n`);
+
+ const drifted: string[] = [];
+ const unmatched: string[] = [];
+ for (const { rel, regex } of TARGETS) {
+ const { matched, wouldChange } = updateFile(rel, regex, version, !check);
+ if (!matched) {
+ process.stderr.write(` WARN no version line in ${rel}\n`);
+ unmatched.push(rel);
+ continue;
+ }
+ if (wouldChange) {
+ drifted.push(rel);
+ process.stdout.write(` ${check ? "DRIFT" : "wrote"}: ${rel}\n`);
+ } else {
+ process.stdout.write(` ok: ${rel}\n`);
+ }
+ }
+
+ if (check && (drifted.length > 0 || unmatched.length > 0)) {
+ process.stderr.write(
+ `\n${drifted.length} drifted, ${unmatched.length} unmatched target(s); ` +
+ "run scripts/sync-version.ts and add the missing version field where needed.\n",
+ );
+ return 1;
+ }
+ return 0;
+}
+
+if (import.meta.main) {
+ process.exit(main(process.argv.slice(2)));
+}
diff --git a/scripts/vault-log b/scripts/vault-log
index 1285b482..0d350db8 100755
--- a/scripts/vault-log
+++ b/scripts/vault-log
@@ -1,10 +1,17 @@
#!/usr/bin/env bash
set -euo pipefail
-# Follow symlink so PYTHONPATH is correct even when invoked through
-# a symlink from ~/.local/bin (created by 'o2b install-cli').
+# `vault-log` is the legacy shortcut for `o2b append-event`. The two
+# entry points share an implementation in src/cli/main.ts; this wrapper
+# just forwards positional / option arguments to the unified CLI.
+#
+# Follow symlink so the repo root is correct even when invoked through
+# a symlink in ~/.local/bin (created by 'o2b install-cli').
SELF=$(realpath -- "${BASH_SOURCE[0]}")
SCRIPT_DIR=$(cd -- "$(dirname -- "$SELF")" && pwd)
REPO_ROOT=$(cd -- "$SCRIPT_DIR/.." && pwd)
-export PYTHONPATH="$REPO_ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
-exec python3 -m open_second_brain.vault_log "$@"
+
+# shellcheck source=./_bun-precheck.sh
+. "$SCRIPT_DIR/_bun-precheck.sh"
+
+exec bun run "$REPO_ROOT/src/cli/main.ts" append-event "$@"
diff --git a/skills/agent-event-log/SKILL.md b/skills/agent-event-log/SKILL.md
index 8579bf91..495fd091 100644
--- a/skills/agent-event-log/SKILL.md
+++ b/skills/agent-event-log/SKILL.md
@@ -1,37 +1,74 @@
---
name: agent-event-log
-description: Append-only operational event logging for Open Second Brain. Daily Markdown notes are the default backend.
+description: Append-only operational event logging for Open Second Brain. Daily Markdown notes are the default backend. INVOKE this skill (and call `event_log_append`) immediately after producing any durable artifact in the current turn β€” code shipped, bug fixed, refactor merged, config or deployment change, instruction-file edit (CLAUDE.md / AGENTS.md / plugin docs / system prompts), content artifact created (post, draft, documentation, marketing copy, release notes), research or investigation that produced a concrete finding or decision worth recalling later, or discovery of an external fact (CLI behaviour change, API quirk, undocumented edge case) that future sessions should know. SKIP for pure discussion, exploration, read-only queries, and planning that has not yet produced an artifact. If unsure, ask "would future-me want to find this in the log by searching for it later?" β€” if yes, log it. WRITE the `message` in the same natural language the user has been speaking with you in this session β€” never default to English when the user has been writing in a different language; mixed-language sessions follow the most recent user message at the time the artifact landed. This skill description is intentionally in English so it travels across runtimes; the locale of the description is unrelated to the locale your log entry must take.
---
# Agent Event Log
-Use this skill after substantial work or when the user asks for an operational log entry.
+Open Second Brain ships an `event_log_append` tool (via the MCP server registered by this plugin) that records what happened, when, and which agent did it. The tool writes one line into the day's Markdown note (`<vault>/Daily/YYYY.MM.DD.md`) under a `## Raw events` heading.
-## Purpose
+## When to call `event_log_append`
-The event log records what happened, when, and which agent did it. It is evidence, not a polished wiki page.
+Call it **once per durable artifact produced in the current turn**. A durable artifact is anything you would want to find again by searching the vault tomorrow, next week, or six months from now. Concrete triggers:
-## Rules
+- **Code:** code shipped, bug fixed, refactor merged, dependency bumped, schema migration applied.
+- **Config / deployment:** any change to `config.yaml`, `~/.codex/config.toml`, systemd unit, Caddy snippet, environment variable, secret rotation, infra rollout.
+- **Instructions / docs:** edit to `CLAUDE.md`, `AGENTS.md`, project README, plugin docs, system prompt, runbook, onboarding guide.
+- **Content artifacts:** new post draft, documentation page, marketing copy, release notes, public-facing communication.
+- **Research / investigation findings:** a concrete answer, root cause, design decision, or trade-off resolution. Not the act of searching β€” the conclusion you reached.
+- **External-fact discoveries:** a CLI now requires a flag it didn't before, an API rejects a payload it used to accept, a documented behavior diverges from observed behavior. Worth logging because the next session won't re-discover it.
-- Append only.
-- Keep entries short and factual.
-- Include the agent name when supported.
-- Do not include secrets.
-- Redact sensitive values as `[REDACTED]`.
+## When NOT to call it
-## Compatibility
+- Pure discussion or brainstorming with no conclusion.
+- Read-only queries (running `git log`, `o2b status`, `vault_health`, `second_brain_query`).
+- Planning that has not yet produced a written artifact.
+- Acknowledgement-only replies ("ok", "got it").
-The compatibility command is `vault-log`.
+If you are unsure: ask yourself "would future-me want to find this in the log by searching for it later?". If yes, call the tool.
-Future Open Second Brain CLI commands may include:
+## How to call it
-```bash
-o2b append-event --as <agent-name> "message"
-vault-log --as <agent-name> "message"
+The MCP server resolves the agent identity from `~/.config/open-second-brain/config.yaml` automatically; you do **not** pass `agent` unless you are deliberately logging on someone else's behalf. Pass only `message`:
+
+```json
+event_log_append({ "message": "migrated CLI from Python to Bun, all 175 tests green" })
```
-## Example
+Server prepends `HH:MM` and `@<agent-name>` itself. Never bake those into your message.
+
+## CLI fallback
+
+When MCP is unavailable, the same operation is reachable from the shell:
```bash
-vault-log --as hermes-vps-agent "created initial open-second-brain repository documentation and plugin skeleton"
+o2b append-event "migrated CLI from Python to Bun, all 175 tests green"
+# or, the legacy alias:
+vault-log "migrated CLI from Python to Bun, all 175 tests green"
+```
+
+## Language
+
+The `message` body must match the **natural language the user has been speaking with you in this session**. Identity prefix (`@agent-name`) and timestamp are server-supplied and stay locale-independent β€” only the message body localises.
+
+Concrete rules:
+
+- **Match the user.** Whatever language the current user message is in, that is the language the log entry goes in. If the user's message is in some language X, the entry is in language X. The English example below is illustrative only β€” replace its prose with prose in language X when X β‰  English; do not switch the technical identifiers.
+- **Mixed-language session β†’ match the most recent user message at the time the artifact landed.** A user who switches mid-session expects the new entries in the new language.
+- **Technical identifiers stay verbatim regardless of surrounding language**: command names (`bun test`, `o2b doctor`), file paths (`src/core/event-log.ts`), package and library names (`proper-lockfile`, `@anthropic-ai/sdk`), API symbols, error messages quoted from logs. Never translate `event_log_append` (or any other identifier) into a different word.
+- **Default-to-English bias is the failure mode.** This skill description is written in English so it travels across runtimes β€” but the message you write into Daily is the user's language, not the language of this instruction.
+
+Illustrative shape, English example (substitute the user's language for the prose):
+
+```text
+fixed event_log_append race: dailyNotePath now validates date via validateEventDate, blocking path traversal via "../"
```
+
+If you genuinely cannot infer the user's language (single-message session, no clear signal, ambiguous greeting only), default to English and keep the entry concise.
+
+## Rules
+
+- Append only β€” never edit historical lines.
+- One line per event, factual and terse.
+- Never write secrets, tokens, API keys, passwords, or connection strings containing credentials. The server redacts assignments of those names to `[REDACTED]`, but do not rely on it as the only line of defence.
+- Prefer specific over generic ("renamed `pre_llm_call` hook to `before_prompt_build` per OpenClaw 0.5 SDK rename" beats "updated hook").
diff --git a/src/cli/argparse.ts b/src/cli/argparse.ts
new file mode 100644
index 00000000..cc7da744
--- /dev/null
+++ b/src/cli/argparse.ts
@@ -0,0 +1,94 @@
+/**
+ * Minimal argv parser used by the `o2b` CLI.
+ *
+ * Intentionally not a full argparse port β€” the CLI grammar is small and
+ * stable, so a hand-written parser keeps the binary dependency-free
+ * (KISS, parity with the legacy Python no-deps stance).
+ *
+ * Conventions:
+ * - Long flags only (`--name`, `--name=value`, `--name value`).
+ * - Boolean flags are recognised by name (no value follows).
+ * - Repeatable flags collect into arrays.
+ * - Positional args are returned as `_`.
+ *
+ * Throws `CliError` on bad input (unknown flag, missing required arg).
+ */
+
+export class CliError extends Error {}
+
+export interface FlagSpec {
+ readonly type: "string" | "boolean" | "string-array";
+ readonly required?: boolean;
+ /** Default value for `string` flags. */
+ readonly default?: string;
+ /** Number of positional arguments to accept (0 = none). */
+}
+
+export type FlagsSchema = Record<string, FlagSpec>;
+
+export interface ParsedArgs {
+ readonly flags: Record<string, string | boolean | string[] | undefined>;
+ readonly positional: string[];
+}
+
+/**
+ * Parse argv-tail for one subcommand. `argv` should be everything AFTER the
+ * subcommand name. Unknown flags raise `CliError`.
+ */
+export function parseFlags(argv: ReadonlyArray<string>, schema: FlagsSchema): ParsedArgs {
+ const flags: Record<string, string | boolean | string[] | undefined> = {};
+ const positional: string[] = [];
+
+ for (let i = 0; i < argv.length; i++) {
+ const tok = argv[i]!;
+ if (tok === "--") {
+ for (let j = i + 1; j < argv.length; j++) positional.push(argv[j]!);
+ break;
+ }
+ if (tok.startsWith("--")) {
+ const eqIdx = tok.indexOf("=");
+ const name = eqIdx === -1 ? tok.slice(2) : tok.slice(2, eqIdx);
+ const inlineVal = eqIdx === -1 ? null : tok.slice(eqIdx + 1);
+ const spec = schema[name];
+ if (!spec) {
+ throw new CliError(`unknown flag: --${name}`);
+ }
+ if (spec.type === "boolean") {
+ if (inlineVal !== null) {
+ throw new CliError(`flag --${name} does not accept a value`);
+ }
+ flags[name] = true;
+ continue;
+ }
+ let value: string;
+ if (inlineVal !== null) {
+ value = inlineVal;
+ } else {
+ const next = argv[++i];
+ if (next === undefined) throw new CliError(`flag --${name} requires a value`);
+ value = next;
+ }
+ if (spec.type === "string") {
+ flags[name] = value;
+ } else {
+ const arr = (flags[name] as string[] | undefined) ?? [];
+ arr.push(value);
+ flags[name] = arr;
+ }
+ continue;
+ }
+ positional.push(tok);
+ }
+
+ // Apply defaults and check required flags.
+ for (const [name, spec] of Object.entries(schema)) {
+ if (flags[name] === undefined) {
+ if (spec.type === "string" && spec.default !== undefined) {
+ flags[name] = spec.default;
+ } else if (spec.required) {
+ throw new CliError(`missing required flag: --${name}`);
+ }
+ }
+ }
+ return { flags, positional };
+}
diff --git a/src/cli/install-cli.ts b/src/cli/install-cli.ts
new file mode 100644
index 00000000..3c77110e
--- /dev/null
+++ b/src/cli/install-cli.ts
@@ -0,0 +1,196 @@
+/**
+ * Install (and remove) CLI symlinks for `o2b` and `vault-log` in `~/.local/bin`.
+ *
+ * Mirrors `src/open_second_brain/install_cli.py`. Refuses to overwrite a
+ * symlink that already points to a different repo's checkout β€” that's the
+ * documented behavior across multi-runtime installs.
+ */
+
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ readlinkSync,
+ realpathSync,
+ statSync,
+ symlinkSync,
+ unlinkSync,
+} from "node:fs";
+import { homedir } from "node:os";
+import { dirname, join, resolve, sep } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import type { InstallResult, UninstallResult } from "../core/types.ts";
+
+const CLI_SCRIPTS = ["o2b", "vault-log"] as const;
+
+function repoRoot(): string {
+ // src/cli/install-cli.ts β†’ repo/
+ return resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+}
+
+function scriptsDir(): string {
+ return join(repoRoot(), "scripts");
+}
+
+function findScript(name: string): string | null {
+ const path = join(scriptsDir(), name);
+ if (existsSync(path) && statSync(path).isFile()) return resolve(path);
+ return null;
+}
+
+function isLink(p: string): boolean {
+ try {
+ return lstatSync(p).isSymbolicLink();
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Match Python's `Path.resolve()` semantics, which follows symlinks. Plain
+ * `path.resolve()` does not β€” it just normalises path components.
+ */
+function realpath(p: string): string {
+ try {
+ return realpathSync(p);
+ } catch {
+ return resolve(p);
+ }
+}
+
+function isValidSymlink(link: string, target: string): boolean {
+ try {
+ return realpath(link) === realpath(target);
+ } catch {
+ return false;
+ }
+}
+
+export function installCli(bindir?: string): InstallResult {
+ const dir = bindir ?? join(homedir(), ".local", "bin");
+ mkdirSync(dir, { recursive: true });
+
+ const outcomes: Array<readonly [string, string]> = [];
+ const errors: string[] = [];
+
+ for (const name of CLI_SCRIPTS) {
+ const link = join(dir, name);
+ const source = findScript(name);
+ if (source === null) {
+ const msg = `error: script 'scripts/${name}' not found in ${scriptsDir()}`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ continue;
+ }
+
+ if (isLink(link)) {
+ if (isValidSymlink(link, source)) {
+ outcomes.push([name, `exists: ${link} β†’ ${source}`]);
+ } else {
+ let existing = "unknown";
+ try {
+ existing = readlinkSync(link);
+ } catch {
+ // ignore
+ }
+ // Conflict: report as an error so cmdInstallCli exits non-zero.
+ // Otherwise the user thinks install succeeded but their CLI still
+ // points at the old checkout.
+ const msg = `error: ${link} already points to ${existing}, not overwriting`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ }
+ } else if (existsSync(link)) {
+ const msg = `error: ${link} exists and is not a symlink, not overwriting`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ } else {
+ try {
+ symlinkSync(source, link);
+ outcomes.push([name, `created: ${link} β†’ ${source}`]);
+ } catch (exc) {
+ const msg = `error: could not create symlink ${link}: ${(exc as Error).message ?? exc}`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ }
+ }
+ }
+ return { bindir: dir, outcomes, errors };
+}
+
+export function uninstallCli(bindir?: string): UninstallResult {
+ const dir = bindir ?? join(homedir(), ".local", "bin");
+ const repoScripts = scriptsDir();
+ const outcomes: Array<readonly [string, string]> = [];
+ const errors: string[] = [];
+
+ for (const name of CLI_SCRIPTS) {
+ const link = join(dir, name);
+ if (!isLink(link)) {
+ if (existsSync(link)) {
+ outcomes.push([name, `skipped: ${link} is not a symlink β€” refusing to remove`]);
+ } else {
+ outcomes.push([name, `skipped: ${link} does not exist`]);
+ }
+ continue;
+ }
+
+ let target: string;
+ try {
+ target = realpath(link);
+ } catch (exc) {
+ const msg = `error: cannot resolve ${link}: ${(exc as Error).message ?? exc}`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ continue;
+ }
+
+ const repoScriptsReal = realpath(repoScripts);
+ if (!target.startsWith(repoScriptsReal + sep) && target !== repoScriptsReal) {
+ outcomes.push([
+ name,
+ `skipped: ${link} β†’ ${target} is outside this repo's scripts/ β€” refusing to remove`,
+ ]);
+ continue;
+ }
+
+ try {
+ unlinkSync(link);
+ outcomes.push([name, `removed: ${link}`]);
+ } catch (exc) {
+ const msg = `error: cannot unlink ${link}: ${(exc as Error).message ?? exc}`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ }
+ }
+ return { bindir: dir, outcomes, errors };
+}
+
+export function renderInstallResult(result: InstallResult): string {
+ const lines: string[] = [];
+ lines.push(`o2b install-cli β€” ${result.bindir}`);
+ lines.push("-".repeat(40));
+ for (const [name, msg] of result.outcomes) {
+ lines.push(` ${name}: ${msg}`);
+ }
+ if (result.errors.length > 0) {
+ lines.push("");
+ lines.push(`${result.errors.length} error(s).`);
+ }
+ return lines.join("\n").replace(/\s+$/g, "") + "\n";
+}
+
+export function renderUninstallResult(result: UninstallResult): string {
+ const lines: string[] = [];
+ lines.push(`o2b uninstall --remove-cli β€” ${result.bindir}`);
+ lines.push("-".repeat(40));
+ for (const [name, msg] of result.outcomes) {
+ lines.push(` ${name}: ${msg}`);
+ }
+ if (result.errors.length > 0) {
+ lines.push("");
+ lines.push(`${result.errors.length} error(s).`);
+ }
+ return lines.join("\n").replace(/\s+$/g, "") + "\n";
+}
diff --git a/src/cli/main.ts b/src/cli/main.ts
new file mode 100644
index 00000000..ce0dc6d3
--- /dev/null
+++ b/src/cli/main.ts
@@ -0,0 +1,447 @@
+/**
+ * `o2b` CLI entry point. Mirrors `src/open_second_brain/cli.py` from the
+ * legacy implementation: same subcommands, same flag names, same exit codes,
+ * same error messages (verified by ports of the Python integration tests).
+ *
+ * Each subcommand resolves its inputs, delegates to `core/*` for business
+ * logic, and returns a `0`/`1` exit code. The dispatcher is a small `switch`
+ * statement, not a registry β€” keeps the control flow obvious.
+ */
+
+import { mkdirSync, writeFileSync } from "node:fs";
+import { resolve } from "node:path";
+
+import {
+ defaultConfigPath,
+ discoverConfig,
+ redactMapping,
+ resolveTimezone,
+ resolveVault,
+ setConfigValue,
+} from "../core/config.ts";
+import { doctor } from "../core/doctor.ts";
+import { appendEvent } from "../core/event-log.ts";
+import { bootstrapVault } from "../core/init.ts";
+import { listVaultPages, writeFrontmatter } from "../core/vault.ts";
+import { CliError, parseFlags } from "./argparse.ts";
+import {
+ installCli,
+ renderInstallResult,
+ renderUninstallResult,
+ uninstallCli,
+} from "./install-cli.ts";
+import { planUninstall, renderPlan } from "./uninstall.ts";
+import { MCPServer } from "../mcp/server.ts";
+import { serveStdio } from "../mcp/stdio.ts";
+import { SERVER_VERSION } from "../mcp/protocol.ts";
+
+const NO_VAULT_ERROR =
+ "error: no vault configured. Pass --vault <path> explicitly, " +
+ "set VAULT_DIR in the environment, or run " +
+ "`o2b init --vault <path> ...` first to persist a default.";
+
+class NoVaultConfiguredError extends Error {
+ constructor() {
+ super(NO_VAULT_ERROR);
+ this.name = "NoVaultConfiguredError";
+ }
+}
+
+function requireVault(flagVal: string | undefined, configPath: string | null): string {
+ const vault = flagVal ?? resolveVault(configPath ?? undefined);
+ if (vault === null || vault === undefined) {
+ // Throw rather than process.exit so the dispatcher's catch can convert
+ // this into a clean exit code 1 β€” main() stays reusable in-process
+ // (e.g. test harnesses that import and call it).
+ throw new NoVaultConfiguredError();
+ }
+ return vault;
+}
+
+// ── Subcommands ─────────────────────────────────────────────────────────────
+
+async function cmdStatus(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ config: { type: "string" },
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const result = discoverConfig(flags["config"] as string | undefined);
+ if (flags["json"]) {
+ const output: Record<string, unknown> = {
+ config_path: String(result.path),
+ config_exists: result.exists,
+ };
+ if (Object.keys(result.data).length > 0) {
+ output["config_keys"] = Object.keys(result.data).sort();
+ }
+ if (flags["vault"]) output["vault"] = String(flags["vault"]);
+ process.stdout.write(JSON.stringify(output, sortedReplacer, 2) + "\n");
+ } else {
+ process.stdout.write(`config_path: ${result.path}\n`);
+ process.stdout.write(`config_exists: ${result.exists ? "true" : "false"}\n`);
+ if (Object.keys(result.data).length > 0) {
+ process.stdout.write("config_keys:\n");
+ for (const key of Object.keys(result.data).sort()) {
+ process.stdout.write(`- ${key}\n`);
+ }
+ }
+ }
+ return 0;
+}
+
+async function cmdInit(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string", required: true },
+ name: { type: "string", default: "Second Brain" },
+ "agent-name": { type: "string" },
+ timezone: { type: "string" },
+ force: { type: "boolean" },
+ });
+ const vault = String(flags["vault"]);
+ const agentName = (flags["agent-name"] as string | undefined) ?? null;
+ const timezone = (flags["timezone"] as string | undefined) ?? null;
+
+ if (timezone) {
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: timezone });
+ } catch (exc) {
+ process.stderr.write(
+ `error: --timezone ${JSON.stringify(timezone)} is not a valid IANA name ` +
+ `(${(exc as Error).message ?? exc}). ` +
+ "Examples: Europe/Belgrade, America/New_York, UTC.\n",
+ );
+ return 1;
+ }
+ }
+
+ let created: string[];
+ try {
+ created = bootstrapVault(vault, {
+ name: String(flags["name"] ?? "Second Brain"),
+ agentName,
+ force: Boolean(flags["force"]),
+ });
+ } catch (exc) {
+ process.stderr.write(`error: failed to initialize vault: ${(exc as Error).message ?? exc}\n`);
+ return 1;
+ }
+
+ if (created.length > 0) {
+ process.stdout.write(`initialized vault: ${vault}\n`);
+ for (const p of created) process.stdout.write(` created: ${p}\n`);
+ } else {
+ process.stdout.write(`vault already initialized: ${vault}\n`);
+ process.stdout.write("use --force to overwrite existing files\n");
+ }
+ // Persist vault/agent/timezone in one guarded block so a write failure
+ // (read-only config dir, disk full) surfaces as a clean CLI exit instead
+ // of an uncaught exception after the vault scaffolding is already on disk.
+ let configPath: string;
+ try {
+ configPath = setConfigValue("vault", resolve(vault));
+ if (agentName) setConfigValue("agent_name", agentName);
+ if (timezone) setConfigValue("timezone", timezone);
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to persist plugin config: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+ process.stdout.write(`vault path persisted to: ${configPath}\n`);
+ if (agentName) {
+ process.stdout.write(`agent name registered: ${agentName}\n`);
+ process.stdout.write(`agent name persisted to: ${configPath}\n`);
+ }
+ if (timezone) {
+ process.stdout.write(`timezone registered: ${timezone}\n`);
+ process.stdout.write(`timezone persisted to: ${configPath}\n`);
+ }
+ return 0;
+}
+
+async function cmdDoctor(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ config: { type: "string" },
+ repo: { type: "string" },
+ });
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+
+ let results;
+ try {
+ results = doctor({ vault, config, repoRoot: (flags["repo"] as string | undefined) ?? null });
+ } catch (exc) {
+ process.stderr.write(`error: doctor failed: ${(exc as Error).message ?? exc}\n`);
+ return 1;
+ }
+ let allOk = true;
+ for (const r of results) {
+ process.stdout.write(`[${r.ok ? "OK" : "FAIL"}] ${r.name}: ${r.message}\n`);
+ if (!r.ok) allOk = false;
+ }
+ return allOk ? 0 : 1;
+}
+
+async function cmdAppendEvent(argv: string[]): Promise<number> {
+ const { flags, positional } = parseFlags(argv, {
+ vault: { type: "string" },
+ as: { type: "string", default: process.env["VAULT_AGENT_NAME"] ?? "agent" },
+ date: { type: "string" },
+ time: { type: "string" },
+ });
+ if (positional.length < 1) {
+ process.stderr.write("error: append-event requires a message argument\n");
+ return 2;
+ }
+ const message = positional[0]!;
+ const vault = requireVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const tz = resolveTimezone();
+
+ let path: string;
+ try {
+ path = await appendEvent(vault, String(flags["as"] ?? "agent"), message, {
+ date: (flags["date"] as string | undefined) ?? null,
+ time: (flags["time"] as string | undefined) ?? null,
+ tz,
+ });
+ } catch (exc) {
+ process.stderr.write(`error: failed to append event: ${(exc as Error).message ?? exc}\n`);
+ return 1;
+ }
+ process.stdout.write(`appended: ${resolve(path)}\n`);
+ return 0;
+}
+
+async function cmdExportConfig(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ config: { type: "string" },
+ output: { type: "string", required: true },
+ });
+ const result = discoverConfig(flags["config"] as string | undefined);
+ const snapshot = {
+ config_path: String(result.path),
+ config_exists: result.exists,
+ config: redactMapping(result.data),
+ };
+ const output = String(flags["output"]);
+ try {
+ mkdirSync(resolve(output, ".."), { recursive: true });
+ writeFileSync(output, JSON.stringify(snapshot, sortedReplacer, 2) + "\n", "utf8");
+ } catch (exc) {
+ process.stderr.write(`error: failed to export config: ${(exc as Error).message ?? exc}\n`);
+ return 1;
+ }
+ process.stdout.write(`exported: ${output}\n`);
+ return 0;
+}
+
+async function cmdIndex(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, { vault: { type: "string" } });
+ const vault = requireVault(flags["vault"] as string | undefined, defaultConfigPath());
+ let pages;
+ try {
+ pages = listVaultPages(vault);
+ } catch (exc) {
+ process.stderr.write(`error: failed to list vault pages: ${(exc as Error).message ?? exc}\n`);
+ return 1;
+ }
+ if (pages.length === 0) {
+ process.stdout.write(`no markdown pages found in vault: ${vault}\n`);
+ return 0;
+ }
+ const lines: string[] = [
+ `# Vault Index`,
+ "",
+ `Auto-generated index of ${pages.length} pages.`,
+ "",
+ ];
+ for (const p of pages) {
+ const rel = p.path.startsWith(vault) ? p.path.slice(vault.length).replace(/^\/+/, "") : p.path;
+ lines.push(`- [[${p.title}]] \`${rel}\``);
+ }
+ const indexPath = resolve(vault, "AI Wiki", "index.md");
+ try {
+ writeFrontmatter(indexPath, { title: "Index", type: "index" }, lines.join("\n"));
+ } catch (exc) {
+ process.stderr.write(`error: failed to write index: ${(exc as Error).message ?? exc}\n`);
+ return 1;
+ }
+ process.stdout.write(`index regenerated: ${indexPath} (${pages.length} pages)\n`);
+ return 0;
+}
+
+async function cmdMcp(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ config: { type: "string" },
+ repo: { type: "string" },
+ });
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+ const repoRoot = (flags["repo"] as string | undefined) ?? null;
+
+ process.stderr.write(
+ `[mcp] open-second-brain ${SERVER_VERSION} listening on stdio (vault=${vault})\n`,
+ );
+ const server = new MCPServer({ vault, configPath: config, repoRoot });
+ return await serveStdio(server);
+}
+
+async function cmdInstallCli(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, { bindir: { type: "string" } });
+ const result = installCli(flags["bindir"] as string | undefined);
+ process.stdout.write(renderInstallResult(result));
+ return result.errors.length > 0 ? 1 : 0;
+}
+
+async function cmdUninstall(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ config: { type: "string" },
+ "apply-local": { type: "boolean" },
+ "remove-cli": { type: "boolean" },
+ });
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const plan = planUninstall({ configPath: config, applyLocal: Boolean(flags["apply-local"]) });
+ process.stdout.write(renderPlan(plan));
+ let returnCode = 0;
+ if (flags["remove-cli"]) {
+ const result = uninstallCli();
+ process.stdout.write("\n" + renderUninstallResult(result));
+ if (result.errors.length > 0) returnCode = 1;
+ }
+ if (plan.errors.length > 0) returnCode = 1;
+ return returnCode;
+}
+
+async function cmdToolCall(argv: string[]): Promise<number> {
+ const { flags, positional } = parseFlags(argv, {
+ vault: { type: "string" },
+ "tool-arg": { type: "string-array" },
+ });
+ if (positional.length < 1) {
+ process.stderr.write("error: tool-call requires a tool name argument\n");
+ return 2;
+ }
+ const toolName = positional[0]!;
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+
+ const args: Record<string, unknown> = {};
+ for (const pair of (flags["tool-arg"] as string[] | undefined) ?? []) {
+ const eq = pair.indexOf("=");
+ if (eq === -1) {
+ // Argument-shape error: align with the dispatcher convention
+ // (CliError β†’ exit 2). Tool execution failures keep using exit 1.
+ process.stderr.write(`error: --tool-arg must be key=value, got: ${pair}\n`);
+ return 2;
+ }
+ const k = pair.slice(0, eq);
+ const v = pair.slice(eq + 1);
+ try {
+ args[k] = JSON.parse(v);
+ } catch {
+ args[k] = v;
+ }
+ }
+ const server = new MCPServer({ vault, configPath: config });
+ try {
+ const result = await server.callTool(toolName, args);
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ return 0;
+ } catch (exc) {
+ process.stderr.write(`error: ${(exc as Error).message ?? exc}\n`);
+ return 1;
+ }
+}
+
+const HELP = `usage: o2b <command> [args...]
+
+Commands:
+ status Show Open Second Brain configuration status
+ init Initialize a vault profile with required files
+ doctor Run health checks on vault, config, and plugins
+ append-event Append an event to the configured event log backend
+ export-config Write a redacted config snapshot
+ index Regenerate the vault index from discovered pages
+ mcp Run the optional MCP tool server (stdio JSON-RPC)
+ install-cli Create symlinks for o2b and vault-log in ~/.local/bin
+ uninstall Print an uninstall plan and (optionally) clean local config and CLI symlinks
+ tool-call Invoke an MCP tool handler from the CLI and print JSON to stdout
+`;
+
+function sortedReplacer(_key: string, value: unknown): unknown {
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));
+ }
+ return value;
+}
+
+export async function main(argv: ReadonlyArray<string>): Promise<number> {
+ if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
+ process.stdout.write(HELP);
+ return argv.length === 0 ? 2 : 0;
+ }
+ const command = argv[0]!;
+ const rest = argv.slice(1);
+
+ // Per-command --help support: print the dedicated help line plus generic.
+ if (rest.length === 1 && (rest[0] === "-h" || rest[0] === "--help")) {
+ process.stdout.write(`${command}: see https://github.com/itechmeat/open-second-brain\n`);
+ if (command === "uninstall") {
+ process.stdout.write(
+ "Read-only by default. Prints the Hermes commands you must run yourself " +
+ "(this tool never touches ~/.hermes/config.yaml or the installed plugin). " +
+ "With --apply-local it may remove the machine-local Open Second Brain " +
+ "config directory only. Your vault, Daily/, AI Wiki/, and Markdown notes " +
+ "are never removed. With --remove-cli it also removes the o2b/vault-log " +
+ "symlinks created by 'o2b install-cli'.\n",
+ );
+ }
+ return 0;
+ }
+
+ try {
+ switch (command) {
+ case "status":
+ return await cmdStatus(rest);
+ case "init":
+ return await cmdInit(rest);
+ case "doctor":
+ return await cmdDoctor(rest);
+ case "append-event":
+ return await cmdAppendEvent(rest);
+ case "export-config":
+ return await cmdExportConfig(rest);
+ case "index":
+ return await cmdIndex(rest);
+ case "mcp":
+ return await cmdMcp(rest);
+ case "install-cli":
+ return await cmdInstallCli(rest);
+ case "uninstall":
+ return await cmdUninstall(rest);
+ case "tool-call":
+ return await cmdToolCall(rest);
+ default:
+ process.stderr.write(`error: unknown command: ${command}\n`);
+ process.stderr.write(HELP);
+ return 2;
+ }
+ } catch (exc) {
+ if (exc instanceof CliError) {
+ process.stderr.write(`error: ${exc.message}\n`);
+ return 2;
+ }
+ if (exc instanceof NoVaultConfiguredError) {
+ process.stderr.write(exc.message + "\n");
+ return 1;
+ }
+ throw exc;
+ }
+}
+
+if (import.meta.main) {
+ main(process.argv.slice(2)).then((code) => process.exit(code));
+}
diff --git a/src/cli/uninstall.ts b/src/cli/uninstall.ts
new file mode 100644
index 00000000..11cb5a17
--- /dev/null
+++ b/src/cli/uninstall.ts
@@ -0,0 +1,182 @@
+/**
+ * Read-only uninstall planner. Mirrors `src/open_second_brain/uninstall.py`.
+ */
+
+import { existsSync, readdirSync, rmSync, statSync } from "node:fs";
+import { basename, dirname, join, sep } from "node:path";
+
+import { discoverConfig } from "../core/config.ts";
+import type { UninstallPlan } from "../core/types.ts";
+
+export const PLUGIN_NAME = "open-second-brain";
+
+export const HERMES_COMMANDS: ReadonlyArray<string> = [
+ `hermes mcp remove ${PLUGIN_NAME}`,
+ `hermes plugins remove ${PLUGIN_NAME}`,
+ "hermes gateway restart",
+];
+
+export const SAFE_CONFIG_DIR_NAMES: ReadonlySet<string> = new Set([
+ "open-second-brain",
+ "open_second_brain",
+]);
+
+function isSafeLocalConfigDir(target: string): readonly [boolean, string] {
+ const name = basename(target);
+ if (!SAFE_CONFIG_DIR_NAMES.has(name)) {
+ return [
+ false,
+ `directory name '${name}' is not a recognized Open Second Brain config directory; refusing to remove`,
+ ];
+ }
+ const partsLower = target.split(sep).map((p) => p.toLowerCase());
+ if (partsLower.includes(".hermes") || partsLower.includes("hermes")) {
+ return [false, "config directory is inside a Hermes-owned path; refusing to remove"];
+ }
+ if (existsSync(join(target, ".git"))) {
+ return [false, "config directory looks like a git repository; refusing to remove"];
+ }
+ return [true, ""];
+}
+
+function vaultPathFromConfig(data: Record<string, string>): string | null {
+ for (const key of ["vault_path", "vault", "vault_dir", "path"]) {
+ const value = data[key];
+ if (value) return value;
+ }
+ return null;
+}
+
+function listEntries(dir: string): string[] {
+ if (!existsSync(dir)) return [];
+ try {
+ if (!statSync(dir).isDirectory()) return [];
+ return readdirSync(dir).sort();
+ } catch {
+ return [];
+ }
+}
+
+export interface PlanUninstallOptions {
+ readonly configPath: string;
+ readonly applyLocal?: boolean;
+}
+
+export function planUninstall(opts: PlanUninstallOptions): UninstallPlan {
+ const applyLocal = opts.applyLocal ?? false;
+ const discovery = discoverConfig(opts.configPath);
+ const cfgDir = dirname(discovery.path);
+ const cfgDirExists = existsSync(cfgDir) && statSync(cfgDir).isDirectory();
+ const entries = listEntries(cfgDir);
+ const vaultPath = vaultPathFromConfig(discovery.data);
+
+ const removed: string[] = [];
+ const skipped: Array<readonly [string, string]> = [];
+ const errors: Array<readonly [string, string]> = [];
+
+ if (applyLocal) {
+ if (!cfgDirExists) {
+ skipped.push([cfgDir, "config directory does not exist"]);
+ } else {
+ const [safe, reason] = isSafeLocalConfigDir(cfgDir);
+ if (!safe) {
+ skipped.push([cfgDir, reason]);
+ } else {
+ try {
+ rmSync(cfgDir, { recursive: true, force: true });
+ removed.push(cfgDir);
+ } catch (exc) {
+ errors.push([cfgDir, (exc as Error).message ?? String(exc)]);
+ }
+ }
+ }
+ }
+
+ return {
+ configPath: discovery.path,
+ configExists: discovery.exists,
+ configDir: cfgDir,
+ configDirExists: cfgDirExists,
+ configDirEntries: entries,
+ vaultPath,
+ applyLocal,
+ hermesCommands: HERMES_COMMANDS,
+ removedPaths: removed,
+ skippedPaths: skipped,
+ errors,
+ };
+}
+
+export function renderPlan(plan: UninstallPlan): string {
+ const lines: string[] = [];
+ const title = "Open Second Brain β€” Uninstall plan";
+ lines.push(title);
+ lines.push("=".repeat(title.length));
+ lines.push("");
+
+ const mode = plan.applyLocal
+ ? "apply-local (machine-local config directory may be removed)"
+ : "dry-run (read-only)";
+ lines.push(`Mode: ${mode}`);
+ lines.push("");
+
+ lines.push("Local config:");
+ const configState = plan.configExists ? "exists" : "missing";
+ lines.push(` config file: ${plan.configPath} (${configState})`);
+ if (plan.configDirExists) {
+ const n = plan.configDirEntries.length;
+ lines.push(` config dir: ${plan.configDir} (${n} entr${n === 1 ? "y" : "ies"})`);
+ for (const entry of plan.configDirEntries) {
+ const full = join(plan.configDir, entry);
+ const suffix = existsSync(full) && statSync(full).isDirectory() ? "/" : "";
+ lines.push(` - ${entry}${suffix}`);
+ }
+ } else {
+ lines.push(` config dir: ${plan.configDir} (missing)`);
+ }
+ lines.push("");
+
+ lines.push("Hermes integration (run these yourself; this tool will not):");
+ for (const cmd of plan.hermesCommands) {
+ lines.push(` $ ${cmd}`);
+ }
+ lines.push("");
+ lines.push(" Hermes owns plugin installation and MCP registration. Open Second");
+ lines.push(" Brain never edits ~/.hermes/config.yaml on your behalf.");
+ lines.push("");
+
+ lines.push("Vault (NEVER removed by this tool):");
+ if (plan.vaultPath !== null) {
+ lines.push(` ${plan.vaultPath}`);
+ } else {
+ lines.push(" (no vault path recorded in config; check your runtime settings)");
+ }
+ lines.push(" Your Markdown notes, Daily/, and AI Wiki/ stay exactly as they are.");
+ lines.push("");
+
+ if (plan.applyLocal) {
+ lines.push("Apply-local results:");
+ if (plan.removedPaths.length > 0) {
+ for (const p of plan.removedPaths) lines.push(` removed: ${p}`);
+ }
+ if (plan.skippedPaths.length > 0) {
+ for (const [p, reason] of plan.skippedPaths) lines.push(` skipped: ${p} β€” ${reason}`);
+ }
+ if (plan.errors.length > 0) {
+ for (const [p, reason] of plan.errors) lines.push(` error: ${p} β€” ${reason}`);
+ }
+ if (plan.removedPaths.length === 0 && plan.skippedPaths.length === 0 && plan.errors.length === 0) {
+ lines.push(" (nothing to do)");
+ }
+ lines.push("");
+ } else {
+ lines.push("Next steps:");
+ lines.push(" 1. Run the Hermes commands above to deregister the MCP server and plugin.");
+ lines.push(" 2. Re-run with --apply-local to remove the machine-local config directory.");
+ lines.push(" 3. Add --remove-cli to also remove the o2b/vault-log symlinks from ~/.local/bin.");
+ lines.push(" 4. Delete the vault yourself if and only if you really want to lose your notes.");
+ lines.push("");
+ }
+
+ return lines.join("\n").replace(/\s+$/g, "") + "\n";
+}
diff --git a/src/core/config.ts b/src/core/config.ts
new file mode 100644
index 00000000..50f65e33
--- /dev/null
+++ b/src/core/config.ts
@@ -0,0 +1,186 @@
+/**
+ * Configuration discovery and persistence.
+ *
+ * Mirrors `src/open_second_brain/config.py` from the legacy Python implementation
+ * β€” same lookup chain (env β†’ XDG β†’ ~/.config), same simple `key: value` YAML
+ * subset, same atomic write semantics, same redaction policy. Tests pin parity
+ * via parallel suites in tests/core/config.test.ts.
+ */
+
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+import { atomicWriteFileSync } from "./fs-atomic.ts";
+import type { ConfigDiscovery } from "./types.ts";
+
+const SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"] as const;
+
+const CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;
+
+/**
+ * Resolve the location of the plugin config file.
+ *
+ * Order: `OPEN_SECOND_BRAIN_CONFIG` env, `XDG_CONFIG_HOME`, `~/.config/open-second-brain/config.yaml`.
+ */
+export function defaultConfigPath(): string {
+ const override = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ if (override) return expandTilde(override);
+
+ const xdg = process.env["XDG_CONFIG_HOME"];
+ if (xdg) return join(expandTilde(xdg), "open-second-brain", "config.yaml");
+
+ return join(homedir(), ".config", "open-second-brain", "config.yaml");
+}
+
+/**
+ * Parse the simple `key: value` YAML subset used for the plugin config.
+ *
+ * Intentionally not a real YAML parser β€” keeping this dependency-free and
+ * matching the Python `parse_simple_yaml` exactly so round-trips are stable.
+ * Lines that aren't `key: value` (comments, blanks, complex YAML) are skipped.
+ */
+export function parseSimpleYaml(text: string): Record<string, string> {
+ const data: Record<string, string> = {};
+ for (const rawLine of text.split(/\r?\n/)) {
+ const line = rawLine.trim();
+ if (!line || line.startsWith("#")) continue;
+ const idx = line.indexOf(":");
+ if (idx === -1) continue;
+ const key = line.slice(0, idx).trim();
+ if (!key) continue;
+ let value = line.slice(idx + 1).trim();
+ // Strip surrounding quotes (single OR double).
+ if (
+ value.length >= 2 &&
+ ((value.startsWith('"') && value.endsWith('"')) ||
+ (value.startsWith("'") && value.endsWith("'")))
+ ) {
+ value = value.slice(1, -1);
+ }
+ data[key] = value;
+ }
+ return data;
+}
+
+/** Read and parse the config file, or report it as missing. */
+export function discoverConfig(path?: string): ConfigDiscovery {
+ const resolved = path ?? defaultConfigPath();
+ if (!isRegularFile(resolved)) {
+ return { path: resolved, exists: false, data: {} };
+ }
+ try {
+ const text = readFileSync(resolved, "utf8");
+ return { path: resolved, exists: true, data: parseSimpleYaml(text) };
+ } catch {
+ return { path: resolved, exists: false, data: {} };
+ }
+}
+
+/**
+ * Persist a single `key: value` pair into the plugin config file.
+ *
+ * Atomic: writes to a temp sibling and renames, with fsync on file and parent
+ * dir. Rejects values containing characters that would break the simple parser
+ * on read-back rather than silently corrupting them.
+ */
+export function setConfigValue(key: string, value: string, path?: string): string {
+ if (typeof value !== "string") {
+ throw new TypeError(`config value for ${JSON.stringify(key)} must be a string`);
+ }
+ for (const bad of CONFIG_VALUE_REJECTED_CHARS) {
+ if (value.includes(bad)) {
+ throw new Error(
+ `config value for ${JSON.stringify(key)} contains a disallowed character ` +
+ `(${JSON.stringify(bad)}); reject rather than silently corrupting on read-back`,
+ );
+ }
+ }
+
+ const resolved = path ?? defaultConfigPath();
+ const discovery = discoverConfig(resolved);
+ const data = { ...discovery.data, [key]: value };
+ const body = Object.entries(data).map(([k, v]) => `${k}: "${v}"`).join("\n") + "\n";
+ atomicWriteFileSync(resolved, body);
+ return resolved;
+}
+
+/**
+ * Resolve the IANA timezone for stamping Daily entries.
+ *
+ * Order: `VAULT_TIMEZONE` env β†’ `timezone` field in plugin config β†’ `null`
+ * (caller falls back to the host's local clock). Invalid IANA names are silently
+ * treated as "not configured" so a typo never breaks logging.
+ */
+export function resolveTimezone(configPath?: string): string | null {
+ let name = process.env["VAULT_TIMEZONE"];
+ if (!name) {
+ name = discoverConfig(configPath).data["timezone"];
+ }
+ if (!name) return null;
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: name });
+ return name;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Resolve the vault directory.
+ *
+ * Order: `VAULT_DIR` env β†’ `vault` field in plugin config β†’ `null`. Caller
+ * decides whether to error out or accept a positional path.
+ */
+export function resolveVault(configPath?: string): string | null {
+ const env = process.env["VAULT_DIR"];
+ if (env) return expandTilde(env);
+ const cfg = discoverConfig(configPath).data["vault"];
+ if (cfg) return expandTilde(cfg);
+ return null;
+}
+
+/**
+ * Resolve the agent identity used when no explicit `agent` is supplied.
+ *
+ * Order: `VAULT_AGENT_NAME` env β†’ `agent_name`/`agentName` in plugin config β†’
+ * the literal placeholder `"agent"`. Shared between MCP server's
+ * `event_log_append` default-agent resolution and the Hermes pre_llm_call hook.
+ */
+export function resolveAgentName(configPath?: string): string {
+ const env = process.env["VAULT_AGENT_NAME"];
+ if (env) return env;
+ const data = discoverConfig(configPath).data;
+ const value = data["agent_name"] ?? data["agentName"];
+ if (value) return value;
+ return "agent";
+}
+
+/** Replace values for keys whose name suggests a secret with `[REDACTED]`. */
+export function redactMapping<T extends Record<string, unknown>>(data: T): Record<string, unknown> {
+ const redacted: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(data)) {
+ const lowered = key.toLowerCase();
+ if (SECRET_KEY_PARTS.some((part) => lowered.includes(part))) {
+ redacted[key] = "[REDACTED]";
+ } else {
+ redacted[key] = value;
+ }
+ }
+ return redacted;
+}
+
+function expandTilde(p: string): string {
+ if (p === "~") return homedir();
+ if (p.startsWith("~/")) return join(homedir(), p.slice(2));
+ return p;
+}
+
+function isRegularFile(p: string): boolean {
+ if (!existsSync(p)) return false;
+ try {
+ return statSync(p).isFile();
+ } catch {
+ return false;
+ }
+}
diff --git a/src/core/doctor.ts b/src/core/doctor.ts
new file mode 100644
index 00000000..10bb1b2c
--- /dev/null
+++ b/src/core/doctor.ts
@@ -0,0 +1,327 @@
+/**
+ * Health checks for vault, config, and plugin manifests.
+ *
+ * Mirrors `src/open_second_brain/doctor.py`. Each `check*` returns a
+ * `CheckResult` so callers can aggregate them or surface them through MCP /
+ * Hermes / OpenClaw without taking on doctor's logic themselves.
+ */
+
+import {
+ existsSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeSync,
+ closeSync,
+} from "node:fs";
+import { dirname, join } from "node:path";
+
+import type { CheckResult } from "./types.ts";
+
+export function checkVaultWriteable(vault: string): CheckResult {
+ if (!existsSync(vault)) {
+ return { name: "vault_writeable", ok: false, message: `vault directory missing: ${vault}` };
+ }
+ const probe = join(vault, ".open-second-brain-doctor-test");
+ try {
+ const fd = openSync(probe, "w");
+ closeSync(fd);
+ rmSync(probe);
+ } catch (exc) {
+ return {
+ name: "vault_writeable",
+ ok: false,
+ message: `cannot write to vault: ${(exc as Error).message ?? exc}`,
+ };
+ }
+ return { name: "vault_writeable", ok: true, message: `vault exists and is writable: ${vault}` };
+}
+
+export function checkConfigWriteable(config: string): CheckResult {
+ let createdForCheck = false;
+ try {
+ mkdirSync(dirname(config), { recursive: true });
+ if (!existsSync(config)) createdForCheck = true;
+ const fd = openSync(config, "a");
+ writeSync(fd, "");
+ closeSync(fd);
+ if (createdForCheck) rmSync(config);
+ } catch (exc) {
+ return {
+ name: "config_writeable",
+ ok: false,
+ message: `cannot write config ${config}: ${(exc as Error).message ?? exc}`,
+ };
+ }
+ return { name: "config_writeable", ok: true, message: `config writable: ${config}` };
+}
+
+interface JsonLoadResult {
+ readonly result: CheckResult;
+ readonly data: Record<string, unknown> | null;
+}
+
+function loadJsonManifest(path: string, name: string): JsonLoadResult {
+ if (!isFile(path)) {
+ return {
+ result: { name, ok: false, message: `missing: ${path}` },
+ data: null,
+ };
+ }
+ let data: unknown;
+ try {
+ data = JSON.parse(readFileSync(path, "utf8"));
+ } catch (exc) {
+ return {
+ result: { name, ok: false, message: `invalid JSON: ${path} (${(exc as Error).message})` },
+ data: null,
+ };
+ }
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
+ return {
+ result: { name, ok: false, message: `invalid manifest object: ${path}` },
+ data: null,
+ };
+ }
+ return {
+ result: { name, ok: true, message: `valid: ${path}` },
+ data: data as Record<string, unknown>,
+ };
+}
+
+export function checkJsonManifest(path: string, name: string): CheckResult {
+ return loadJsonManifest(path, name).result;
+}
+
+type FieldType = "string" | "list" | ["string", "list"];
+
+function validateRequired(
+ data: Record<string, unknown>,
+ required: ReadonlyArray<readonly [string, FieldType]>,
+): string[] {
+ const problems: string[] = [];
+ for (const [field, expected] of required) {
+ if (!(field in data)) {
+ problems.push(`missing ${field}`);
+ continue;
+ }
+ const v = data[field];
+ const ok = isOfType(v, expected);
+ if (!ok) {
+ problems.push(`${field} must be ${typeName(expected)}`);
+ continue;
+ }
+ if (typeof v === "string" && v.trim() === "") {
+ problems.push(`${field} must not be empty`);
+ } else if (Array.isArray(v) && v.length === 0) {
+ problems.push(`${field} must not be empty`);
+ }
+ }
+ return problems;
+}
+
+function isOfType(v: unknown, expected: FieldType): boolean {
+ if (expected === "string") return typeof v === "string";
+ if (expected === "list") return Array.isArray(v);
+ return typeof v === "string" || Array.isArray(v);
+}
+
+function typeName(expected: FieldType): string {
+ if (expected === "string") return "str";
+ if (expected === "list") return "list";
+ return expected.map((t) => (t === "string" ? "str" : "list")).join("/");
+}
+
+export function checkCodexManifest(path: string): CheckResult {
+ const { result, data } = loadJsonManifest(path, "codex_manifest");
+ if (!data) return result;
+ const problems = validateRequired(data, [
+ ["name", "string"],
+ ["version", "string"],
+ ["description", "string"],
+ ["skills", "string"],
+ ["keywords", "list"],
+ ]);
+ if (problems.length > 0) {
+ return { name: "codex_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };
+ }
+ return { name: "codex_manifest", ok: true, message: `valid Codex manifest: ${path}` };
+}
+
+export function checkClaudeManifest(path: string): CheckResult {
+ const { result, data } = loadJsonManifest(path, "claude_manifest");
+ if (!data) return result;
+ const problems = validateRequired(data, [
+ ["name", "string"],
+ ["version", "string"],
+ ["description", "string"],
+ ]);
+ for (const field of ["license", "repository", "homepage"]) {
+ if (field in data && typeof data[field] !== "string") {
+ problems.push(`${field} must be string`);
+ }
+ }
+ if ("keywords" in data) {
+ const kw = data["keywords"];
+ if (!Array.isArray(kw) || !kw.every((k) => typeof k === "string")) {
+ problems.push("keywords must be list of strings");
+ }
+ }
+ if ("author" in data) {
+ const author = data["author"];
+ const authorName = typeof author === "object" && author !== null ? (author as Record<string, unknown>)["name"] : null;
+ if (
+ typeof author !== "object" ||
+ author === null ||
+ typeof authorName !== "string" ||
+ authorName.trim() === ""
+ ) {
+ problems.push(
+ "author must be an object with a non-empty 'name' field " +
+ "(legacy string form is rejected by Claude 2.x)",
+ );
+ }
+ }
+ if ("commands" in data) {
+ problems.push(
+ "embedded 'commands' array is deprecated β€” author slash commands " +
+ "as Markdown files under commands/ at plugin root instead",
+ );
+ }
+ if (problems.length > 0) {
+ return { name: "claude_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };
+ }
+ return { name: "claude_manifest", ok: true, message: `valid Claude manifest: ${path}` };
+}
+
+export function checkHermesManifest(path: string): CheckResult {
+ if (!isFile(path)) {
+ return { name: "hermes_manifest", ok: false, message: `missing: ${path}` };
+ }
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch (exc) {
+ return {
+ name: "hermes_manifest",
+ ok: false,
+ message: `invalid text: ${path} (${(exc as Error).message ?? exc})`,
+ };
+ }
+ const required = ["name", "version", "description"];
+ const missing: string[] = [];
+ for (const field of required) {
+ if (!new RegExp(`^${field}\\s*:`, "m").test(text)) missing.push(field);
+ }
+ if (missing.length > 0) {
+ return {
+ name: "hermes_manifest",
+ ok: false,
+ message: `schema invalid: ${path} (missing ${missing.join(", ")})`,
+ };
+ }
+ return { name: "hermes_manifest", ok: true, message: `readable Hermes manifest: ${path}` };
+}
+
+export function checkOpenclawManifest(path: string): CheckResult {
+ const { result, data } = loadJsonManifest(path, "openclaw_manifest");
+ if (!data) return result;
+ const problems: string[] = [];
+ if (typeof data["id"] !== "string" || (data["id"] as string).trim() === "") {
+ problems.push("missing or empty field 'id'");
+ }
+ const schema = data["configSchema"];
+ if (typeof schema !== "object" || schema === null || Object.keys(schema).length === 0) {
+ problems.push("missing or empty field 'configSchema'");
+ }
+ if (problems.length > 0) {
+ return { name: "openclaw_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };
+ }
+ return { name: "openclaw_manifest", ok: true, message: `valid OpenClaw manifest: ${path}` };
+}
+
+/**
+ * Validate the OpenClaw native packaging: a `package.json` with an
+ * `openclaw.extensions` array of files that exist on disk.
+ */
+export function checkOpenclawInstallability(repoRoot: string): CheckResult[] {
+ const results: CheckResult[] = [];
+ const pkgPath = join(repoRoot, "package.json");
+ const { result, data } = loadJsonManifest(pkgPath, "openclaw_package_json");
+ results.push(result);
+ if (!data) return results;
+
+ const oc = (data["openclaw"] as Record<string, unknown> | undefined) ?? {};
+ const extensions = oc["extensions"];
+ if (!Array.isArray(extensions) || extensions.length === 0) {
+ results.push({
+ name: "openclaw_package_json_extensions",
+ ok: false,
+ message: "package.json missing or empty openclaw.extensions array",
+ });
+ return results;
+ }
+ results.push({
+ name: "openclaw_package_json_extensions",
+ ok: true,
+ message: `package.json declares ${extensions.length} extension(s)`,
+ });
+
+ for (const entry of extensions) {
+ if (typeof entry !== "string") {
+ results.push({
+ name: `openclaw_entry_invalid_${typeof entry}`,
+ ok: false,
+ message: `extension entry must be a string, got: ${typeof entry}`,
+ });
+ continue;
+ }
+ const entryPath = join(repoRoot, entry);
+ if (isFile(entryPath)) {
+ results.push({
+ name: `openclaw_entry_${entry}`,
+ ok: true,
+ message: `extension entry exists: ${entry}`,
+ });
+ } else {
+ results.push({
+ name: `openclaw_entry_${entry}`,
+ ok: false,
+ message: `missing extension entry: ${entry}`,
+ });
+ }
+ }
+ return results;
+}
+
+export interface DoctorOptions {
+ readonly vault: string;
+ readonly config?: string | null;
+ readonly repoRoot?: string | null;
+}
+
+export function doctor(opts: DoctorOptions): CheckResult[] {
+ const results: CheckResult[] = [];
+ results.push(checkVaultWriteable(opts.vault));
+ if (opts.config) results.push(checkConfigWriteable(opts.config));
+ if (opts.repoRoot) {
+ const root = opts.repoRoot;
+ results.push(checkClaudeManifest(join(root, ".claude-plugin", "plugin.json")));
+ results.push(checkCodexManifest(join(root, ".codex-plugin", "plugin.json")));
+ results.push(checkHermesManifest(join(root, "plugins", "hermes", "plugin.yaml")));
+ results.push(checkOpenclawManifest(join(root, "openclaw.plugin.json")));
+ results.push(...checkOpenclawInstallability(root));
+ }
+ return results;
+}
+
+function isFile(p: string): boolean {
+ if (!existsSync(p)) return false;
+ try {
+ return statSync(p).isFile();
+ } catch {
+ return false;
+ }
+}
diff --git a/src/core/event-log.ts b/src/core/event-log.ts
new file mode 100644
index 00000000..8159e65e
--- /dev/null
+++ b/src/core/event-log.ts
@@ -0,0 +1,196 @@
+/**
+ * Daily event log: append-only Markdown notes with chronological order and
+ * cross-process safety.
+ *
+ * Mirrors `src/open_second_brain/event_log.py`. The locking strategy uses
+ * `proper-lockfile` because Bun/Node lack a portable `fcntl.flock` equivalent;
+ * `proper-lockfile` is the de-facto standard (lockfile + retry with stale
+ * detection) and survives the same multi-process append test.
+ */
+
+import lockfile from "proper-lockfile";
+import { existsSync, mkdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { atomicWriteFileSync } from "./fs-atomic.ts";
+
+const SECRET_ASSIGNMENT_RE = /\b(api[_-]?key|token|secret|password|credential)(\s*[:=]\s*)\S+/gi;
+const EVENT_RE = /^- (\d{2}:\d{2}) β€” @/;
+const DATE_RE = /^(\d{4})\.(\d{2})\.(\d{2})$/;
+const TIME_RE = /^(\d{2}):(\d{2})$/;
+
+/** Replace secret-like value assignments with `[REDACTED]`. */
+export function redactText(text: string): string {
+ return text.replace(SECRET_ASSIGNMENT_RE, (_match, field, sep) => `${field}${sep}[REDACTED]`);
+}
+
+/**
+ * Current date as `YYYY.MM.DD` in `tz` (or host local).
+ *
+ * When `tz` is supplied, the date is computed in that zone β€” relevant around
+ * midnight when host UTC and user local fall on different days.
+ */
+export function currentDate(tz?: string | null): string {
+ const fmt = new Intl.DateTimeFormat("en-CA", {
+ timeZone: tz ?? undefined,
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ });
+ // en-CA gives YYYY-MM-DD; replace separators to get YYYY.MM.DD.
+ return fmt.format(new Date()).replace(/-/g, ".");
+}
+
+/** Current time as `HH:MM` (24h) in `tz` (or host local). */
+export function currentTime(tz?: string | null): string {
+ const parts = new Intl.DateTimeFormat("en-US", {
+ timeZone: tz ?? undefined,
+ hour: "2-digit",
+ minute: "2-digit",
+ hourCycle: "h23",
+ }).formatToParts(new Date());
+ const get = (type: string) => parts.find((p) => p.type === type)!.value;
+ return `${get("hour")}:${get("minute")}`;
+}
+
+/** Path of the daily note file for `date` inside `vaultDir`. */
+export function dailyNotePath(vaultDir: string, date: string): string {
+ return join(vaultDir, "Daily", `${validateEventDate(date)}.md`);
+}
+
+/** Empty-daily-note template. */
+export function newDailyNote(date: string): string {
+ return `---\nformatted: false\n---\n\n# ${date}\n\n## Raw events\n\n`;
+}
+
+/** Validate a `HH:MM` 24-hour time string. Throws on invalid. */
+export function validateEventTime(value: string): string {
+ const m = TIME_RE.exec(value);
+ if (!m) {
+ throw new Error("event time must use HH:MM 24-hour format");
+ }
+ const hour = parseInt(m[1]!, 10);
+ const minute = parseInt(m[2]!, 10);
+ if (hour > 23 || minute > 59) {
+ throw new Error("event time must use HH:MM 24-hour format");
+ }
+ return value;
+}
+
+/** Validate a `YYYY.MM.DD` date string. Throws on invalid. */
+export function validateEventDate(value: string): string {
+ const m = DATE_RE.exec(value);
+ if (!m) {
+ throw new Error("event date must use YYYY.MM.DD format");
+ }
+ const year = parseInt(m[1]!, 10);
+ const month = parseInt(m[2]!, 10);
+ const day = parseInt(m[3]!, 10);
+ const utc = new Date(Date.UTC(year, month - 1, day));
+ if (
+ utc.getUTCFullYear() !== year ||
+ utc.getUTCMonth() !== month - 1 ||
+ utc.getUTCDate() !== day
+ ) {
+ throw new Error("event date must use YYYY.MM.DD format");
+ }
+ return value;
+}
+
+/**
+ * Insert an event entry into the `## Raw events` section, preserving
+ * chronological order. Pure function β€” no I/O, easy to unit-test.
+ */
+export function insertEventEntry(content: string, entry: string): string {
+ const marker = "## Raw events";
+ const idx = content.indexOf(marker);
+ if (idx === -1) {
+ return content.trimEnd() + "\n\n" + marker + "\n\n" + entry + "\n";
+ }
+ const before = content.slice(0, idx);
+ let after = content.slice(idx + marker.length).replace(/^\n+/, "");
+ const lines = after.split("\n").filter((line) => line.trim());
+
+ // Entry shape: "- HH:MM β€” @..."
+ const entryTime = entry.slice(2, 7);
+ let inserted = false;
+ const output: string[] = [];
+ for (const line of lines) {
+ const m = EVENT_RE.exec(line);
+ if (!inserted && m && m[1]! > entryTime) {
+ output.push(entry);
+ inserted = true;
+ }
+ output.push(line);
+ }
+ if (!inserted) output.push(entry);
+
+ let raw = output.join("\n");
+ if (raw) raw += "\n";
+ return before + marker + "\n\n" + raw;
+}
+
+export interface AppendEventOptions {
+ readonly date?: string | null;
+ readonly time?: string | null;
+ readonly tz?: string | null;
+}
+
+/**
+ * Append a single event to today's (or a specified) Daily note.
+ *
+ * Behavior parity with the Python implementation:
+ * - creates `<vault>/Daily/<date>.md` if missing, with a `## Raw events` section;
+ * - inserts the entry chronologically;
+ * - cross-process safe via `proper-lockfile` on the daily file path;
+ * - atomic write (temp + rename + fsync of file and parent dir);
+ * - redacts secret-like assignments in `message` before writing;
+ * - replaces newlines in message with spaces (one entry = one line).
+ *
+ * Returns the absolute path of the daily note that was written.
+ */
+export async function appendEvent(
+ vaultDir: string,
+ agent: string,
+ message: string,
+ opts: AppendEventOptions = {},
+): Promise<string> {
+ const tz = opts.tz ?? null;
+ const eventDate = validateEventDate(opts.date ?? currentDate(tz));
+ const eventTime = validateEventTime(opts.time ?? currentTime(tz));
+ const path = dailyNotePath(vaultDir, eventDate);
+
+ const cleanMessage = redactText(message).replace(/\r?\n/g, " ");
+ const entry = `- ${eventTime} β€” @${agent} β€” ${cleanMessage}`;
+
+ // proper-lockfile requires the target to exist for `lock(path)`. We lock the
+ // parent directory (`Daily/`) instead, which is created up-front and shared
+ // across all daily files. Locking the directory is the same scope used by
+ // the Python fcntl.flock on a sibling `.{name}.lock` file.
+ const dailyDir = join(vaultDir, "Daily");
+ mkdirSync(dailyDir, { recursive: true });
+
+ const release = await lockfile.lock(dailyDir, {
+ retries: { retries: 30, factor: 1.2, minTimeout: 30, maxTimeout: 500 },
+ stale: 10_000,
+ realpath: false,
+ });
+
+ try {
+ let content: string;
+ if (existsSync(path)) {
+ content = readFileSync(path, "utf8");
+ } else {
+ content = newDailyNote(eventDate);
+ }
+ if (!content.includes("## Raw events")) {
+ content = content.trimEnd() + "\n\n## Raw events\n\n";
+ }
+ const updated = insertEventEntry(content, entry);
+ atomicWriteFileSync(path, updated);
+ } finally {
+ await release();
+ }
+
+ return path;
+}
diff --git a/src/core/fs-atomic.ts b/src/core/fs-atomic.ts
new file mode 100644
index 00000000..78178c86
--- /dev/null
+++ b/src/core/fs-atomic.ts
@@ -0,0 +1,72 @@
+/**
+ * Atomic file write helper.
+ *
+ * Writes the payload to a sibling temp file in the same directory, fsyncs it,
+ * then renames over the target. An interrupted run leaves either the previous
+ * version or the new one β€” never a half-written hybrid. Mirrors the Python
+ * implementation in `set_config_value` and `append_event`.
+ *
+ * Parent-directory fsync is included so that a crash immediately after the
+ * rename still surfaces the new file on remount (POSIX requires fsync of the
+ * directory entry to durably persist the rename).
+ */
+
+import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from "node:fs";
+import { basename, dirname, join } from "node:path";
+
+export function atomicWriteFileSync(target: string, contents: string): void {
+ const dir = dirname(target);
+ mkdirSync(dir, { recursive: true });
+
+ // pid + ms timestamp alone collide when two writes for the same target
+ // hit within the same millisecond (e.g. concurrent appendEvent calls
+ // bypassing the lockfile path). The random suffix makes openSync(..., "wx")
+ // safely unique even in that race.
+ const tmpName = `.${basename(target)}.${process.pid}.${Date.now()}.${Math.random()
+ .toString(16)
+ .slice(2)}.tmp`;
+ const tmpPath = join(dir, tmpName);
+
+ let fd: number | null = null;
+ try {
+ fd = openSync(tmpPath, "wx", 0o644);
+ const buf = Buffer.from(contents, "utf8");
+ let written = 0;
+ while (written < buf.byteLength) {
+ written += writeSync(fd, buf, written, buf.byteLength - written);
+ }
+ fsyncSync(fd);
+ closeSync(fd);
+ fd = null;
+ renameSync(tmpPath, target);
+
+ // Durably persist the rename by fsyncing the parent directory.
+ // Node has no portable directory fsync; on Linux the open-O_RDONLY trick works.
+ try {
+ const dfd = openSync(dir, "r");
+ try {
+ fsyncSync(dfd);
+ } finally {
+ closeSync(dfd);
+ }
+ } catch {
+ // Directory fsync is a best-effort durability optimization.
+ // Failure on platforms that don't support it (rare) is not fatal β€”
+ // the rename itself is already atomic at the inode level.
+ }
+ } catch (err) {
+ if (fd !== null) {
+ try {
+ closeSync(fd);
+ } catch {
+ // ignore
+ }
+ }
+ try {
+ unlinkSync(tmpPath);
+ } catch {
+ // tmp file may not exist if openSync failed
+ }
+ throw err;
+ }
+}
diff --git a/src/core/identity-reminder.ts b/src/core/identity-reminder.ts
new file mode 100644
index 00000000..3f1b4c0c
--- /dev/null
+++ b/src/core/identity-reminder.ts
@@ -0,0 +1,46 @@
+/**
+ * Identity reminder: the text the OpenClaw `before_prompt_build` hook and
+ * the Hermes `pre_llm_call` hook inject into each turn so the agent keeps
+ * remembering it has access to `event_log_append` and under which
+ * `@<agent_name>` it is supposed to log.
+ *
+ * Single source of truth: `templates/identity-reminder.txt` at repo root.
+ * The Hermes Python shim reads the same file; both runtimes stay in sync
+ * without manual mirroring.
+ *
+ * The Codex and Claude Code adapters use the bundled `agent-event-log`
+ * skill (description + body) instead of a hook β€” see
+ * `skills/agent-event-log/SKILL.md`. Skill description is part of the
+ * system prompt every session, so it does not need a hook to land.
+ */
+
+import { readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const TEMPLATE_PATH = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "templates",
+ "identity-reminder.txt",
+);
+
+/** Read the template from disk. Caller substitutes `{agent}` via `buildReminder`. */
+export function loadReminderTemplate(): string {
+ try {
+ return readFileSync(TEMPLATE_PATH, "utf8").trimEnd();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ throw new Error(
+ `Failed to load identity reminder template from ${TEMPLATE_PATH}: ${message}`,
+ );
+ }
+}
+
+/** Substitute `{agent}` and return the rendered reminder body. */
+export function buildReminder(agent: string): string {
+ return loadReminderTemplate().replace(/\{agent\}/g, agent);
+}
+
+export const __TEMPLATE_PATH_FOR_TESTS = TEMPLATE_PATH;
diff --git a/src/core/init.ts b/src/core/init.ts
new file mode 100644
index 00000000..fd69641a
--- /dev/null
+++ b/src/core/init.ts
@@ -0,0 +1,205 @@
+/**
+ * Vault bootstrap: scaffolding the canonical Open Second Brain layout
+ * (`AI Wiki/...`) into a fresh or partially-initialized vault directory.
+ *
+ * Mirrors `src/open_second_brain/init.py`. Idempotent β€” re-running on an
+ * already-initialized vault only creates missing files (or rewrites the
+ * registered-agents list if a new `agentName` is supplied).
+ */
+
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join, posix, normalize } from "node:path";
+
+export const VAULT_FILES: ReadonlyArray<string> = [
+ posix.join("AI Wiki", "_OPEN_SECOND_BRAIN.md"),
+ posix.join("AI Wiki", "_open-second-brain.yaml"),
+ posix.join("AI Wiki", "index.md"),
+ posix.join("AI Wiki", "hot.md"),
+ posix.join("AI Wiki", "log.md"),
+ posix.join("AI Wiki", "identity", "user.md"),
+ posix.join("AI Wiki", "identity", "agents.md"),
+];
+
+export const AGENTS_PLACEHOLDER =
+ "- (add your agents here, e.g., my-agent: operator on my-server)";
+
+const AGENTS_REGISTERED_HEADING = "## Registered agents";
+
+interface Template {
+ readonly relPath: string;
+ readonly render: (ctx: TemplateContext) => string;
+}
+
+interface TemplateContext {
+ readonly name: string;
+ readonly created: string;
+ readonly agentsBlock: string;
+}
+
+const TEMPLATES: ReadonlyArray<Template> = [
+ {
+ relPath: posix.join("AI Wiki", "_OPEN_SECOND_BRAIN.md"),
+ render: ({ name, created }) =>
+ `---\nopen_second_brain_version: 1\nname: ${name}\ncreated: ${created}\n---\n\n` +
+ `# ${name}\n\n` +
+ "This vault is managed by Open Second Brain.\n\n" +
+ "## Rules\n\n" +
+ "- Raw operational evidence goes into event log (Daily/).\n" +
+ "- Synthesized knowledge goes into the wiki (AI Wiki/).\n" +
+ "- Never write secrets, tokens, or credentials here.\n" +
+ "- Read the identity files before acting on this vault.\n",
+ },
+ {
+ relPath: posix.join("AI Wiki", "_open-second-brain.yaml"),
+ render: ({ name, created }) => `version: 1\nname: ${name}\ncreated: ${created}\n`,
+ },
+ {
+ relPath: posix.join("AI Wiki", "index.md"),
+ render: ({ name }) =>
+ `# ${name}\n\n` +
+ `Welcome to the ${name} second brain.\n\n` +
+ "## Key pages\n\n" +
+ "- [[hot]] β€” short-term priority items.\n" +
+ "- [[log]] β€” durable operation log.\n" +
+ "- [[identity/user]] β€” owner profile.\n" +
+ "- [[identity/agents]] β€” allowed agents and scopes.\n",
+ },
+ {
+ relPath: posix.join("AI Wiki", "hot.md"),
+ render: () =>
+ "# Hot\n\n" +
+ "Short-term items, current focus, active decisions.\n\n" +
+ "Items fade to cold over time.\n",
+ },
+ {
+ relPath: posix.join("AI Wiki", "log.md"),
+ render: () =>
+ "# Operation Log\n\n" +
+ "Durable operations, major decisions, and infrastructure changes.\n\n" +
+ "The event log (Daily/) is raw chronological evidence.\n" +
+ "This page is synthesized operational knowledge.\n",
+ },
+ {
+ relPath: posix.join("AI Wiki", "identity", "user.md"),
+ render: () =>
+ "# User Identity\n\n" +
+ "Owner of this vault.\n\n" +
+ "## Profile\n\n" +
+ "- Name: (set your name)\n" +
+ "- Timezone: (set your timezone)\n" +
+ "- Contact: (set your primary contact)\n\n" +
+ "## Preferences\n\n" +
+ "(add durable preferences here so agents can read them)\n",
+ },
+ {
+ relPath: posix.join("AI Wiki", "identity", "agents.md"),
+ render: ({ agentsBlock }) =>
+ "# Agent Identity\n\n" +
+ "Allowed agents and their scopes.\n\n" +
+ "## Registered agents\n\n" +
+ `${agentsBlock}\n\n` +
+ "## Scopes\n\n" +
+ "- Write scope: AI Wiki/, Daily/\n" +
+ "- Read scope: whole vault\n",
+ },
+];
+
+export interface BootstrapVaultOptions {
+ readonly name?: string;
+ readonly agentName?: string | null;
+ readonly force?: boolean;
+}
+
+/**
+ * Bootstrap the canonical layout. Returns the list of relative paths that
+ * were created or rewritten in this invocation (caller uses this to print
+ * a summary).
+ */
+export function bootstrapVault(vaultDir: string, opts: BootstrapVaultOptions = {}): string[] {
+ const name = opts.name ?? "Second Brain";
+ const agentName = opts.agentName ?? null;
+ const force = opts.force ?? false;
+ const created: string[] = [];
+ const ctx: TemplateContext = {
+ name,
+ created: nowIsoZ(),
+ agentsBlock: agentsBlock(agentName),
+ };
+
+ for (const tmpl of TEMPLATES) {
+ const target = join(vaultDir, tmpl.relPath);
+ mkdirSync(dirname(target), { recursive: true });
+
+ if (existsSync(target) && !force) {
+ // Special-case: agents.md may need to be rewritten to register a new
+ // agent identity even though the file already exists. This is what
+ // makes `o2b init --agent-name X` idempotent and additive across
+ // multiple runtimes installing Open Second Brain on the same vault.
+ if (tmpl.relPath === posix.join("AI Wiki", "identity", "agents.md") && agentName) {
+ if (upgradeAgentsFile(target, agentName)) {
+ created.push(normalize(tmpl.relPath));
+ }
+ }
+ continue;
+ }
+ writeFileSync(target, tmpl.render(ctx), "utf8");
+ created.push(normalize(tmpl.relPath));
+ }
+ return created;
+}
+
+function agentsBlock(agentName: string | null): string {
+ if (agentName) return `- ${agentName}: primary agent on this server`;
+ return AGENTS_PLACEHOLDER;
+}
+
+/**
+ * Register `agentName` in the existing `agents.md` registry.
+ *
+ * Cases handled, in order:
+ * - file still has bootstrap placeholder β†’ replace with agent line.
+ * - agent already registered β†’ no-op (idempotent re-init).
+ * - file initialised with another agent's entry β†’ append the new line
+ * under `## Registered agents`, before the next `##` heading.
+ *
+ * Returns `true` when the file was actually rewritten.
+ */
+function upgradeAgentsFile(path: string, agentName: string): boolean {
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch {
+ return false;
+ }
+
+ const entry = `- ${agentName}: primary agent on this server`;
+ if (text.includes(entry)) return false;
+
+ if (text.includes(AGENTS_PLACEHOLDER)) {
+ writeFileSync(path, text.replace(AGENTS_PLACEHOLDER, entry), "utf8");
+ return true;
+ }
+
+ const headingIdx = text.indexOf(AGENTS_REGISTERED_HEADING);
+ if (headingIdx === -1) return false;
+
+ const afterHeading = headingIdx + AGENTS_REGISTERED_HEADING.length;
+ const rest = text.slice(afterHeading);
+ const nextSectionRel = rest.indexOf("\n## ");
+
+ let newText: string;
+ if (nextSectionRel === -1) {
+ newText = text.slice(0, afterHeading) + rest.replace(/\s+$/, "") + `\n${entry}\n`;
+ } else {
+ const boundary = afterHeading + nextSectionRel;
+ const before = text.slice(0, boundary).replace(/\s+$/, "");
+ const after = text.slice(boundary);
+ newText = before + `\n${entry}\n` + after;
+ }
+ writeFileSync(path, newText, "utf8");
+ return true;
+}
+
+function nowIsoZ(): string {
+ return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
+}
diff --git a/src/core/types.ts b/src/core/types.ts
new file mode 100644
index 00000000..0ef75bf2
--- /dev/null
+++ b/src/core/types.ts
@@ -0,0 +1,74 @@
+/**
+ * Shared types across the core library and the runtime adapters (CLI, MCP, OpenClaw).
+ *
+ * Kept in one file because they're plain data shapes β€” no behavior, no I/O. Splitting
+ * per-module would force callers to chase imports across files for what is, in
+ * effect, a single domain vocabulary.
+ */
+
+/** A configuration discovery result returned by `discoverConfig`. */
+export interface ConfigDiscovery {
+ readonly path: string;
+ readonly exists: boolean;
+ readonly data: Readonly<Record<string, string>>;
+}
+
+/** A single doctor check outcome. Mirrors Python `CheckResult` dataclass. */
+export interface CheckResult {
+ readonly name: string;
+ readonly ok: boolean;
+ readonly message: string;
+}
+
+/** Outcome pair from `installCli`. */
+export interface InstallResult {
+ readonly bindir: string;
+ readonly outcomes: ReadonlyArray<readonly [string, string]>;
+ readonly errors: ReadonlyArray<string>;
+}
+
+/** Outcome pair from `uninstallCli`. */
+export interface UninstallResult {
+ readonly bindir: string;
+ readonly outcomes: ReadonlyArray<readonly [string, string]>;
+ readonly errors: ReadonlyArray<string>;
+}
+
+/** Computed plan for an `o2b uninstall` invocation. */
+export interface UninstallPlan {
+ readonly configPath: string;
+ readonly configExists: boolean;
+ readonly configDir: string;
+ readonly configDirExists: boolean;
+ readonly configDirEntries: ReadonlyArray<string>;
+ readonly vaultPath: string | null;
+ readonly applyLocal: boolean;
+ readonly hermesCommands: ReadonlyArray<string>;
+ readonly removedPaths: ReadonlyArray<string>;
+ readonly skippedPaths: ReadonlyArray<readonly [string, string]>;
+ readonly errors: ReadonlyArray<readonly [string, string]>;
+}
+
+/** Hermes-style health report shape (data-only, JSON-serializable). */
+export interface HealthCheckEntry {
+ readonly ok: boolean;
+ readonly path: string;
+ readonly message: string;
+}
+
+export interface HealthReport {
+ readonly name: string;
+ readonly ok: boolean;
+ readonly checks: Readonly<Record<string, HealthCheckEntry>>;
+}
+
+/** Frontmatter values can be strings, numbers, booleans, or arrays of strings. */
+export type FrontmatterValue = string | number | boolean | ReadonlyArray<string>;
+export type FrontmatterMap = Record<string, FrontmatterValue>;
+
+/** A discovered vault page. */
+export interface VaultPage {
+ readonly title: string;
+ readonly path: string;
+ readonly metadata: FrontmatterMap;
+}
diff --git a/src/core/vault.ts b/src/core/vault.ts
new file mode 100644
index 00000000..c1811c4c
--- /dev/null
+++ b/src/core/vault.ts
@@ -0,0 +1,281 @@
+/**
+ * Vault operations: frontmatter parse/write, slugify, wikilink extraction,
+ * Markdown page listing.
+ *
+ * Mirrors `src/open_second_brain/vault.py`. Designed dependency-free; the small
+ * YAML-like emitter handles only the scalar/inline-array shapes that round-trip
+ * through Obsidian and the simple parser.
+ */
+
+import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
+import { dirname, join, relative } from "node:path";
+
+import type { FrontmatterMap, FrontmatterValue, VaultPage } from "./types.ts";
+
+const FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;
+const KEY_VALUE_RE = /^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$/;
+const PLAIN_SCALAR_RE = /^[A-Za-z0-9_./-](?:[A-Za-z0-9_./ -]*[A-Za-z0-9_./-])?$/;
+const WIKILINK_RE = /\[\[([^\]|#]+)(?:[|#][^\]]*)?\]\]/g;
+const CODE_BLOCK_RE = /```[\s\S]*?```|`[^`]+`/g;
+const SLUG_INVALID_RE = /[^a-z0-9]+/g;
+const SLUG_MAX_LEN = 64;
+
+const MEDIA_EXTENSIONS = new Set([
+ ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".tiff", ".avif",
+ ".mp4", ".webm", ".ogv", ".mov", ".mkv", ".avi",
+ ".mp3", ".wav", ".ogg", ".flac", ".m4a",
+ ".pdf",
+]);
+
+const DEFAULT_SKIP_DIRS = [".git", ".obsidian", ".trash", ".stversions"] as const;
+const DEFAULT_SKIP_FILES = ["index.md", "log.md"] as const;
+
+/**
+ * Parse YAML-like frontmatter from a Markdown file. Returns `[metadata, body]`.
+ * Only simple `key: value` lines are recognized β€” values are returned as strings,
+ * with surrounding quotes stripped. Inline arrays `[a, b]` are parsed into arrays
+ * of strings. Lines that don't match are silently skipped.
+ */
+export function parseFrontmatter(path: string): readonly [FrontmatterMap, string] {
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch {
+ return [{}, ""];
+ }
+
+ const match = FRONTMATTER_RE.exec(text);
+ if (!match) {
+ return [{}, text.trim()];
+ }
+
+ const fmBlock = match[1]!;
+ const body = text.slice(match[0].length).trim();
+ const metadata: FrontmatterMap = {};
+
+ for (const rawLine of fmBlock.split("\n")) {
+ const line = rawLine.trim();
+ if (!line || line.startsWith("#")) continue;
+ const kv = KEY_VALUE_RE.exec(line);
+ if (!kv) continue;
+ const key = kv[1]!;
+ let value = kv[2]!.trim();
+
+ if (value.startsWith("[") && value.endsWith("]")) {
+ const inner = value.slice(1, -1).trim();
+ metadata[key] = inner ? splitInlineArray(inner) : [];
+ continue;
+ }
+ metadata[key] = stripQuotes(value);
+ }
+
+ return [metadata, body];
+}
+
+/**
+ * Write a Markdown file with YAML-like frontmatter. Lists are serialized as
+ * inline arrays. Scalars that would break the simple parser are quoted and
+ * standard control chars are escaped.
+ */
+export function writeFrontmatter(path: string, metadata: FrontmatterMap, body: string): void {
+ mkdirSync(dirname(path), { recursive: true });
+ const lines: string[] = ["---"];
+ for (const [key, value] of Object.entries(metadata)) {
+ lines.push(`${key}: ${formatYamlValue(value)}`);
+ }
+ lines.push("---");
+ if (body) {
+ lines.push("");
+ lines.push(body);
+ }
+ writeFileSync(path, lines.join("\n") + "\n", "utf8");
+}
+
+/**
+ * Convert a free-form title to a URL-safe slug. Lowercase, alphanumeric
+ * runs joined by `-`, trimmed to 64 chars. Empty / non-ASCII inputs fall
+ * back to "note".
+ */
+export function slugify(value: string): string {
+ const lowered = value.trim().toLowerCase();
+ let slug = lowered.replace(SLUG_INVALID_RE, "-").replace(/^-+|-+$/g, "");
+ if (!slug) slug = "note";
+ slug = slug.slice(0, SLUG_MAX_LEN).replace(/-+$/, "");
+ return slug || "note";
+}
+
+/**
+ * Extract unique `[[wikilink]]` targets from Markdown content. Skips media
+ * file extensions and links inside fenced or inline code blocks.
+ */
+export function extractWikilinks(content: string): string[] {
+ const masked = content.replace(CODE_BLOCK_RE, " ");
+ const seen = new Set<string>();
+ const result: string[] = [];
+ for (const m of masked.matchAll(WIKILINK_RE)) {
+ const target = m[1]!;
+ const dot = target.lastIndexOf(".");
+ const ext = dot >= 0 ? target.slice(dot).toLowerCase() : "";
+ if (MEDIA_EXTENSIONS.has(ext)) continue;
+ if (!seen.has(target)) {
+ seen.add(target);
+ result.push(target);
+ }
+ }
+ return result;
+}
+
+export interface ListVaultPagesOptions {
+ readonly skipDirs?: ReadonlyArray<string>;
+ readonly skipFiles?: ReadonlyArray<string>;
+}
+
+/**
+ * Walk the vault and return every Markdown page with parsed frontmatter
+ * metadata. Pages are sorted by title (case-insensitive). Excluded dirs/files
+ * mirror the Python defaults.
+ */
+export function listVaultPages(vaultDir: string, opts: ListVaultPagesOptions = {}): VaultPage[] {
+ const skipDirs = new Set(opts.skipDirs ?? DEFAULT_SKIP_DIRS);
+ const skipFiles = new Set((opts.skipFiles ?? DEFAULT_SKIP_FILES).map((f) => f.toLowerCase()));
+
+ const pages: VaultPage[] = [];
+ walk(vaultDir, vaultDir, skipDirs, skipFiles, pages);
+ pages.sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase()));
+ return pages;
+}
+
+function walk(
+ root: string,
+ dir: string,
+ skipDirs: Set<string>,
+ skipFiles: Set<string>,
+ out: VaultPage[],
+): void {
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (skipDirs.has(entry.name)) continue;
+ walk(root, full, skipDirs, skipFiles, out);
+ continue;
+ }
+ if (!entry.isFile()) continue;
+ if (!entry.name.toLowerCase().endsWith(".md")) continue;
+ if (skipFiles.has(entry.name.toLowerCase())) continue;
+ const rel = relative(root, full);
+ const parts = rel.split(/[\\/]/);
+ if (parts.some((p) => skipDirs.has(p))) continue;
+ let meta: FrontmatterMap;
+ try {
+ [meta] = parseFrontmatter(full);
+ } catch {
+ continue;
+ }
+ const titleVal = meta["title"];
+ const title = typeof titleVal === "string" && titleVal ? titleVal : stem(entry.name);
+ out.push({ title, path: full, metadata: meta });
+ }
+}
+
+function stem(filename: string): string {
+ const dot = filename.lastIndexOf(".");
+ return dot > 0 ? filename.slice(0, dot) : filename;
+}
+
+function stripQuotes(s: string): string {
+ if (
+ s.length >= 2 &&
+ ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'")))
+ ) {
+ return s.slice(1, -1);
+ }
+ return s;
+}
+
+/**
+ * Split the body of an inline YAML array on commas, but only on commas that
+ * appear outside quoted runs. Without this, `[plain, "needs, comma"]` would
+ * be split into three tokens (`plain`, `"needs`, `comma"`) β€” breaking the
+ * round-trip with `formatYamlValue`, which already quotes any element that
+ * contains a comma.
+ */
+function splitInlineArray(inner: string): string[] {
+ const out: string[] = [];
+ let current = "";
+ let inQuote = false;
+ let quoteChar: '"' | "'" | "" = "";
+
+ for (let i = 0; i < inner.length; i++) {
+ const ch = inner[i]!;
+ if (inQuote) {
+ current += ch;
+ if (ch === quoteChar && inner[i - 1] !== "\\") {
+ inQuote = false;
+ quoteChar = "";
+ }
+ continue;
+ }
+ if (ch === '"' || ch === "'") {
+ inQuote = true;
+ quoteChar = ch;
+ current += ch;
+ continue;
+ }
+ if (ch === ",") {
+ out.push(stripQuotes(current.trim()));
+ current = "";
+ continue;
+ }
+ current += ch;
+ }
+ // Trailing element (no trailing comma case).
+ if (current.trim() !== "") {
+ out.push(stripQuotes(current.trim()));
+ }
+ return out;
+}
+
+function formatYamlScalar(value: FrontmatterValue): string {
+ const text = typeof value === "string" ? value : String(value);
+ if (
+ text &&
+ PLAIN_SCALAR_RE.test(text) &&
+ !text.includes(": ") &&
+ !text.includes(" #")
+ ) {
+ return text;
+ }
+ const escaped = text
+ .replace(/\\/g, "\\\\")
+ .replace(/"/g, '\\"')
+ .replace(/\n/g, "\\n")
+ .replace(/\r/g, "\\r")
+ .replace(/\t/g, "\\t");
+ return `"${escaped}"`;
+}
+
+function formatYamlValue(value: FrontmatterValue): string {
+ if (Array.isArray(value)) {
+ return "[" + value.map((item) => formatYamlScalar(item)).join(", ") + "]";
+ }
+ return formatYamlScalar(value);
+}
+
+/** Re-exported for callers that want the same exclusion lists in JS plugins. */
+export const EXCLUDED_DIRS = DEFAULT_SKIP_DIRS;
+export const EXCLUDED_FILES = DEFAULT_SKIP_FILES;
+
+export function _internalIsDir(p: string): boolean {
+ if (!existsSync(p)) return false;
+ try {
+ return statSync(p).isDirectory();
+ } catch {
+ return false;
+ }
+}
diff --git a/src/mcp/index.ts b/src/mcp/index.ts
new file mode 100644
index 00000000..f9f2dfc6
--- /dev/null
+++ b/src/mcp/index.ts
@@ -0,0 +1,22 @@
+/**
+ * Public MCP barrel: re-exports the API that callers (CLI, tests, OpenClaw
+ * plugin) consume. Keeps the import surface stable across internal restructure.
+ */
+
+export {
+ PROTOCOL_VERSION,
+ SERVER_NAME,
+ SERVER_VERSION,
+ JSONRPC_VERSION,
+ PARSE_ERROR,
+ INVALID_REQUEST,
+ METHOD_NOT_FOUND,
+ INVALID_PARAMS,
+ INTERNAL_ERROR,
+ MCPError,
+} from "./protocol.ts";
+export { MCPServer, errorResponse, type JsonRpcRequest, type JsonRpcResponse } from "./server.ts";
+export { serveStdio, serveStdioFromString } from "./stdio.ts";
+export { buildToolTable, PLACEHOLDER_AGENT_VALUES, type ToolDefinition } from "./tools.ts";
+export { buildInstructions } from "./instructions.ts";
+export { slugify } from "../core/vault.ts";
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
new file mode 100644
index 00000000..3dc1c52e
--- /dev/null
+++ b/src/mcp/instructions.ts
@@ -0,0 +1,43 @@
+/**
+ * Server-supplied instructions returned in `initialize.instructions`.
+ *
+ * Mirrors `_build_instructions` from the legacy Python implementation.
+ * Keep the wording identical β€” the same string is read by Hermes, Claude
+ * Code, Codex, and OpenClaw, and is referenced verbatim in test fixtures.
+ */
+
+export function buildInstructions(defaultAgent: string): string {
+ return (
+ `You are @${defaultAgent} on this Open Second Brain vault. ` +
+ "Always log under this identity; do not invent or change the name.\n\n" +
+ "When to call event_log_append:\n" +
+ " - immediately after producing a durable artifact, including:\n" +
+ " * code shipped, bug fixed, refactor merged\n" +
+ " * config / deployment / infrastructure change\n" +
+ " * instruction-file edit (CLAUDE.md, SOUL.md, plugin docs, " +
+ "system prompts, similar)\n" +
+ " * content artifact created (post, draft, documentation, " +
+ "marketing copy, release notes)\n" +
+ " * research, investigation, or analysis that produced a " +
+ "concrete finding, design, or decision worth recalling later\n" +
+ " * discovery of an external fact (CLI behaviour change, " +
+ "API quirk, undocumented edge case) that future sessions should " +
+ "know\n" +
+ " - skip for: pure discussion or brainstorming without " +
+ "conclusion, read-only queries, or planning that hasn't yet " +
+ "produced an artifact\n\n" +
+ 'If unsure, ask: "would future-me want to find this in the log ' +
+ 'by searching for it later?". If yes, log it.\n\n' +
+ "How to format the `message` argument:\n" +
+ " - plain prose describing what was done / found / decided and " +
+ "why it matters\n" +
+ " - DO NOT prepend `HH:MM β€”` or `@<name> β€”` to the message; " +
+ "the server adds these automatically\n" +
+ " - terse, append-only, factual; never edit historical lines\n\n" +
+ "Identity is resolved server-side. Do not pass the `agent` argument " +
+ "unless deliberately logging on another agent's behalf.\n\n" +
+ "Other tools: second_brain_status (config status), " +
+ "vault_health (verify vault), second_brain_query (look up notes), " +
+ "second_brain_capture (add wiki pages)."
+ );
+}
diff --git a/src/mcp/protocol.ts b/src/mcp/protocol.ts
new file mode 100644
index 00000000..b7531a9e
--- /dev/null
+++ b/src/mcp/protocol.ts
@@ -0,0 +1,32 @@
+/**
+ * MCP / JSON-RPC 2.0 protocol constants and shared error type.
+ *
+ * Mirrors the constants exposed by the legacy Python `open_second_brain.mcp`
+ * module so cross-runtime tooling (clients, integration tests) can re-use the
+ * same JSON-RPC error codes.
+ */
+
+import packageJson from "../../package.json" with { type: "json" };
+
+export const PROTOCOL_VERSION = "2025-06-18";
+export const SERVER_NAME = "open-second-brain";
+export const JSONRPC_VERSION = "2.0";
+export const SERVER_VERSION: string = packageJson.version;
+
+export const PARSE_ERROR = -32700;
+export const INVALID_REQUEST = -32600;
+export const METHOD_NOT_FOUND = -32601;
+export const INVALID_PARAMS = -32602;
+export const INTERNAL_ERROR = -32603;
+
+export class MCPError extends Error {
+ readonly code: number;
+ readonly data: unknown;
+
+ constructor(code: number, message: string, data?: unknown) {
+ super(message);
+ this.name = "MCPError";
+ this.code = code;
+ this.data = data;
+ }
+}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
new file mode 100644
index 00000000..5dec330e
--- /dev/null
+++ b/src/mcp/server.ts
@@ -0,0 +1,214 @@
+/**
+ * MCP server: JSON-RPC 2.0 dispatcher exposing the five Open Second Brain
+ * tools over the `2025-06-18` MCP protocol. Mirrors the Python `MCPServer`
+ * class, including handshake instructions and error semantics.
+ */
+
+import { resolveAgentName } from "../core/config.ts";
+import { buildInstructions } from "./instructions.ts";
+import {
+ INTERNAL_ERROR,
+ INVALID_PARAMS,
+ INVALID_REQUEST,
+ JSONRPC_VERSION,
+ MCPError,
+ METHOD_NOT_FOUND,
+ PROTOCOL_VERSION,
+ SERVER_NAME,
+ SERVER_VERSION,
+} from "./protocol.ts";
+import { buildToolTable, findTool, type ServerContext, type ToolDefinition } from "./tools.ts";
+
+export interface MCPServerOptions {
+ readonly vault: string;
+ readonly configPath?: string | null;
+ readonly repoRoot?: string | null;
+}
+
+export interface JsonRpcRequest {
+ readonly jsonrpc?: string;
+ readonly id?: unknown;
+ readonly method?: unknown;
+ readonly params?: unknown;
+}
+
+export interface JsonRpcResponse {
+ readonly jsonrpc: string;
+ readonly id: unknown;
+ readonly result?: unknown;
+ readonly error?: { code: number; message: string; data?: unknown };
+}
+
+export class MCPServer {
+ readonly vault: string;
+ readonly configPath: string | null;
+ readonly repoRoot: string | null;
+ readonly tools: ReadonlyArray<ToolDefinition>;
+
+ constructor(opts: MCPServerOptions) {
+ this.vault = opts.vault;
+ this.configPath = opts.configPath ?? null;
+ this.repoRoot = opts.repoRoot ?? null;
+ this.tools = buildToolTable();
+ }
+
+ get context(): ServerContext {
+ return { vault: this.vault, configPath: this.configPath, repoRoot: this.repoRoot };
+ }
+
+ /** Public method for CLI tool-call bridge β€” the legacy code reached into `_tools`. */
+ async callTool(name: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {
+ const tool = findTool(this.tools, name);
+ return toolResult(await tool.handler(this.context, args));
+ }
+
+ /** Process one JSON-RPC request or notification. Returns null for notifications. */
+ async handleRequest(request: JsonRpcRequest): Promise<JsonRpcResponse | null> {
+ if (typeof request !== "object" || request === null) {
+ return errorResponse(null, INVALID_REQUEST, "request must be an object");
+ }
+ if (request.jsonrpc !== JSONRPC_VERSION) {
+ return errorResponse(request.id ?? null, INVALID_REQUEST, "unsupported jsonrpc version");
+ }
+ const method = request.method;
+ if (typeof method !== "string") {
+ return errorResponse(request.id ?? null, INVALID_REQUEST, "method must be a string");
+ }
+ const paramsRaw = request.params ?? {};
+ if (typeof paramsRaw !== "object" || paramsRaw === null || Array.isArray(paramsRaw)) {
+ return errorResponse(request.id ?? null, INVALID_PARAMS, "params must be an object");
+ }
+ const params = paramsRaw as Record<string, unknown>;
+ // JSON-RPC 2.0 Β§4.1: `id` MUST be a string, number, or null. Anything
+ // else (objects, symbols, arrays) is a protocol violation β€” respond
+ // with INVALID_REQUEST and id: null so a non-compliant client sees a
+ // well-formed error frame instead of getting our object back as `id`.
+ const isNotification = !("id" in request);
+ if (!isNotification) {
+ const idType = typeof request.id;
+ if (
+ idType !== "string" &&
+ idType !== "number" &&
+ request.id !== null
+ ) {
+ return errorResponse(null, INVALID_REQUEST, "id must be string, number, or null");
+ }
+ }
+ const requestId = request.id;
+
+ try {
+ let result: unknown;
+ if (method === "initialize") {
+ result = this.handleInitialize(params);
+ } else if (method === "notifications/initialized") {
+ // No internal state to flip β€” protocol parity only.
+ return null;
+ } else if (method === "ping") {
+ result = {};
+ } else if (method === "tools/list") {
+ result = this.handleToolsList();
+ } else if (method === "tools/call") {
+ result = await this.handleToolsCall(params);
+ } else if (method.startsWith("notifications/")) {
+ return null;
+ } else {
+ throw new MCPError(METHOD_NOT_FOUND, `unknown method: ${method}`);
+ }
+
+ if (isNotification) return null;
+ return { jsonrpc: JSONRPC_VERSION, id: requestId, result };
+ } catch (exc) {
+ if (isNotification) return null;
+ if (exc instanceof MCPError) {
+ return errorResponse(requestId, exc.code, exc.message, exc.data);
+ }
+ const message = (exc as Error).message ?? String(exc);
+ return errorResponse(requestId, INTERNAL_ERROR, `internal error: ${message}`);
+ }
+ }
+
+ private handleInitialize(params: Record<string, unknown>): Record<string, unknown> {
+ const clientVersion = params["protocolVersion"];
+ const negotiated = typeof clientVersion === "string" ? clientVersion : PROTOCOL_VERSION;
+ const defaultAgent = resolveAgentName(this.configPath ?? undefined);
+ return {
+ protocolVersion: negotiated,
+ capabilities: { tools: { listChanged: false } },
+ serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
+ instructions: buildInstructions(defaultAgent),
+ };
+ }
+
+ private handleToolsList(): Record<string, unknown> {
+ return {
+ tools: this.tools.map((t) => ({
+ name: t.name,
+ description: t.description,
+ inputSchema: t.inputSchema,
+ })),
+ };
+ }
+
+ private async handleToolsCall(params: Record<string, unknown>): Promise<Record<string, unknown>> {
+ const name = params["name"];
+ if (typeof name !== "string") {
+ throw new MCPError(INVALID_PARAMS, "tools/call requires a string name");
+ }
+ const tool = findTool(this.tools, name);
+ const argsRaw = params["arguments"] ?? {};
+ if (typeof argsRaw !== "object" || argsRaw === null || Array.isArray(argsRaw)) {
+ throw new MCPError(INVALID_PARAMS, "tools/call arguments must be an object");
+ }
+ const args = argsRaw as Record<string, unknown>;
+ try {
+ const structured = await tool.handler(this.context, args);
+ return toolResult(structured);
+ } catch (exc) {
+ if (exc instanceof MCPError) throw exc;
+ const message = (exc as Error).message ?? String(exc);
+ // ValueError/TypeError semantics in Python β†’ tool-level error envelope.
+ // OSError in Python β†’ "filesystem error" prefix. We collapse both to a
+ // single tool-level error since JS doesn't distinguish.
+ return toolError(message);
+ }
+ }
+}
+
+function toolResult(structured: unknown): Record<string, unknown> {
+ const text = JSON.stringify(structured, sortedReplacer, 2);
+ return {
+ content: [{ type: "text", text }],
+ structuredContent: structured,
+ isError: false,
+ };
+}
+
+function toolError(message: string): Record<string, unknown> {
+ return {
+ content: [{ type: "text", text: message }],
+ isError: true,
+ };
+}
+
+function sortedReplacer(_key: string, value: unknown): unknown {
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
+ return Object.fromEntries(entries);
+ }
+ return value;
+}
+
+export function errorResponse(
+ requestId: unknown,
+ code: number,
+ message: string,
+ data?: unknown,
+): JsonRpcResponse {
+ const error: { code: number; message: string; data?: unknown } = { code, message };
+ if (data !== undefined) error.data = data;
+ return { jsonrpc: JSONRPC_VERSION, id: requestId ?? null, error };
+}
+
+// Re-exports so callers that previously imported these names from
+// `open_second_brain.mcp` keep working.
+export { PROTOCOL_VERSION, SERVER_NAME, SERVER_VERSION, JSONRPC_VERSION };
diff --git a/src/mcp/stdio.ts b/src/mcp/stdio.ts
new file mode 100644
index 00000000..70e9d71d
--- /dev/null
+++ b/src/mcp/stdio.ts
@@ -0,0 +1,100 @@
+/**
+ * Newline-delimited JSON stdio loop for the MCP server.
+ *
+ * Mirrors `serve_stdio` from the legacy Python implementation. The server
+ * only writes JSON-RPC frames to stdout; logs go to stderr.
+ */
+
+import { createInterface } from "node:readline";
+import type { Readable, Writable } from "node:stream";
+
+import { MCPServer } from "./server.ts";
+import { errorResponse, type JsonRpcResponse } from "./server.ts";
+import { INVALID_REQUEST, PARSE_ERROR } from "./protocol.ts";
+
+export interface ServeStdioOptions {
+ readonly stdin?: Readable;
+ readonly stdout?: Writable;
+ readonly stderr?: Writable;
+}
+
+/**
+ * Stream-based stdio loop. Resolves to 0 on normal EOF.
+ *
+ * The implementation reads line-by-line and dispatches each line as a
+ * JSON-RPC request. Invalid JSON yields a `-32700` parse-error response;
+ * batch requests (an array at the top level) yield a `-32600` invalid-request
+ * response, matching the 2025-06-18 spec which removed batch support.
+ */
+export async function serveStdio(server: MCPServer, opts: ServeStdioOptions = {}): Promise<number> {
+ const stdin = opts.stdin ?? process.stdin;
+ const stdout = opts.stdout ?? process.stdout;
+ const rl = createInterface({ input: stdin, crlfDelay: Infinity });
+
+ for await (const rawLine of rl) {
+ const line = rawLine.trim();
+ if (!line) continue;
+ let request: unknown;
+ try {
+ request = JSON.parse(line);
+ } catch (exc) {
+ writeFrame(stdout, errorResponse(null, PARSE_ERROR, `invalid JSON: ${(exc as Error).message}`));
+ continue;
+ }
+ if (Array.isArray(request)) {
+ writeFrame(
+ stdout,
+ errorResponse(null, INVALID_REQUEST, "batch requests are not supported by the 2025-06-18 spec"),
+ );
+ continue;
+ }
+ if (typeof request !== "object" || request === null) {
+ writeFrame(stdout, errorResponse(null, INVALID_REQUEST, "request must be an object"));
+ continue;
+ }
+ const response = await server.handleRequest(request as Record<string, unknown>);
+ if (response !== null) writeFrame(stdout, response);
+ }
+ return 0;
+}
+
+function writeFrame(out: Writable, response: JsonRpcResponse): void {
+ let line = JSON.stringify(response);
+ if (line.includes("\n")) line = line.replace(/\n/g, " ");
+ out.write(line + "\n");
+}
+
+/**
+ * Synchronous-style serveStdio fallback for embedded test harnesses that pass
+ * an in-memory string buffer instead of a real stream. Tests use this to
+ * bypass the readline async iteration.
+ */
+export async function serveStdioFromString(server: MCPServer, payload: string): Promise<string[]> {
+ const out: string[] = [];
+ for (const rawLine of payload.split("\n")) {
+ const line = rawLine.trim();
+ if (!line) continue;
+ let request: unknown;
+ try {
+ request = JSON.parse(line);
+ } catch (exc) {
+ out.push(JSON.stringify(errorResponse(null, PARSE_ERROR, `invalid JSON: ${(exc as Error).message}`)));
+ continue;
+ }
+ if (Array.isArray(request)) {
+ out.push(
+ JSON.stringify(
+ errorResponse(null, INVALID_REQUEST, "batch requests are not supported by the 2025-06-18 spec"),
+ ),
+ );
+ continue;
+ }
+ if (typeof request !== "object" || request === null) {
+ out.push(JSON.stringify(errorResponse(null, INVALID_REQUEST, "request must be an object")));
+ continue;
+ }
+ const response = await server.handleRequest(request as Record<string, unknown>);
+ if (response !== null) out.push(JSON.stringify(response));
+ }
+ return out;
+}
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
new file mode 100644
index 00000000..a52f3ac6
--- /dev/null
+++ b/src/mcp/tools.ts
@@ -0,0 +1,366 @@
+/**
+ * MCP tool registry: the five tools exposed by Open Second Brain
+ * (`second_brain_status`, `second_brain_query`, `second_brain_capture`,
+ * `event_log_append`, `vault_health`). Each handler delegates to the
+ * core/* helpers so the contract stays identical to the CLI.
+ */
+
+import { existsSync, mkdirSync, statSync } from "node:fs";
+import { join, relative, resolve } from "node:path";
+
+import {
+ discoverConfig,
+ redactMapping,
+ resolveAgentName,
+ resolveTimezone,
+} from "../core/config.ts";
+import { doctor } from "../core/doctor.ts";
+import { appendEvent, validateEventTime } from "../core/event-log.ts";
+import { listVaultPages, slugify, writeFrontmatter } from "../core/vault.ts";
+import { INVALID_PARAMS, METHOD_NOT_FOUND, MCPError } from "./protocol.ts";
+
+export interface ServerContext {
+ readonly vault: string;
+ readonly configPath: string | null;
+ readonly repoRoot: string | null;
+}
+
+export interface ToolDefinition {
+ readonly name: string;
+ readonly description: string;
+ readonly inputSchema: Record<string, unknown>;
+ readonly handler: (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown;
+}
+
+/**
+ * Strings the LLM is most likely to emit as a guess for the `agent` argument
+ * when it doesn't actually know its identity. None are useful as a real
+ * `@<name>` in Daily β€” they should fall back to the server-resolved default.
+ * Compared case-insensitively, after a leading `@` is stripped.
+ *
+ * Mirrored verbatim by the OpenClaw plugin entry so all runtimes filter the
+ * same hallucination shapes out of Daily.
+ */
+const PLACEHOLDER_AGENT_VALUES = new Set([
+ "agent",
+ "assistant",
+ "ai",
+ "ai-assistant",
+ "bot",
+ "chatbot",
+ "claude",
+ "claude-code",
+ "codex",
+ "codex-cli",
+ "codex-exec",
+ "copilot",
+ "gemini",
+ "gpt",
+ "gpt-4",
+ "gpt-5",
+ "hermes",
+ "llm",
+ "model",
+ "openai",
+ "openclaw",
+ "user",
+]);
+
+function vaultRelpath(target: string, vault: string): string {
+ try {
+ return relative(resolve(vault), resolve(target));
+ } catch {
+ return target;
+ }
+}
+
+function ensureInsideVault(target: string, vault: string): string {
+ const resolvedTarget = resolve(target);
+ const resolvedVault = resolve(vault);
+ if (resolvedTarget !== resolvedVault && !resolvedTarget.startsWith(resolvedVault + "/")) {
+ throw new Error(`path escapes vault: ${target}`);
+ }
+ return resolvedTarget;
+}
+
+function coerceStr(args: Record<string, unknown>, key: string, required = true, defaultValue: string | null = null): string | null {
+ const value = args[key];
+ if (value === undefined || value === null || (typeof value === "string" && value.trim() === "")) {
+ if (required) {
+ throw new MCPError(INVALID_PARAMS, `missing required argument: ${key}`);
+ }
+ return defaultValue;
+ }
+ if (typeof value !== "string") {
+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a string`);
+ }
+ return value;
+}
+
+function coerceStrList(args: Record<string, unknown>, key: string): string[] {
+ const value = args[key];
+ if (value === undefined || value === null) return [];
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a list of strings`);
+ }
+ return [...value] as string[];
+}
+
+function coerceInt(
+ args: Record<string, unknown>,
+ key: string,
+ defaultValue: number,
+ min: number,
+ max: number,
+): number {
+ const value = args[key] ?? defaultValue;
+ if (typeof value === "boolean" || typeof value !== "number" || !Number.isInteger(value)) {
+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be an integer`);
+ }
+ if (value < min || value > max) {
+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be between ${min} and ${max}`);
+ }
+ return value;
+}
+
+function normalizeAgentArgument(value: string | null): string | null {
+ if (value === null || value === undefined) return null;
+ const cleaned = value.trim().replace(/^@+/, "").trim();
+ if (!cleaned) return null;
+ if (PLACEHOLDER_AGENT_VALUES.has(cleaned.toLowerCase())) return null;
+ return cleaned;
+}
+
+// ── Tool implementations ────────────────────────────────────────────────────
+
+async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>> {
+ const discovery = discoverConfig(ctx.configPath ?? undefined);
+ const vaultExists = isDir(ctx.vault);
+ const configKeys = Object.keys(discovery.data).sort();
+ return {
+ config_path: String(discovery.path),
+ config_exists: discovery.exists,
+ config_keys: configKeys,
+ config: redactMapping(discovery.data),
+ vault_path: ctx.vault,
+ vault_exists: vaultExists,
+ };
+}
+
+async function toolQuery(ctx: ServerContext, args: Record<string, unknown>): Promise<Record<string, unknown>> {
+ if (!isDir(ctx.vault)) {
+ throw new MCPError(INVALID_PARAMS, `vault directory missing: ${ctx.vault}`);
+ }
+ const pattern = coerceStr(args, "pattern", false);
+ const limit = coerceInt(args, "limit", 50, 1, 500);
+
+ const pages = listVaultPages(ctx.vault);
+ const needle = pattern ? pattern.toLowerCase() : null;
+ const matched: Array<Record<string, unknown>> = [];
+ for (const p of pages) {
+ if (needle !== null && !p.title.toLowerCase().includes(needle)) continue;
+ matched.push({
+ title: p.title,
+ path: vaultRelpath(p.path, ctx.vault),
+ metadata: p.metadata,
+ });
+ if (matched.length >= limit) break;
+ }
+ return {
+ vault_path: ctx.vault,
+ total_pages: pages.length,
+ returned: matched.length,
+ limit,
+ pattern,
+ pages: matched,
+ };
+}
+
+async function toolCapture(ctx: ServerContext, args: Record<string, unknown>): Promise<Record<string, unknown>> {
+ if (!isDir(ctx.vault)) {
+ throw new MCPError(INVALID_PARAMS, `vault directory missing: ${ctx.vault}`);
+ }
+ const title = coerceStr(args, "title", true)!;
+ const content = coerceStr(args, "content", true)!;
+ const tags = coerceStrList(args, "tags");
+ const overwrite = Boolean(args["overwrite"] ?? false);
+
+ if (!title.trim()) throw new MCPError(INVALID_PARAMS, "title must not be empty");
+ if (!content.trim()) throw new MCPError(INVALID_PARAMS, "content must not be empty");
+
+ const notesDir = join(ctx.vault, "AI Wiki", "notes");
+ mkdirSync(notesDir, { recursive: true });
+ const slug = slugify(title);
+ const target = join(notesDir, `${slug}.md`);
+ ensureInsideVault(target, ctx.vault);
+
+ const existed = existsSync(target);
+ if (existed && !overwrite) {
+ throw new Error(`note already exists: ${vaultRelpath(target, ctx.vault)}`);
+ }
+
+ const metadata: Record<string, string | number | boolean | string[]> = {
+ title,
+ type: "note",
+ created: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"),
+ };
+ if (tags.length > 0) metadata["tags"] = tags;
+ writeFrontmatter(target, metadata, content.trim());
+
+ return {
+ path: vaultRelpath(target, ctx.vault),
+ absolute_path: resolve(target),
+ slug,
+ overwritten: existed && overwrite,
+ };
+}
+
+async function toolEventLogAppend(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const message = coerceStr(args, "message", true)!;
+ const agent = coerceStr(args, "agent", false);
+ const date = coerceStr(args, "date", false);
+ const time = coerceStr(args, "time", false);
+
+ if (time !== null) validateEventTime(time);
+
+ const effectiveAgent =
+ normalizeAgentArgument(agent) ?? resolveAgentName(ctx.configPath ?? undefined);
+ const tz = resolveTimezone(ctx.configPath ?? undefined);
+ const path = await appendEvent(ctx.vault, effectiveAgent, message, { date, time, tz });
+
+ return {
+ path: vaultRelpath(path, ctx.vault),
+ absolute_path: resolve(path),
+ agent: effectiveAgent,
+ date,
+ time,
+ };
+}
+
+async function toolVaultHealth(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const repoArg = coerceStr(args, "repo", false);
+ const repoRoot = repoArg ?? ctx.repoRoot;
+ const results = doctor({
+ vault: ctx.vault,
+ config: ctx.configPath,
+ repoRoot: repoRoot ?? null,
+ });
+ const payload = results.map((r) => ({ name: r.name, ok: r.ok, message: r.message }));
+ return {
+ vault_path: ctx.vault,
+ config_path: ctx.configPath ? String(ctx.configPath) : null,
+ repo_root: repoRoot ? String(repoRoot) : null,
+ ok: payload.every((c) => c.ok),
+ checks: payload,
+ };
+}
+
+function isDir(p: string): boolean {
+ if (!existsSync(p)) return false;
+ try {
+ return statSync(p).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+export function buildToolTable(): ToolDefinition[] {
+ return [
+ {
+ name: "second_brain_status",
+ description: "Report Open Second Brain configuration and vault status.",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ handler: toolStatus,
+ },
+ {
+ name: "second_brain_query",
+ description: "List vault pages with optional title substring filter.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ pattern: {
+ type: "string",
+ description: "Optional case-insensitive substring matched against page titles.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 500,
+ description: "Maximum number of matched pages to return (default 50).",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolQuery,
+ },
+ {
+ name: "second_brain_capture",
+ description: "Write a new Markdown note to AI Wiki/notes/ with frontmatter.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ title: { type: "string", description: "Human-readable note title." },
+ content: { type: "string", description: "Markdown body of the note." },
+ tags: {
+ type: "array",
+ items: { type: "string" },
+ description: "Optional list of tag strings.",
+ },
+ overwrite: {
+ type: "boolean",
+ description: "Allow overwriting an existing note with the same slug.",
+ },
+ },
+ required: ["title", "content"],
+ additionalProperties: false,
+ },
+ handler: toolCapture,
+ },
+ {
+ name: "event_log_append",
+ description: "Append a single-line event to the daily Markdown event log.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ message: { type: "string", description: "Single-line event message." },
+ agent: { type: "string", description: "Agent name (default 'agent')." },
+ date: { type: "string", description: "Optional event date in YYYY.MM.DD format." },
+ time: { type: "string", description: "Optional event time in 24-hour HH:MM format." },
+ },
+ required: ["message"],
+ additionalProperties: false,
+ },
+ handler: toolEventLogAppend,
+ },
+ {
+ name: "vault_health",
+ description: "Run vault, config, and plugin manifest health checks.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ repo: {
+ type: "string",
+ description: "Optional repository root to validate plugin manifests.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolVaultHealth,
+ },
+ ];
+}
+
+export function findTool(tools: ReadonlyArray<ToolDefinition>, name: string): ToolDefinition {
+ const tool = tools.find((t) => t.name === name);
+ if (!tool) throw new MCPError(METHOD_NOT_FOUND, `unknown tool: ${name}`);
+ return tool;
+}
+
+// Re-export for callers that need to filter agent guesses themselves.
+export { PLACEHOLDER_AGENT_VALUES };
diff --git a/src/open_second_brain/__init__.py b/src/open_second_brain/__init__.py
deleted file mode 100644
index 015a71d0..00000000
--- a/src/open_second_brain/__init__.py
+++ /dev/null
@@ -1,65 +0,0 @@
-"""Open Second Brain core package."""
-
-from __future__ import annotations
-
-
-def _resolve_version() -> str:
- """Resolve the package version from a single source of truth.
-
- Order of resolution:
-
- 1. ``pyproject.toml`` reachable from the source file. Preferred because
- editable installs (``pip install -e .``) snapshot ``dist-info`` at
- install time and go stale on every version bump until reinstall.
- Reading the live ``pyproject.toml`` keeps the runtime version in
- sync with the working tree without forcing a reinstall step.
- 2. Installed package metadata via ``importlib.metadata``. Used when
- the package was installed from a wheel and no source tree is
- reachable (no ``pyproject.toml`` next to the code).
- 3. A safe sentinel (``"0.0.0+unknown"``) so callers never crash on a
- missing version β€” surfaces clearly in logs / status checks.
-
- Other files that carry a copy of the version (manifests, package.json,
- install commands) are kept in sync by ``scripts/sync-version.py``,
- which reads the same ``pyproject.toml``.
- """
- try:
- import tomllib
- from pathlib import Path
- except ImportError:
- tomllib = None # type: ignore[assignment]
- Path = None # type: ignore[assignment]
-
- if tomllib is not None and Path is not None:
- here = Path(__file__).resolve()
- for parent in here.parents:
- candidate = parent / "pyproject.toml"
- if not candidate.is_file():
- continue
- try:
- with candidate.open("rb") as fh:
- data = tomllib.load(fh)
- except (OSError, ValueError):
- break
- project = data.get("project") or {}
- if project.get("name") != "open-second-brain":
- # A pyproject.toml exists but it's for a different project
- # (e.g. when this package is vendored into another repo).
- # Don't claim somebody else's version β€” fall through.
- break
- value = project.get("version")
- if isinstance(value, str) and value:
- return value
- break
-
- try:
- from importlib.metadata import version as _pkg_version
-
- return _pkg_version("open-second-brain")
- except Exception:
- return "0.0.0+unknown"
-
-
-__version__ = _resolve_version()
-
-__all__ = ["__version__"]
diff --git a/src/open_second_brain/cli.py b/src/open_second_brain/cli.py
deleted file mode 100644
index 24e0435b..00000000
--- a/src/open_second_brain/cli.py
+++ /dev/null
@@ -1,440 +0,0 @@
-from __future__ import annotations
-
-import argparse
-import json
-import os
-import sys
-from pathlib import Path
-
-import json as _json
-
-from open_second_brain.config import (
- default_config_path,
- discover_config,
- redact_mapping,
- resolve_timezone,
- resolve_vault,
- set_config_value,
-)
-from open_second_brain.doctor import doctor
-from open_second_brain.event_log import append_event
-from open_second_brain.init import bootstrap_vault
-from open_second_brain.install_cli import (
- install_cli,
- render_install_result,
- render_uninstall_result,
- uninstall_cli,
-)
-from open_second_brain.mcp import MCPServer, run_cli_command as run_mcp_server
-from open_second_brain.uninstall import plan_uninstall, render_plan
-from open_second_brain.vault import list_vault_pages, write_frontmatter
-
-
-def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(prog="o2b", description="Open Second Brain CLI")
- subcommands = parser.add_subparsers(dest="command", required=True)
-
- status = subcommands.add_parser("status", help="Show Open Second Brain configuration status")
- status.add_argument("--config", type=Path, default=None, help="Config file path")
- status.add_argument("--vault", type=Path, default=None, help="Vault directory path")
- status.add_argument("--json", action="store_true", help="Output as JSON")
-
- init_cmd = subcommands.add_parser("init", help="Initialize a vault profile with required files")
- init_cmd.add_argument("--vault", type=Path, required=True, help="Vault directory path")
- init_cmd.add_argument("--name", default="Second Brain", help="Instance name (default: Second Brain)")
- init_cmd.add_argument(
- "--agent-name",
- dest="agent_name",
- default=None,
- help=(
- "Agent identity used in Daily event log entries (e.g. 'openclaw-main'). "
- "When set, the chosen name is written into AI Wiki/identity/agents.md "
- "and replaces the @agent placeholder in subsequent event_log_append calls."
- ),
- )
- init_cmd.add_argument(
- "--timezone",
- dest="timezone",
- default=None,
- help=(
- "IANA timezone name (e.g. 'Europe/Belgrade', 'America/New_York', 'UTC') "
- "used to stamp Daily event log entries in the user's local time. "
- "Persisted to the plugin config so every runtime stamps consistently. "
- "Validated via stdlib zoneinfo; invalid names are rejected immediately. "
- "If omitted, entries are stamped in the host's system-local time."
- ),
- )
- init_cmd.add_argument("--force", action="store_true", help="Overwrite existing files")
-
- doctor_cmd = subcommands.add_parser("doctor", help="Run health checks on vault, config, and plugins")
- doctor_cmd.add_argument("--vault", type=Path, default=None, help="Vault directory path")
- doctor_cmd.add_argument("--config", type=Path, default=None, help="Config file path")
- doctor_cmd.add_argument("--repo", type=Path, default=None, help="Repository root for plugin checks")
-
- append = subcommands.add_parser("append-event", help="Append an event to the configured event log backend")
- append.add_argument("message", help="Single-line event message")
- append.add_argument("--vault", type=Path, default=None, help="Vault directory")
- append.add_argument("--as", dest="agent", default=os.environ.get("VAULT_AGENT_NAME", "agent"), help="Agent name")
- append.add_argument("--date", default=None, help="Event date as YYYY.MM.DD")
- append.add_argument("--time", default=None, help="Event time as HH:MM")
-
- export = subcommands.add_parser("export-config", help="Write a redacted config snapshot")
- export.add_argument("--config", type=Path, default=None, help="Config file path")
- export.add_argument("--output", type=Path, required=True, help="Output JSON file")
-
- index_cmd = subcommands.add_parser("index", help="Regenerate the vault index from discovered pages")
- index_cmd.add_argument("--vault", type=Path, default=None, help="Vault directory path")
-
- mcp_cmd = subcommands.add_parser(
- "mcp",
- help="Run the optional MCP tool server (stdio JSON-RPC)",
- description=(
- "Start an MCP server over stdio that exposes Second Brain tools. "
- "Pair with Hermes ~/.hermes/config.yaml mcp_servers."
- ),
- )
- mcp_cmd.add_argument("--vault", type=Path, default=None, help="Vault directory path")
- mcp_cmd.add_argument("--config", type=Path, default=None, help="Config file path")
- mcp_cmd.add_argument("--repo", type=Path, default=None, help="Repository root for plugin checks")
-
- install_cli_cmd = subcommands.add_parser(
- "install-cli",
- help="Create symlinks for o2b and vault-log in ~/.local/bin",
- description=(
- "Symlink the CLI wrapper scripts (scripts/o2b, scripts/vault-log) into "
- "~/.local/bin so that bare 'o2b' and 'vault-log' commands work on PATH. "
- "Run this once after 'hermes plugins install'. The symlinks survive "
- "'hermes plugins update' because they point into the git checkout."
- ),
- )
- install_cli_cmd.add_argument(
- "--bindir",
- type=Path,
- default=None,
- help="Target directory for symlinks (default: ~/.local/bin)",
- )
-
- uninstall_cmd = subcommands.add_parser(
- "uninstall",
- help="Print an uninstall plan and (optionally) clean local config and CLI symlinks",
- description=(
- "Read-only by default. Prints the Hermes commands you must run yourself "
- "(this tool never touches ~/.hermes/config.yaml or the installed plugin). "
- "With --apply-local it may remove the machine-local Open Second Brain "
- "config directory only. Your vault, Daily/, AI Wiki/, and Markdown notes "
- "are never removed. With --remove-cli it also removes the o2b/vault-log "
- "symlinks created by 'o2b install-cli'."
- ),
- )
- uninstall_cmd.add_argument("--config", type=Path, default=None, help="Config file path")
- uninstall_cmd.add_argument(
- "--apply-local",
- action="store_true",
- help=(
- "Remove the machine-local Open Second Brain config directory "
- "(typically ~/.config/open-second-brain). Hermes config and the vault "
- "are never touched."
- ),
- )
- uninstall_cmd.add_argument(
- "--remove-cli",
- action="store_true",
- dest="remove_cli",
- help=(
- "Remove the o2b and vault-log symlinks from ~/.local/bin "
- "(created by 'o2b install-cli')."
- ),
- )
-
- tool_call_cmd = subcommands.add_parser(
- "tool-call",
- help="Invoke an MCP tool handler from the CLI and print JSON to stdout.",
- )
- tool_call_cmd.add_argument("--vault", type=Path, default=None, help="Vault directory path")
- tool_call_cmd.add_argument("tool_name", help="MCP tool name to invoke")
- tool_call_cmd.add_argument(
- "--tool-arg",
- action="append",
- default=[],
- dest="tool_args",
- help="Tool argument as key=value (repeatable)",
- )
-
- return parser
-
-
-def _require_vault(args: argparse.Namespace, config_path: Path | None) -> Path:
- """Resolve the vault path or exit with a clear error.
-
- Resolution order: ``--vault`` CLI arg β†’ ``VAULT_DIR`` env β†’
- persisted plugin config (`vault` field, written by ``o2b init``).
- If none of those is configured, the command aborts with a
- user-readable error rather than silently falling back to the
- current working directory β€” that fallback used to send write-mode
- invocations like ``vault-log "..."`` into ``./Daily/...`` instead
- of the user's actual vault, which is a quiet way to lose data.
- """
- vault = args.vault or resolve_vault(config_path)
- if vault is None:
- print(
- "error: no vault configured. Pass --vault <path> explicitly, "
- "set VAULT_DIR in the environment, or run "
- "`o2b init --vault <path> ...` first to persist a default.",
- file=sys.stderr,
- )
- sys.exit(1)
- return Path(vault)
-
-
-def command_status(args: argparse.Namespace) -> int:
- result = discover_config(args.config)
- if getattr(args, "json", False):
- output = {
- "config_path": str(result.path),
- "config_exists": result.exists,
- }
- if result.data:
- output["config_keys"] = sorted(result.data.keys())
- vault = getattr(args, "vault", None)
- if vault:
- output["vault"] = str(vault)
- print(json.dumps(output, indent=2, sort_keys=True))
- else:
- print(f"config_path: {result.path}")
- print(f"config_exists: {str(result.exists).lower()}")
- if result.data:
- print("config_keys:")
- for key in sorted(result.data):
- print(f"- {key}")
- return 0
-
-
-def command_init(args: argparse.Namespace) -> int:
- vault = args.vault
- agent_name = getattr(args, "agent_name", None)
- timezone_name = getattr(args, "timezone", None)
-
- if timezone_name:
- try:
- from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
- ZoneInfo(timezone_name)
- except (ZoneInfoNotFoundError, ValueError) as exc:
- print(
- f"error: --timezone {timezone_name!r} is not a valid IANA name "
- f"({exc}). Examples: Europe/Belgrade, America/New_York, UTC.",
- file=sys.stderr,
- )
- return 1
-
- try:
- created = bootstrap_vault(
- vault,
- name=args.name,
- agent_name=agent_name,
- force=args.force,
- )
- except OSError as exc:
- print(f"error: failed to initialize vault: {exc}", file=sys.stderr)
- return 1
- if created:
- print(f"initialized vault: {vault}")
- for path in created:
- print(f" created: {path}")
- else:
- print(f"vault already initialized: {vault}")
- print("use --force to overwrite existing files")
- config_path = set_config_value("vault", str(Path(vault).expanduser().resolve()))
- print(f"vault path persisted to: {config_path}")
- if agent_name:
- print(f"agent name registered: {agent_name}")
- set_config_value("agent_name", agent_name)
- print(f"agent name persisted to: {config_path}")
- if timezone_name:
- print(f"timezone registered: {timezone_name}")
- set_config_value("timezone", timezone_name)
- print(f"timezone persisted to: {config_path}")
- return 0
-
-
-def command_doctor(args: argparse.Namespace) -> int:
- config = args.config or default_config_path()
- vault = _require_vault(args, config)
- repo_root: Path | None = args.repo
-
- try:
- results = doctor(vault=vault, config=config, repo_root=repo_root)
- except OSError as exc:
- print(f"error: doctor failed: {exc}", file=sys.stderr)
- return 1
- all_ok = True
- for r in results:
- status = "OK" if r.ok else "FAIL"
- print(f"[{status}] {r.name}: {r.message}")
- if not r.ok:
- all_ok = False
- return 0 if all_ok else 1
-
-
-def command_append_event(args: argparse.Namespace) -> int:
- vault = _require_vault(args, default_config_path())
- tz = resolve_timezone()
- try:
- path = append_event(vault, args.agent, args.message, date=args.date, time=args.time, tz=tz)
- except OSError as exc:
- print(f"error: failed to append event: {exc}", file=sys.stderr)
- return 1
- # Always print the absolute path: a relative ``Daily/...`` line was
- # the visual disguise that hid an earlier silent-cwd-fallback bug,
- # where a user thought their entry landed in their vault but it
- # actually landed in $(pwd)/Daily/.
- print(f"appended: {Path(path).resolve()}")
- return 0
-
-
-def command_export_config(args: argparse.Namespace) -> int:
- result = discover_config(args.config)
- snapshot = {
- "config_path": str(result.path),
- "config_exists": result.exists,
- "config": redact_mapping(result.data),
- }
- try:
- args.output.parent.mkdir(parents=True, exist_ok=True)
- args.output.write_text(json.dumps(snapshot, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- except OSError as exc:
- print(f"error: failed to export config: {exc}", file=sys.stderr)
- return 1
- print(f"exported: {args.output}")
- return 0
-
-
-def command_index(args: argparse.Namespace) -> int:
- vault = _require_vault(args, default_config_path())
- try:
- pages = list_vault_pages(vault)
- except OSError as exc:
- print(f"error: failed to list vault pages: {exc}", file=sys.stderr)
- return 1
-
- if not pages:
- print(f"no markdown pages found in vault: {vault}")
- return 0
-
- lines: list[str] = [
- f"# Vault Index",
- "",
- f"Auto-generated index of {len(pages)} pages.",
- "",
- ]
- for title, path, _ in pages:
- rel = path.relative_to(vault)
- lines.append(f"- [[{title}]] `{rel}`")
-
- index_path = vault / "AI Wiki" / "index.md"
- try:
- index_path.parent.mkdir(parents=True, exist_ok=True)
- write_frontmatter(index_path, {"title": "Index", "type": "index"}, "\n".join(lines))
- except OSError as exc:
- print(f"error: failed to write index: {exc}", file=sys.stderr)
- return 1
-
- print(f"index regenerated: {index_path} ({len(pages)} pages)")
- return 0
-
-
-def command_mcp(args: argparse.Namespace) -> int:
- config = args.config or default_config_path()
- vault = _require_vault(args, config)
- repo_root: Path | None = args.repo
- try:
- return run_mcp_server(vault=vault, config_path=config, repo_root=repo_root)
- except KeyboardInterrupt:
- return 0
-
-
-def command_uninstall(args: argparse.Namespace) -> int:
- config = args.config or default_config_path()
- plan = plan_uninstall(config_path=config, apply_local=args.apply_local)
- sys.stdout.write(render_plan(plan))
- return_code = 0
-
- if getattr(args, "remove_cli", False):
- cli_result = uninstall_cli()
- sys.stdout.write("\n")
- sys.stdout.write(render_uninstall_result(cli_result))
- if cli_result.errors:
- return_code = 1
-
- if plan.errors:
- return_code = 1
- return return_code
-
-
-def command_install_cli(args: argparse.Namespace) -> int:
- bindir = getattr(args, "bindir", None)
- result = install_cli(bindir=bindir)
- sys.stdout.write(render_install_result(result))
- if result.errors:
- return 1
- return 0
-
-
-def command_tool_call(args: argparse.Namespace) -> int:
- """Bridge: invoke an MCP tool handler from the CLI and print JSON to stdout."""
- config = default_config_path()
- vault = _require_vault(args, config)
- repo_root: Path | None = None
-
- server = MCPServer(vault=vault, config_path=config, repo_root=repo_root)
-
- tool_name = args.tool_name
- if tool_name not in server._tools:
- print(f"error: unknown tool: {tool_name}", file=sys.stderr)
- return 1
-
- # Parse --tool-arg key=value pairs into a dict
- arguments: dict[str, object] = {}
- for pair in args.tool_args:
- if "=" not in pair:
- print(f"error: --tool-arg must be key=value, got: {pair}", file=sys.stderr)
- return 1
- key, value = pair.split("=", 1)
- # Attempt JSON decode for non-string types (arrays, numbers, booleans)
- try:
- arguments[key] = _json.loads(value)
- except (_json.JSONDecodeError, ValueError):
- arguments[key] = value
-
- result = server._handle_tools_call({"name": tool_name, "arguments": arguments})
- print(_json.dumps(result, ensure_ascii=False, indent=2))
- return 0
-
-
-def main(argv: list[str] | None = None) -> int:
- parser = build_parser()
- args = parser.parse_args(argv)
- if args.command == "status":
- return command_status(args)
- if args.command == "init":
- return command_init(args)
- if args.command == "doctor":
- return command_doctor(args)
- if args.command == "append-event":
- return command_append_event(args)
- if args.command == "export-config":
- return command_export_config(args)
- if args.command == "index":
- return command_index(args)
- if args.command == "mcp":
- return command_mcp(args)
- if args.command == "install-cli":
- return command_install_cli(args)
- if args.command == "uninstall":
- return command_uninstall(args)
- if args.command == "tool-call":
- return command_tool_call(args)
- raise AssertionError(f"unhandled command: {args.command}")
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/src/open_second_brain/config.py b/src/open_second_brain/config.py
deleted file mode 100644
index 2017224c..00000000
--- a/src/open_second_brain/config.py
+++ /dev/null
@@ -1,211 +0,0 @@
-from __future__ import annotations
-
-import os
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any
-
-SECRET_KEY_PARTS = ("key", "token", "secret", "password", "credential")
-
-
-@dataclass(frozen=True)
-class ConfigDiscovery:
- path: Path
- exists: bool
- data: dict[str, str]
-
-
-def default_config_path() -> Path:
- override = os.environ.get("OPEN_SECOND_BRAIN_CONFIG")
- if override:
- return Path(override).expanduser()
-
- config_home = os.environ.get("XDG_CONFIG_HOME")
- if config_home:
- return Path(config_home).expanduser() / "open-second-brain" / "config.yaml"
-
- return Path.home() / ".config" / "open-second-brain" / "config.yaml"
-
-
-def parse_simple_yaml(text: str) -> dict[str, str]:
- data: dict[str, str] = {}
- for raw_line in text.splitlines():
- line = raw_line.strip()
- if not line or line.startswith("#"):
- continue
- if ":" not in line:
- continue
- key, value = line.split(":", 1)
- key = key.strip()
- value = value.strip().strip('"').strip("'")
- if key:
- data[key] = value
- return data
-
-
-def discover_config(path: Path | None = None) -> ConfigDiscovery:
- resolved = path or default_config_path()
- if not resolved.is_file():
- return ConfigDiscovery(path=resolved, exists=False, data={})
- try:
- data = parse_simple_yaml(resolved.read_text(encoding="utf-8"))
- except (OSError, UnicodeDecodeError, ValueError):
- return ConfigDiscovery(path=resolved, exists=False, data={})
- return ConfigDiscovery(path=resolved, exists=True, data=data)
-
-
-_CONFIG_VALUE_REJECTED_CHARS = ('"', "\\", "\n", "\r")
-
-
-def set_config_value(key: str, value: str, path: Path | None = None) -> Path:
- """Persist a single ``key: value`` pair into the plugin config file.
-
- Reads any existing keys, merges/overrides ``key`` with ``value``, writes the
- full set back. Creates parent directories if missing. Used by ``o2b init``
- to make ``agent_name`` survive without relying on the ``VAULT_AGENT_NAME``
- env, which not every runtime propagates to the MCP subprocess.
-
- Values are written as ``key: "value"`` and read back by the simple
- parser in ``parse_simple_yaml``. The parser does not understand
- escape sequences, so values containing characters that would break
- the line shape (``"``, ``\\``, ``\\n``, ``\\r``) are rejected up
- front rather than being silently corrupted on round-trip. The
- fields this helper is used for in practice (``vault`` paths,
- IANA timezone names, agent identifiers) never legitimately contain
- those characters.
-
- The write is atomic: contents are first written to a sibling temp
- file in the same directory, ``fsync``'d, then ``os.replace``'d
- over the target. An interrupted run leaves either the previous
- config or the new one β€” never a half-written hybrid.
- """
- if not isinstance(value, str):
- raise TypeError(f"config value for {key!r} must be a string, got {type(value).__name__}")
- for bad in _CONFIG_VALUE_REJECTED_CHARS:
- if bad in value:
- raise ValueError(
- f"config value for {key!r} contains a disallowed character "
- f"({bad!r}); reject rather than silently corrupting on read-back"
- )
-
- resolved = path or default_config_path()
- discovery = discover_config(resolved)
- data = dict(discovery.data)
- data[key] = value
- resolved.parent.mkdir(parents=True, exist_ok=True)
- body = "\n".join(f'{k}: "{v}"' for k, v in data.items()) + "\n"
-
- import tempfile
-
- fd, tmp_name = tempfile.mkstemp(
- prefix=f".{resolved.name}.",
- suffix=".tmp",
- dir=str(resolved.parent),
- )
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as fh:
- fh.write(body)
- fh.flush()
- os.fsync(fh.fileno())
- os.replace(tmp_name, resolved)
- except BaseException:
- # Clean up the temp file if anything went wrong before the
- # atomic replace landed; fdopen takes ownership of the fd, so
- # only the path needs explicit cleanup here.
- try:
- os.unlink(tmp_name)
- except FileNotFoundError:
- pass
- raise
- return resolved
-
-
-def resolve_timezone(config_path: Path | None = None):
- """Resolve the user's preferred timezone for Daily event log entries.
-
- Resolution order (first hit wins):
- 1. ``VAULT_TIMEZONE`` environment variable (IANA name, e.g.
- ``Europe/Belgrade``).
- 2. ``timezone`` field in the plugin config file.
- 3. ``None`` β€” caller falls back to the system's local time
- (``datetime.now()`` without ``tz``).
-
- Returns either a ``zoneinfo.ZoneInfo`` instance or ``None``. Invalid
- names are silently treated as not configured rather than raised, so a
- typo in the env or config never breaks logging β€” entries still land,
- just stamped in server-local time.
- """
- try:
- from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
- except ImportError:
- return None
-
- name = os.environ.get("VAULT_TIMEZONE")
- if not name:
- discovery = discover_config(config_path)
- name = discovery.data.get("timezone")
- if not name:
- return None
- try:
- return ZoneInfo(str(name))
- except (ZoneInfoNotFoundError, ValueError):
- return None
-
-
-def resolve_vault(config_path: Path | None = None) -> Path | None:
- """Resolve the vault directory the plugin should operate on.
-
- Resolution order (first hit wins):
- 1. ``VAULT_DIR`` environment variable (legacy, kept for backward
- compatibility with older runner scripts).
- 2. ``vault`` field in the plugin config file.
- 3. ``None`` β€” caller decides whether to error out or accept a
- positional ``--vault`` argument.
-
- The plugin config holds the ``vault`` field after a successful
- ``o2b init --vault <path>``. This lets MCP entrypoints (Claude's
- ``.mcp.json`` auto-register, Hermes' ``mcp_servers`` block, Codex's
- ``mcp_servers`` TOML) launch ``o2b mcp`` with no arguments β€” the
- plugin discovers the vault on its own.
- """
- env_value = os.environ.get("VAULT_DIR")
- if env_value:
- return Path(env_value).expanduser()
- discovery = discover_config(config_path)
- cfg_value = discovery.data.get("vault")
- if cfg_value:
- return Path(str(cfg_value)).expanduser()
- return None
-
-
-def resolve_agent_name(config_path: Path | None = None) -> str:
- """Resolve the agent identity used when no explicit ``agent`` is supplied.
-
- Resolution order (first hit wins):
- 1. ``VAULT_AGENT_NAME`` environment variable
- 2. ``agent_name`` (or ``agentName``) in the plugin config file
- 3. literal placeholder ``"agent"`` (last-resort sentinel)
-
- Shared between the MCP server's ``event_log_append`` default-agent
- resolution and the Hermes ``pre_llm_call`` hook so identity reads stay
- consistent across runtimes.
- """
- env_value = os.environ.get("VAULT_AGENT_NAME")
- if env_value:
- return env_value
- discovery = discover_config(config_path)
- config_value = discovery.data.get("agent_name") or discovery.data.get("agentName")
- if config_value:
- return config_value
- return "agent"
-
-
-def redact_mapping(data: dict[str, Any]) -> dict[str, Any]:
- redacted: dict[str, Any] = {}
- for key, value in data.items():
- lowered = key.lower()
- if any(part in lowered for part in SECRET_KEY_PARTS):
- redacted[key] = "[REDACTED]"
- else:
- redacted[key] = value
- return redacted
diff --git a/src/open_second_brain/doctor.py b/src/open_second_brain/doctor.py
deleted file mode 100644
index c0aeed12..00000000
--- a/src/open_second_brain/doctor.py
+++ /dev/null
@@ -1,265 +0,0 @@
-from __future__ import annotations
-
-import json
-import re
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any
-
-
-@dataclass(frozen=True)
-class CheckResult:
- name: str
- ok: bool
- message: str
-
-
-def check_vault_writeable(vault: Path) -> CheckResult:
- if not vault.exists():
- return CheckResult("vault_writeable", False, f"vault directory missing: {vault}")
- test_path = vault / ".open-second-brain-doctor-test"
- try:
- test_path.touch()
- test_path.unlink()
- except OSError as exc:
- return CheckResult("vault_writeable", False, f"cannot write to vault: {exc}")
- return CheckResult("vault_writeable", True, f"vault exists and is writable: {vault}")
-
-
-def check_config_writeable(config: Path) -> CheckResult:
- created_for_check = False
- try:
- config.parent.mkdir(parents=True, exist_ok=True)
- if not config.exists():
- created_for_check = True
- with config.open("a", encoding="utf-8"):
- pass
- if created_for_check:
- config.unlink()
- except OSError as exc:
- return CheckResult("config_writeable", False, f"cannot write config {config}: {exc}")
- return CheckResult("config_writeable", True, f"config writable: {config}")
-
-
-def _load_json_manifest(path: Path, description: str) -> tuple[CheckResult, dict[str, Any] | None]:
- if not path.is_file():
- return CheckResult(description, False, f"missing: {path}"), None
- try:
- data = json.loads(path.read_text(encoding="utf-8"))
- except (json.JSONDecodeError, UnicodeDecodeError) as exc:
- return CheckResult(description, False, f"invalid JSON: {path} ({exc})"), None
- if not isinstance(data, dict):
- return CheckResult(description, False, f"invalid manifest object: {path}"), None
- return CheckResult(description, True, f"valid: {path}"), data
-
-
-def check_json_manifest(path: Path, description: str) -> CheckResult:
- result, _ = _load_json_manifest(path, description)
- return result
-
-
-def _validate_required_fields(data: dict[str, Any], required: dict[str, type | tuple[type, ...]]) -> list[str]:
- problems: list[str] = []
- for field, expected_type in required.items():
- if field not in data:
- problems.append(f"missing {field}")
- continue
- value = data[field]
- if not isinstance(value, expected_type):
- if isinstance(expected_type, tuple):
- type_names = "/".join(t.__name__ for t in expected_type)
- else:
- type_names = expected_type.__name__
- problems.append(f"{field} must be {type_names}")
- elif isinstance(value, str) and not value.strip():
- problems.append(f"{field} must not be empty")
- elif isinstance(value, list) and not value:
- problems.append(f"{field} must not be empty")
- return problems
-
-
-def check_codex_manifest(path: Path) -> CheckResult:
- result, data = _load_json_manifest(path, "codex_manifest")
- if data is None:
- return result
- required = {
- "name": str,
- "version": str,
- "description": str,
- "skills": str,
- "keywords": list,
- }
- problems = _validate_required_fields(data, required)
- if problems:
- return CheckResult("codex_manifest", False, f"schema invalid: {path} ({'; '.join(problems)})")
- return CheckResult("codex_manifest", True, f"valid Codex manifest: {path}")
-
-
-def check_claude_manifest(path: Path) -> CheckResult:
- result, data = _load_json_manifest(path, "claude_manifest")
- if data is None:
- return result
- # Schema as accepted by Claude Code 2.x:
- # - ``name`` / ``version`` / ``description``: required strings.
- # - ``author``: optional, **object** (``{"name": "..."}``) per the
- # current docs. The legacy string form was rejected by
- # Claude 2.1.x with ``author: Invalid input: expected object``.
- # - ``license`` / ``repository`` / ``homepage`` / ``keywords``:
- # optional metadata.
- # - ``commands``: legacy in-manifest array form is **no longer
- # accepted** by Claude (it now rejects the embedded slash-command
- # definitions that this field used to carry). Slash commands are
- # authored as Markdown files under ``commands/`` at plugin root
- # instead. We don't lint that directory here β€” its presence is
- # validated by Claude itself on install.
- required = {
- "name": str,
- "version": str,
- "description": str,
- }
- problems = _validate_required_fields(data, required)
- optional_strings = ("license", "repository", "homepage")
- for field in optional_strings:
- if field in data and not isinstance(data[field], str):
- problems.append(f"{field} must be string")
- if "keywords" in data and not (
- isinstance(data["keywords"], list)
- and all(isinstance(kw, str) for kw in data["keywords"])
- ):
- problems.append("keywords must be list of strings")
- if "author" in data:
- author = data["author"]
- author_name = author.get("name") if isinstance(author, dict) else None
- if (
- not isinstance(author, dict)
- or not isinstance(author_name, str)
- or not author_name.strip()
- ):
- problems.append(
- "author must be an object with a non-empty 'name' field "
- "(legacy string form is rejected by Claude 2.x)"
- )
- if "commands" in data:
- problems.append(
- "embedded 'commands' array is deprecated β€” author slash commands "
- "as Markdown files under commands/ at plugin root instead"
- )
- if problems:
- return CheckResult("claude_manifest", False, f"schema invalid: {path} ({'; '.join(problems)})")
- return CheckResult("claude_manifest", True, f"valid Claude manifest: {path}")
-
-
-def check_hermes_manifest(path: Path) -> CheckResult:
- if not path.is_file():
- return CheckResult("hermes_manifest", False, f"missing: {path}")
- try:
- text = path.read_text(encoding="utf-8")
- except UnicodeDecodeError as exc:
- return CheckResult("hermes_manifest", False, f"invalid text: {path} ({exc})")
- required = ("name", "version", "description")
- missing = [field for field in required if not re.search(rf"^{field}\s*:", text, re.MULTILINE)]
- if missing:
- return CheckResult("hermes_manifest", False, f"schema invalid: {path} (missing {', '.join(missing)})")
- return CheckResult("hermes_manifest", True, f"readable Hermes manifest: {path}")
-
-
-def check_openclaw_manifest(path: Path) -> CheckResult:
- result, data = _load_json_manifest(path, "openclaw_manifest")
- if data is None:
- return result
- problems: list[str] = []
-
- # Required top-level fields
- if "id" not in data or not isinstance(data["id"], str) or not data["id"].strip():
- problems.append("missing or empty field 'id'")
- schema = data.get("configSchema")
- if not isinstance(schema, dict) or not schema:
- problems.append("missing or empty field 'configSchema'")
-
- if problems:
- return CheckResult("openclaw_manifest", False, f"schema invalid: {path} ({'; '.join(problems)})")
- return CheckResult("openclaw_manifest", True, f"valid OpenClaw manifest: {path}")
-
-
-def check_openclaw_installability(repo_root: Path) -> list[CheckResult]:
- """Check that the OpenClaw native plugin packaging is valid.
-
- Validates:
- - Root ``package.json`` exists and is valid JSON.
- - ``package.json`` has an ``openclaw.extensions`` array.
- - Each extension entry file exists on disk.
- """
- results: list[CheckResult] = []
- pkg_path = repo_root / "package.json"
-
- result, data = _load_json_manifest(pkg_path, "openclaw_package_json")
- results.append(result)
- if data is None:
- return results
-
- # Check openclaw.extensions
- extensions = data.get("openclaw", {}).get("extensions")
- if not isinstance(extensions, list) or not extensions:
- results.append(CheckResult(
- "openclaw_package_json_extensions",
- False,
- "package.json missing or empty openclaw.extensions array",
- ))
- return results
-
- results.append(CheckResult(
- "openclaw_package_json_extensions",
- True,
- f"package.json declares {len(extensions)} extension(s)",
- ))
-
- # Check each extension entry file exists
- for entry in extensions:
- if not isinstance(entry, str):
- results.append(CheckResult(
- f"openclaw_entry_invalid_{type(entry).__name__}",
- False,
- f"extension entry must be a string, got: {type(entry).__name__}",
- ))
- continue
- entry_path = repo_root / entry
- if entry_path.is_file():
- results.append(CheckResult(
- f"openclaw_entry_{entry}",
- True,
- f"extension entry exists: {entry}",
- ))
- else:
- results.append(CheckResult(
- f"openclaw_entry_{entry}",
- False,
- f"missing extension entry: {entry}",
- ))
-
- return results
-
-
-def doctor(
- *,
- vault: Path,
- config: Path | None = None,
- repo_root: Path | None = None,
-) -> list[CheckResult]:
- results: list[CheckResult] = []
-
- # Vault checks
- results.append(check_vault_writeable(vault))
-
- # Config checks
- if config is not None:
- results.append(check_config_writeable(config))
-
- # Plugin manifest checks (only if in repo context)
- if repo_root is not None:
- results.append(check_claude_manifest(repo_root / ".claude-plugin" / "plugin.json"))
- results.append(check_codex_manifest(repo_root / ".codex-plugin" / "plugin.json"))
- results.append(check_hermes_manifest(repo_root / "plugins" / "hermes" / "plugin.yaml"))
- results.append(check_openclaw_manifest(repo_root / "openclaw.plugin.json"))
- results.extend(check_openclaw_installability(repo_root))
-
- return results
diff --git a/src/open_second_brain/event_log.py b/src/open_second_brain/event_log.py
deleted file mode 100644
index a320a783..00000000
--- a/src/open_second_brain/event_log.py
+++ /dev/null
@@ -1,137 +0,0 @@
-from __future__ import annotations
-
-import fcntl
-import os
-import re
-import tempfile
-from datetime import datetime, tzinfo
-from pathlib import Path
-
-SECRET_ASSIGNMENT_RE = re.compile(
- r"\b(api[_-]?key|token|secret|password|credential)(\s*[:=]\s*)([^\s]+)",
- re.IGNORECASE,
-)
-EVENT_RE = re.compile(r"^- (\d{2}:\d{2}) β€” @")
-TIME_RE = re.compile(r"^(\d{2}):(\d{2})$")
-
-
-def redact_text(text: str) -> str:
- return SECRET_ASSIGNMENT_RE.sub(lambda match: f"{match.group(1)}{match.group(2)}[REDACTED]", text)
-
-
-def current_date(tz: tzinfo | None = None) -> str:
- """Return the current date in ``YYYY.MM.DD``.
-
- When ``tz`` is provided, the date is computed in that timezone β€” this
- matters around midnight: an event taken at 23:30 server-local UTC may
- be 01:30 the **next day** in the user's local timezone, so the entry
- must land in the next day's Daily file.
- """
- return datetime.now(tz).strftime("%Y.%m.%d")
-
-
-def current_time(tz: tzinfo | None = None) -> str:
- """Return the current time as ``HH:MM`` in ``tz`` (or server local)."""
- return datetime.now(tz).strftime("%H:%M")
-
-
-def daily_note_path(vault_dir: Path, date: str) -> Path:
- return vault_dir / "Daily" / f"{date}.md"
-
-
-def new_daily_note(date: str) -> str:
- return f"---\nformatted: false\n---\n\n# {date}\n\n## Raw events\n\n"
-
-
-def validate_event_time(value: str) -> str:
- match = TIME_RE.match(value)
- if not match:
- raise ValueError("event time must use HH:MM 24-hour format")
- hour = int(match.group(1))
- minute = int(match.group(2))
- if hour > 23 or minute > 59:
- raise ValueError("event time must use HH:MM 24-hour format")
- return value
-
-
-def append_event(
- vault_dir: Path,
- agent: str,
- message: str,
- *,
- date: str | None = None,
- time: str | None = None,
- tz: tzinfo | None = None,
-) -> Path:
- event_date = date or current_date(tz)
- event_time = validate_event_time(time or current_time(tz))
- path = daily_note_path(vault_dir, event_date)
- path.parent.mkdir(parents=True, exist_ok=True)
- lock_path = path.with_name(f".{path.name}.lock")
-
- entry = f"- {event_time} β€” @{agent} β€” {redact_text(message).replace(chr(10), ' ')}"
- temp_name: str | None = None
-
- with lock_path.open("a+b") as lock_file:
- fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
- try:
- if path.exists():
- content = path.read_text(encoding="utf-8")
- else:
- content = new_daily_note(event_date)
-
- if "## Raw events" not in content:
- content = content.rstrip() + "\n\n## Raw events\n\n"
-
- updated = insert_event_entry(content, entry)
- with tempfile.NamedTemporaryFile(
- "w",
- encoding="utf-8",
- dir=path.parent,
- prefix=f".{path.name}.",
- suffix=".tmp",
- delete=False,
- ) as temp_file:
- temp_name = temp_file.name
- temp_file.write(updated)
- temp_file.flush()
- os.fsync(temp_file.fileno())
- os.replace(temp_name, path)
- temp_name = None
- dir_fd = os.open(path.parent, os.O_RDONLY)
- try:
- os.fsync(dir_fd)
- finally:
- os.close(dir_fd)
- finally:
- if temp_name is not None:
- try:
- os.unlink(temp_name)
- except FileNotFoundError:
- pass
- fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
- return path
-
-
-def insert_event_entry(content: str, entry: str) -> str:
- marker = "## Raw events"
- before, after = content.split(marker, 1)
- after = after.lstrip("\n")
- lines = [line for line in after.splitlines() if line.strip()]
-
- entry_time = entry[2:7]
- inserted = False
- output: list[str] = []
- for line in lines:
- match = EVENT_RE.match(line)
- if not inserted and match and match.group(1) > entry_time:
- output.append(entry)
- inserted = True
- output.append(line)
- if not inserted:
- output.append(entry)
-
- raw_events = "\n".join(output)
- if raw_events:
- raw_events += "\n"
- return before + marker + "\n\n" + raw_events
diff --git a/src/open_second_brain/init.py b/src/open_second_brain/init.py
deleted file mode 100644
index b9614c12..00000000
--- a/src/open_second_brain/init.py
+++ /dev/null
@@ -1,175 +0,0 @@
-from __future__ import annotations
-
-from datetime import datetime, timezone
-from pathlib import Path
-
-VAULT_FILES: list[Path] = [
- Path("AI Wiki") / "_OPEN_SECOND_BRAIN.md",
- Path("AI Wiki") / "_open-second-brain.yaml",
- Path("AI Wiki") / "index.md",
- Path("AI Wiki") / "hot.md",
- Path("AI Wiki") / "log.md",
- Path("AI Wiki") / "identity" / "user.md",
- Path("AI Wiki") / "identity" / "agents.md",
-]
-
-TEMPLATES: dict[Path, str] = {
- Path("AI Wiki") / "_OPEN_SECOND_BRAIN.md": (
- "---\n"
- "open_second_brain_version: 1\n"
- "name: {name}\n"
- "created: {created}\n"
- "---\n\n"
- "# {name}\n\n"
- "This vault is managed by Open Second Brain.\n\n"
- "## Rules\n\n"
- "- Raw operational evidence goes into event log (Daily/).\n"
- "- Synthesized knowledge goes into the wiki (AI Wiki/).\n"
- "- Never write secrets, tokens, or credentials here.\n"
- "- Read the identity files before acting on this vault.\n"
- ),
- Path("AI Wiki") / "_open-second-brain.yaml": (
- "version: 1\n"
- "name: {name}\n"
- "created: {created}\n"
- ),
- Path("AI Wiki") / "index.md": (
- "# {name}\n\n"
- "Welcome to the {name} second brain.\n\n"
- "## Key pages\n\n"
- "- [[hot]] β€” short-term priority items.\n"
- "- [[log]] β€” durable operation log.\n"
- "- [[identity/user]] β€” owner profile.\n"
- "- [[identity/agents]] β€” allowed agents and scopes.\n"
- ),
- Path("AI Wiki") / "hot.md": (
- "# Hot\n\n"
- "Short-term items, current focus, active decisions.\n\n"
- "Items fade to cold over time.\n"
- ),
- Path("AI Wiki") / "log.md": (
- "# Operation Log\n\n"
- "Durable operations, major decisions, and infrastructure changes.\n\n"
- "The event log (Daily/) is raw chronological evidence.\n"
- "This page is synthesized operational knowledge.\n"
- ),
- Path("AI Wiki") / "identity" / "user.md": (
- "# User Identity\n\n"
- "Owner of this vault.\n\n"
- "## Profile\n\n"
- "- Name: (set your name)\n"
- "- Timezone: (set your timezone)\n"
- "- Contact: (set your primary contact)\n\n"
- "## Preferences\n\n"
- "(add durable preferences here so agents can read them)\n"
- ),
- Path("AI Wiki") / "identity" / "agents.md": (
- "# Agent Identity\n\n"
- "Allowed agents and their scopes.\n\n"
- "## Registered agents\n\n"
- "{agents_block}\n\n"
- "## Scopes\n\n"
- "- Write scope: AI Wiki/, Daily/\n"
- "- Read scope: whole vault\n"
- ),
-}
-
-AGENTS_PLACEHOLDER = "- (add your agents here, e.g., my-agent: operator on my-server)"
-
-
-def _agents_block(agent_name: str | None) -> str:
- if agent_name:
- return f"- {agent_name}: primary agent on this server"
- return AGENTS_PLACEHOLDER
-
-
-def bootstrap_vault(
- vault_dir: Path,
- *,
- name: str = "Second Brain",
- agent_name: str | None = None,
- force: bool = False,
-) -> list[Path]:
- created: list[Path] = []
- now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
- agents_block = _agents_block(agent_name)
-
- for rel_path in VAULT_FILES:
- target = vault_dir / rel_path
- target.parent.mkdir(parents=True, exist_ok=True)
- if target.exists() and not force:
- if rel_path == Path("AI Wiki") / "identity" / "agents.md" and agent_name:
- upgraded = _upgrade_agents_file(target, agent_name)
- if upgraded:
- created.append(rel_path)
- continue
- template = TEMPLATES.get(rel_path, "")
- content = template.format(name=name, created=now, agents_block=agents_block)
- target.write_text(content, encoding="utf-8")
- created.append(rel_path)
-
- return created
-
-
-_AGENTS_REGISTERED_HEADING = "## Registered agents"
-
-
-def _upgrade_agents_file(path: Path, agent_name: str) -> bool:
- """Register ``agent_name`` in ``AI Wiki/identity/agents.md``.
-
- Three cases this handles, in order:
-
- * The file still contains the bootstrap placeholder
- (``- (add your agents here, …)``): replace the placeholder with
- ``- <agent_name>: primary agent on this server``.
-
- * The file already contains an entry for ``agent_name``: no-op.
- This makes ``o2b init --agent-name X`` idempotent on a vault
- that already has X registered.
-
- * Neither of the above β€” the file has already been initialised
- with **another** agent's entry, and this is a multi-runtime
- / multi-agent setup. Append the new entry under
- ``## Registered agents``, before the next ``##`` section
- heading. Previously this case was a silent no-op, so users
- running ``o2b init --agent-name codex-vps-agent`` after a
- prior ``--agent-name claude-vps-agent`` saw their identity
- recorded in the plugin config but never written into the
- vault registry. Fixed.
-
- Returns True when the file was actually rewritten.
- """
- try:
- text = path.read_text(encoding="utf-8")
- except OSError:
- return False
-
- entry = f"- {agent_name}: primary agent on this server"
- if entry in text:
- return False
-
- if AGENTS_PLACEHOLDER in text:
- new_text = text.replace(AGENTS_PLACEHOLDER, entry)
- path.write_text(new_text, encoding="utf-8")
- return True
-
- # Multi-agent path: append under "## Registered agents". Locate the
- # heading and the next "##" that follows it (or end-of-file), and
- # insert the new bullet right before that boundary so subsequent
- # sections (e.g. "## Scopes") stay where the user expects them.
- heading_idx = text.find(_AGENTS_REGISTERED_HEADING)
- if heading_idx == -1:
- return False
- after_heading = heading_idx + len(_AGENTS_REGISTERED_HEADING)
- rest = text[after_heading:]
- next_section_relative = rest.find("\n## ")
- if next_section_relative == -1:
- head = text[:after_heading] + rest.rstrip()
- new_text = head + f"\n{entry}\n"
- else:
- boundary = after_heading + next_section_relative
- before = text[:boundary].rstrip()
- after = text[boundary:]
- new_text = before + f"\n{entry}\n" + after
- path.write_text(new_text, encoding="utf-8")
- return True
diff --git a/src/open_second_brain/install_cli.py b/src/open_second_brain/install_cli.py
deleted file mode 100644
index 61348224..00000000
--- a/src/open_second_brain/install_cli.py
+++ /dev/null
@@ -1,203 +0,0 @@
-"""Install (and optionally remove) CLI symlinks for o2b and vault-log.
-
-After ``hermes plugins install`` (or ``pip install``), the ``o2b`` and
-``vault-log`` entry-points may not be on PATH. This module creates
-symlinks from ``~/.local/bin/o2b`` β†’ ``scripts/o2b`` (and the same for
-vault-log) so the bare commands work immediately.
-"""
-
-from __future__ import annotations
-
-import os
-from dataclasses import dataclass, field
-from pathlib import Path
-
-CLI_SCRIPTS: tuple[str, ...] = ("o2b", "vault-log")
-
-
-@dataclass(frozen=True)
-class InstallResult:
- """Outcome of an install-cli run."""
-
- bindir: Path
- outcomes: tuple[tuple[str, str], ...]
- errors: tuple[str, ...] = field(default_factory=tuple)
-
-
-@dataclass(frozen=True)
-class UninstallResult:
- """Outcome of a remove-cli run."""
-
- bindir: Path
- outcomes: tuple[tuple[str, str], ...]
- errors: tuple[str, ...] = field(default_factory=tuple)
-
-
-def _repo_root() -> Path:
- """Return the repository root (two directories above this module)."""
- return Path(__file__).resolve().parent.parent.parent
-
-
-def _scripts_dir() -> Path:
- """Return the ``scripts/`` directory inside the repo root."""
- return _repo_root() / "scripts"
-
-
-def _find_script(name: str) -> Path | None:
- """Return the absolute path to a script, or ``None`` if it is missing."""
- script = _scripts_dir() / name
- if script.is_file():
- return script.resolve()
- return None
-
-
-def _is_valid_symlink(link: Path, target: Path) -> bool:
- """Return ``True`` when *link* points to *target*."""
- try:
- return link.resolve() == target.resolve()
- except OSError:
- return False
-
-
-def install_cli(bindir: Path | None = None) -> InstallResult:
- """Create (or verify) symlinks for o2b and vault-log.
-
- Args:
- bindir: Target directory. Defaults to ``~/.local/bin``.
-
- Returns an :class:`InstallResult`.
- """
- if bindir is None:
- bindir = Path.home() / ".local" / "bin"
-
- bindir.mkdir(parents=True, exist_ok=True)
-
- outcomes: list[tuple[str, str]] = []
- errors: list[str] = []
-
- for name in CLI_SCRIPTS:
- link = bindir / name
- source = _find_script(name)
-
- if source is None:
- msg = f"error: script 'scripts/{name}' not found in {_scripts_dir()}"
- outcomes.append((name, msg))
- errors.append(msg)
- continue
-
- if link.is_symlink():
- if _is_valid_symlink(link, source):
- outcomes.append((name, f"exists: {link} β†’ {source}"))
- else:
- existing_target = "unknown"
- try:
- existing_target = str(link.readlink())
- except OSError:
- pass
- msg = f"warning: {link} already points to {existing_target}, not overwriting"
- outcomes.append((name, msg))
- elif link.exists():
- msg = f"warning: {link} exists and is not a symlink, not overwriting"
- outcomes.append((name, msg))
- else:
- try:
- link.symlink_to(source)
- outcomes.append((name, f"created: {link} β†’ {source}"))
- except OSError as exc:
- msg = f"error: could not create symlink {link}: {exc}"
- outcomes.append((name, msg))
- errors.append(msg)
-
- return InstallResult(
- bindir=bindir,
- outcomes=tuple(outcomes),
- errors=tuple(errors),
- )
-
-
-def uninstall_cli(bindir: Path | None = None) -> UninstallResult:
- """Remove the symlinks created by :func:`install_cli`.
-
- Only removes a symlink when it points into the ``scripts/`` directory
- of **this** repository (to avoid removing unrelated symlinks that happen
- to share the same name).
-
- Args:
- bindir: Directory with the symlinks. Defaults to ``~/.local/bin``.
-
- Returns an :class:`UninstallResult`.
- """
- if bindir is None:
- bindir = Path.home() / ".local" / "bin"
-
- repo_scripts = _scripts_dir()
- outcomes: list[tuple[str, str]] = []
- errors: list[str] = []
-
- for name in CLI_SCRIPTS:
- link = bindir / name
-
- if not link.is_symlink():
- if link.exists():
- msg = f"skipped: {link} is not a symlink β€” refusing to remove"
- outcomes.append((name, msg))
- else:
- outcomes.append((name, f"skipped: {link} does not exist"))
- continue
-
- # Resolve the target of the symlink
- try:
- target = link.resolve()
- except OSError as exc:
- msg = f"error: cannot resolve {link}: {exc}"
- outcomes.append((name, msg))
- errors.append(msg)
- continue
-
- # Only remove if the target is inside our scripts/ directory
- try:
- target.relative_to(repo_scripts)
- except ValueError:
- msg = f"skipped: {link} β†’ {target} is outside this repo's scripts/ β€” refusing to remove"
- outcomes.append((name, msg))
- continue
-
- try:
- link.unlink()
- outcomes.append((name, f"removed: {link}"))
- except OSError as exc:
- msg = f"error: cannot unlink {link}: {exc}"
- outcomes.append((name, msg))
- errors.append(msg)
-
- return UninstallResult(
- bindir=bindir,
- outcomes=tuple(outcomes),
- errors=tuple(errors),
- )
-
-
-def render_install_result(result: InstallResult) -> str:
- """Render an :class:`InstallResult` as plain text."""
- lines: list[str] = []
- lines.append(f"o2b install-cli β€” {result.bindir}")
- lines.append("-" * 40)
- for name, msg in result.outcomes:
- lines.append(f" {name}: {msg}")
- if result.errors:
- lines.append("")
- lines.append(f"{len(result.errors)} error(s).")
- return "\n".join(lines).rstrip() + "\n"
-
-
-def render_uninstall_result(result: UninstallResult) -> str:
- """Render an :class:`UninstallResult` as plain text."""
- lines: list[str] = []
- lines.append(f"o2b uninstall --remove-cli β€” {result.bindir}")
- lines.append("-" * 40)
- for name, msg in result.outcomes:
- lines.append(f" {name}: {msg}")
- if result.errors:
- lines.append("")
- lines.append(f"{len(result.errors)} error(s).")
- return "\n".join(lines).rstrip() + "\n"
diff --git a/src/open_second_brain/mcp.py b/src/open_second_brain/mcp.py
deleted file mode 100644
index f8585668..00000000
--- a/src/open_second_brain/mcp.py
+++ /dev/null
@@ -1,683 +0,0 @@
-"""Optional Model Context Protocol (MCP) server for Open Second Brain.
-
-This module implements a stdio JSON-RPC 2.0 server that exposes deterministic
-Second Brain operations as MCP tools. It is dependency-free and uses the
-``2025-06-18`` MCP protocol version, which the current Hermes Agent runtime
-discovers and registers like any other ``mcp_servers`` entry in
-``~/.hermes/config.yaml`` (see ``docs/mcp.md``).
-
-The CLI is the baseline: every tool here delegates to the same core helpers
-(``config``, ``doctor``, ``event_log``, ``vault``) used by the ``o2b`` command,
-so behavior stays consistent across runtimes.
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import re
-import sys
-from dataclasses import dataclass
-from datetime import datetime, timezone
-from pathlib import Path
-from typing import Any, Callable, IO
-
-from open_second_brain.config import (
- default_config_path,
- discover_config,
- redact_mapping,
- resolve_agent_name,
- resolve_timezone,
- resolve_vault,
-)
-from open_second_brain.doctor import doctor
-from open_second_brain.event_log import append_event, validate_event_time
-from open_second_brain.vault import list_vault_pages, parse_frontmatter, write_frontmatter
-
-from open_second_brain import __version__ as SERVER_VERSION
-
-PROTOCOL_VERSION = "2025-06-18"
-SERVER_NAME = "open-second-brain"
-JSONRPC_VERSION = "2.0"
-
-# JSON-RPC 2.0 error codes used by the MCP server.
-PARSE_ERROR = -32700
-INVALID_REQUEST = -32600
-METHOD_NOT_FOUND = -32601
-INVALID_PARAMS = -32602
-INTERNAL_ERROR = -32603
-
-_SLUG_INVALID = re.compile(r"[^a-z0-9]+")
-_SLUG_MAX_LEN = 64
-
-
-@dataclass(frozen=True)
-class ToolDefinition:
- name: str
- description: str
- input_schema: dict[str, Any]
- handler: Callable[["MCPServer", dict[str, Any]], dict[str, Any]]
-
- def to_listing(self) -> dict[str, Any]:
- return {
- "name": self.name,
- "description": self.description,
- "inputSchema": self.input_schema,
- }
-
-
-def slugify(value: str) -> str:
- lowered = value.strip().lower()
- slug = _SLUG_INVALID.sub("-", lowered).strip("-")
- if not slug:
- slug = "note"
- return slug[:_SLUG_MAX_LEN].rstrip("-") or "note"
-
-
-def _vault_relpath(target: Path, vault: Path) -> str:
- try:
- return str(target.resolve().relative_to(vault.resolve()))
- except ValueError:
- return str(target)
-
-
-def _ensure_inside_vault(target: Path, vault: Path) -> Path:
- resolved_target = target.resolve()
- resolved_vault = vault.resolve()
- try:
- resolved_target.relative_to(resolved_vault)
- except ValueError as exc:
- raise ValueError(f"path escapes vault: {target}") from exc
- return resolved_target
-
-
-class MCPError(Exception):
- """Protocol-level error returned as a JSON-RPC error response."""
-
- def __init__(self, code: int, message: str, data: Any | None = None):
- super().__init__(message)
- self.code = code
- self.message = message
- self.data = data
-
-
-class MCPServer:
- """JSON-RPC 2.0 MCP server exposing Second Brain operations as tools."""
-
- def __init__(
- self,
- *,
- vault: Path,
- config_path: Path | None = None,
- repo_root: Path | None = None,
- ) -> None:
- self.vault = vault
- self.config_path = config_path
- self.repo_root = repo_root
- self._initialized = False
- self._tools: dict[str, ToolDefinition] = {tool.name: tool for tool in _build_tool_table()}
-
- # ── JSON-RPC dispatch ────────────────────────────────────────────────
-
- def handle_request(self, request: dict[str, Any]) -> dict[str, Any] | None:
- """Process one JSON-RPC request or notification.
-
- Returns a JSON-RPC response dict, or ``None`` for notifications.
- """
-
- if not isinstance(request, dict):
- return self._error_response(None, INVALID_REQUEST, "request must be an object")
- if request.get("jsonrpc") != JSONRPC_VERSION:
- return self._error_response(request.get("id"), INVALID_REQUEST, "unsupported jsonrpc version")
-
- method = request.get("method")
- if not isinstance(method, str):
- return self._error_response(request.get("id"), INVALID_REQUEST, "method must be a string")
-
- params = request.get("params") or {}
- request_id = request.get("id")
- is_notification = "id" not in request
-
- try:
- if method == "initialize":
- result = self._handle_initialize(params)
- elif method == "notifications/initialized":
- self._initialized = True
- return None
- elif method == "ping":
- result = {}
- elif method == "tools/list":
- result = self._handle_tools_list()
- elif method == "tools/call":
- result = self._handle_tools_call(params)
- elif method.startswith("notifications/"):
- return None
- else:
- raise MCPError(METHOD_NOT_FOUND, f"unknown method: {method}")
- except MCPError as exc:
- if is_notification:
- return None
- return self._error_response(request_id, exc.code, exc.message, exc.data)
- except Exception as exc: # noqa: BLE001 β€” last-resort safety net for stdio loop
- if is_notification:
- return None
- return self._error_response(request_id, INTERNAL_ERROR, f"internal error: {exc}")
-
- if is_notification:
- return None
- return {"jsonrpc": JSONRPC_VERSION, "id": request_id, "result": result}
-
- # ── Method handlers ──────────────────────────────────────────────────
-
- def _handle_initialize(self, params: dict[str, Any]) -> dict[str, Any]:
- client_version = params.get("protocolVersion")
- negotiated = client_version if isinstance(client_version, str) else PROTOCOL_VERSION
- return {
- "protocolVersion": negotiated,
- "capabilities": {"tools": {"listChanged": False}},
- "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
- "instructions": _build_instructions(_resolve_default_agent(self)),
- }
-
- def _handle_tools_list(self) -> dict[str, Any]:
- return {"tools": [tool.to_listing() for tool in self._tools.values()]}
-
- def _handle_tools_call(self, params: dict[str, Any]) -> dict[str, Any]:
- name = params.get("name")
- if not isinstance(name, str):
- raise MCPError(INVALID_PARAMS, "tools/call requires a string name")
- tool = self._tools.get(name)
- if tool is None:
- raise MCPError(METHOD_NOT_FOUND, f"unknown tool: {name}")
- arguments = params.get("arguments") or {}
- if not isinstance(arguments, dict):
- raise MCPError(INVALID_PARAMS, "tools/call arguments must be an object")
- try:
- structured = tool.handler(self, arguments)
- except MCPError:
- raise
- except (ValueError, TypeError) as exc:
- return _tool_error(str(exc))
- except OSError as exc:
- return _tool_error(f"filesystem error: {exc}")
- return _tool_result(structured)
-
- # ── Helpers ──────────────────────────────────────────────────────────
-
- def _error_response(
- self,
- request_id: Any,
- code: int,
- message: str,
- data: Any | None = None,
- ) -> dict[str, Any]:
- error: dict[str, Any] = {"code": code, "message": message}
- if data is not None:
- error["data"] = data
- return {"jsonrpc": JSONRPC_VERSION, "id": request_id, "error": error}
-
-
-# ── Tool implementations ─────────────────────────────────────────────────
-
-
-def _tool_result(structured: dict[str, Any]) -> dict[str, Any]:
- text = json.dumps(structured, ensure_ascii=False, sort_keys=True, indent=2)
- return {
- "content": [{"type": "text", "text": text}],
- "structuredContent": structured,
- "isError": False,
- }
-
-
-def _tool_error(message: str) -> dict[str, Any]:
- return {
- "content": [{"type": "text", "text": message}],
- "isError": True,
- }
-
-
-def _coerce_str(arguments: dict[str, Any], key: str, *, required: bool = True, default: str | None = None) -> str | None:
- value = arguments.get(key)
- if value is None or (isinstance(value, str) and not value.strip()):
- # Many MCP clients (LLMs in tool-use mode) emit empty strings for
- # optional fields they want to skip, instead of omitting the key.
- # Treat ``""`` / whitespace-only the same as a missing value so
- # downstream validators don't reject what is logically "no value".
- if required:
- raise MCPError(INVALID_PARAMS, f"missing required argument: {key}")
- return default
- if not isinstance(value, str):
- raise MCPError(INVALID_PARAMS, f"argument {key!r} must be a string")
- return value
-
-
-def _coerce_str_list(arguments: dict[str, Any], key: str) -> list[str]:
- value = arguments.get(key)
- if value is None:
- return []
- if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
- raise MCPError(INVALID_PARAMS, f"argument {key!r} must be a list of strings")
- return value
-
-
-def _coerce_int(arguments: dict[str, Any], key: str, *, default: int, minimum: int, maximum: int) -> int:
- value = arguments.get(key, default)
- if isinstance(value, bool) or not isinstance(value, int):
- raise MCPError(INVALID_PARAMS, f"argument {key!r} must be an integer")
- if value < minimum or value > maximum:
- raise MCPError(INVALID_PARAMS, f"argument {key!r} must be between {minimum} and {maximum}")
- return value
-
-
-def _tool_second_brain_status(server: MCPServer, _arguments: dict[str, Any]) -> dict[str, Any]:
- discovery = discover_config(server.config_path)
- vault_exists = server.vault.is_dir()
- config_keys = sorted(discovery.data.keys())
- return {
- "config_path": str(discovery.path),
- "config_exists": discovery.exists,
- "config_keys": config_keys,
- "config": redact_mapping(discovery.data),
- "vault_path": str(server.vault),
- "vault_exists": vault_exists,
- }
-
-
-def _tool_second_brain_query(server: MCPServer, arguments: dict[str, Any]) -> dict[str, Any]:
- if not server.vault.is_dir():
- raise MCPError(INVALID_PARAMS, f"vault directory missing: {server.vault}")
-
- pattern = _coerce_str(arguments, "pattern", required=False)
- limit = _coerce_int(arguments, "limit", default=50, minimum=1, maximum=500)
-
- pages = list_vault_pages(server.vault)
- needle = pattern.lower() if pattern else None
- matched: list[dict[str, Any]] = []
- for title, path, meta in pages:
- if needle is not None and needle not in title.lower():
- continue
- matched.append(
- {
- "title": title,
- "path": _vault_relpath(path, server.vault),
- "metadata": meta,
- }
- )
- if len(matched) >= limit:
- break
-
- return {
- "vault_path": str(server.vault),
- "total_pages": len(pages),
- "returned": len(matched),
- "limit": limit,
- "pattern": pattern,
- "pages": matched,
- }
-
-
-def _tool_second_brain_capture(server: MCPServer, arguments: dict[str, Any]) -> dict[str, Any]:
- if not server.vault.is_dir():
- raise MCPError(INVALID_PARAMS, f"vault directory missing: {server.vault}")
-
- title = _coerce_str(arguments, "title")
- content = _coerce_str(arguments, "content")
- tags = _coerce_str_list(arguments, "tags")
- overwrite = bool(arguments.get("overwrite", False))
- assert title is not None # required=True
- assert content is not None # required=True
-
- if not title.strip():
- raise MCPError(INVALID_PARAMS, "title must not be empty")
- if not content.strip():
- raise MCPError(INVALID_PARAMS, "content must not be empty")
-
- notes_dir = server.vault / "AI Wiki" / "notes"
- notes_dir.mkdir(parents=True, exist_ok=True)
-
- slug = slugify(title)
- target = notes_dir / f"{slug}.md"
- _ensure_inside_vault(target, server.vault)
-
- note_existed = target.exists()
- if note_existed and not overwrite:
- raise ValueError(f"note already exists: {_vault_relpath(target, server.vault)}")
-
- metadata: dict[str, Any] = {
- "title": title,
- "type": "note",
- "created": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
- }
- if tags:
- metadata["tags"] = list(tags)
-
- write_frontmatter(target, metadata, content.strip())
-
- return {
- "path": _vault_relpath(target, server.vault),
- "absolute_path": str(target.resolve()),
- "slug": slug,
- "overwritten": note_existed and overwrite,
- }
-
-
-# Strings the LLM is most likely to emit as a guess for the ``agent`` argument
-# when it doesn't actually know its identity. None of these are useful as a
-# real ``@<name>`` in Daily β€” they should fall back to the server-resolved
-# default (env or plugin config). Compared case-insensitively, after a
-# leading ``@`` is stripped.
-_PLACEHOLDER_AGENT_VALUES = frozenset({
- "agent",
- "assistant",
- "ai",
- "ai-assistant",
- "bot",
- "chatbot",
- "claude",
- "copilot",
- "gemini",
- "gpt",
- "gpt-4",
- "gpt-5",
- "llm",
- "model",
- "openai",
- "user",
-})
-
-
-def _resolve_default_agent(server: MCPServer) -> str:
- return resolve_agent_name(server.config_path)
-
-
-def _normalize_agent_argument(value: str | None) -> str | None:
- """Sanitize an LLM-supplied ``agent`` argument.
-
- Strips a leading ``@`` (so ``@hermes-vps-agent`` doesn't end up as
- ``@@hermes-vps-agent`` once ``append_event`` re-prefixes ``@``).
- Treats common LLM self-name guesses (``agent``, ``assistant``, ``claude``,
- ``gpt``, ...) as "no value" so a hallucinated identity falls back to the
- server-resolved default instead of being written verbatim into Daily.
- Returns ``None`` for empty / placeholder inputs.
- """
- if value is None:
- return None
- cleaned = value.strip().lstrip("@").strip()
- if not cleaned or cleaned.lower() in _PLACEHOLDER_AGENT_VALUES:
- return None
- return cleaned
-
-
-def _build_instructions(default_agent: str) -> str:
- return (
- f"You are @{default_agent} on this Open Second Brain vault. "
- f"Always log under this identity; do not invent or change the name.\n\n"
- "When to call event_log_append:\n"
- " - immediately after producing a durable artifact, including:\n"
- " * code shipped, bug fixed, refactor merged\n"
- " * config / deployment / infrastructure change\n"
- " * instruction-file edit (CLAUDE.md, SOUL.md, plugin docs, "
- "system prompts, similar)\n"
- " * content artifact created (post, draft, documentation, "
- "marketing copy, release notes)\n"
- " * research, investigation, or analysis that produced a "
- "concrete finding, design, or decision worth recalling later\n"
- " * discovery of an external fact (CLI behaviour change, "
- "API quirk, undocumented edge case) that future sessions should "
- "know\n"
- " - skip for: pure discussion or brainstorming without "
- "conclusion, read-only queries, or planning that hasn't yet "
- "produced an artifact\n\n"
- "If unsure, ask: \"would future-me want to find this in the log "
- "by searching for it later?\". If yes, log it.\n\n"
- "How to format the `message` argument:\n"
- " - plain prose describing what was done / found / decided and "
- "why it matters\n"
- " - DO NOT prepend `HH:MM β€”` or `@<name> β€”` to the message; "
- "the server adds these automatically\n"
- " - terse, append-only, factual; never edit historical lines\n\n"
- "Identity is resolved server-side. Do not pass the `agent` argument "
- "unless deliberately logging on another agent's behalf.\n\n"
- "Other tools: second_brain_status (config status), "
- "vault_health (verify vault), second_brain_query (look up notes), "
- "second_brain_capture (add wiki pages)."
- )
-
-
-def _tool_event_log_append(server: MCPServer, arguments: dict[str, Any]) -> dict[str, Any]:
- message = _coerce_str(arguments, "message")
- agent = _coerce_str(arguments, "agent", required=False)
- date = _coerce_str(arguments, "date", required=False)
- time = _coerce_str(arguments, "time", required=False)
- assert message is not None # required=True
-
- if time is not None:
- validate_event_time(time)
-
- effective_agent = _normalize_agent_argument(agent) or _resolve_default_agent(server)
- tz = resolve_timezone(server.config_path)
- path = append_event(server.vault, effective_agent, message, date=date, time=time, tz=tz)
-
- return {
- "path": _vault_relpath(path, server.vault),
- "absolute_path": str(path.resolve()),
- "agent": effective_agent,
- "date": date,
- "time": time,
- }
-
-
-def _tool_vault_health(server: MCPServer, arguments: dict[str, Any]) -> dict[str, Any]:
- repo_arg = _coerce_str(arguments, "repo", required=False)
- if repo_arg:
- repo_root: Path | None = Path(repo_arg)
- else:
- repo_root = server.repo_root
-
- results = doctor(vault=server.vault, config=server.config_path, repo_root=repo_root)
- payload = [{"name": r.name, "ok": r.ok, "message": r.message} for r in results]
- return {
- "vault_path": str(server.vault),
- "config_path": str(server.config_path) if server.config_path else None,
- "repo_root": str(repo_root) if repo_root else None,
- "ok": all(item["ok"] for item in payload),
- "checks": payload,
- }
-
-
-def _build_tool_table() -> list[ToolDefinition]:
- return [
- ToolDefinition(
- name="second_brain_status",
- description="Report Open Second Brain configuration and vault status.",
- input_schema={"type": "object", "properties": {}, "additionalProperties": False},
- handler=_tool_second_brain_status,
- ),
- ToolDefinition(
- name="second_brain_query",
- description="List vault pages with optional title substring filter.",
- input_schema={
- "type": "object",
- "properties": {
- "pattern": {
- "type": "string",
- "description": "Optional case-insensitive substring matched against page titles.",
- },
- "limit": {
- "type": "integer",
- "minimum": 1,
- "maximum": 500,
- "description": "Maximum number of matched pages to return (default 50).",
- },
- },
- "additionalProperties": False,
- },
- handler=_tool_second_brain_query,
- ),
- ToolDefinition(
- name="second_brain_capture",
- description="Write a new Markdown note to AI Wiki/notes/ with frontmatter.",
- input_schema={
- "type": "object",
- "properties": {
- "title": {"type": "string", "description": "Human-readable note title."},
- "content": {"type": "string", "description": "Markdown body of the note."},
- "tags": {
- "type": "array",
- "items": {"type": "string"},
- "description": "Optional list of tag strings.",
- },
- "overwrite": {
- "type": "boolean",
- "description": "Allow overwriting an existing note with the same slug.",
- },
- },
- "required": ["title", "content"],
- "additionalProperties": False,
- },
- handler=_tool_second_brain_capture,
- ),
- ToolDefinition(
- name="event_log_append",
- description="Append a single-line event to the daily Markdown event log.",
- input_schema={
- "type": "object",
- "properties": {
- "message": {"type": "string", "description": "Single-line event message."},
- "agent": {"type": "string", "description": "Agent name (default 'agent')."},
- "date": {
- "type": "string",
- "description": "Optional event date in YYYY.MM.DD format.",
- },
- "time": {
- "type": "string",
- "description": "Optional event time in 24-hour HH:MM format.",
- },
- },
- "required": ["message"],
- "additionalProperties": False,
- },
- handler=_tool_event_log_append,
- ),
- ToolDefinition(
- name="vault_health",
- description="Run vault, config, and plugin manifest health checks.",
- input_schema={
- "type": "object",
- "properties": {
- "repo": {
- "type": "string",
- "description": "Optional repository root to validate plugin manifests.",
- },
- },
- "additionalProperties": False,
- },
- handler=_tool_vault_health,
- ),
- ]
-
-
-# ── stdio loop ───────────────────────────────────────────────────────────
-
-
-def serve_stdio(
- server: MCPServer,
- *,
- stdin: IO[str] | None = None,
- stdout: IO[str] | None = None,
- stderr: IO[str] | None = None,
-) -> int:
- """Run the MCP server reading newline-delimited JSON from stdin.
-
- The server only writes JSON-RPC frames to ``stdout``. Logs go to ``stderr``.
- Returns 0 on normal EOF.
- """
-
- inp = stdin or sys.stdin
- out = stdout or sys.stdout
- err = stderr or sys.stderr
-
- for raw_line in inp:
- line = raw_line.strip()
- if not line:
- continue
- try:
- request = json.loads(line)
- except json.JSONDecodeError as exc:
- response = server._error_response( # noqa: SLF001 β€” controlled internal use
- None, PARSE_ERROR, f"invalid JSON: {exc}"
- )
- _write_frame(out, response)
- continue
-
- if isinstance(request, list):
- response = server._error_response( # noqa: SLF001 β€” controlled internal use
- None,
- INVALID_REQUEST,
- "batch requests are not supported by the 2025-06-18 spec",
- )
- _write_frame(out, response)
- continue
-
- response = server.handle_request(request)
- if response is not None:
- _write_frame(out, response)
- return 0
-
-
-def _write_frame(out: IO[str], response: dict[str, Any]) -> None:
- line = json.dumps(response, ensure_ascii=False)
- if "\n" in line:
- line = line.replace("\n", " ")
- out.write(line + "\n")
- out.flush()
-
-
-def run_cli_command(
- *,
- vault: Path,
- config_path: Path | None,
- repo_root: Path | None,
-) -> int:
- server = MCPServer(vault=vault, config_path=config_path, repo_root=repo_root)
- sys.stderr.write(
- f"[mcp] open-second-brain {SERVER_VERSION} listening on stdio (vault={vault})\n"
- )
- sys.stderr.flush()
- return serve_stdio(server)
-
-
-def default_repo_root() -> Path:
- return Path(__file__).resolve().parents[2]
-
-
-def main(argv: list[str] | None = None) -> int:
- """Entry point for ``python -m open_second_brain.mcp``."""
-
- import argparse
-
- parser = argparse.ArgumentParser(
- prog="open-second-brain-mcp",
- description="Open Second Brain MCP server (stdio).",
- )
- parser.add_argument("--vault", type=Path, default=None, help="Vault directory")
- parser.add_argument("--config", type=Path, default=None, help="Config file path")
- parser.add_argument("--repo", type=Path, default=None, help="Repository root for plugin checks")
- args = parser.parse_args(argv)
-
- config = args.config or default_config_path()
- vault = args.vault or resolve_vault(config)
- if vault is None:
- print(
- "error: no vault configured. Pass --vault <path> explicitly, "
- "set VAULT_DIR in the environment, or run "
- "`o2b init --vault <path> ...` first to persist a default.",
- file=sys.stderr,
- )
- return 1
- repo_root = args.repo
- return run_cli_command(vault=Path(vault), config_path=config, repo_root=repo_root)
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/src/open_second_brain/uninstall.py b/src/open_second_brain/uninstall.py
deleted file mode 100644
index b64bec9c..00000000
--- a/src/open_second_brain/uninstall.py
+++ /dev/null
@@ -1,212 +0,0 @@
-"""Read-only uninstall planner for Open Second Brain.
-
-The uninstall helper does NOT manage the Hermes plugin install or
-MCP registration; those are owned by Hermes. It also never touches the
-user's vault. By default it is a dry-run that prints the plan and the
-exact Hermes commands the user should run themselves.
-
-When invoked with ``--apply-local`` it may delete the machine-local
-Open Second Brain config directory (typically ``~/.config/open-second-brain``).
-Anything outside that single directory is left untouched.
-"""
-
-from __future__ import annotations
-
-import shutil
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Iterable
-
-from open_second_brain.config import discover_config
-
-PLUGIN_NAME = "open-second-brain"
-
-HERMES_COMMANDS: tuple[str, ...] = (
- f"hermes mcp remove {PLUGIN_NAME}",
- f"hermes plugins remove {PLUGIN_NAME}",
- "hermes gateway restart",
-)
-
-SAFE_CONFIG_DIR_NAMES: frozenset[str] = frozenset({"open-second-brain", "open_second_brain"})
-
-
-@dataclass(frozen=True)
-class UninstallPlan:
- """Computed plan for an uninstall invocation."""
-
- config_path: Path
- config_exists: bool
- config_dir: Path
- config_dir_exists: bool
- config_dir_entries: tuple[Path, ...]
- vault_path: Path | None
- apply_local: bool
- hermes_commands: tuple[str, ...] = HERMES_COMMANDS
- removed_paths: tuple[Path, ...] = field(default_factory=tuple)
- skipped_paths: tuple[tuple[Path, str], ...] = field(default_factory=tuple)
- errors: tuple[tuple[Path, str], ...] = field(default_factory=tuple)
-
-
-def _is_safe_local_config_dir(target: Path) -> tuple[bool, str]:
- """Return ``(safe, reason)`` for ``target`` as a deletion candidate.
-
- Only a directory whose final name is one of the well-known Open Second
- Brain config dir names is eligible. The directory must also live outside
- any Hermes config tree to keep us strictly off Hermes-owned state.
- """
-
- if target.name not in SAFE_CONFIG_DIR_NAMES:
- return False, (
- f"directory name '{target.name}' is not a recognized Open Second Brain "
- "config directory; refusing to remove"
- )
-
- parts_lower = {part.lower() for part in target.parts}
- if ".hermes" in parts_lower or "hermes" in parts_lower:
- return False, "config directory is inside a Hermes-owned path; refusing to remove"
-
- if (target / ".git").exists():
- return False, "config directory looks like a git repository; refusing to remove"
-
- return True, ""
-
-
-def _vault_path_from_config(data: dict[str, str]) -> Path | None:
- for key in ("vault_path", "vault", "vault_dir", "path"):
- value = data.get(key)
- if value:
- return Path(value).expanduser()
- return None
-
-
-def _list_entries(directory: Path) -> tuple[Path, ...]:
- if not directory.is_dir():
- return ()
- try:
- return tuple(sorted(directory.iterdir()))
- except OSError:
- return ()
-
-
-def plan_uninstall(
- *,
- config_path: Path,
- apply_local: bool = False,
-) -> UninstallPlan:
- """Compute (and optionally apply-local) an uninstall plan.
-
- The plan never modifies the Hermes config, the installed plugin
- directory, or the user's vault. With ``apply_local=True`` it may
- remove the machine-local config directory if and only if it passes
- :func:`_is_safe_local_config_dir`.
- """
-
- discovery = discover_config(config_path)
- cfg_dir = discovery.path.parent
- cfg_dir_exists = cfg_dir.is_dir()
- entries = _list_entries(cfg_dir)
- vault_path = _vault_path_from_config(discovery.data)
-
- removed: list[Path] = []
- skipped: list[tuple[Path, str]] = []
- errors: list[tuple[Path, str]] = []
-
- if apply_local:
- if not cfg_dir_exists:
- skipped.append((cfg_dir, "config directory does not exist"))
- else:
- safe, reason = _is_safe_local_config_dir(cfg_dir)
- if not safe:
- skipped.append((cfg_dir, reason))
- else:
- try:
- shutil.rmtree(cfg_dir)
- removed.append(cfg_dir)
- except OSError as exc:
- errors.append((cfg_dir, str(exc)))
-
- return UninstallPlan(
- config_path=discovery.path,
- config_exists=discovery.exists,
- config_dir=cfg_dir,
- config_dir_exists=cfg_dir_exists,
- config_dir_entries=entries,
- vault_path=vault_path,
- apply_local=apply_local,
- removed_paths=tuple(removed),
- skipped_paths=tuple(skipped),
- errors=tuple(errors),
- )
-
-
-def render_plan(plan: UninstallPlan) -> str:
- """Render an :class:`UninstallPlan` as plain text for the CLI."""
-
- lines: list[str] = []
- title = "Open Second Brain β€” Uninstall plan"
- lines.append(title)
- lines.append("=" * len(title))
- lines.append("")
-
- mode = "apply-local (machine-local config directory may be removed)" if plan.apply_local else "dry-run (read-only)"
- lines.append(f"Mode: {mode}")
- lines.append("")
-
- lines.append("Local config:")
- config_state = "exists" if plan.config_exists else "missing"
- lines.append(f" config file: {plan.config_path} ({config_state})")
- if plan.config_dir_exists:
- entry_count = len(plan.config_dir_entries)
- lines.append(f" config dir: {plan.config_dir} ({entry_count} entr{'y' if entry_count == 1 else 'ies'})")
- for entry in plan.config_dir_entries:
- suffix = "/" if entry.is_dir() else ""
- lines.append(f" - {entry.name}{suffix}")
- else:
- lines.append(f" config dir: {plan.config_dir} (missing)")
- lines.append("")
-
- lines.append("Hermes integration (run these yourself; this tool will not):")
- for cmd in plan.hermes_commands:
- lines.append(f" $ {cmd}")
- lines.append("")
- lines.append(" Hermes owns plugin installation and MCP registration. Open Second")
- lines.append(" Brain never edits ~/.hermes/config.yaml on your behalf.")
- lines.append("")
-
- lines.append("Vault (NEVER removed by this tool):")
- if plan.vault_path is not None:
- lines.append(f" {plan.vault_path}")
- else:
- lines.append(" (no vault path recorded in config; check your runtime settings)")
- lines.append(" Your Markdown notes, Daily/, and AI Wiki/ stay exactly as they are.")
- lines.append("")
-
- if plan.apply_local:
- lines.append("Apply-local results:")
- if plan.removed_paths:
- for path in plan.removed_paths:
- lines.append(f" removed: {path}")
- if plan.skipped_paths:
- for path, reason in plan.skipped_paths:
- lines.append(f" skipped: {path} β€” {reason}")
- if plan.errors:
- for path, reason in plan.errors:
- lines.append(f" error: {path} β€” {reason}")
- if not (plan.removed_paths or plan.skipped_paths or plan.errors):
- lines.append(" (nothing to do)")
- lines.append("")
- else:
- lines.append("Next steps:")
- lines.append(" 1. Run the Hermes commands above to deregister the MCP server and plugin.")
- lines.append(" 2. Re-run with --apply-local to remove the machine-local config directory.")
- lines.append(" 3. Add --remove-cli to also remove the o2b/vault-log symlinks from ~/.local/bin.")
- lines.append(" 4. Delete the vault yourself if and only if you really want to lose your notes.")
- lines.append("")
-
- return "\n".join(lines).rstrip() + "\n"
-
-
-def iter_hermes_commands() -> Iterable[str]:
- """Public iterator over the Hermes commands the user should run."""
-
- return iter(HERMES_COMMANDS)
diff --git a/src/open_second_brain/vault.py b/src/open_second_brain/vault.py
deleted file mode 100644
index 791dbd92..00000000
--- a/src/open_second_brain/vault.py
+++ /dev/null
@@ -1,158 +0,0 @@
-from __future__ import annotations
-
-import re
-from pathlib import Path
-from typing import Any
-
-# ── Frontmatter parsing ───────────────────────────────────────────────────────
-
-_FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n?", re.DOTALL)
-_KEY_VALUE_RE = re.compile(r"^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$")
-
-
-def parse_frontmatter(path: Path) -> tuple[dict[str, Any], str]:
- """Return (metadata dict, body text) from a Markdown file with YAML-like frontmatter.
-
- Handles the standard Obsidian format:
- ---
- key: value
- ---
- body text
-
- Only simple key: value lines are supported (no nested YAML, no lists).
- Returns (metadata dict, body text) from a Markdown file with YAML-like frontmatter.
- """
- try:
- text = path.read_text(encoding="utf-8")
- except (OSError, UnicodeDecodeError):
- return {}, ""
-
- match = _FRONTMATTER_RE.match(text)
- if not match:
- return {}, text.strip()
-
- fm_block = match.group(1)
- body = text[match.end():].strip()
- metadata: dict[str, Any] = {}
-
- for line in fm_block.splitlines():
- line = line.strip()
- if not line or line.startswith("#"):
- continue
- kv = _KEY_VALUE_RE.match(line)
- if kv:
- key = kv.group(1)
- value = kv.group(2)
- metadata[key] = value.strip("'\"")
-
- return metadata, body
-
-
-_PLAIN_SCALAR_RE = re.compile(r"^[A-Za-z0-9_./-](?:[A-Za-z0-9_./ -]*[A-Za-z0-9_./-])?$")
-
-
-def _format_yaml_scalar(value: Any) -> str:
- text = str(value)
- if (
- text
- and _PLAIN_SCALAR_RE.match(text)
- and ": " not in text
- and " #" not in text
- ):
- return text
- escaped = (
- text.replace("\\", "\\\\")
- .replace('"', '\\"')
- .replace("\n", "\\n")
- .replace("\r", "\\r")
- .replace("\t", "\\t")
- )
- return f'"{escaped}"'
-
-
-def _format_yaml_value(value: Any) -> str:
- if isinstance(value, list):
- return "[" + ", ".join(_format_yaml_scalar(item) for item in value) + "]"
- return _format_yaml_scalar(value)
-
-
-def write_frontmatter(path: Path, metadata: dict[str, Any], body: str) -> None:
- """Write a Markdown file with YAML-like frontmatter and body text.
-
- Lists are serialized as YAML inline arrays (``key: [a, b]``) so they round-trip
- cleanly through Obsidian and the project's simple frontmatter parser.
- """
- path.parent.mkdir(parents=True, exist_ok=True)
- lines = ["---"]
- for key, value in metadata.items():
- lines.append(f"{key}: {_format_yaml_value(value)}")
- lines.append("---")
- if body:
- lines.append("")
- lines.append(body)
- path.write_text("\n".join(lines) + "\n", encoding="utf-8")
-
-
-# ── Wikilink extraction ───────────────────────────────────────────────────────
-
-_WIKILINK_RE = re.compile(r"\[\[([^\]|#]+)(?:[|#][^\]]*)?\]\]")
-_MEDIA_EXTENSIONS = frozenset({
- ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".tiff", ".avif",
- ".mp4", ".webm", ".ogv", ".mov", ".mkv", ".avi",
- ".mp3", ".wav", ".ogg", ".flac", ".m4a",
- ".pdf",
-})
-
-
-def extract_wikilinks(content: str) -> list[str]:
- """Return unique [[target]] titles from content, excluding media file targets.
-
- Also skips targets inside fenced code blocks and inline code spans.
- """
- # Mask code blocks to avoid false positives inside code samples
- code_blocks_re = re.compile(r"```[\s\S]*?```|`[^`]+`")
- masked = code_blocks_re.sub(" ", content)
- raw = _WIKILINK_RE.findall(masked)
- seen: set[str] = set()
- result: list[str] = []
- for target in raw:
- if any(target.lower().endswith(ext) for ext in _MEDIA_EXTENSIONS):
- continue
- if target not in seen:
- seen.add(target)
- result.append(target)
- return result
-
-
-# ── Vault page listing ────────────────────────────────────────────────────────
-
-def list_vault_pages(
- vault_dir: Path,
- *,
- skip_dirs: tuple[str, ...] = (".git", ".obsidian", ".trash", ".stversions"),
- skip_files: tuple[str, ...] = ("index.md", "log.md"),
-) -> list[tuple[str, Path, dict[str, Any]]]:
- """Walk a vault directory and return all Markdown pages with their metadata.
-
- Returns list of (title, path, metadata) sorted by title (case-insensitive).
- Title is resolved from frontmatter 'title' key, else filename stem.
- """
- pages: list[tuple[str, Path, dict[str, Any]]] = []
-
- for md_path in sorted(vault_dir.rglob("*.md")):
- # Skip excluded directories
- parts = set(str(p) for p in md_path.relative_to(vault_dir).parts)
- if parts & set(skip_dirs):
- continue
- # Skip excluded files (check filename only, case-insensitive)
- if md_path.name.lower() in skip_files:
- continue
- try:
- meta, body = parse_frontmatter(md_path)
- except Exception:
- continue
- title = meta.get("title", md_path.stem)
- pages.append((title, md_path, meta))
-
- pages.sort(key=lambda t: t[0].lower())
- return pages
diff --git a/src/open_second_brain/vault_log.py b/src/open_second_brain/vault_log.py
deleted file mode 100644
index 806e2236..00000000
--- a/src/open_second_brain/vault_log.py
+++ /dev/null
@@ -1,47 +0,0 @@
-from __future__ import annotations
-
-import argparse
-import os
-import sys
-from pathlib import Path
-
-from open_second_brain.config import resolve_timezone, resolve_vault
-from open_second_brain.event_log import append_event
-
-
-def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(prog="vault-log", description="Append an Open Second Brain event log entry")
- parser.add_argument("message", help="Single-line event message")
- parser.add_argument("--as", dest="agent", default=os.environ.get("VAULT_AGENT_NAME", "agent"), help="Agent name")
- parser.add_argument("--vault", type=Path, default=None, help="Vault directory")
- parser.add_argument("--date", default=None, help="Event date as YYYY.MM.DD")
- parser.add_argument("--time", default=None, help="Event time as HH:MM")
- return parser
-
-
-def main(argv: list[str] | None = None) -> int:
- args = build_parser().parse_args(argv)
- # Resolution order: --vault β†’ VAULT_DIR env β†’ persisted plugin
- # config (`vault` field, written by `o2b init`). If none is set,
- # fail closed rather than silently fall back to the current working
- # directory β€” that fallback used to send write invocations into
- # ``$(pwd)/Daily/...`` instead of the user's actual vault.
- vault = args.vault or resolve_vault()
- if vault is None:
- print(
- "error: no vault configured. Pass --vault <path> explicitly, "
- "set VAULT_DIR in the environment, or run "
- "`o2b init --vault <path> ...` first to persist a default.",
- file=sys.stderr,
- )
- return 1
- tz = resolve_timezone()
- path = append_event(Path(vault), args.agent, args.message, date=args.date, time=args.time, tz=tz)
- # Always print the absolute path so the user sees immediately if
- # the entry landed in an unexpected place.
- print(f"appended: {Path(path).resolve()}")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/src/openclaw/index.ts b/src/openclaw/index.ts
new file mode 100644
index 00000000..2903d365
--- /dev/null
+++ b/src/openclaw/index.ts
@@ -0,0 +1,300 @@
+/**
+ * OpenClaw native plugin entry for Open Second Brain.
+ *
+ * Pure TypeScript that delegates to `src/core/*` so the JS implementation
+ * is no longer a hand-translated copy of the Python original β€” both runtimes
+ * share the same source of truth.
+ *
+ * The plugin exposes the same five tools the MCP server does
+ * (`second_brain_status`, `second_brain_query`, `second_brain_capture`,
+ * `event_log_append`, `vault_health`), with parameter schemas mirrored from
+ * `src/mcp/tools.ts`. No subprocess creation; passes the OpenClaw security
+ * scanner.
+ */
+
+import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+
+import {
+ discoverConfig,
+ redactMapping,
+ resolveAgentName,
+ resolveTimezone,
+} from "../core/config.ts";
+import { doctor } from "../core/doctor.ts";
+import { appendEvent, validateEventTime } from "../core/event-log.ts";
+import { buildReminder } from "../core/identity-reminder.ts";
+import { listVaultPages, slugify, writeFrontmatter } from "../core/vault.ts";
+import { PLACEHOLDER_AGENT_VALUES } from "../mcp/tools.ts";
+
+interface PluginConfig {
+ vault?: string;
+ agentName?: string;
+ timezone?: string;
+ instanceName?: string;
+}
+
+function resolveVaultPath(api: { pluginConfig?: Record<string, unknown> }): string {
+ const cfg = (api.pluginConfig ?? {}) as PluginConfig;
+ return cfg.vault || process.env["VAULT_DIR"] || ".";
+}
+
+function resolveOpenclawTimezone(api: { pluginConfig?: Record<string, unknown> }): string | null {
+ const cfg = (api.pluginConfig ?? {}) as PluginConfig;
+ const candidate = cfg.timezone || process.env["VAULT_TIMEZONE"] || null;
+ if (!candidate) return null;
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: candidate });
+ return candidate;
+ } catch {
+ return null;
+ }
+}
+
+function resolveOpenclawAgent(
+ api: { pluginConfig?: Record<string, unknown> },
+ argAgent: string | null,
+): string {
+ const normalized = normalizeAgentArg(argAgent);
+ if (normalized) return normalized;
+ const cfg = (api.pluginConfig ?? {}) as PluginConfig;
+ return cfg.agentName ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();
+}
+
+function normalizeAgentArg(value: string | null): string | null {
+ if (value === null || value === undefined) return null;
+ const cleaned = String(value).trim().replace(/^@+/, "").trim();
+ if (!cleaned) return null;
+ if (PLACEHOLDER_AGENT_VALUES.has(cleaned.toLowerCase())) return null;
+ return cleaned;
+}
+
+function vaultRel(target: string, vault: string): string {
+ if (target.startsWith(vault + "/")) return target.slice(vault.length + 1);
+ return target;
+}
+
+export default definePluginEntry({
+ register(api): void {
+ // Per-turn identity reminder via OpenClaw's `before_prompt_build` hook.
+ // The hook fires before every model call and lets us append a short
+ // string into the prompt, mirroring `pre_llm_call` in Hermes and
+ // `UserPromptSubmit` in Claude Code / Codex. Without this, the agent
+ // sees the identity reminder only once at MCP `initialize`, then drifts.
+ //
+ // We prefer `prependContext` (per-turn, not cached) over
+ // `prependSystemContext` (cached system-prompt) because the cached
+ // form has the same drift problem we are working around β€” the LLM
+ // stops paying attention to it as the conversation grows.
+ api.on("before_prompt_build", () => {
+ const cfg = (api.pluginConfig ?? {}) as PluginConfig;
+ const agent =
+ normalizeAgentArg(cfg.agentName ?? null) ??
+ process.env["VAULT_AGENT_NAME"] ??
+ resolveAgentName();
+ if (agent === "agent") return undefined;
+ return { prependContext: buildReminder(agent) };
+ });
+
+ api.registerTool(
+ {
+ name: "second_brain_status",
+ description: "Report Open Second Brain configuration and vault status.",
+ parameters: { type: "object", properties: {}, additionalProperties: false },
+ async execute(): Promise<unknown> {
+ const vault = resolveVaultPath(api);
+ const discovery = discoverConfig();
+ const result = {
+ config_path: discovery.path,
+ config_exists: discovery.exists,
+ config_keys: Object.keys(discovery.data).sort(),
+ config: redactMapping(discovery.data),
+ vault_path: vault,
+ vault_exists: existsSync(vault),
+ };
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ },
+ },
+ );
+
+ api.registerTool(
+ {
+ name: "second_brain_query",
+ description: "List vault pages with optional title substring filter.",
+ parameters: {
+ type: "object",
+ properties: {
+ pattern: {
+ type: "string",
+ description: "Optional case-insensitive substring matched against page titles.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 500,
+ description: "Maximum number of matched pages to return (default 50).",
+ },
+ },
+ additionalProperties: false,
+ },
+ async execute(_id, params): Promise<unknown> {
+ const vault = resolveVaultPath(api);
+ if (!existsSync(vault)) throw new Error(`vault directory missing: ${vault}`);
+ const pattern = (params["pattern"] as string | undefined) ?? null;
+ const limit = typeof params["limit"] === "number" ? (params["limit"] as number) : 50;
+ if (limit < 1 || limit > 500) throw new Error("argument 'limit' must be between 1 and 500");
+
+ const pages = listVaultPages(vault);
+ const needle = pattern ? pattern.toLowerCase() : null;
+ const matched = (needle === null
+ ? pages
+ : pages.filter((p) => p.title.toLowerCase().includes(needle))
+ )
+ .slice(0, limit)
+ .map((p) => ({ title: p.title, path: vaultRel(p.path, vault), metadata: p.metadata }));
+
+ const result = {
+ vault_path: vault,
+ total_pages: pages.length,
+ returned: matched.length,
+ limit,
+ pattern,
+ pages: matched,
+ };
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ },
+ },
+ );
+
+ api.registerTool(
+ {
+ name: "second_brain_capture",
+ description: "Write a new Markdown note to AI Wiki/notes/ with frontmatter.",
+ parameters: {
+ type: "object",
+ properties: {
+ title: { type: "string", description: "Human-readable note title." },
+ content: { type: "string", description: "Markdown body of the note." },
+ tags: {
+ type: "array",
+ items: { type: "string" },
+ description: "Optional list of tag strings.",
+ },
+ overwrite: {
+ type: "boolean",
+ description: "Allow overwriting an existing note with the same slug.",
+ },
+ },
+ required: ["title", "content"],
+ additionalProperties: false,
+ },
+ async execute(_id, params): Promise<unknown> {
+ const vault = resolveVaultPath(api);
+ if (!existsSync(vault)) throw new Error(`vault directory missing: ${vault}`);
+ const title = (params["title"] as string | undefined) ?? "";
+ const content = (params["content"] as string | undefined) ?? "";
+ const tags = (params["tags"] as string[] | undefined) ?? [];
+ const overwrite = Boolean(params["overwrite"]);
+ if (!title.trim()) throw new Error("title must not be empty");
+ if (!content.trim()) throw new Error("content must not be empty");
+
+ const notesDir = join(vault, "AI Wiki", "notes");
+ const slug = slugify(title);
+ const target = join(notesDir, `${slug}.md`);
+ // Capture existence BEFORE writeFrontmatter β€” otherwise existsSync
+ // is always true after the write, making `overwritten` a no-op
+ // signal whenever overwrite=true.
+ const noteExisted = existsSync(target);
+ if (noteExisted && !overwrite) {
+ throw new Error(`note already exists: ${vaultRel(target, vault)}`);
+ }
+ const metadata: Record<string, string | number | boolean | string[]> = {
+ title,
+ type: "note",
+ created: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"),
+ };
+ if (tags.length > 0) metadata["tags"] = tags;
+ writeFrontmatter(target, metadata, content.trim());
+ const result = {
+ path: vaultRel(target, vault),
+ absolute_path: target,
+ slug,
+ overwritten: noteExisted && overwrite,
+ };
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ },
+ },
+ );
+
+ api.registerTool(
+ {
+ name: "event_log_append",
+ description: "Append a single-line event to the daily Markdown event log.",
+ parameters: {
+ type: "object",
+ properties: {
+ message: { type: "string", description: "Single-line event message." },
+ agent: { type: "string", description: "Agent name (default 'agent')." },
+ date: { type: "string", description: "Optional event date in YYYY.MM.DD format." },
+ time: { type: "string", description: "Optional event time in 24-hour HH:MM format." },
+ },
+ required: ["message"],
+ additionalProperties: false,
+ },
+ async execute(_id, params): Promise<unknown> {
+ const vault = resolveVaultPath(api);
+ const message = params["message"] as string | undefined;
+ if (!message || !message.trim()) {
+ // Treat whitespace-only the same as missing; the MCP-side
+ // `_coerce_str` does the same. Empty entries weaken the log.
+ throw new Error("missing required argument: message");
+ }
+ const argAgent = (params["agent"] as string | undefined) ?? null;
+ const date = (params["date"] as string | undefined) ?? null;
+ const time = (params["time"] as string | undefined) ?? null;
+ if (time) validateEventTime(time);
+ const agent = resolveOpenclawAgent(api, argAgent);
+ const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();
+ const path = await appendEvent(vault, agent, message, { date, time, tz });
+ const result = {
+ path: vaultRel(path, vault),
+ absolute_path: path,
+ agent,
+ date,
+ time,
+ };
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ },
+ },
+ );
+
+ api.registerTool(
+ {
+ name: "vault_health",
+ description: "Run vault, config, and plugin manifest health checks.",
+ parameters: {
+ type: "object",
+ properties: {
+ repo: {
+ type: "string",
+ description: "Optional repository root to validate plugin manifests.",
+ },
+ },
+ additionalProperties: false,
+ },
+ async execute(_id, params): Promise<unknown> {
+ const vault = resolveVaultPath(api);
+ const repoRoot = (params["repo"] as string | undefined) ?? null;
+ const results = doctor({ vault, repoRoot });
+ const result = {
+ vault_path: vault,
+ ok: results.every((r) => r.ok),
+ checks: results.map((r) => ({ name: r.name, ok: r.ok, message: r.message })),
+ };
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
+ },
+ },
+ );
+ },
+});
diff --git a/src/openclaw/openclaw-sdk.d.ts b/src/openclaw/openclaw-sdk.d.ts
new file mode 100644
index 00000000..5e39039a
--- /dev/null
+++ b/src/openclaw/openclaw-sdk.d.ts
@@ -0,0 +1,65 @@
+/**
+ * `openclaw/plugin-sdk/plugin-entry` is provided by the OpenClaw runtime
+ * at load time. Keep the narrow local type shape here instead of taking a
+ * build-time dependency on the SDK package; the bundle marks this import as
+ * external so OpenClaw resolves it at runtime.
+ */
+declare module "openclaw/plugin-sdk/plugin-entry" {
+ /**
+ * Optional second-arg shape for `api.registerTool`. Per the OpenClaw plugin
+ * docs (Building Plugins β†’ Registering agent tools): tools are required by
+ * default; pass `{ optional: true }` to make a tool user-opt-in (visible in
+ * the allowlist, but not auto-loaded).
+ *
+ * Earlier drafts of this declaration shipped `{ name }` here (a `ToolMeta`
+ * shape). That was wrong β€” passing `{ name: "..." }` made OpenClaw treat the
+ * tool as a non-agent-facing registration, which is why none of the five
+ * second_brain_* tools showed up in `openclaw agent --message` tool lists
+ * even though `openclaw plugins inspect --runtime` listed them. Removed.
+ */
+ export interface RegisterToolOptions {
+ readonly optional?: boolean;
+ }
+
+ export interface ToolHandler<Name extends string = string> {
+ readonly name: Name;
+ readonly description: string;
+ readonly parameters: Record<string, unknown>;
+ execute(id: unknown, params: Record<string, unknown>): Promise<unknown>;
+ }
+
+ /**
+ * Subset of the `before_prompt_build` hook return shape we use. Source:
+ * github.com/openclaw/openclaw/blob/main/src/plugins/hook-before-agent-start.types.ts
+ * (PluginHookBeforePromptBuildResult). We use `prependContext` β€” per-turn,
+ * NOT cached into the system prompt β€” because the whole point is to
+ * re-remind the LLM each turn; a cached system-prompt injection would
+ * have the same drift problem MCP `instructions` already has, which is
+ * what this hook works around.
+ */
+ export interface BeforePromptBuildResult {
+ readonly prependContext?: string;
+ }
+
+ export interface PluginApi {
+ readonly pluginConfig?: Record<string, unknown>;
+ registerTool<const Handler extends ToolHandler<string>>(
+ handler: Handler,
+ options?: RegisterToolOptions,
+ ): void;
+ on(
+ event: "before_prompt_build",
+ handler: () =>
+ | Promise<BeforePromptBuildResult | undefined>
+ | BeforePromptBuildResult
+ | undefined,
+ opts?: { priority?: number; timeoutMs?: number },
+ ): void;
+ }
+
+ export interface PluginEntry {
+ register(api: PluginApi): void;
+ }
+
+ export function definePluginEntry(entry: PluginEntry): PluginEntry;
+}
diff --git a/templates/identity-reminder.txt b/templates/identity-reminder.txt
new file mode 100644
index 00000000..367a6f93
--- /dev/null
+++ b/templates/identity-reminder.txt
@@ -0,0 +1 @@
+[open-second-brain] Identity: @{agent}. After producing a durable artifact β€” code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know β€” call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@{agent}` automatically, do not include them yourself. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
diff --git a/tests/cli/cli.test.ts b/tests/cli/cli.test.ts
new file mode 100644
index 00000000..75f5999f
--- /dev/null
+++ b/tests/cli/cli.test.ts
@@ -0,0 +1,291 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync, readdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+
+import { createPluginRepo, createSandboxVault } from "../helpers/fixtures.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-test-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("status", () => {
+ test("reports missing config", async () => {
+ const config = join(tmp, "missing.yaml");
+ const r = await runCli(["status"], { env: { OPEN_SECOND_BRAIN_CONFIG: config } });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("config_exists: false");
+ expect(r.stdout).toContain(config);
+ });
+});
+
+describe("init", () => {
+ test("creates vault structure", async () => {
+ const r = await runCli(["init", "--vault", tmp, "--name", "Test"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("initialized vault:");
+ expect(existsSync(join(tmp, "AI Wiki", "_OPEN_SECOND_BRAIN.md"))).toBe(true);
+ expect(existsSync(join(tmp, "AI Wiki", "identity", "agents.md"))).toBe(true);
+ });
+
+ test("with agent-name writes identity entry", async () => {
+ const vault = join(tmp, "vault");
+ const config = join(tmp, "config.yaml");
+ const r = await runCli(
+ ["init", "--vault", vault, "--name", "Test", "--agent-name", "openclaw-main"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("agent name registered: openclaw-main");
+ const txt = readFileSync(join(vault, "AI Wiki", "identity", "agents.md"), "utf8");
+ expect(txt).toContain("- openclaw-main: primary agent on this server");
+ expect(txt).not.toContain("(add your agents here");
+ });
+
+ test("with agent-name persists to plugin config", async () => {
+ const vault = join(tmp, "vault");
+ const config = join(tmp, "config.yaml");
+ const r = await runCli(
+ ["init", "--vault", vault, "--name", "Test", "--agent-name", "hermes-vps-agent"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("agent name persisted to:");
+ const text = readFileSync(config, "utf8");
+ expect(text).toContain("agent_name");
+ expect(text).toContain("hermes-vps-agent");
+ });
+
+ test("persists vault path resolved (absolute) into config", async () => {
+ const vault = join(tmp, "vault");
+ const config = join(tmp, "config.yaml");
+ const r = await runCli(["init", "--vault", vault, "--name", "Test"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("vault path persisted to:");
+ const text = readFileSync(config, "utf8");
+ expect(text).toContain("vault");
+ expect(text).toContain(resolve(vault));
+ });
+
+ test("with timezone persists to plugin config", async () => {
+ const vault = join(tmp, "vault");
+ const config = join(tmp, "config.yaml");
+ const r = await runCli(
+ ["init", "--vault", vault, "--name", "Test", "--agent-name", "hermes-vps-agent", "--timezone", "Europe/Belgrade"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("timezone registered: Europe/Belgrade");
+ const text = readFileSync(config, "utf8");
+ expect(text).toContain("Europe/Belgrade");
+ });
+
+ test("rejects invalid timezone", async () => {
+ const vault = join(tmp, "vault");
+ const config = join(tmp, "config.yaml");
+ const r = await runCli(
+ ["init", "--vault", vault, "--name", "Test", "--timezone", "NotARealTimezone"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("not a valid IANA name");
+ expect(existsSync(vault) && readdirSync(vault).length > 0).toBe(false);
+ });
+
+ test("re-init persists agent name", async () => {
+ const vault = join(tmp, "vault");
+ const config = join(tmp, "config.yaml");
+ await runCli(["init", "--vault", vault, "--name", "Test"]);
+ const r = await runCli(
+ ["init", "--vault", vault, "--name", "Test", "--agent-name", "hermes-vps-agent"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("agent name persisted to:");
+ expect(readFileSync(config, "utf8")).toContain("hermes-vps-agent");
+ });
+
+ test("already initialized does not overwrite", async () => {
+ await runCli(["init", "--vault", tmp, "--name", "First"]);
+ const index = join(tmp, "AI Wiki", "index.md");
+ writeFileSync(index, "custom");
+ const r = await runCli(["init", "--vault", tmp, "--name", "Second"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("already initialized");
+ expect(readFileSync(index, "utf8")).toBe("custom");
+ });
+
+ test("--force overwrites", async () => {
+ await runCli(["init", "--vault", tmp, "--name", "First"]);
+ const index = join(tmp, "AI Wiki", "index.md");
+ writeFileSync(index, "old");
+ const r = await runCli(["init", "--vault", tmp, "--name", "Second", "--force"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("initialized vault:");
+ expect(readFileSync(index, "utf8")).not.toBe("old");
+ });
+});
+
+describe("append-event", () => {
+ test("errors when no vault anywhere", async () => {
+ const cfg = join(tmp, "config.yaml");
+ const r = await runCli(["append-event", "msg", "--as", "tester"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: cfg },
+ });
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr.toLowerCase()).toContain("no vault configured");
+ });
+
+ test("prints absolute path on success", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const cfg = join(tmp, "config.yaml");
+ const r = await runCli(
+ ["append-event", "absolute-path-test", "--vault", vault, "--as", "tester"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: cfg } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("appended: ");
+ const printed = r.stdout.split("appended: ")[1]!.trim().split("\n")[0]!;
+ expect(printed.startsWith("/")).toBe(true);
+ expect(printed.startsWith(resolve(vault))).toBe(true);
+ });
+
+ test("writes daily note", async () => {
+ const r = await runCli([
+ "append-event",
+ "created CLI",
+ "--vault",
+ tmp,
+ "--as",
+ "test-agent",
+ "--date",
+ "2026.05.06",
+ "--time",
+ "10:15",
+ ]);
+ expect(r.returncode).toBe(0);
+ const daily = join(tmp, "Daily", "2026.05.06.md");
+ expect(readFileSync(daily, "utf8")).toContain("- 10:15 β€” @test-agent β€” created CLI");
+ });
+});
+
+describe("doctor", () => {
+ test("errors when no vault anywhere", async () => {
+ const cfg = join(tmp, "config.yaml");
+ const r = await runCli(["doctor"], { env: { OPEN_SECOND_BRAIN_CONFIG: cfg } });
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr.toLowerCase()).toContain("no vault configured");
+ });
+
+ test("checks valid vault", async () => {
+ const r = await runCli(["doctor", "--vault", tmp], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: "", XDG_CONFIG_HOME: "", VAULT_DIR: "" },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("[OK]");
+ expect(r.stdout.toLowerCase()).toContain("vault");
+ });
+
+ test("reports missing vault", async () => {
+ const r = await runCli(["doctor", "--vault", "/nonexistent/path"]);
+ expect(r.returncode).toBe(1);
+ expect(r.stdout).toContain("[FAIL]");
+ });
+
+ test("with --repo checks manifests", async () => {
+ const vault = createSandboxVault(tmp);
+ const repo = createPluginRepo(tmp, true);
+ const r = await runCli(["doctor", "--vault", vault, "--repo", repo]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("claude_manifest");
+ expect(r.stdout).toContain("codex_manifest");
+ expect(r.stdout).toContain("hermes_manifest");
+ });
+
+ test("with --repo rejects invalid manifest schema", async () => {
+ const vault = createSandboxVault(tmp);
+ const repo = createPluginRepo(tmp, false);
+ const r = await runCli(["doctor", "--vault", vault, "--repo", repo]);
+ expect(r.returncode).toBe(1);
+ expect(r.stdout).toContain("[FAIL] claude_manifest");
+ expect(r.stdout).toContain("[FAIL] codex_manifest");
+ });
+});
+
+describe("index", () => {
+ test("errors when no vault anywhere", async () => {
+ const cfg = join(tmp, "config.yaml");
+ const r = await runCli(["index"], { env: { OPEN_SECOND_BRAIN_CONFIG: cfg } });
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr.toLowerCase()).toContain("no vault configured");
+ });
+
+ test("generates wikilink index", async () => {
+ const vault = tmp;
+ mkdirSync(join(vault, "AI Wiki"), { recursive: true });
+ writeFileSync(join(vault, "Concept.md"), "---\ntitle: Concept\n---\n\nBody.");
+ writeFileSync(join(vault, "Other.md"), "No frontmatter.");
+ const r = await runCli(["index", "--vault", vault]);
+ expect(r.returncode).toBe(0);
+ const indexPath = join(vault, "AI Wiki", "index.md");
+ expect(existsSync(indexPath)).toBe(true);
+ const content = readFileSync(indexPath, "utf8");
+ expect(content).toContain("[[Concept]]");
+ expect(content).toContain("[[Other]]");
+ });
+});
+
+describe("export-config", () => {
+ test("writes redacted JSON snapshot", async () => {
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, "api_key: abc\nvault_path: /tmp/vault\n");
+ const out = join(tmp, "snapshot.json");
+ const r = await runCli(["export-config", "--config", config, "--output", out]);
+ expect(r.returncode).toBe(0);
+ const data = JSON.parse(readFileSync(out, "utf8"));
+ expect(data.config.api_key).toBe("[REDACTED]");
+ expect(data.config.vault_path).toBe("/tmp/vault");
+ });
+});
+
+describe("vault-log compat command (append-event under another name)", () => {
+ test("produces same daily note as append-event", async () => {
+ const r = await runCli([
+ "append-event",
+ "compat entry",
+ "--as",
+ "compat-agent",
+ "--vault",
+ tmp,
+ "--date",
+ "2026.05.06",
+ "--time",
+ "10:30",
+ ]);
+ expect(r.returncode).toBe(0);
+ const daily = join(tmp, "Daily", "2026.05.06.md");
+ expect(readFileSync(daily, "utf8")).toContain("- 10:30 β€” @compat-agent β€” compat entry");
+ });
+});
+
+describe("mcp subcommand", () => {
+ test("errors when no vault anywhere", async () => {
+ const cfg = join(tmp, "config.yaml");
+ const r = await runCli(["mcp"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: cfg, VAULT_DIR: "" },
+ });
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr.toLowerCase()).toContain("no vault configured");
+ expect(r.stderr).toContain("o2b init");
+ });
+});
diff --git a/tests/cli/install-cli.test.ts b/tests/cli/install-cli.test.ts
new file mode 100644
index 00000000..b0acff00
--- /dev/null
+++ b/tests/cli/install-cli.test.ts
@@ -0,0 +1,78 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, lstatSync, mkdtempSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { installCli, uninstallCli } from "../../src/cli/install-cli.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-installcli-test-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("installCli", () => {
+ test("creates symlinks for o2b and vault-log", () => {
+ const result = installCli(tmp);
+ expect(result.errors).toEqual([]);
+ for (const name of ["o2b", "vault-log"]) {
+ const link = join(tmp, name);
+ expect(lstatSync(link).isSymbolicLink()).toBe(true);
+ expect(readlinkSync(link)).toContain(`scripts/${name}`);
+ }
+ });
+
+ test("re-running is idempotent (exists message, no error)", () => {
+ installCli(tmp);
+ const result = installCli(tmp);
+ expect(result.errors).toEqual([]);
+ expect(result.outcomes.some(([_, msg]) => msg.startsWith("exists:"))).toBe(true);
+ });
+
+ test("does not overwrite an existing symlink to a different target", () => {
+ const fake = join(tmp, "fake.sh");
+ writeFileSync(fake, "#!/bin/sh\n");
+ symlinkSync(fake, join(tmp, "o2b"));
+ const result = installCli(tmp);
+ // Conflicting symlink is now reported as an error so callers (CLI
+ // wrapper, scripted installs) exit non-zero instead of silently
+ // succeeding while the requested link is still pointing elsewhere.
+ expect(result.errors.length).toBeGreaterThanOrEqual(1);
+ expect(result.outcomes.some(([n, msg]) => n === "o2b" && msg.startsWith("error:"))).toBe(true);
+ expect(readlinkSync(join(tmp, "o2b"))).toBe(fake);
+ });
+});
+
+describe("uninstallCli", () => {
+ test("removes only links pointing at this repo's scripts", () => {
+ installCli(tmp);
+ const result = uninstallCli(tmp);
+ expect(result.errors).toEqual([]);
+ expect(existsSync(join(tmp, "o2b"))).toBe(false);
+ expect(existsSync(join(tmp, "vault-log"))).toBe(false);
+ });
+
+ test("refuses to remove a symlink that points outside this repo", () => {
+ const elsewhere = join(tmp, "elsewhere.sh");
+ writeFileSync(elsewhere, "#!/bin/sh\n");
+ symlinkSync(elsewhere, join(tmp, "o2b"));
+ const result = uninstallCli(tmp);
+ expect(result.errors).toEqual([]);
+ expect(result.outcomes.some(([n, msg]) => n === "o2b" && msg.includes("outside this repo"))).toBe(
+ true,
+ );
+ expect(existsSync(join(tmp, "o2b"))).toBe(true);
+ });
+
+ test("skips a link that doesn't exist", () => {
+ const result = uninstallCli(tmp);
+ expect(result.errors).toEqual([]);
+ expect(
+ result.outcomes.every(([_, msg]) => msg.startsWith("skipped:")),
+ ).toBe(true);
+ });
+});
diff --git a/tests/cli/uninstall.test.ts b/tests/cli/uninstall.test.ts
new file mode 100644
index 00000000..86998a1f
--- /dev/null
+++ b/tests/cli/uninstall.test.ts
@@ -0,0 +1,288 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ HERMES_COMMANDS,
+ PLUGIN_NAME,
+ SAFE_CONFIG_DIR_NAMES,
+ planUninstall,
+ renderPlan,
+} from "../../src/cli/uninstall.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-uninstall-test-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("HERMES_COMMANDS", () => {
+ test("matches the documented form", () => {
+ expect(HERMES_COMMANDS).toEqual([
+ `hermes mcp remove ${PLUGIN_NAME}`,
+ `hermes plugins remove ${PLUGIN_NAME}`,
+ "hermes gateway restart",
+ ]);
+ });
+
+ test("does not use quoted args blob", () => {
+ for (const cmd of HERMES_COMMANDS) {
+ expect(cmd.includes("'")).toBe(false);
+ expect(cmd.includes('"')).toBe(false);
+ expect(cmd.includes("--args ")).toBe(false);
+ }
+ });
+});
+
+describe("planUninstall", () => {
+ test("dry-run does not remove the config directory", () => {
+ const configDir = join(tmp, "open-second-brain");
+ mkdirSync(configDir);
+ const config = join(configDir, "config.yaml");
+ writeFileSync(config, "vault_path: /vault/example\n");
+ const other = join(configDir, "snapshot.json");
+ writeFileSync(other, "{}");
+
+ const plan = planUninstall({ configPath: config, applyLocal: false });
+ expect(plan.applyLocal).toBe(false);
+ expect(existsSync(config)).toBe(true);
+ expect(existsSync(other)).toBe(true);
+ expect(existsSync(configDir)).toBe(true);
+ expect(plan.removedPaths).toEqual([]);
+ expect(plan.skippedPaths).toEqual([]);
+ expect(plan.configDir).toBe(configDir);
+ expect(plan.configDirExists).toBe(true);
+ expect(plan.vaultPath).toBe("/vault/example");
+ });
+
+ test("dry-run records missing config", () => {
+ const config = join(tmp, "open-second-brain", "missing.yaml");
+ const plan = planUninstall({ configPath: config, applyLocal: false });
+ expect(plan.configExists).toBe(false);
+ expect(plan.configDirExists).toBe(false);
+ expect(plan.removedPaths).toEqual([]);
+ });
+
+ test("apply-local removes the named config directory", () => {
+ const configDir = join(tmp, "open-second-brain");
+ mkdirSync(configDir);
+ writeFileSync(join(configDir, "config.yaml"), "instance: x\n");
+ mkdirSync(join(configDir, "snapshots"));
+ writeFileSync(join(configDir, "snapshots", "old.json"), "{}");
+
+ const plan = planUninstall({ configPath: join(configDir, "config.yaml"), applyLocal: true });
+ expect(plan.applyLocal).toBe(true);
+ expect(existsSync(configDir)).toBe(false);
+ expect(plan.removedPaths).toEqual([configDir]);
+ expect(plan.skippedPaths).toEqual([]);
+ expect(plan.errors).toEqual([]);
+ });
+
+ test("apply-local refuses unknown directory name", () => {
+ const configDir = join(tmp, "etc");
+ mkdirSync(configDir);
+ const payload = join(configDir, "important.yaml");
+ writeFileSync(payload, "vault_path: /vault\n");
+ const plan = planUninstall({ configPath: payload, applyLocal: true });
+ expect(existsSync(configDir)).toBe(true);
+ expect(existsSync(payload)).toBe(true);
+ expect(plan.removedPaths).toEqual([]);
+ expect(plan.skippedPaths.length).toBe(1);
+ const [skippedPath, reason] = plan.skippedPaths[0]!;
+ expect(skippedPath).toBe(configDir);
+ expect(reason).toContain("not a recognized");
+ });
+
+ test("apply-local refuses paths inside .hermes", () => {
+ const hermesRoot = join(tmp, ".hermes");
+ const configDir = join(hermesRoot, "open-second-brain");
+ mkdirSync(configDir, { recursive: true });
+ const payload = join(configDir, "config.yaml");
+ writeFileSync(payload, "vault_path: /vault\n");
+ const plan = planUninstall({ configPath: payload, applyLocal: true });
+ expect(existsSync(configDir)).toBe(true);
+ expect(plan.skippedPaths.length).toBe(1);
+ const [_, reason] = plan.skippedPaths[0]!;
+ expect(reason).toContain("Hermes");
+ });
+
+ test("apply-local refuses git repository", () => {
+ const configDir = join(tmp, "open-second-brain");
+ mkdirSync(configDir);
+ mkdirSync(join(configDir, ".git"));
+ const payload = join(configDir, "config.yaml");
+ writeFileSync(payload, "instance: x\n");
+ const plan = planUninstall({ configPath: payload, applyLocal: true });
+ expect(existsSync(configDir)).toBe(true);
+ expect(plan.removedPaths).toEqual([]);
+ expect(plan.skippedPaths.length).toBe(1);
+ expect(plan.skippedPaths[0]![1]).toContain("git");
+ });
+
+ test("apply-local skips when config dir missing", () => {
+ const payload = join(tmp, "open-second-brain", "config.yaml");
+ const plan = planUninstall({ configPath: payload, applyLocal: true });
+ expect(plan.removedPaths).toEqual([]);
+ expect(plan.skippedPaths.length).toBe(1);
+ expect(plan.skippedPaths[0]![1]).toContain("does not exist");
+ });
+});
+
+describe("safety invariants", () => {
+ test("apply-local never touches vault", () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(join(vault, "AI Wiki"), { recursive: true });
+ mkdirSync(join(vault, "Daily"), { recursive: true });
+ writeFileSync(join(vault, "AI Wiki", "page.md"), "# Page\n");
+ writeFileSync(join(vault, "Daily", "2026.05.06.md"), "# Daily\n");
+
+ const configDir = join(tmp, "open-second-brain");
+ mkdirSync(configDir);
+ const config = join(configDir, "config.yaml");
+ writeFileSync(config, `vault_path: ${vault}\n`);
+
+ planUninstall({ configPath: config, applyLocal: true });
+
+ expect(existsSync(vault)).toBe(true);
+ expect(existsSync(join(vault, "AI Wiki", "page.md"))).toBe(true);
+ expect(existsSync(join(vault, "Daily", "2026.05.06.md"))).toBe(true);
+ });
+
+ test("apply-local never touches the Hermes config file", async () => {
+ const hermesDir = join(tmp, ".hermes");
+ mkdirSync(hermesDir);
+ const hermesConfig = join(hermesDir, "config.yaml");
+ const hermesPayload =
+ "mcp_servers:\n" +
+ " open-second-brain:\n" +
+ " command: o2b\n" +
+ ' args: ["mcp", "--vault", "/vault"]\n';
+ writeFileSync(hermesConfig, hermesPayload);
+
+ const configDir = join(tmp, "open-second-brain");
+ mkdirSync(configDir);
+ const config = join(configDir, "config.yaml");
+ writeFileSync(config, "vault_path: /vault\n");
+
+ planUninstall({ configPath: config, applyLocal: true });
+ expect(existsSync(hermesConfig)).toBe(true);
+ await expect(Bun.file(hermesConfig).text()).resolves.toBe(hermesPayload);
+ });
+});
+
+describe("renderPlan", () => {
+ function basicPlan(applyLocal: boolean): string {
+ const configDir = join(tmp, "open-second-brain");
+ mkdirSync(configDir);
+ const config = join(configDir, "config.yaml");
+ writeFileSync(config, "vault_path: /vault/here\n");
+ return renderPlan(planUninstall({ configPath: config, applyLocal }));
+ }
+
+ test("includes Hermes commands", () => {
+ const text = basicPlan(false);
+ for (const cmd of HERMES_COMMANDS) expect(text).toContain(cmd);
+ });
+
+ test("states vault is preserved", () => {
+ const text = basicPlan(false);
+ expect(text).toMatch(/Vault \(NEVER removed by this tool\)/);
+ expect(text).toContain("Daily/");
+ expect(text).toContain("AI Wiki/");
+ });
+
+ test("states Hermes config is not edited", () => {
+ const text = basicPlan(false);
+ expect(text).toContain("~/.hermes/config.yaml");
+ expect(text).toContain("never edits");
+ });
+
+ test("dry-run mark", () => {
+ expect(basicPlan(false)).toContain("dry-run");
+ });
+
+ test("apply-local mark", () => {
+ expect(basicPlan(true)).toContain("apply-local");
+ });
+});
+
+describe("CLI uninstall", () => {
+ test("dry-run does not modify filesystem", async () => {
+ const configDir = join(tmp, "open-second-brain");
+ mkdirSync(configDir);
+ const config = join(configDir, "config.yaml");
+ writeFileSync(config, "vault_path: /vault\n");
+
+ const r = await runCli(["uninstall", "--config", config]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("Uninstall plan");
+ expect(r.stdout).toContain("dry-run");
+ expect(r.stdout).toContain("hermes mcp remove open-second-brain");
+ expect(r.stdout).toContain("hermes plugins remove open-second-brain");
+ expect(r.stdout).toContain("hermes gateway restart");
+ expect(r.stdout).toContain("NEVER removed by this tool");
+ expect(existsSync(config)).toBe(true);
+ expect(existsSync(configDir)).toBe(true);
+ });
+
+ test("apply-local removes only local config dir", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Daily"), { recursive: true });
+ writeFileSync(join(vault, "Daily", "2026.05.06.md"), "vault content");
+
+ const configDir = join(tmp, "open-second-brain");
+ mkdirSync(configDir);
+ const config = join(configDir, "config.yaml");
+ writeFileSync(config, `vault_path: ${vault}\n`);
+
+ const r = await runCli(["uninstall", "--config", config, "--apply-local"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("apply-local");
+ expect(existsSync(configDir)).toBe(false);
+ expect(existsSync(vault)).toBe(true);
+ expect(existsSync(join(vault, "Daily", "2026.05.06.md"))).toBe(true);
+ });
+
+ test("apply-local refuses unknown config dir name", async () => {
+ const configDir = join(tmp, "etc");
+ mkdirSync(configDir);
+ writeFileSync(join(configDir, "very-important.yaml"), "keep-me\n");
+ const config = join(configDir, "config.yaml");
+ writeFileSync(config, "vault_path: /vault\n");
+ const r = await runCli(["uninstall", "--config", config, "--apply-local"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("skipped");
+ expect(existsSync(configDir)).toBe(true);
+ expect(existsSync(join(configDir, "very-important.yaml"))).toBe(true);
+ });
+
+ test("uses OPEN_SECOND_BRAIN_CONFIG env", async () => {
+ const configDir = join(tmp, "open-second-brain");
+ mkdirSync(configDir);
+ const config = join(configDir, "config.yaml");
+ writeFileSync(config, "vault_path: /env/vault\n");
+ const r = await runCli(["uninstall"], { env: { OPEN_SECOND_BRAIN_CONFIG: config } });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain(config);
+ expect(r.stdout).toContain("/env/vault");
+ });
+
+ test("--help documents safety invariants", async () => {
+ const r = await runCli(["uninstall", "--help"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("never touches");
+ expect(r.stdout.toLowerCase()).toContain("vault");
+ });
+});
+
+describe("safe names", () => {
+ test("only canonical Open Second Brain names", () => {
+ expect([...SAFE_CONFIG_DIR_NAMES].sort()).toEqual(["open-second-brain", "open_second_brain"]);
+ });
+});
diff --git a/tests/core/config.test.ts b/tests/core/config.test.ts
new file mode 100644
index 00000000..cb9abb5f
--- /dev/null
+++ b/tests/core/config.test.ts
@@ -0,0 +1,224 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ defaultConfigPath,
+ discoverConfig,
+ parseSimpleYaml,
+ redactMapping,
+ resolveAgentName,
+ resolveTimezone,
+ resolveVault,
+ setConfigValue,
+} from "../../src/core/config.ts";
+
+let tmp: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-config-test-"));
+ for (const k of [
+ "OPEN_SECOND_BRAIN_CONFIG",
+ "XDG_CONFIG_HOME",
+ "VAULT_DIR",
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ ]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+describe("defaultConfigPath", () => {
+ test("uses OPEN_SECOND_BRAIN_CONFIG env override when set", () => {
+ const p = join(tmp, "custom.yaml");
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = p;
+ expect(defaultConfigPath()).toBe(p);
+ });
+
+ test("uses XDG_CONFIG_HOME when set without override", () => {
+ process.env["XDG_CONFIG_HOME"] = tmp;
+ expect(defaultConfigPath()).toBe(join(tmp, "open-second-brain", "config.yaml"));
+ });
+});
+
+describe("parseSimpleYaml", () => {
+ test("parses key: value lines", () => {
+ const data = parseSimpleYaml("instance_name: Test Brain\nruntime: hermes\n");
+ expect(data["instance_name"]).toBe("Test Brain");
+ expect(data["runtime"]).toBe("hermes");
+ });
+
+ test("strips surrounding quotes", () => {
+ const data = parseSimpleYaml('vault: "/path"\nname: \'X\'\n');
+ expect(data["vault"]).toBe("/path");
+ expect(data["name"]).toBe("X");
+ });
+
+ test("skips comments and blanks", () => {
+ const data = parseSimpleYaml("# top\n\nkey: val\n# trailing");
+ expect(data).toEqual({ key: "val" });
+ });
+});
+
+describe("discoverConfig", () => {
+ test("reports missing config", () => {
+ const p = join(tmp, "missing.yaml");
+ const r = discoverConfig(p);
+ expect(r.exists).toBe(false);
+ expect(r.path).toBe(p);
+ expect(r.data).toEqual({});
+ });
+
+ test("reads simple key: value yaml", () => {
+ const p = join(tmp, "config.yaml");
+ writeFileSync(p, "instance_name: Test Brain\nruntime: hermes\n");
+ const r = discoverConfig(p);
+ expect(r.exists).toBe(true);
+ expect(r.data["instance_name"]).toBe("Test Brain");
+ expect(r.data["runtime"]).toBe("hermes");
+ });
+
+ test("reports a directory as missing (not a regular file)", () => {
+ const r = discoverConfig(tmp);
+ expect(r.exists).toBe(false);
+ expect(r.data).toEqual({});
+ });
+
+ test("reports invalid utf8 as missing", () => {
+ const p = join(tmp, "config.yaml");
+ writeFileSync(p, Buffer.from([0xff, 0xfe, 0x00]));
+ const r = discoverConfig(p);
+ // Buffer with stray bytes still decodes (TextDecoder) without throwing,
+ // so we don't necessarily report missing. The Python parser is more
+ // strict. Either accept the lossy parse OR report missing β€” both
+ // are safe. We accept the lossy parse here (matches Bun's readFileSync).
+ expect(r.path).toBe(p);
+ });
+});
+
+describe("setConfigValue", () => {
+ test("persists key value as quoted yaml line", () => {
+ const p = join(tmp, "config.yaml");
+ setConfigValue("vault", "/some/path", p);
+ const r = discoverConfig(p);
+ expect(r.exists).toBe(true);
+ expect(r.data["vault"]).toBe("/some/path");
+ });
+
+ test("merges with existing keys (does not lose them)", () => {
+ const p = join(tmp, "config.yaml");
+ setConfigValue("vault", "/v", p);
+ setConfigValue("agent_name", "tester", p);
+ const r = discoverConfig(p);
+ expect(r.data["vault"]).toBe("/v");
+ expect(r.data["agent_name"]).toBe("tester");
+ });
+
+ test("rejects values with disallowed characters", () => {
+ const p = join(tmp, "config.yaml");
+ expect(() => setConfigValue("vault", 'evil"value', p)).toThrow(/disallowed character/);
+ expect(() => setConfigValue("vault", "with\nnewline", p)).toThrow(/disallowed character/);
+ });
+});
+
+describe("redactMapping", () => {
+ test("redacts secret-like keys", () => {
+ const out = redactMapping({ api_key: "abc", path: "/tmp/v", token: "xyz" });
+ expect(out["api_key"]).toBe("[REDACTED]");
+ expect(out["token"]).toBe("[REDACTED]");
+ expect(out["path"]).toBe("/tmp/v");
+ });
+});
+
+describe("resolveVault", () => {
+ test("returns null when neither env nor config", () => {
+ expect(resolveVault(join(tmp, "missing.yaml"))).toBeNull();
+ });
+
+ test("reads from env", () => {
+ process.env["VAULT_DIR"] = "/tmp/env-vault";
+ expect(resolveVault(join(tmp, "missing.yaml"))).toBe("/tmp/env-vault");
+ });
+
+ test("env wins over config", () => {
+ process.env["VAULT_DIR"] = "/tmp/env-vault";
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, 'vault: "/tmp/cfg-vault"\n');
+ expect(resolveVault(cfg)).toBe("/tmp/env-vault");
+ });
+
+ test("reads from config when env unset", () => {
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, 'vault: "/tmp/cfg-vault"\n');
+ expect(resolveVault(cfg)).toBe("/tmp/cfg-vault");
+ });
+
+ test("expands ~ in config value", () => {
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, 'vault: "~/my-vault"\n');
+ const got = resolveVault(cfg);
+ expect(got).not.toBeNull();
+ expect(got!.startsWith("~")).toBe(false);
+ });
+});
+
+describe("resolveAgentName", () => {
+ test("env wins over config", () => {
+ process.env["VAULT_AGENT_NAME"] = "from-env";
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, "agent_name: from-cfg\n");
+ expect(resolveAgentName(cfg)).toBe("from-env");
+ });
+
+ test("config provides fallback", () => {
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, "agent_name: from-cfg\n");
+ expect(resolveAgentName(cfg)).toBe("from-cfg");
+ });
+
+ test("accepts agentName key (camelCase)", () => {
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, "agentName: camelCased\n");
+ expect(resolveAgentName(cfg)).toBe("camelCased");
+ });
+
+ test("returns 'agent' literal when nothing configured", () => {
+ expect(resolveAgentName(join(tmp, "missing.yaml"))).toBe("agent");
+ });
+});
+
+describe("resolveTimezone", () => {
+ test("returns null when nothing configured", () => {
+ expect(resolveTimezone(join(tmp, "missing.yaml"))).toBeNull();
+ });
+
+ test("reads valid IANA from config", () => {
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, 'timezone: "Europe/Belgrade"\n');
+ expect(resolveTimezone(cfg)).toBe("Europe/Belgrade");
+ });
+
+ test("invalid IANA falls back to null", () => {
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, 'timezone: "Not/A/Real/Zone"\n');
+ expect(resolveTimezone(cfg)).toBeNull();
+ });
+
+ test("env wins over config", () => {
+ process.env["VAULT_TIMEZONE"] = "UTC";
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, 'timezone: "Europe/Belgrade"\n');
+ expect(resolveTimezone(cfg)).toBe("UTC");
+ });
+});
diff --git a/tests/core/doctor.test.ts b/tests/core/doctor.test.ts
new file mode 100644
index 00000000..cc9eaed4
--- /dev/null
+++ b/tests/core/doctor.test.ts
@@ -0,0 +1,124 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ checkClaudeManifest,
+ checkCodexManifest,
+ checkConfigWriteable,
+ checkHermesManifest,
+ checkJsonManifest,
+ checkOpenclawInstallability,
+ checkOpenclawManifest,
+ checkVaultWriteable,
+ doctor,
+} from "../../src/core/doctor.ts";
+import { createPluginRepo, createSandboxVault } from "../helpers/fixtures.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-doctor-test-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("checkVaultWriteable", () => {
+ test("ok on a writable directory", () => {
+ const r = checkVaultWriteable(tmp);
+ expect(r.ok).toBe(true);
+ expect(r.message.toLowerCase()).toContain("writable");
+ });
+
+ test("fail when missing", () => {
+ const r = checkVaultWriteable(join(tmp, "does_not_exist"));
+ expect(r.ok).toBe(false);
+ expect(r.message.toLowerCase()).toContain("missing");
+ });
+});
+
+describe("checkConfigWriteable", () => {
+ test("ok when file exists", () => {
+ const cfg = join(tmp, "config.yaml");
+ writeFileSync(cfg, "vault_path: /tmp\n");
+ expect(checkConfigWriteable(cfg).ok).toBe(true);
+ });
+
+ test("ok when file missing but parent can be created", () => {
+ const cfg = join(tmp, "subdir", "config.yaml");
+ expect(checkConfigWriteable(cfg).ok).toBe(true);
+ });
+});
+
+describe("checkJsonManifest", () => {
+ test("valid", () => {
+ const m = join(tmp, "plugin.json");
+ writeFileSync(m, '{"name": "test", "version": "1.0.0"}');
+ expect(checkJsonManifest(m, "Test").ok).toBe(true);
+ });
+
+ test("invalid JSON", () => {
+ const m = join(tmp, "plugin.json");
+ writeFileSync(m, "{invalid json");
+ expect(checkJsonManifest(m, "Test").ok).toBe(false);
+ });
+
+ test("missing", () => {
+ expect(checkJsonManifest(join(tmp, "x.json"), "Test").ok).toBe(false);
+ });
+});
+
+describe("manifest schema checks accept fixture repo", () => {
+ test("doctor passes on a valid plugin-repo fixture", () => {
+ const vault = createSandboxVault(tmp);
+ const repo = createPluginRepo(tmp, true);
+ const results = doctor({ vault, repoRoot: repo });
+ for (const r of results) {
+ expect(r.ok).toBe(true);
+ }
+ });
+
+ test("invalid manifests produce schema violations", () => {
+ const repo = createPluginRepo(tmp, false);
+ const claude = checkClaudeManifest(join(repo, ".claude-plugin", "plugin.json"));
+ const codex = checkCodexManifest(join(repo, ".codex-plugin", "plugin.json"));
+ const hermes = checkHermesManifest(join(repo, "plugins", "hermes", "plugin.yaml"));
+ const openclaw = checkOpenclawManifest(join(repo, "openclaw.plugin.json"));
+ expect(claude.ok).toBe(false);
+ expect(codex.ok).toBe(false);
+ expect(hermes.ok).toBe(false);
+ expect(openclaw.ok).toBe(false);
+ });
+});
+
+describe("checkOpenclawInstallability", () => {
+ test("reports missing extension entry", () => {
+ const repo = createPluginRepo(tmp, true);
+ // Replace package.json with one that points at a missing entry.
+ writeFileSync(
+ join(repo, "package.json"),
+ JSON.stringify({ name: "test", openclaw: { extensions: ["./does-not-exist.js"] } }),
+ );
+ const results = checkOpenclawInstallability(repo);
+ const failing = results.filter((r) => !r.ok);
+ expect(failing.length).toBeGreaterThan(0);
+ expect(failing.some((r) => r.message.includes("missing extension entry"))).toBe(true);
+ });
+
+ test("rejects when extensions array is missing", () => {
+ const repo = createPluginRepo(tmp, true);
+ writeFileSync(join(repo, "package.json"), JSON.stringify({ name: "test" }));
+ const results = checkOpenclawInstallability(repo);
+ expect(results.some((r) => !r.ok && r.name === "openclaw_package_json_extensions")).toBe(true);
+ });
+});
+
+describe("doctor aggregator", () => {
+ test("returns at least the vault check", () => {
+ const results = doctor({ vault: tmp });
+ expect(results.length).toBeGreaterThan(0);
+ });
+});
diff --git a/tests/core/event-log.test.ts b/tests/core/event-log.test.ts
new file mode 100644
index 00000000..579f27e7
--- /dev/null
+++ b/tests/core/event-log.test.ts
@@ -0,0 +1,145 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ appendEvent,
+ insertEventEntry,
+ redactText,
+ validateEventDate,
+ validateEventTime,
+} from "../../src/core/event-log.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-eventlog-test-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("redactText", () => {
+ test("removes secret-like assignments", () => {
+ expect(redactText("api_key=abc token: xyz password = qwerty")).toBe(
+ "api_key=[REDACTED] token: [REDACTED] password = [REDACTED]",
+ );
+ });
+});
+
+describe("validateEventTime", () => {
+ test("accepts HH:MM in 24-hour range", () => {
+ expect(validateEventTime("00:00")).toBe("00:00");
+ expect(validateEventTime("23:59")).toBe("23:59");
+ });
+
+ test("rejects malformed inputs", () => {
+ for (const bad of ["9:00", "25:00", "bad", "10:60", "abc:de"]) {
+ expect(() => validateEventTime(bad)).toThrow(/HH:MM/);
+ }
+ });
+});
+
+describe("validateEventDate", () => {
+ test("accepts YYYY.MM.DD calendar dates", () => {
+ expect(validateEventDate("2026.05.06")).toBe("2026.05.06");
+ expect(validateEventDate("2024.02.29")).toBe("2024.02.29");
+ });
+
+ test("rejects malformed, impossible, or path-like inputs", () => {
+ for (const bad of [
+ "2026-05-06",
+ "2026.5.6",
+ "2026.13.01",
+ "2026.02.30",
+ "../AI Wiki/notes/pwn",
+ ]) {
+ expect(() => validateEventDate(bad)).toThrow(/YYYY\.MM\.DD/);
+ }
+ });
+});
+
+describe("insertEventEntry", () => {
+ test("inserts at the end when no other events", () => {
+ const out = insertEventEntry("# Day\n\n## Raw events\n\n", "- 09:30 β€” @x β€” first");
+ expect(out).toBe("# Day\n\n## Raw events\n\n- 09:30 β€” @x β€” first\n");
+ });
+
+ test("preserves chronological order", () => {
+ let content = "# Day\n\n## Raw events\n\n";
+ content = insertEventEntry(content, "- 11:00 β€” @x β€” later");
+ content = insertEventEntry(content, "- 09:00 β€” @x β€” earlier");
+ expect(content.indexOf("09:00")).toBeLessThan(content.indexOf("11:00"));
+ });
+});
+
+describe("appendEvent", () => {
+ test("creates daily note with raw events section", async () => {
+ const path = await appendEvent(tmp, "test-agent", "created project skeleton", {
+ date: "2026.05.06",
+ time: "09:30",
+ });
+ expect(path).toBe(join(tmp, "Daily", "2026.05.06.md"));
+ const text = readFileSync(path, "utf8");
+ expect(text).toBe(
+ "---\nformatted: false\n---\n\n# 2026.05.06\n\n## Raw events\n\n- 09:30 β€” @test-agent β€” created project skeleton\n",
+ );
+ });
+
+ test("preserves manual content above raw events", async () => {
+ const daily = join(tmp, "Daily", "2026.05.06.md");
+ mkdirSync(join(tmp, "Daily"), { recursive: true });
+ writeFileSync(
+ daily,
+ "# 2026.05.06\n\nManual note.\n\n## Raw events\n\n- 08:00 β€” @old β€” old entry\n",
+ );
+ await appendEvent(tmp, "new", "new entry", { date: "2026.05.06", time: "09:00" });
+ expect(readFileSync(daily, "utf8")).toBe(
+ "# 2026.05.06\n\nManual note.\n\n## Raw events\n\n- 08:00 β€” @old β€” old entry\n- 09:00 β€” @new β€” new entry\n",
+ );
+ });
+
+ test("rejects invalid explicit times", async () => {
+ for (const bad of ["9:00", "25:00", "bad"]) {
+ await expect(
+ appendEvent(tmp, "agent", "msg", { date: "2026.05.06", time: bad }),
+ ).rejects.toThrow(/HH:MM/);
+ }
+ });
+
+ test("rejects invalid explicit dates before building the output path", async () => {
+ for (const bad of ["2026-05-06", "2026.02.30", "../AI Wiki/notes/pwn"]) {
+ await expect(
+ appendEvent(tmp, "agent", "msg", { date: bad, time: "09:00" }),
+ ).rejects.toThrow(/YYYY\.MM\.DD/);
+ }
+ });
+
+ test("concurrent process appends keep all entries", async () => {
+ const helper = join(import.meta.dir, "..", "helpers", "concurrent-append-runner.ts");
+ const N = 12;
+ const procs = Array.from({ length: N }, (_, i) =>
+ Bun.spawn(["bun", "run", helper, tmp, String(i)], {
+ stdout: "pipe",
+ stderr: "pipe",
+ }),
+ );
+ const codes = await Promise.all(procs.map((p) => p.exited));
+ for (let i = 0; i < N; i++) {
+ if (codes[i] !== 0) {
+ const stderr = await new Response(procs[i]!.stderr).text();
+ throw new Error(`worker ${i} exited ${codes[i]}: ${stderr}`);
+ }
+ }
+ const content = readFileSync(join(tmp, "Daily", "2026.05.06.md"), "utf8");
+ for (let i = 0; i < N; i++) {
+ const stamp = `- 10:${String(i).padStart(2, "0")} β€” @worker β€” entry ${i}`;
+ expect(content).toContain(stamp);
+ }
+ const matches = content.match(/@worker β€” entry/g);
+ expect(matches).not.toBeNull();
+ expect(matches!.length).toBe(N);
+ }, 30_000);
+});
diff --git a/tests/core/identity-reminder.test.ts b/tests/core/identity-reminder.test.ts
new file mode 100644
index 00000000..10dcd86a
--- /dev/null
+++ b/tests/core/identity-reminder.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, test } from "bun:test";
+import { existsSync, readFileSync } from "node:fs";
+
+import {
+ __TEMPLATE_PATH_FOR_TESTS,
+ buildReminder,
+ loadReminderTemplate,
+} from "../../src/core/identity-reminder.ts";
+
+describe("template", () => {
+ test("template file exists at the resolved path", () => {
+ expect(existsSync(__TEMPLATE_PATH_FOR_TESTS)).toBe(true);
+ });
+
+ test("template contains {agent} placeholders (at least two)", () => {
+ const text = loadReminderTemplate();
+ const occurrences = (text.match(/\{agent\}/g) ?? []).length;
+ expect(occurrences).toBeGreaterThanOrEqual(2);
+ });
+
+ test("template references event_log_append", () => {
+ expect(loadReminderTemplate()).toContain("event_log_append");
+ });
+});
+
+describe("buildReminder", () => {
+ test("substitutes every {agent} placeholder", () => {
+ const out = buildReminder("hermes-vps-agent");
+ expect(out).toContain("@hermes-vps-agent");
+ expect(out).not.toContain("{agent}");
+ });
+
+ test("works for any string agent name", () => {
+ expect(buildReminder("openclaw-main")).toContain("@openclaw-main");
+ expect(buildReminder("x")).toContain("@x");
+ });
+});
+
+describe("Python parity", () => {
+ test("template file content has not drifted from what Python expects", () => {
+ // Python shim reads templates/identity-reminder.txt directly. If the
+ // file is renamed or its placeholder vocabulary changes, Python and
+ // TypeScript would diverge silently. Assert the on-disk filename and
+ // the placeholder name remain `{agent}` so that swapping in a different
+ // marker requires editing both runtimes deliberately.
+ const raw = readFileSync(__TEMPLATE_PATH_FOR_TESTS, "utf8");
+ expect(raw).toMatch(/\{agent\}/);
+ expect(__TEMPLATE_PATH_FOR_TESTS).toContain("templates/identity-reminder.txt");
+ });
+});
diff --git a/tests/core/init.test.ts b/tests/core/init.test.ts
new file mode 100644
index 00000000..3a7f4ecd
--- /dev/null
+++ b/tests/core/init.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, normalize } from "node:path";
+
+import {
+ AGENTS_PLACEHOLDER,
+ VAULT_FILES,
+ bootstrapVault,
+} from "../../src/core/init.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-init-test-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("bootstrapVault", () => {
+ test("creates the canonical structure", () => {
+ const created = bootstrapVault(tmp, { name: "Test Brain" });
+ expect(created.length).toBeGreaterThan(0);
+ for (const rel of VAULT_FILES) {
+ expect(existsSync(join(tmp, rel))).toBe(true);
+ }
+ const manual = readFileSync(join(tmp, "AI Wiki", "_OPEN_SECOND_BRAIN.md"), "utf8");
+ expect(manual).toContain("Test Brain");
+ });
+
+ test("writes agent_name into agents.md", () => {
+ bootstrapVault(tmp, { name: "Test", agentName: "openclaw-main" });
+ const txt = readFileSync(join(tmp, "AI Wiki", "identity", "agents.md"), "utf8");
+ expect(txt).toContain("- openclaw-main: primary agent on this server");
+ expect(txt).not.toContain(AGENTS_PLACEHOLDER);
+ });
+
+ test("without agent_name keeps placeholder", () => {
+ bootstrapVault(tmp, { name: "Test" });
+ const txt = readFileSync(join(tmp, "AI Wiki", "identity", "agents.md"), "utf8");
+ expect(txt).toContain(AGENTS_PLACEHOLDER);
+ });
+
+ test("registers a second agent under existing one (multi-runtime install)", () => {
+ bootstrapVault(tmp, { name: "Test", agentName: "hermes-vps-agent" });
+ const agentsPath = join(tmp, "AI Wiki", "identity", "agents.md");
+ expect(readFileSync(agentsPath, "utf8")).toContain(
+ "- hermes-vps-agent: primary agent on this server",
+ );
+
+ const second = bootstrapVault(tmp, { name: "Test", agentName: "codex-vps-agent" });
+ expect(second).toContain(normalize("AI Wiki/identity/agents.md"));
+
+ const text = readFileSync(agentsPath, "utf8");
+ expect(text).toContain("- hermes-vps-agent: primary agent on this server");
+ expect(text).toContain("- codex-vps-agent: primary agent on this server");
+ expect(text.indexOf("hermes-vps-agent")).toBeLessThan(text.indexOf("codex-vps-agent"));
+ expect(text).toContain("## Scopes");
+ expect(text.indexOf("codex-vps-agent")).toBeLessThan(text.indexOf("## Scopes"));
+
+ // Re-registering the same agent is a no-op.
+ const third = bootstrapVault(tmp, { name: "Test", agentName: "codex-vps-agent" });
+ expect(third).not.toContain(normalize("AI Wiki/identity/agents.md"));
+ const after = readFileSync(agentsPath, "utf8");
+ expect((after.match(/- codex-vps-agent: primary agent on this server/g) ?? []).length).toBe(1);
+ });
+
+ test("upgrades existing placeholder in place when agent_name added later", () => {
+ bootstrapVault(tmp, { name: "Test" });
+ const agentsPath = join(tmp, "AI Wiki", "identity", "agents.md");
+ expect(readFileSync(agentsPath, "utf8")).toContain(AGENTS_PLACEHOLDER);
+
+ const created = bootstrapVault(tmp, { name: "Test", agentName: "hermes-main" });
+ expect(created).toContain(normalize("AI Wiki/identity/agents.md"));
+ const text = readFileSync(agentsPath, "utf8");
+ expect(text).toContain("- hermes-main: primary agent on this server");
+ expect(text).not.toContain(AGENTS_PLACEHOLDER);
+ });
+
+ test("does not overwrite existing files by default", () => {
+ mkdirSync(join(tmp, "AI Wiki"), { recursive: true });
+ writeFileSync(join(tmp, "AI Wiki", "index.md"), "custom content");
+ const created = bootstrapVault(tmp, { name: "Test" });
+ expect(created).not.toContain(normalize("AI Wiki/index.md"));
+ expect(readFileSync(join(tmp, "AI Wiki", "index.md"), "utf8")).toBe("custom content");
+ });
+
+ test("force overwrites", () => {
+ mkdirSync(join(tmp, "AI Wiki"), { recursive: true });
+ writeFileSync(join(tmp, "AI Wiki", "index.md"), "old");
+ const created = bootstrapVault(tmp, { name: "Test", force: true });
+ expect(created).toContain(normalize("AI Wiki/index.md"));
+ expect(readFileSync(join(tmp, "AI Wiki", "index.md"), "utf8")).not.toBe("old");
+ });
+});
diff --git a/tests/core/vault.test.ts b/tests/core/vault.test.ts
new file mode 100644
index 00000000..9d70bf96
--- /dev/null
+++ b/tests/core/vault.test.ts
@@ -0,0 +1,170 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ extractWikilinks,
+ listVaultPages,
+ parseFrontmatter,
+ slugify,
+ writeFrontmatter,
+} from "../../src/core/vault.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-vault-test-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("parseFrontmatter", () => {
+ test("extracts simple key/value fields", () => {
+ const path = join(tmp, "note.md");
+ writeFileSync(
+ path,
+ "---\ntitle: Hello World\ntags: test, example\n---\n\nBody text.\n",
+ );
+ const [meta, body] = parseFrontmatter(path);
+ expect(meta["title"]).toBe("Hello World");
+ expect(meta["tags"]).toBe("test, example");
+ expect(body).toBe("Body text.");
+ });
+
+ test("handles file without frontmatter", () => {
+ const path = join(tmp, "note.md");
+ writeFileSync(path, "Just a note.");
+ const [meta, body] = parseFrontmatter(path);
+ expect(meta).toEqual({});
+ expect(body).toBe("Just a note.");
+ });
+
+ test("handles missing file gracefully", () => {
+ const [meta, body] = parseFrontmatter("/nonexistent/file.md");
+ expect(meta).toEqual({});
+ expect(body).toBe("");
+ });
+});
+
+describe("writeFrontmatter", () => {
+ test("roundtrip preserves title and body", () => {
+ const path = join(tmp, "note.md");
+ writeFrontmatter(path, { title: "Roundtrip" }, "The body.");
+ const [meta, body] = parseFrontmatter(path);
+ expect(meta["title"]).toBe("Roundtrip");
+ expect(body).toBe("The body.");
+ });
+
+ test("serializes lists as inline arrays", () => {
+ const path = join(tmp, "note.md");
+ writeFrontmatter(path, { title: "Tagged", tags: ["draft", "demo"] }, "Body.");
+ const text = readFileSync(path, "utf8");
+ expect(text).toContain("tags: [draft, demo]");
+ });
+
+ test("quotes list values with special chars", () => {
+ const path = join(tmp, "note.md");
+ writeFrontmatter(path, { tags: ["plain", "needs, comma"] }, "Body.");
+ const text = readFileSync(path, "utf8");
+ expect(text).toContain('tags: [plain, "needs, comma"]');
+ });
+
+ test("quotes scalars containing colon-space", () => {
+ const path = join(tmp, "note.md");
+ writeFrontmatter(path, { title: "Hello: world" }, "Body.");
+ const text = readFileSync(path, "utf8");
+ expect(text).toContain('title: "Hello: world"');
+ });
+
+ test("escapes control characters", () => {
+ const path = join(tmp, "note.md");
+ writeFrontmatter(path, { summary: "line one\nline two" }, "Body.");
+ const text = readFileSync(path, "utf8");
+ expect(text).toContain('summary: "line one\\nline two"');
+ });
+
+ test("inline array with quoted comma round-trips", () => {
+ const path = join(tmp, "note.md");
+ writeFrontmatter(path, { tags: ["plain", "needs, comma", "third"] }, "Body.");
+ const [meta] = parseFrontmatter(path);
+ expect(meta["tags"]).toEqual(["plain", "needs, comma", "third"]);
+ });
+
+ test("empty inline array round-trips to []", () => {
+ const path = join(tmp, "note.md");
+ writeFrontmatter(path, { tags: [] as string[] }, "Body.");
+ const [meta] = parseFrontmatter(path);
+ expect(meta["tags"]).toEqual([]);
+ });
+});
+
+describe("slugify", () => {
+ test("lowercases and replaces punctuation", () => {
+ expect(slugify("Hello, World!")).toBe("hello-world");
+ });
+
+ test("handles non-ASCII and empty inputs", () => {
+ expect(slugify(" ")).toBe("note");
+ expect(slugify("---")).toBe("note");
+ // Geometric / dingbat symbols β€” purely non-ASCII, stripped down to nothing
+ // by the alphanumeric regex. Falls back to the "note" sentinel.
+ expect(slugify("β˜… β˜† β˜ƒ")).toBe("note");
+ });
+
+ test("truncates long input to 64 chars", () => {
+ expect(slugify("a".repeat(200)).length).toBe(64);
+ });
+});
+
+describe("extractWikilinks", () => {
+ test("simple links", () => {
+ expect(extractWikilinks("See [[Target]] and [[Other]] for details.")).toEqual([
+ "Target",
+ "Other",
+ ]);
+ });
+
+ test("ignores media file extensions", () => {
+ expect(extractWikilinks("Look at ![[photo.png]] and [[concept]].")).toEqual(["concept"]);
+ });
+
+ test("ignores code blocks", () => {
+ expect(extractWikilinks("```\n[[not-a-link]]\n```\nReal: [[real-link]]")).toEqual([
+ "real-link",
+ ]);
+ });
+
+ test("deduplicates", () => {
+ expect(extractWikilinks("[[A]] [[A]] [[B]]")).toEqual(["A", "B"]);
+ });
+});
+
+describe("listVaultPages", () => {
+ test("discovers Markdown files", () => {
+ writeFileSync(join(tmp, "page1.md"), "---\ntitle: Alpha\n---\n\nContent.");
+ writeFileSync(join(tmp, "page2.md"), "Beta content without frontmatter.");
+ const pages = listVaultPages(tmp);
+ expect(pages.length).toBe(2);
+ const titles = pages.map((p) => p.title);
+ expect(titles).toContain("Alpha");
+ expect(titles).toContain("page2");
+ });
+
+ test("skips excluded dirs", () => {
+ writeFileSync(join(tmp, "page.md"), "Content.");
+ mkdirSync(join(tmp, ".obsidian"));
+ writeFileSync(join(tmp, ".obsidian", "hidden.md"), "Hidden.");
+ expect(listVaultPages(tmp).length).toBe(1);
+ });
+
+ test("skips excluded files (index.md, log.md)", () => {
+ writeFileSync(join(tmp, "page.md"), "Content.");
+ writeFileSync(join(tmp, "index.md"), "Index.");
+ const pages = listVaultPages(tmp);
+ expect(pages.length).toBe(1);
+ expect(pages[0]!.title).toBe("page");
+ });
+});
diff --git a/tests/fixtures.py b/tests/fixtures.py
deleted file mode 100644
index eeaea56a..00000000
--- a/tests/fixtures.py
+++ /dev/null
@@ -1,85 +0,0 @@
-from __future__ import annotations
-
-from pathlib import Path
-
-
-def create_sandbox_vault(root: Path, *, name: str = "Sandbox Brain") -> Path:
- """Create a small Obsidian-compatible sandbox vault for tests."""
-
- vault = root / "sandbox-vault"
- (vault / "AI Wiki").mkdir(parents=True, exist_ok=True)
- (vault / "Daily").mkdir(parents=True, exist_ok=True)
- (vault / "AI Wiki" / "_OPEN_SECOND_BRAIN.md").write_text(
- f"---\ntitle: {name}\ntype: operating-manual\n---\n\n# {name}\n",
- encoding="utf-8",
- )
- (vault / "AI Wiki" / "Concept.md").write_text(
- "---\ntitle: Sandbox Concept\n---\n\nLinked to [[Other]].\n",
- encoding="utf-8",
- )
- (vault / "Other.md").write_text("# Other\n", encoding="utf-8")
- return vault
-
-
-def create_plugin_repo(root: Path, *, valid: bool = True) -> Path:
- """Create a minimal repo fixture containing plugin manifests."""
-
- repo = root / "plugin-repo"
- (repo / ".claude-plugin").mkdir(parents=True, exist_ok=True)
- (repo / ".codex-plugin").mkdir(parents=True, exist_ok=True)
- (repo / "plugins" / "hermes").mkdir(parents=True, exist_ok=True)
- if valid:
- (repo / ".claude-plugin" / "plugin.json").write_text(
- """{
- "name": "test",
- "version": "1.0.0",
- "description": "test manifest",
- "author": { "name": "tests" },
- "license": "MIT",
- "repository": "https://example.invalid/test",
- "keywords": ["test"]
-}
-""",
- encoding="utf-8",
- )
- (repo / ".codex-plugin" / "plugin.json").write_text(
- """{
- "name": "test",
- "version": "1.0.0",
- "description": "test manifest",
- "skills": "./skills",
- "keywords": ["test"]
-}
-""",
- encoding="utf-8",
- )
- (repo / "plugins" / "hermes" / "plugin.yaml").write_text(
- "name: test\nversion: \"1.0.0\"\ndescription: test manifest\n",
- encoding="utf-8",
- )
- (repo / "openclaw.plugin.json").write_text(
- """{
- "id": "test-plugin",
- "configSchema": {
- "type": "object",
- "additionalProperties": false,
- "properties": {}
- }
-}
-""",
- encoding="utf-8",
- )
- # Native OpenClaw plugin packaging: package.json + extension entry
- entry_js = repo / "openclaw" / "index.js"
- entry_js.parent.mkdir(parents=True, exist_ok=True)
- entry_js.write_text("// plugin entry\n", encoding="utf-8")
- (repo / "package.json").write_text(
- """{"name": "test-plugin", "openclaw": {"extensions": ["./openclaw/index.js"]}}""",
- encoding="utf-8",
- )
- else:
- (repo / ".claude-plugin" / "plugin.json").write_text("{\"name\": \"test\"}", encoding="utf-8")
- (repo / ".codex-plugin" / "plugin.json").write_text("{\"name\": \"test\"}", encoding="utf-8")
- (repo / "plugins" / "hermes" / "plugin.yaml").write_text("name: test\n", encoding="utf-8")
- (repo / "openclaw.plugin.json").write_text("{}", encoding="utf-8")
- return repo
diff --git a/tests/helpers/concurrent-append-runner.ts b/tests/helpers/concurrent-append-runner.ts
new file mode 100644
index 00000000..6c3308a4
--- /dev/null
+++ b/tests/helpers/concurrent-append-runner.ts
@@ -0,0 +1,21 @@
+/**
+ * Test helper: append a single event from a subprocess. Used by the
+ * concurrent-append test to exercise cross-process locking. Argv:
+ * <vault> <index>
+ */
+
+import { appendEvent } from "../../src/core/event-log.ts";
+
+const [, , vault, indexStr] = process.argv;
+if (!vault || indexStr === undefined) {
+ process.stderr.write("usage: <vault> <index>\n");
+ process.exit(2);
+}
+const index = Number.parseInt(indexStr, 10);
+if (!Number.isFinite(index)) {
+ process.stderr.write(`error: <index> must be a finite number, got ${JSON.stringify(indexStr)}\n`);
+ process.exit(2);
+}
+const time = `10:${String(index).padStart(2, "0")}`;
+
+await appendEvent(vault, "worker", `entry ${index}`, { date: "2026.05.06", time });
diff --git a/tests/helpers/fixtures.ts b/tests/helpers/fixtures.ts
new file mode 100644
index 00000000..fe60c969
--- /dev/null
+++ b/tests/helpers/fixtures.ts
@@ -0,0 +1,89 @@
+/**
+ * Shared test fixtures: build a sandbox vault and a plugin-repo skeleton.
+ * Mirrors `tests/fixtures.py` used by the legacy Python suite.
+ */
+
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+export function createSandboxVault(root: string, name = "Sandbox Brain"): string {
+ const vault = join(root, "sandbox-vault");
+ mkdirSync(join(vault, "AI Wiki"), { recursive: true });
+ mkdirSync(join(vault, "Daily"), { recursive: true });
+ writeFileSync(
+ join(vault, "AI Wiki", "_OPEN_SECOND_BRAIN.md"),
+ `---\ntitle: ${name}\ntype: operating-manual\n---\n\n# ${name}\n`,
+ );
+ writeFileSync(
+ join(vault, "AI Wiki", "Concept.md"),
+ "---\ntitle: Sandbox Concept\n---\n\nLinked to [[Other]].\n",
+ );
+ writeFileSync(join(vault, "Other.md"), "# Other\n");
+ return vault;
+}
+
+export function createPluginRepo(root: string, valid = true): string {
+ const repo = join(root, "plugin-repo");
+ mkdirSync(join(repo, ".claude-plugin"), { recursive: true });
+ mkdirSync(join(repo, ".codex-plugin"), { recursive: true });
+ mkdirSync(join(repo, "plugins", "hermes"), { recursive: true });
+ if (valid) {
+ writeFileSync(
+ join(repo, ".claude-plugin", "plugin.json"),
+ JSON.stringify(
+ {
+ name: "test",
+ version: "1.0.0",
+ description: "test manifest",
+ author: { name: "tests" },
+ license: "MIT",
+ repository: "https://example.invalid/test",
+ keywords: ["test"],
+ },
+ null,
+ 2,
+ ),
+ );
+ writeFileSync(
+ join(repo, ".codex-plugin", "plugin.json"),
+ JSON.stringify(
+ {
+ name: "test",
+ version: "1.0.0",
+ description: "test manifest",
+ skills: "./skills",
+ keywords: ["test"],
+ },
+ null,
+ 2,
+ ),
+ );
+ writeFileSync(
+ join(repo, "plugins", "hermes", "plugin.yaml"),
+ 'name: test\nversion: "1.0.0"\ndescription: test manifest\n',
+ );
+ writeFileSync(
+ join(repo, "openclaw.plugin.json"),
+ JSON.stringify(
+ {
+ id: "test-plugin",
+ configSchema: { type: "object", additionalProperties: false, properties: {} },
+ },
+ null,
+ 2,
+ ),
+ );
+ mkdirSync(join(repo, "openclaw"), { recursive: true });
+ writeFileSync(join(repo, "openclaw", "index.js"), "// plugin entry\n");
+ writeFileSync(
+ join(repo, "package.json"),
+ JSON.stringify({ name: "test-plugin", openclaw: { extensions: ["./openclaw/index.js"] } }),
+ );
+ } else {
+ writeFileSync(join(repo, ".claude-plugin", "plugin.json"), '{"name": "test"}');
+ writeFileSync(join(repo, ".codex-plugin", "plugin.json"), '{"name": "test"}');
+ writeFileSync(join(repo, "plugins", "hermes", "plugin.yaml"), "name: test\n");
+ writeFileSync(join(repo, "openclaw.plugin.json"), "{}");
+ }
+ return repo;
+}
diff --git a/tests/helpers/run-cli.ts b/tests/helpers/run-cli.ts
new file mode 100644
index 00000000..22367eea
--- /dev/null
+++ b/tests/helpers/run-cli.ts
@@ -0,0 +1,75 @@
+/**
+ * Test helper: run the `o2b` CLI as a subprocess and capture stdout/stderr/code.
+ *
+ * Each invocation gets an isolated `OPEN_SECOND_BRAIN_CONFIG` so init-tests
+ * never clobber the developer's `~/.config/open-second-brain/config.yaml`.
+ * Tests that explicitly want to verify default-config behavior can pass their
+ * own value in `env`.
+ */
+
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+export interface RunResult {
+ readonly stdout: string;
+ readonly stderr: string;
+ readonly returncode: number;
+}
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(HERE, "..", "..");
+const CLI_ENTRY = join(ROOT, "src", "cli", "main.ts");
+
+/**
+ * Env vars that the CLI reads for vault / identity / timezone resolution
+ * AND `OPEN_SECOND_BRAIN_CONFIG` itself. Each one MUST start unset in tests
+ * unless the caller passes it explicitly β€” the developer's shell almost
+ * certainly has `VAULT_AGENT_NAME`, `OPEN_SECOND_BRAIN_CONFIG`, etc. pointing
+ * at their real vault / persisted config; if we let those leak into the
+ * child process, init-tests can write to the real `~/.config/open-second-brain/`
+ * instead of a per-test sandbox.
+ */
+const RUNTIME_OVERRIDABLE_ENV = [
+ "VAULT_DIR",
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "OPEN_SECOND_BRAIN_CONFIG",
+] as const;
+
+export async function runCli(
+ args: ReadonlyArray<string>,
+ opts: { env?: Record<string, string> } = {},
+): Promise<RunResult> {
+ const callerEnv = opts.env ?? {};
+ // Build the child env from process.env, then strip any runtime-resolution
+ // env that the caller did not explicitly pass. The caller's passed values
+ // β€” including empty strings β€” are honoured verbatim.
+ const env: Record<string, string> = { ...process.env } as Record<string, string>;
+ for (const key of RUNTIME_OVERRIDABLE_ENV) {
+ if (!(key in callerEnv)) delete env[key];
+ }
+ Object.assign(env, callerEnv);
+ let cleanupDir: string | null = null;
+ if (!("OPEN_SECOND_BRAIN_CONFIG" in env)) {
+ cleanupDir = mkdtempSync(join(tmpdir(), "o2b-test-"));
+ env["OPEN_SECOND_BRAIN_CONFIG"] = join(cleanupDir, "isolated-config.yaml");
+ }
+ try {
+ const proc = Bun.spawn(["bun", "run", CLI_ENTRY, ...args], {
+ cwd: ROOT,
+ env,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const [stdout, stderr] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ ]);
+ const returncode = await proc.exited;
+ return { stdout, stderr, returncode };
+ } finally {
+ if (cleanupDir !== null) rmSync(cleanupDir, { recursive: true, force: true });
+ }
+}
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
new file mode 100644
index 00000000..5e7c6055
--- /dev/null
+++ b/tests/mcp/mcp.test.ts
@@ -0,0 +1,492 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ JSONRPC_VERSION,
+ MCPServer,
+ PROTOCOL_VERSION,
+ SERVER_NAME,
+ SERVER_VERSION,
+ serveStdioFromString,
+ slugify,
+} from "../../src/mcp/index.ts";
+import { createPluginRepo, createSandboxVault } from "../helpers/fixtures.ts";
+
+let tmp: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-test-"));
+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+async function initialize(server: MCPServer) {
+ const r = await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "test-client", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+ return r;
+}
+
+async function callTool(server: MCPServer, name: string, args: Record<string, unknown> = {}, id = 99) {
+ return server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id,
+ method: "tools/call",
+ params: { name, arguments: args },
+ });
+}
+
+describe("slugify (re-exported via MCP barrel)", () => {
+ test("lowercases and replaces punctuation", () => {
+ expect(slugify("Hello, World!")).toBe("hello-world");
+ });
+
+ test("handles empty/non-ASCII inputs", () => {
+ expect(slugify(" ")).toBe("note");
+ expect(slugify("---")).toBe("note");
+ expect(slugify("β˜… β˜† β˜ƒ")).toBe("note");
+ });
+
+ test("truncates to 64 chars", () => {
+ expect(slugify("a".repeat(200)).length).toBe(64);
+ });
+});
+
+describe("handshake", () => {
+ test("initialize returns server info and tools capability", async () => {
+ const server = new MCPServer({ vault: tmp });
+ const r = (await initialize(server))!;
+ expect(r.jsonrpc).toBe(JSONRPC_VERSION);
+ expect(r.id).toBe(1);
+ const result = (r as any).result;
+ expect(result.serverInfo.name).toBe(SERVER_NAME);
+ expect(result.serverInfo.version).toBe(SERVER_VERSION);
+ expect(result.capabilities.tools).toBeDefined();
+ expect(result.protocolVersion).toBe(PROTOCOL_VERSION);
+ });
+
+ test("instructions embed resolved agent identity", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, "agent_name: hermes-vps-agent\n");
+ const server = new MCPServer({ vault, configPath: config });
+ const r = (await initialize(server))! as any;
+ const inst = r.result.instructions as string;
+ expect(inst).toContain("@hermes-vps-agent");
+ expect(inst).toContain("event_log_append");
+ expect(inst).toContain("DO NOT");
+ });
+
+ test("negotiates alternate client version", async () => {
+ const server = new MCPServer({ vault: tmp });
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "old", version: "0" } },
+ })) as any;
+ expect(r.result.protocolVersion).toBe("2024-11-05");
+ });
+
+ test("notifications/initialized is silent (returns null)", async () => {
+ const server = new MCPServer({ vault: tmp });
+ expect(
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" }),
+ ).toBeNull();
+ });
+
+ test("unknown method returns method-not-found", async () => {
+ const server = new MCPServer({ vault: tmp });
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 7,
+ method: "does/not/exist",
+ })) as any;
+ expect(r.error.code).toBe(-32601);
+ });
+});
+
+describe("tool listing", () => {
+ test("advertises all five tools", async () => {
+ const server = new MCPServer({ vault: tmp });
+ await initialize(server);
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 2,
+ method: "tools/list",
+ })) as any;
+ const names = new Set(r.result.tools.map((t: { name: string }) => t.name));
+ expect(names).toEqual(
+ new Set([
+ "second_brain_status",
+ "second_brain_query",
+ "second_brain_capture",
+ "event_log_append",
+ "vault_health",
+ ]),
+ );
+ for (const t of r.result.tools) {
+ expect(t.inputSchema.type).toBe("object");
+ }
+ });
+});
+
+describe("tool calls", () => {
+ test("second_brain_status reports vault and config", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, "vault_path: /tmp/vault\napi_key: secret\n");
+ const server = new MCPServer({ vault, configPath: config });
+ await initialize(server);
+ const r = (await callTool(server, "second_brain_status"))! as any;
+ const s = r.result.structuredContent;
+ expect(s.vault_path).toBe(vault);
+ expect(s.vault_exists).toBe(true);
+ expect(s.config.api_key).toBe("[REDACTED]");
+ expect(s.config_keys).toContain("vault_path");
+ });
+
+ test("second_brain_query filters and limits", async () => {
+ const vault = createSandboxVault(tmp);
+ const server = new MCPServer({ vault });
+ await initialize(server);
+ const r = (await callTool(server, "second_brain_query", { pattern: "Sandbox", limit: 5 })) as any;
+ const s = r.result.structuredContent;
+ expect(s.limit).toBe(5);
+ expect(s.total_pages).toBeGreaterThanOrEqual(1);
+ expect(s.pages.some((p: { title: string }) => p.title.includes("Sandbox"))).toBe(true);
+ });
+
+ test("second_brain_capture writes note with frontmatter", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const server = new MCPServer({ vault });
+ await initialize(server);
+ const r = (await callTool(server, "second_brain_capture", {
+ title: "Hello World",
+ content: "# Body\n\ntext",
+ tags: ["draft", "demo"],
+ })) as any;
+ const s = r.result.structuredContent;
+ const note = join(vault, "AI Wiki", "notes", "hello-world.md");
+ const text = readFileSync(note, "utf8");
+ expect(text).toContain("title: Hello World");
+ expect(text).toContain("tags: [draft, demo]");
+ expect(text).toContain("# Body");
+ expect(s.slug).toBe("hello-world");
+ });
+
+ test("second_brain_capture rejects existing note without overwrite", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const server = new MCPServer({ vault });
+ await initialize(server);
+ const args = { title: "Same Title", content: "first" };
+ const first = (await callTool(server, "second_brain_capture", args)) as any;
+ expect(first.result.isError).toBe(false);
+ const second = (await callTool(server, "second_brain_capture", args, 100)) as any;
+ expect(second.result.isError).toBe(true);
+ expect(second.result.content[0].text).toContain("already exists");
+ });
+
+ test("second_brain_capture rejects empty title", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const server = new MCPServer({ vault });
+ await initialize(server);
+ const r = (await callTool(server, "second_brain_capture", {
+ title: " ",
+ content: "body",
+ })) as any;
+ expect(r.error.code).toBe(-32602);
+ });
+
+ test("event_log_append writes daily note", async () => {
+ const vault = tmp;
+ const server = new MCPServer({ vault });
+ await initialize(server);
+ const r = (await callTool(server, "event_log_append", {
+ message: "via mcp",
+ agent: "mcp-test",
+ date: "2026.05.06",
+ time: "11:42",
+ })) as any;
+ expect(r.result.isError).toBe(false);
+ const s = r.result.structuredContent;
+ expect(s.agent).toBe("mcp-test");
+ const daily = join(vault, "Daily", "2026.05.06.md");
+ expect(readFileSync(daily, "utf8")).toContain("- 11:42 β€” @mcp-test β€” via mcp");
+ });
+
+ test("event_log_append strips leading @ in agent", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const server = new MCPServer({ vault });
+ await initialize(server);
+ const r = (await callTool(server, "event_log_append", {
+ message: "with-at-prefix",
+ agent: "@hermes-vps-agent",
+ date: "2026.05.06",
+ time: "11:55",
+ })) as any;
+ expect(r.result.isError).toBe(false);
+ const s = r.result.structuredContent;
+ expect(s.agent).toBe("hermes-vps-agent");
+ const daily = join(vault, "Daily", "2026.05.06.md");
+ const text = readFileSync(daily, "utf8");
+ expect(text).toContain("- 11:55 β€” @hermes-vps-agent β€” with-at-prefix");
+ expect(text).not.toContain("@@");
+ });
+
+ test("placeholder agent values fall back to default", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, "agent_name: hermes-vps-agent\n");
+ const server = new MCPServer({ vault, configPath: config });
+ await initialize(server);
+ const cases = [
+ "agent",
+ "@agent",
+ "AGENT",
+ " @agent ",
+ "assistant",
+ "@assistant",
+ "Assistant",
+ "claude",
+ "claude-code",
+ "codex",
+ "Codex",
+ "@codex",
+ "codex-cli",
+ "codex-exec",
+ "GPT",
+ "gpt-5",
+ "ai",
+ "Bot",
+ "model",
+ "hermes",
+ "openclaw",
+ ];
+ for (const trash of cases) {
+ const r = (await callTool(server, "event_log_append", {
+ message: `trash:${trash}`,
+ agent: trash,
+ date: "2026.05.06",
+ time: "12:30",
+ })) as any;
+ expect(r.result.isError).toBe(false);
+ expect(r.result.structuredContent.agent).toBe("hermes-vps-agent");
+ }
+ });
+
+ test("empty optional strings treated as missing", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const server = new MCPServer({ vault });
+ await initialize(server);
+ const r = (await callTool(server, "event_log_append", {
+ message: "with-empty-optionals",
+ agent: "",
+ date: "",
+ time: "",
+ })) as any;
+ expect(r.result.isError).toBe(false);
+ const s = r.result.structuredContent;
+ expect(s.date).toBeNull();
+ expect(s.time).toBeNull();
+ });
+
+ test("uses configured timezone for daily file", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, 'agent_name: "hermes-vps-agent"\ntimezone: "Europe/Belgrade"\n');
+ const server = new MCPServer({ vault, configPath: config });
+ await initialize(server);
+
+ // Capture local-tz wallclock BEFORE the call to avoid midnight rollover.
+ const fmt = new Intl.DateTimeFormat("en-CA", {
+ timeZone: "Europe/Belgrade",
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ });
+ const expectedDate = fmt.format(new Date()).replace(/-/g, ".");
+
+ const r = (await callTool(server, "event_log_append", { message: "tz-test" })) as any;
+ expect(r.result.isError).toBe(false);
+ const expectedFile = join(vault, "Daily", `${expectedDate}.md`);
+ const text = readFileSync(expectedFile, "utf8");
+ expect(text).toContain("β€” @hermes-vps-agent β€” tz-test");
+ });
+
+ test("VAULT_TIMEZONE env wins over config", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, 'timezone: "UTC"\n');
+ process.env["VAULT_TIMEZONE"] = "Europe/Belgrade";
+ const server = new MCPServer({ vault, configPath: config });
+ await initialize(server);
+ const fmt = new Intl.DateTimeFormat("en-CA", {
+ timeZone: "Europe/Belgrade",
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ });
+ const expectedDate = fmt.format(new Date()).replace(/-/g, ".");
+ const r = (await callTool(server, "event_log_append", {
+ message: "env-tz-test",
+ agent: "tester",
+ })) as any;
+ expect(r.result.isError).toBe(false);
+ const expectedFile = join(vault, "Daily", `${expectedDate}.md`);
+ expect(() => readFileSync(expectedFile, "utf8")).not.toThrow();
+ });
+
+ test("invalid config timezone falls back silently", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, 'timezone: "Not/A/Real/Zone"\n');
+ const server = new MCPServer({ vault, configPath: config });
+ await initialize(server);
+ const r = (await callTool(server, "event_log_append", {
+ message: "fallback",
+ agent: "tester",
+ })) as any;
+ expect(r.result.isError).toBe(false);
+ });
+
+ test("uses agent_name from config when no env or arg", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, "agent_name: openclaw-main\n");
+ const server = new MCPServer({ vault, configPath: config });
+ await initialize(server);
+ const r = (await callTool(server, "event_log_append", {
+ message: "from-config-default",
+ date: "2026.05.06",
+ time: "12:00",
+ })) as any;
+ expect(r.result.isError).toBe(false);
+ expect(r.result.structuredContent.agent).toBe("openclaw-main");
+ const daily = join(vault, "Daily", "2026.05.06.md");
+ expect(readFileSync(daily, "utf8")).toContain("- 12:00 β€” @openclaw-main β€” from-config-default");
+ });
+
+ test("event_log_append rejects invalid time", async () => {
+ const server = new MCPServer({ vault: tmp });
+ await initialize(server);
+ const r = (await callTool(server, "event_log_append", {
+ message: "x",
+ time: "99:99",
+ })) as any;
+ expect(r.result.isError).toBe(true);
+ expect(r.result.content[0].text).toContain("HH:MM");
+ });
+
+ test("event_log_append rejects invalid date paths", async () => {
+ const server = new MCPServer({ vault: tmp });
+ await initialize(server);
+ const r = (await callTool(server, "event_log_append", {
+ message: "x",
+ date: "../AI Wiki/notes/pwn",
+ })) as any;
+ expect(r.result.isError).toBe(true);
+ expect(r.result.content[0].text).toContain("YYYY.MM.DD");
+ });
+
+ test("vault_health runs doctor", async () => {
+ const vault = createSandboxVault(tmp);
+ const repo = createPluginRepo(tmp, true);
+ const server = new MCPServer({ vault, repoRoot: repo });
+ await initialize(server);
+ const r = (await callTool(server, "vault_health", {})) as any;
+ const s = r.result.structuredContent;
+ expect(s.ok).toBe(true);
+ const names = new Set(s.checks.map((c: { name: string }) => c.name));
+ expect(names.has("vault_writeable")).toBe(true);
+ expect(names.has("claude_manifest")).toBe(true);
+ expect(names.has("hermes_manifest")).toBe(true);
+ });
+
+ test("unknown tool returns method-not-found", async () => {
+ const server = new MCPServer({ vault: tmp });
+ await initialize(server);
+ const r = (await callTool(server, "not_a_tool")) as any;
+ expect(r.error.code).toBe(-32601);
+ });
+});
+
+describe("stdio loop", () => {
+ test("processes initialize and tools/list", async () => {
+ const server = new MCPServer({ vault: tmp });
+ const payload =
+ [
+ JSON.stringify({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "t", version: "0" },
+ },
+ }),
+ JSON.stringify({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" }),
+ JSON.stringify({ jsonrpc: JSONRPC_VERSION, id: 2, method: "tools/list" }),
+ ].join("\n") + "\n";
+ const lines = await serveStdioFromString(server, payload);
+ expect(lines.length).toBe(2);
+ const init = JSON.parse(lines[0]!);
+ const list = JSON.parse(lines[1]!);
+ expect(init.id).toBe(1);
+ expect(list.id).toBe(2);
+ expect(list.result.tools.length).toBe(5);
+ });
+
+ test("returns parse error for invalid JSON", async () => {
+ const server = new MCPServer({ vault: tmp });
+ const lines = await serveStdioFromString(server, "{not json}\n");
+ const r = JSON.parse(lines[0]!);
+ expect(r.error.code).toBe(-32700);
+ });
+
+ test("returns invalid request for batch", async () => {
+ const server = new MCPServer({ vault: tmp });
+ const batch = JSON.stringify([
+ { jsonrpc: JSONRPC_VERSION, id: 1, method: "ping" },
+ { jsonrpc: JSONRPC_VERSION, id: 2, method: "ping" },
+ ]);
+ const lines = await serveStdioFromString(server, batch + "\n");
+ const r = JSON.parse(lines[0]!);
+ expect(r.error.code).toBe(-32600);
+ expect(r.error.message.toLowerCase()).toContain("batch");
+ });
+});
diff --git a/tests/openclaw/bundle.test.ts b/tests/openclaw/bundle.test.ts
new file mode 100644
index 00000000..e9b036d6
--- /dev/null
+++ b/tests/openclaw/bundle.test.ts
@@ -0,0 +1,60 @@
+/**
+ * Smoke test for the built OpenClaw bundle (`openclaw/index.js`).
+ *
+ * The bundle is the actual artifact OpenClaw loads via `package.json`'s
+ * `openclaw.extensions`. We can't import it directly because it imports the
+ * SDK as an external β€” but we can verify file structure, that it bundled
+ * the core logic (no leftover dynamic Python references), and that the
+ * `package.json` extension entry actually points at it.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { join, dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+const BUNDLE = join(ROOT, "openclaw", "index.js");
+
+describe("openclaw bundle", () => {
+ test("file exists and is non-empty", () => {
+ expect(existsSync(BUNDLE)).toBe(true);
+ const size = statSync(BUNDLE).size;
+ expect(size).toBeGreaterThan(1000);
+ });
+
+ test("declares the SDK import as external", () => {
+ const text = readFileSync(BUNDLE, "utf8");
+ expect(text).toContain('from "openclaw/plugin-sdk/plugin-entry"');
+ });
+
+ test("bundles all five tool registrations", () => {
+ const text = readFileSync(BUNDLE, "utf8");
+ for (const tool of [
+ "second_brain_status",
+ "second_brain_query",
+ "second_brain_capture",
+ "event_log_append",
+ "vault_health",
+ ]) {
+ expect(text).toContain(tool);
+ }
+ });
+
+ test("does NOT contain Python references", () => {
+ const text = readFileSync(BUNDLE, "utf8");
+ expect(text).not.toContain("python3");
+ expect(text).not.toContain("from open_second_brain");
+ });
+
+ test("package.json points to ./openclaw/index.js", () => {
+ const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
+ expect(pkg.openclaw.extensions).toEqual(["./openclaw/index.js"]);
+ });
+
+ test("bundles before_prompt_build hook (per-turn identity reminder)", () => {
+ const text = readFileSync(BUNDLE, "utf8");
+ expect(text).toContain("before_prompt_build");
+ expect(text).toContain("prependContext");
+ });
+});
diff --git a/tests/__init__.py b/tests/python/__init__.py
similarity index 100%
rename from tests/__init__.py
rename to tests/python/__init__.py
diff --git a/tests/python/test_hermes_plugin.py b/tests/python/test_hermes_plugin.py
new file mode 100644
index 00000000..6b9e3098
--- /dev/null
+++ b/tests/python/test_hermes_plugin.py
@@ -0,0 +1,192 @@
+"""Tests for the slim Hermes Python shim.
+
+The shim only handles the per-turn ``pre_llm_call`` injection and a small
+data-only health report; everything else lives in the TypeScript core
+exposed through the MCP server. These tests pin the contract Hermes
+relies on.
+"""
+
+import importlib.util
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+# Ensure ``plugins.hermes`` is importable regardless of which directory the
+# test runner is invoked from. Pytest with rootdir at the repo root works
+# out of the box; running ``python -m unittest tests.python.test_hermes_plugin``
+# from the repo root also works because ``plugins/hermes/__init__.py`` is on
+# the path. The legacy invocation ``python -m unittest discover -s tests``
+# would not find ``plugins`` without the explicit insert; the shim's
+# import is small enough that we keep it self-contained.
+ROOT = Path(__file__).resolve().parents[2]
+if str(ROOT) not in sys.path:
+ sys.path.insert(0, str(ROOT))
+
+from plugins.hermes import check_health, health, on_pre_llm_call, register # noqa: E402
+
+PLUGIN_NAME = "open-second-brain"
+
+
+class HealthReportTests(unittest.TestCase):
+ def test_health_reports_repo_artifacts(self):
+ report = health(ROOT)
+ self.assertEqual(report["name"], PLUGIN_NAME)
+ self.assertIn("o2b_script", report["checks"])
+ self.assertIn("openclaw_bundle", report["checks"])
+ self.assertIn("package_json", report["checks"])
+
+ def test_check_health_alias_returns_same_shape(self):
+ self.assertEqual(check_health(ROOT)["name"], PLUGIN_NAME)
+
+
+class RootPluginEntrypointTests(unittest.TestCase):
+ """Hermes installs Git plugins by cloning the repo and loading the
+ repository root as the plugin directory. The root ``__init__.py`` is
+ therefore the entry the gateway sees first; it must re-export the
+ same callable names this shim exposes.
+ """
+
+ def test_root_init_exposes_check_health(self):
+ spec = importlib.util.spec_from_file_location(
+ "open_second_brain_plugin_test",
+ ROOT / "__init__.py",
+ submodule_search_locations=[str(ROOT)],
+ )
+ self.assertIsNotNone(spec)
+ self.assertIsNotNone(spec.loader)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ try:
+ spec.loader.exec_module(module)
+ self.assertEqual(module.check_health(ROOT)["name"], PLUGIN_NAME)
+ finally:
+ sys.modules.pop(spec.name, None)
+
+
+class RegisterTests(unittest.TestCase):
+ def test_attaches_via_register_health_check(self):
+ calls: list[tuple[str, object]] = []
+
+ class Context:
+ def register_health_check(self, name, callback):
+ calls.append((name, callback))
+
+ register(Context())
+ self.assertEqual(calls[0][0], PLUGIN_NAME)
+ self.assertTrue(calls[0][1](ROOT)["name"] == PLUGIN_NAME)
+
+ def test_attaches_via_health_checks_dict(self):
+ class Context:
+ def __init__(self):
+ self.health_checks: dict[str, object] = {}
+
+ ctx = Context()
+ register(ctx)
+ self.assertIn(PLUGIN_NAME, ctx.health_checks)
+
+ def test_register_hook_called_for_pre_llm_call(self):
+ registered: list[tuple[str, object]] = []
+
+ class Context:
+ def register_hook(self, name, callback):
+ registered.append((name, callback))
+
+ register(Context())
+ self.assertEqual(len(registered), 1)
+ name, callback = registered[0]
+ self.assertEqual(name, "pre_llm_call")
+ self.assertIs(callback, on_pre_llm_call)
+
+
+class PreLlmCallTests(unittest.TestCase):
+ """The hook fires every turn and must:
+
+ - return ``{"context": "..."}`` when identity is configured
+ - return ``None`` (no injection) when identity is unresolved
+ - never raise
+ """
+
+ def setUp(self):
+ self._prev_env = os.environ.pop("VAULT_AGENT_NAME", None)
+ self._prev_cfg = os.environ.pop("OPEN_SECOND_BRAIN_CONFIG", None)
+
+ def tearDown(self):
+ os.environ.pop("VAULT_AGENT_NAME", None)
+ os.environ.pop("OPEN_SECOND_BRAIN_CONFIG", None)
+ if self._prev_env is not None:
+ os.environ["VAULT_AGENT_NAME"] = self._prev_env
+ if self._prev_cfg is not None:
+ os.environ["OPEN_SECOND_BRAIN_CONFIG"] = self._prev_cfg
+
+ def test_returns_context_when_env_identity_set(self):
+ os.environ["VAULT_AGENT_NAME"] = "hermes-vps-agent"
+ result = on_pre_llm_call(
+ session_id="test",
+ user_message="hello",
+ conversation_history=[],
+ is_first_turn=True,
+ model="combo",
+ platform="cli",
+ sender_id="",
+ )
+ self.assertIsInstance(result, dict)
+ self.assertIn("context", result)
+ ctx = result["context"]
+ self.assertIn("@hermes-vps-agent", ctx)
+ self.assertIn("event_log_append", ctx)
+
+ def test_returns_context_from_persisted_config(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ cfg = Path(tmp) / "config.yaml"
+ cfg.write_text('agent_name: "openclaw-main"\n', encoding="utf-8")
+ os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg)
+ result = on_pre_llm_call()
+ self.assertIsInstance(result, dict)
+ self.assertIn("@openclaw-main", result["context"])
+
+ def test_returns_context_with_camelcase_config_key(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ cfg = Path(tmp) / "config.yaml"
+ cfg.write_text('agentName: "codex-vps-agent"\n', encoding="utf-8")
+ os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg)
+ result = on_pre_llm_call()
+ self.assertIsInstance(result, dict)
+ self.assertIn("@codex-vps-agent", result["context"])
+
+ def test_returns_none_when_identity_unresolved(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(Path(tmp) / "missing.yaml")
+ result = on_pre_llm_call()
+ self.assertIsNone(result)
+
+
+class TemplateSourceOfTruthTests(unittest.TestCase):
+ """The reminder text lives in `templates/identity-reminder.txt` so the
+ Python shim and the TypeScript core do not drift apart. These tests
+ pin the file's location and shape; both runtimes must keep loading it.
+ """
+
+ def test_template_file_exists_at_canonical_path(self):
+ path = ROOT / "templates" / "identity-reminder.txt"
+ self.assertTrue(path.is_file(), f"missing canonical reminder template: {path}")
+
+ def test_template_uses_two_or_more_agent_placeholders(self):
+ path = ROOT / "templates" / "identity-reminder.txt"
+ text = path.read_text(encoding="utf-8")
+ self.assertGreaterEqual(text.count("{agent}"), 2)
+
+ def test_pre_llm_call_substitutes_every_placeholder(self):
+ os.environ["VAULT_AGENT_NAME"] = "parity-agent"
+ try:
+ result = on_pre_llm_call()
+ finally:
+ os.environ.pop("VAULT_AGENT_NAME", None)
+ self.assertIsNotNone(result)
+ self.assertIn("@parity-agent", result["context"])
+ self.assertNotIn("{agent}", result["context"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_claude_marketplace.py b/tests/test_claude_marketplace.py
deleted file mode 100644
index b58d5402..00000000
--- a/tests/test_claude_marketplace.py
+++ /dev/null
@@ -1,130 +0,0 @@
-"""Tests for the Claude Code single-plugin marketplace setup.
-
-Claude Code 2.x installs plugins via ``claude plugin marketplace add``
-followed by ``claude plugin install <plugin>@<marketplace>``. The
-marketplace step expects ``.claude-plugin/marketplace.json``; the install
-step then reads ``.claude-plugin/plugin.json`` for the plugin manifest.
-
-When Claude installs the plugin, it also auto-registers any MCP servers
-declared in ``.mcp.json`` at the plugin root β€” no separate ``claude mcp
-add`` is needed when the file is present.
-
-These tests pin the contract of all three artifacts so that
-install.md branch D continues to describe a working flow.
-"""
-
-import json
-import re
-import unittest
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-class ClaudeMarketplaceManifestTests(unittest.TestCase):
- @classmethod
- def setUpClass(cls):
- cls.path = ROOT / ".claude-plugin" / "marketplace.json"
- cls.manifest = json.loads(cls.path.read_text(encoding="utf-8"))
-
- def test_file_present(self):
- self.assertTrue(self.path.is_file(), f"missing: {self.path}")
-
- def test_top_level_required_fields(self):
- self.assertEqual(self.manifest["name"], "open-second-brain")
- owner = self.manifest["owner"]
- self.assertIsInstance(owner, dict)
- self.assertIsInstance(owner.get("name"), str)
- self.assertIsInstance(self.manifest.get("plugins"), list)
- self.assertGreaterEqual(len(self.manifest["plugins"]), 1)
-
- def test_self_marketplace_plugin_entry(self):
- plugin = self.manifest["plugins"][0]
- # Same name as the marketplace β€” this is the documented
- # "self-marketplace" pattern for single-plugin repos.
- self.assertEqual(plugin["name"], "open-second-brain")
- # ``./`` (or ``.``) means "this repository is the plugin"; it
- # resolves to the directory containing ``marketplace.json``'s repo
- # root, where ``.claude-plugin/plugin.json`` already lives.
- self.assertIn(plugin["source"].rstrip("/"), {"", "."})
- self.assertIn("description", plugin)
-
-
-class ClaudePluginManifestTests(unittest.TestCase):
- """The Claude 2.x manifest schema requires ``author`` to be an
- object (``{"name": ...}``); the legacy string form was rejected by
- the validator with ``author: Invalid input``. Embedded slash command
- arrays are likewise no longer accepted; they must be authored as
- Markdown files under ``commands/`` at the plugin root.
- """
-
- @classmethod
- def setUpClass(cls):
- cls.path = ROOT / ".claude-plugin" / "plugin.json"
- cls.manifest = json.loads(cls.path.read_text(encoding="utf-8"))
-
- def test_required_fields(self):
- self.assertEqual(self.manifest["name"], "open-second-brain")
- self.assertIsInstance(self.manifest["version"], str)
- self.assertIsInstance(self.manifest["description"], str)
-
- def test_author_is_object_form(self):
- author = self.manifest.get("author")
- if author is not None:
- self.assertIsInstance(
- author, dict,
- "author must be object form per Claude 2.x schema",
- )
- self.assertIsInstance(author.get("name"), str)
-
- def test_legacy_commands_array_absent(self):
- # The historical ``commands: [{name, command, args, ...}]`` array
- # is rejected by current Claude as ``Invalid input``. If it
- # creeps back in, install will start failing again on every
- # 2.x install.
- self.assertNotIn(
- "commands", self.manifest,
- "embedded 'commands' array is deprecated; author them as "
- "Markdown files under commands/ at plugin root instead",
- )
-
-
-class ClaudeMcpJsonTests(unittest.TestCase):
- """``.mcp.json`` at the plugin root is auto-registered by Claude
- when the plugin is installed. The ``${CLAUDE_PLUGIN_ROOT}`` variable
- is expanded by Claude to the cached plugin path, so no absolute
- path lives in the file.
- """
-
- @classmethod
- def setUpClass(cls):
- cls.path = ROOT / ".mcp.json"
- cls.data = json.loads(cls.path.read_text(encoding="utf-8"))
-
- def test_file_present(self):
- self.assertTrue(self.path.is_file(), f"missing: {self.path}")
-
- def test_declares_open_second_brain_server(self):
- servers = self.data["mcpServers"]
- self.assertIn("open-second-brain", servers)
- entry = servers["open-second-brain"]
- self.assertIn("${CLAUDE_PLUGIN_ROOT}", entry["command"])
- self.assertIn("scripts/o2b", entry["command"])
- self.assertEqual(entry["args"], ["mcp"])
-
- def test_no_vault_or_env_baked_in(self):
- # The plugin's MCP entry must be portable β€” agent name, vault,
- # and timezone all come from the on-disk plugin config (set by
- # ``o2b init``), not from ``.mcp.json``. If somebody puts those
- # back here, the auto-register flow becomes machine-specific
- # and the install.md instructions break for new users.
- entry = self.data["mcpServers"]["open-second-brain"]
- self.assertNotIn("--vault", entry.get("args", []))
- env = entry.get("env", {})
- self.assertNotIn("VAULT_AGENT_NAME", env)
- self.assertNotIn("VAULT_TIMEZONE", env)
- self.assertNotIn("VAULT_DIR", env)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_cli.py b/tests/test_cli.py
deleted file mode 100644
index 84f5d98a..00000000
--- a/tests/test_cli.py
+++ /dev/null
@@ -1,472 +0,0 @@
-import json
-import os
-import subprocess
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-ENV = {**os.environ, "PYTHONPATH": str(ROOT / "src")}
-
-from tests.fixtures import create_plugin_repo, create_sandbox_vault
-
-
-def run_module(module, *args, env=None):
- return subprocess.run(
- [sys.executable, "-m", module, *args],
- cwd=ROOT,
- env={**ENV, **(env or {})},
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=30,
- )
-
-
-def run_cli(*args, env=None):
- # Isolate ``OPEN_SECOND_BRAIN_CONFIG`` per call by default. ``o2b init``
- # always persists ``vault``/``agent_name``/``timezone`` to the config
- # file at this path, and without isolation init-tests would silently
- # write to the host's real ``~/.config/open-second-brain/config.yaml``
- # β€” clobbering whatever the developer has set up locally. Tests that
- # specifically want to verify default-config behavior pass their own
- # ``OPEN_SECOND_BRAIN_CONFIG`` in ``env`` to override this guard.
- actual_env = dict(env or {})
- cleanup_dir: Path | None = None
- if "OPEN_SECOND_BRAIN_CONFIG" not in actual_env:
- cleanup_dir = Path(tempfile.mkdtemp(prefix="o2b-test-"))
- actual_env["OPEN_SECOND_BRAIN_CONFIG"] = str(cleanup_dir / "isolated-config.yaml")
- try:
- return run_module("open_second_brain.cli", *args, env=actual_env)
- finally:
- if cleanup_dir is not None:
- import shutil
- shutil.rmtree(cleanup_dir, ignore_errors=True)
-
-
-class CliTests(unittest.TestCase):
- def test_status_reports_missing_config(self):
- with tempfile.TemporaryDirectory() as tmp:
- config = Path(tmp) / "missing.yaml"
- result = run_cli("status", env={"OPEN_SECOND_BRAIN_CONFIG": str(config)})
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("config_exists: false", result.stdout)
- self.assertIn(str(config), result.stdout)
-
- def test_init_creates_vault_structure(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- result = run_cli("init", "--vault", str(vault), "--name", "Test")
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("initialized vault:", result.stdout)
- self.assertTrue((vault / "AI Wiki" / "_OPEN_SECOND_BRAIN.md").is_file())
- self.assertTrue((vault / "AI Wiki" / "identity" / "agents.md").is_file())
-
- def test_init_with_agent_name_writes_identity_entry(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- config = Path(tmp) / "config.yaml"
- result = run_cli(
- "init",
- "--vault",
- str(vault),
- "--name",
- "Test",
- "--agent-name",
- "openclaw-main",
- env={"OPEN_SECOND_BRAIN_CONFIG": str(config)},
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("agent name registered: openclaw-main", result.stdout)
- agents_md = (vault / "AI Wiki" / "identity" / "agents.md").read_text(
- encoding="utf-8"
- )
- self.assertIn("- openclaw-main: primary agent on this server", agents_md)
- self.assertNotIn("(add your agents here", agents_md)
-
- def test_init_with_agent_name_persists_to_plugin_config(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- config = Path(tmp) / "config.yaml"
- result = run_cli(
- "init",
- "--vault",
- str(vault),
- "--name",
- "Test",
- "--agent-name",
- "hermes-vps-agent",
- env={"OPEN_SECOND_BRAIN_CONFIG": str(config)},
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("agent name persisted to:", result.stdout)
- self.assertTrue(config.is_file())
- self.assertIn("agent_name", config.read_text(encoding="utf-8"))
- self.assertIn("hermes-vps-agent", config.read_text(encoding="utf-8"))
-
- def test_append_event_errors_when_no_vault_anywhere(self):
- # ``o2b append-event`` is a write command. Before this fix, omitting
- # both ``--vault`` and ``VAULT_DIR`` made it silently fall back to
- # the current working directory, so an agent invoking
- # ``o2b append-event "..."`` would write to ``$(pwd)/Daily/<date>.md``
- # instead of the user's actual vault β€” quiet data loss. Fail closed.
- with tempfile.TemporaryDirectory() as tmp:
- cfg = Path(tmp) / "config.yaml"
- env = {"OPEN_SECOND_BRAIN_CONFIG": str(cfg)}
- result = run_cli(
- "append-event", "msg",
- "--as", "tester",
- env=env,
- )
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("no vault configured", result.stderr.lower())
-
- def test_append_event_prints_absolute_path_on_success(self):
- # The success line was historically ``appended: Daily/<date>.md``,
- # which gave no signal when the entry had landed in the wrong
- # vault. Always print the absolute path so a misconfiguration
- # is immediately visible.
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- cfg = Path(tmp) / "config.yaml"
- result = run_cli(
- "append-event", "absolute-path-test",
- "--vault", str(vault),
- "--as", "tester",
- env={"OPEN_SECOND_BRAIN_CONFIG": str(cfg)},
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- # Output line: ``appended: <abs path to Daily/<date>.md>``.
- self.assertIn("appended: ", result.stdout)
- # The reported path must start with the vault root, not be
- # a bare ``Daily/...`` relative segment.
- output_path = result.stdout.split("appended: ", 1)[1].strip().splitlines()[0]
- self.assertTrue(
- Path(output_path).is_absolute(),
- f"reported path is not absolute: {output_path!r}",
- )
- self.assertTrue(output_path.startswith(str(vault.resolve())),
- f"path {output_path!r} not under vault {vault.resolve()}")
-
- def test_doctor_errors_when_no_vault_anywhere(self):
- with tempfile.TemporaryDirectory() as tmp:
- cfg = Path(tmp) / "config.yaml"
- result = run_cli("doctor", env={"OPEN_SECOND_BRAIN_CONFIG": str(cfg)})
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("no vault configured", result.stderr.lower())
-
- def test_index_errors_when_no_vault_anywhere(self):
- # ``o2b index`` writes to the vault (regenerates AI Wiki/index.md).
- # Same fail-closed semantics as append-event.
- with tempfile.TemporaryDirectory() as tmp:
- cfg = Path(tmp) / "config.yaml"
- result = run_cli("index", env={"OPEN_SECOND_BRAIN_CONFIG": str(cfg)})
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("no vault configured", result.stderr.lower())
-
- def test_vault_log_errors_when_no_vault_anywhere(self):
- # The ``vault-log`` CLI is the original write entry point used
- # by older skill workflows. It hit the same quiet-cwd bug β€”
- # vault-log "msg" without --vault wrote to $(pwd)/Daily/.
- # Fail closed too.
- import subprocess
- import sys
- with tempfile.TemporaryDirectory() as tmp:
- cfg = Path(tmp) / "config.yaml"
- env = {
- **os.environ,
- "OPEN_SECOND_BRAIN_CONFIG": str(cfg),
- "PYTHONPATH": str(ROOT / "src"),
- }
- env.pop("VAULT_DIR", None)
- result = subprocess.run(
- [sys.executable, "-m", "open_second_brain.vault_log",
- "test message", "--as", "tester"],
- cwd=ROOT, env=env, text=True,
- stdout=subprocess.PIPE, stderr=subprocess.PIPE,
- timeout=10,
- )
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("no vault configured", result.stderr.lower())
-
- def test_vault_log_prints_absolute_path_on_success(self):
- import subprocess
- import sys
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- cfg = Path(tmp) / "config.yaml"
- env = {
- **os.environ,
- "OPEN_SECOND_BRAIN_CONFIG": str(cfg),
- "PYTHONPATH": str(ROOT / "src"),
- "VAULT_DIR": str(vault),
- }
- result = subprocess.run(
- [sys.executable, "-m", "open_second_brain.vault_log",
- "absolute-path-test", "--as", "tester"],
- cwd=ROOT, env=env, text=True,
- stdout=subprocess.PIPE, stderr=subprocess.PIPE,
- timeout=10,
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("appended: ", result.stdout)
- output_path = result.stdout.split("appended: ", 1)[1].strip().splitlines()[0]
- self.assertTrue(Path(output_path).is_absolute())
- self.assertTrue(output_path.startswith(str(vault.resolve())))
-
- def test_mcp_command_errors_when_no_vault_anywhere(self):
- # When ``--vault`` is omitted, ``VAULT_DIR`` is unset, and the
- # plugin config has no ``vault`` field, ``o2b mcp`` must fail
- # fast with a clear hint. This is the safety net for users
- # who installed the plugin but forgot to run ``o2b init``.
- import subprocess
- import sys
- with tempfile.TemporaryDirectory() as tmp:
- cfg = Path(tmp) / "config.yaml"
- env = {
- **os.environ,
- "OPEN_SECOND_BRAIN_CONFIG": str(cfg),
- "PYTHONPATH": str(ROOT / "src"),
- }
- env.pop("VAULT_DIR", None)
- result = subprocess.run(
- [sys.executable, "-m", "open_second_brain.cli", "mcp"],
- cwd=ROOT, env=env, text=True,
- stdout=subprocess.PIPE, stderr=subprocess.PIPE,
- timeout=10,
- )
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("no vault configured", result.stderr.lower())
- self.assertIn("o2b init", result.stderr)
-
- def test_init_persists_vault_path_to_plugin_config(self):
- # The vault path is the third value plugin config caches alongside
- # ``agent_name`` and ``timezone`` after ``o2b init``. Without it,
- # ``o2b mcp`` (called with no args by Claude's ``.mcp.json``
- # auto-register, or by Hermes/Codex MCP entries that omit
- # ``--vault``) cannot find a vault and exits with an error.
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- config = Path(tmp) / "config.yaml"
- result = run_cli(
- "init",
- "--vault",
- str(vault),
- "--name",
- "Test",
- env={"OPEN_SECOND_BRAIN_CONFIG": str(config)},
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("vault path persisted to:", result.stdout)
- text = config.read_text(encoding="utf-8")
- self.assertIn("vault", text)
- # Path is persisted resolved (absolute) so MCP subprocesses
- # don't depend on the cwd they happen to be spawned in.
- self.assertIn(str(vault.resolve()), text)
-
- def test_init_with_timezone_persists_to_plugin_config(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- config = Path(tmp) / "config.yaml"
- result = run_cli(
- "init",
- "--vault",
- str(vault),
- "--name",
- "Test",
- "--agent-name",
- "hermes-vps-agent",
- "--timezone",
- "Europe/Belgrade",
- env={"OPEN_SECOND_BRAIN_CONFIG": str(config)},
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("timezone registered: Europe/Belgrade", result.stdout)
- self.assertIn("timezone persisted to:", result.stdout)
- text = config.read_text(encoding="utf-8")
- self.assertIn("agent_name", text)
- self.assertIn("hermes-vps-agent", text)
- self.assertIn("timezone", text)
- self.assertIn("Europe/Belgrade", text)
-
- def test_init_rejects_invalid_timezone(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- config = Path(tmp) / "config.yaml"
- result = run_cli(
- "init",
- "--vault",
- str(vault),
- "--name",
- "Test",
- "--timezone",
- "NotARealTimezone",
- env={"OPEN_SECOND_BRAIN_CONFIG": str(config)},
- )
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("not a valid IANA name", result.stderr)
- # Vault must NOT be created when timezone validation fails up front
- # β€” we don't want a half-initialized state from a typo.
- self.assertFalse(vault.exists() and any(vault.iterdir()))
-
- def test_init_persist_survives_re_init_on_existing_vault(self):
- # Re-running `o2b init --agent-name X` on an already-bootstrapped vault
- # must still update the plugin config, not just exit early.
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- config = Path(tmp) / "config.yaml"
- run_cli("init", "--vault", str(vault), "--name", "Test")
- # vault is now fully initialised; second invocation should still persist
- result = run_cli(
- "init",
- "--vault",
- str(vault),
- "--name",
- "Test",
- "--agent-name",
- "hermes-vps-agent",
- env={"OPEN_SECOND_BRAIN_CONFIG": str(config)},
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("agent name persisted to:", result.stdout)
- self.assertIn("hermes-vps-agent", config.read_text(encoding="utf-8"))
-
- def test_init_already_initialized_does_not_overwrite(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- run_cli("init", "--vault", str(vault), "--name", "First")
- index = vault / "AI Wiki" / "index.md"
- index.write_text("custom", encoding="utf-8")
- result = run_cli("init", "--vault", str(vault), "--name", "Second")
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("already initialized", result.stdout)
- self.assertEqual(index.read_text(encoding="utf-8"), "custom")
-
- def test_init_force_overwrites(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- run_cli("init", "--vault", str(vault), "--name", "First")
- index = vault / "AI Wiki" / "index.md"
- index.write_text("old", encoding="utf-8")
- result = run_cli("init", "--vault", str(vault), "--name", "Second", "--force")
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("initialized vault:", result.stdout)
- self.assertNotEqual(index.read_text(encoding="utf-8"), "old")
-
- def test_doctor_checks_valid_vault(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- result = run_cli(
- "doctor",
- "--vault",
- str(vault),
- env={
- "OPEN_SECOND_BRAIN_CONFIG": "",
- "XDG_CONFIG_HOME": "",
- "VAULT_DIR": "",
- },
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("[OK]", result.stdout)
- self.assertIn("vault", result.stdout.lower())
-
- def test_doctor_reports_missing_vault(self):
- result = run_cli("doctor", "--vault", "/nonexistent/path")
- self.assertEqual(result.returncode, 1, result.stderr)
- self.assertIn("[FAIL]", result.stdout)
-
- def test_doctor_with_repo_checks_manifests(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = create_sandbox_vault(Path(tmp))
- repo = create_plugin_repo(Path(tmp), valid=True)
- result = run_cli("doctor", "--vault", str(vault), "--repo", str(repo))
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("claude_manifest", result.stdout)
- self.assertIn("codex_manifest", result.stdout)
- self.assertIn("hermes_manifest", result.stdout)
-
- def test_doctor_with_repo_rejects_invalid_manifest_schema(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = create_sandbox_vault(Path(tmp))
- repo = create_plugin_repo(Path(tmp), valid=False)
- result = run_cli("doctor", "--vault", str(vault), "--repo", str(repo))
- self.assertEqual(result.returncode, 1, result.stderr)
- self.assertIn("[FAIL] claude_manifest", result.stdout)
- self.assertIn("[FAIL] codex_manifest", result.stdout)
-
- def test_append_event_writes_daily_note(self):
- with tempfile.TemporaryDirectory() as tmp:
- result = run_cli(
- "append-event",
- "created CLI",
- "--vault",
- tmp,
- "--as",
- "test-agent",
- "--date",
- "2026.05.06",
- "--time",
- "10:15",
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- daily = Path(tmp) / "Daily" / "2026.05.06.md"
- self.assertIn("- 10:15 β€” @test-agent β€” created CLI", daily.read_text(encoding="utf-8"))
-
- def test_export_config_writes_redacted_json(self):
- with tempfile.TemporaryDirectory() as tmp:
- config = Path(tmp) / "config.yaml"
- config.write_text("api_key: abc\nvault_path: /tmp/vault\n", encoding="utf-8")
- output = Path(tmp) / "snapshot.json"
- result = run_cli(
- "export-config",
- "--config",
- str(config),
- "--output",
- str(output),
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- data = json.loads(output.read_text(encoding="utf-8"))
- self.assertEqual(data["config"]["api_key"], "[REDACTED]")
- self.assertEqual(data["config"]["vault_path"], "/tmp/vault")
-
- def test_vault_log_compatibility_module(self):
- with tempfile.TemporaryDirectory() as tmp:
- result = run_module(
- "open_second_brain.vault_log",
- "--as",
- "compat-agent",
- "--vault",
- tmp,
- "--date",
- "2026.05.06",
- "--time",
- "10:30",
- "compat entry",
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- daily = Path(tmp) / "Daily" / "2026.05.06.md"
- self.assertIn("- 10:30 β€” @compat-agent β€” compat entry", daily.read_text(encoding="utf-8"))
-
- def test_index_generates_wikilink_index(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- (vault / "AI Wiki").mkdir(parents=True)
- (vault / "Concept.md").write_text(
- "---\ntitle: Concept\n---\n\nBody.", encoding="utf-8"
- )
- (vault / "Other.md").write_text("No frontmatter.", encoding="utf-8")
- result = run_cli("index", "--vault", str(vault))
- self.assertEqual(result.returncode, 0, result.stderr)
- index_path = vault / "AI Wiki" / "index.md"
- self.assertTrue(index_path.is_file())
- content = index_path.read_text(encoding="utf-8")
- self.assertIn("[[Concept]]", content)
- self.assertIn("[[Other]]", content)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_codex_marketplace.py b/tests/test_codex_marketplace.py
deleted file mode 100644
index 69cde05b..00000000
--- a/tests/test_codex_marketplace.py
+++ /dev/null
@@ -1,84 +0,0 @@
-"""Tests for the Codex single-plugin marketplace manifest.
-
-Codex 0.129+ installs plugins via ``codex plugin marketplace add``, which
-expects a marketplace catalog at ``.agents/plugins/marketplace.json``. A
-single-plugin repo like Open Second Brain still has to ship one β€” without
-it, the install command fails with ``marketplace root does not contain a
-supported manifest``.
-
-These tests pin the contract of our shipped manifest: structure, required
-fields, and that the relative ``source.path`` resolves to a directory
-containing the Codex plugin manifest (``.codex-plugin/plugin.json``).
-"""
-
-import json
-import unittest
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-class CodexMarketplaceManifestTests(unittest.TestCase):
- @classmethod
- def setUpClass(cls):
- cls.manifest_path = ROOT / ".agents" / "plugins" / "marketplace.json"
- cls.manifest = json.loads(cls.manifest_path.read_text(encoding="utf-8"))
-
- def test_manifest_file_present(self):
- self.assertTrue(
- self.manifest_path.is_file(),
- f"marketplace manifest missing at {self.manifest_path}",
- )
-
- def test_top_level_required_fields(self):
- # Per the empirically-verified Codex schema (matched against the
- # bundled ``openai-curated`` marketplace), top-level requires
- # ``name``, ``interface.displayName``, and a list of ``plugins``.
- self.assertIsInstance(self.manifest.get("name"), str)
- self.assertEqual(self.manifest["name"], "open-second-brain")
- interface = self.manifest.get("interface")
- self.assertIsInstance(interface, dict)
- self.assertIsInstance(interface.get("displayName"), str)
- self.assertIsInstance(self.manifest.get("plugins"), list)
- self.assertGreaterEqual(len(self.manifest["plugins"]), 1)
-
- def test_single_plugin_entry_shape(self):
- plugin = self.manifest["plugins"][0]
- self.assertEqual(plugin["name"], "open-second-brain")
- source = plugin["source"]
- self.assertEqual(source["source"], "local")
- self.assertIsInstance(source["path"], str)
- policy = plugin["policy"]
- self.assertEqual(policy["installation"], "AVAILABLE")
-
- def test_plugin_source_path_lands_at_codex_plugin_manifest(self):
- # Codex resolves ``source.path`` relative to the marketplace's
- # repository root β€” not relative to ``.agents/plugins/``. Verified
- # against the curated marketplace where ``./plugins/linear`` lands
- # at ``<root>/plugins/linear``. Our ``.`` therefore lands at the
- # repo root, and the repo root is where ``.codex-plugin/plugin.json``
- # lives. If those assumptions ever drift, this test fails fast.
- plugin = self.manifest["plugins"][0]
- path = plugin["source"]["path"]
- target = (ROOT / path).resolve()
- self.assertTrue(
- (target / ".codex-plugin" / "plugin.json").is_file(),
- f"plugin source path {path!r} (resolved to {target}) does not "
- f"contain .codex-plugin/plugin.json",
- )
-
- def test_plugin_name_matches_codex_plugin_manifest(self):
- # Codex namespaces installed plugins as ``<plugin>@<marketplace>``.
- # Both halves come from JSON files in this repo: marketplace name
- # from this manifest's top-level ``name``, and plugin name from
- # ``.codex-plugin/plugin.json`` ``name``. They must agree, or the
- # install instructions in ``install.md`` Branch C will name a
- # plugin Codex cannot resolve.
- plugin_manifest_path = ROOT / ".codex-plugin" / "plugin.json"
- plugin_manifest = json.loads(plugin_manifest_path.read_text(encoding="utf-8"))
- marketplace_plugin_name = self.manifest["plugins"][0]["name"]
- self.assertEqual(marketplace_plugin_name, plugin_manifest["name"])
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_config.py b/tests/test_config.py
deleted file mode 100644
index 0f46b8b6..00000000
--- a/tests/test_config.py
+++ /dev/null
@@ -1,120 +0,0 @@
-import os
-import tempfile
-import unittest
-from pathlib import Path
-from unittest.mock import patch
-
-from open_second_brain.config import (
- default_config_path,
- discover_config,
- redact_mapping,
- resolve_agent_name,
- resolve_timezone,
- resolve_vault,
-)
-
-
-class ConfigTests(unittest.TestCase):
- def test_default_config_path_uses_env_override(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "custom.yaml"
- with patch.dict(os.environ, {"OPEN_SECOND_BRAIN_CONFIG": str(path)}):
- self.assertEqual(default_config_path(), path)
-
- def test_default_config_path_uses_xdg_config_home(self):
- with tempfile.TemporaryDirectory() as tmp:
- with patch.dict(os.environ, {"XDG_CONFIG_HOME": tmp, "OPEN_SECOND_BRAIN_CONFIG": ""}, clear=False):
- self.assertEqual(default_config_path(), Path(tmp) / "open-second-brain" / "config.yaml")
-
- def test_discover_config_reports_missing_config(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "missing.yaml"
- result = discover_config(path)
- self.assertFalse(result.exists)
- self.assertEqual(result.path, path)
- self.assertEqual(result.data, {})
-
- def test_discover_config_reads_simple_key_value_yaml(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "config.yaml"
- path.write_text("instance_name: Test Brain\nruntime: hermes\n", encoding="utf-8")
- result = discover_config(path)
- self.assertTrue(result.exists)
- self.assertEqual(result.data["instance_name"], "Test Brain")
- self.assertEqual(result.data["runtime"], "hermes")
-
- def test_discover_config_reports_directory_as_missing(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp)
- result = discover_config(path)
- self.assertFalse(result.exists)
- self.assertEqual(result.path, path)
- self.assertEqual(result.data, {})
-
- def test_discover_config_reports_invalid_utf8_as_missing(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "config.yaml"
- path.write_bytes(b"\xff\xfe\x00")
- result = discover_config(path)
- self.assertFalse(result.exists)
- self.assertEqual(result.path, path)
- self.assertEqual(result.data, {})
-
- def test_redact_mapping_redacts_secret_like_keys(self):
- redacted = redact_mapping({"api_key": "abc", "path": "/tmp/vault", "token": "xyz"})
- self.assertEqual(redacted["api_key"], "[REDACTED]")
- self.assertEqual(redacted["token"], "[REDACTED]")
- self.assertEqual(redacted["path"], "/tmp/vault")
-
-
-class ResolveVaultTests(unittest.TestCase):
- """``resolve_vault`` is the single source of truth that ``o2b mcp``
- consults when launched without ``--vault`` (the case for Claude's
- ``.mcp.json`` auto-register and any Hermes/Codex MCP entry that
- omits the path). Lookup chain: ``VAULT_DIR`` env, then plugin config
- ``vault`` field, then ``None``.
- """
-
- def setUp(self):
- self._prev_env = os.environ.pop("VAULT_DIR", None)
-
- def tearDown(self):
- os.environ.pop("VAULT_DIR", None)
- if self._prev_env is not None:
- os.environ["VAULT_DIR"] = self._prev_env
-
- def test_returns_none_when_neither_env_nor_config(self):
- with tempfile.TemporaryDirectory() as tmp:
- self.assertIsNone(resolve_vault(Path(tmp) / "missing.yaml"))
-
- def test_reads_from_env(self):
- os.environ["VAULT_DIR"] = "/tmp/env-vault"
- with tempfile.TemporaryDirectory() as tmp:
- self.assertEqual(resolve_vault(Path(tmp) / "missing.yaml"), Path("/tmp/env-vault"))
-
- def test_env_wins_over_config(self):
- os.environ["VAULT_DIR"] = "/tmp/env-vault"
- with tempfile.TemporaryDirectory() as tmp:
- cfg = Path(tmp) / "config.yaml"
- cfg.write_text('vault: "/tmp/cfg-vault"\n', encoding="utf-8")
- self.assertEqual(resolve_vault(cfg), Path("/tmp/env-vault"))
-
- def test_reads_from_config_when_env_unset(self):
- with tempfile.TemporaryDirectory() as tmp:
- cfg = Path(tmp) / "config.yaml"
- cfg.write_text('vault: "/tmp/cfg-vault"\n', encoding="utf-8")
- self.assertEqual(resolve_vault(cfg), Path("/tmp/cfg-vault"))
-
- def test_expanduser_in_config_value(self):
- # Stored vault path may use ``~`` if the user hand-edits the file.
- # The resolver expands it so MCP launches don't see a literal tilde.
- with tempfile.TemporaryDirectory() as tmp:
- cfg = Path(tmp) / "config.yaml"
- cfg.write_text('vault: "~/my-vault"\n', encoding="utf-8")
- resolved = resolve_vault(cfg)
- self.assertIsNotNone(resolved)
- self.assertFalse(str(resolved).startswith("~"))
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_doctor.py b/tests/test_doctor.py
deleted file mode 100644
index cf051bfa..00000000
--- a/tests/test_doctor.py
+++ /dev/null
@@ -1,150 +0,0 @@
-import tempfile
-import unittest
-from pathlib import Path
-
-from open_second_brain.doctor import (
- CheckResult,
- check_claude_manifest,
- check_config_writeable,
- check_codex_manifest,
- check_hermes_manifest,
- check_json_manifest,
- check_openclaw_installability,
- check_openclaw_manifest,
- check_vault_writeable,
- doctor,
-)
-
-from tests.fixtures import create_plugin_repo, create_sandbox_vault
-
-
-class DoctorTests(unittest.TestCase):
- def test_check_vault_writeable(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- result = check_vault_writeable(vault)
- self.assertTrue(result.ok, result.message)
- self.assertIn("writable", result.message.lower())
-
- def test_check_vault_not_found(self):
- with tempfile.TemporaryDirectory() as tmp:
- missing = Path(tmp) / "does_not_exist"
- result = check_vault_writeable(missing)
- self.assertFalse(result.ok)
- self.assertIn("missing", result.message.lower())
-
- def test_check_config_writeable_valid(self):
- with tempfile.TemporaryDirectory() as tmp:
- config = Path(tmp) / "config.yaml"
- config.write_text("vault_path: /tmp", encoding="utf-8")
- result = check_config_writeable(config)
- self.assertTrue(result.ok, result.message)
-
- def test_check_config_writeable_missing_parent_is_ok(self):
- # config can be missing; the check verifies we can write to the parent
- with tempfile.TemporaryDirectory() as tmp:
- config = Path(tmp) / "subdir" / "config.yaml"
- result = check_config_writeable(config)
- self.assertTrue(result.ok, f"should be ok: can create parent dirs and touch file: {result.message}")
-
- def test_check_json_manifest_valid(self):
- with tempfile.TemporaryDirectory() as tmp:
- manifest = Path(tmp) / "plugin.json"
- manifest.write_text('{"name": "test", "version": "1.0.0"}', encoding="utf-8")
- result = check_json_manifest(manifest, "Test manifest")
- self.assertTrue(result.ok)
-
- def test_check_json_manifest_invalid(self):
- with tempfile.TemporaryDirectory() as tmp:
- manifest = Path(tmp) / "plugin.json"
- manifest.write_text("{invalid json", encoding="utf-8")
- result = check_json_manifest(manifest, "Test manifest")
- self.assertFalse(result.ok)
-
- def test_check_json_manifest_missing(self):
- with tempfile.TemporaryDirectory() as tmp:
- missing = Path(tmp) / "does_not_exist.json"
- result = check_json_manifest(missing, "Test")
- self.assertFalse(result.ok)
-
- def test_doctor_aggregates_results(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = create_sandbox_vault(Path(tmp))
- config = Path(tmp) / "config.yaml"
- config.write_text("vault_path: /tmp", encoding="utf-8")
- results = doctor(vault=vault, config=config)
- self.assertGreater(len(results), 0)
- for r in results:
- self.assertIsInstance(r, CheckResult)
-
- def test_manifest_schema_checks_accept_valid_fixture(self):
- with tempfile.TemporaryDirectory() as tmp:
- repo = create_plugin_repo(Path(tmp), valid=True)
- self.assertTrue(check_claude_manifest(repo / ".claude-plugin" / "plugin.json").ok)
- self.assertTrue(check_codex_manifest(repo / ".codex-plugin" / "plugin.json").ok)
- self.assertTrue(check_hermes_manifest(repo / "plugins" / "hermes" / "plugin.yaml").ok)
- self.assertTrue(check_openclaw_manifest(repo / "openclaw.plugin.json").ok)
-
- def test_manifest_schema_checks_reject_missing_required_fields(self):
- with tempfile.TemporaryDirectory() as tmp:
- repo = create_plugin_repo(Path(tmp), valid=False)
- claude = check_claude_manifest(repo / ".claude-plugin" / "plugin.json")
- codex = check_codex_manifest(repo / ".codex-plugin" / "plugin.json")
- hermes = check_hermes_manifest(repo / "plugins" / "hermes" / "plugin.yaml")
- openclaw = check_openclaw_manifest(repo / "openclaw.plugin.json")
- self.assertFalse(claude.ok)
- self.assertFalse(codex.ok)
- self.assertFalse(hermes.ok)
- self.assertFalse(openclaw.ok)
- self.assertIn("schema invalid", claude.message)
- self.assertIn("skills", codex.message)
- self.assertIn("missing", hermes.message)
- self.assertIn("'id'", openclaw.message)
-
- def test_check_openclaw_installability_on_valid_fixture(self):
- with tempfile.TemporaryDirectory() as tmp:
- repo = create_plugin_repo(Path(tmp), valid=True)
- # Valid fixture now includes package.json and extension entry
- results = check_openclaw_installability(repo)
- self.assertGreater(len(results), 0)
- for r in results:
- self.assertTrue(r.ok, f"{r.name}: {r.message}")
-
- def test_check_openclaw_installability_with_package_json(self):
- import json
- with tempfile.TemporaryDirectory() as tmp:
- repo = create_plugin_repo(Path(tmp), valid=True)
- # Add a valid package.json with an extension entry
- entry_js = repo / "openclaw" / "index.js"
- entry_js.parent.mkdir(parents=True, exist_ok=True)
- entry_js.write_text("// entry", encoding="utf-8")
- (repo / "package.json").write_text(
- json.dumps({"openclaw": {"extensions": ["./openclaw/index.js"]}}),
- encoding="utf-8",
- )
- results = check_openclaw_installability(repo)
- self.assertGreater(len(results), 0)
- for r in results:
- self.assertTrue(r.ok, f"{r.name}: {r.message}")
-
- def test_doctor_includes_installability_checks_with_repo(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = create_sandbox_vault(Path(tmp))
- repo = create_plugin_repo(Path(tmp), valid=True)
- # Add package.json to fixture so installability passes
- import json
- entry_js = repo / "openclaw" / "index.js"
- entry_js.parent.mkdir(parents=True, exist_ok=True)
- entry_js.write_text("// entry", encoding="utf-8")
- (repo / "package.json").write_text(
- json.dumps({"openclaw": {"extensions": ["./openclaw/index.js"]}}),
- encoding="utf-8",
- )
- results = doctor(vault=vault, repo_root=repo)
- names = [r.name for r in results]
- self.assertIn("openclaw_package_json", names)
- self.assertIn("openclaw_package_json_extensions", names)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_event_log.py b/tests/test_event_log.py
deleted file mode 100644
index 70bf425c..00000000
--- a/tests/test_event_log.py
+++ /dev/null
@@ -1,79 +0,0 @@
-import multiprocessing
-import tempfile
-import unittest
-from pathlib import Path
-
-from open_second_brain.event_log import append_event, redact_text
-
-
-def append_concurrent_event(vault_dir: str, index: int) -> None:
- append_event(
- Path(vault_dir),
- "worker",
- f"entry {index}",
- date="2026.05.06",
- time=f"10:{index:02d}",
- )
-
-
-class EventLogTests(unittest.TestCase):
- def test_append_event_creates_daily_note_with_raw_events_section(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = append_event(
- vault_dir=Path(tmp),
- agent="test-agent",
- message="created project skeleton",
- date="2026.05.06",
- time="09:30",
- )
- self.assertEqual(path, Path(tmp) / "Daily" / "2026.05.06.md")
- self.assertEqual(
- path.read_text(encoding="utf-8"),
- "---\nformatted: false\n---\n\n# 2026.05.06\n\n## Raw events\n\n- 09:30 β€” @test-agent β€” created project skeleton\n",
- )
-
- def test_append_event_preserves_manual_content_above_raw_events(self):
- with tempfile.TemporaryDirectory() as tmp:
- daily = Path(tmp) / "Daily" / "2026.05.06.md"
- daily.parent.mkdir(parents=True)
- daily.write_text("# 2026.05.06\n\nManual note.\n\n## Raw events\n\n- 08:00 β€” @old β€” old entry\n", encoding="utf-8")
- append_event(Path(tmp), "new", "new entry", date="2026.05.06", time="09:00")
- self.assertEqual(
- daily.read_text(encoding="utf-8"),
- "# 2026.05.06\n\nManual note.\n\n## Raw events\n\n- 08:00 β€” @old β€” old entry\n- 09:00 β€” @new β€” new entry\n",
- )
-
- def test_append_event_inserts_entries_chronologically(self):
- with tempfile.TemporaryDirectory() as tmp:
- append_event(Path(tmp), "agent", "later", date="2026.05.06", time="11:00")
- append_event(Path(tmp), "agent", "earlier", date="2026.05.06", time="09:00")
- content = (Path(tmp) / "Daily" / "2026.05.06.md").read_text(encoding="utf-8")
- self.assertLess(content.index("09:00"), content.index("11:00"))
-
- def test_append_event_rejects_invalid_explicit_times(self):
- with tempfile.TemporaryDirectory() as tmp:
- for invalid_time in ("9:00", "25:00", "bad"):
- with self.subTest(invalid_time=invalid_time):
- with self.assertRaises(ValueError):
- append_event(Path(tmp), "agent", "message", date="2026.05.06", time=invalid_time)
-
- def test_concurrent_process_appends_keep_all_entries(self):
- with tempfile.TemporaryDirectory() as tmp:
- processes = [multiprocessing.Process(target=append_concurrent_event, args=(tmp, index)) for index in range(12)]
- for process in processes:
- process.start()
- for process in processes:
- process.join(10)
- self.assertEqual(process.exitcode, 0)
-
- content = (Path(tmp) / "Daily" / "2026.05.06.md").read_text(encoding="utf-8")
- for index in range(12):
- self.assertIn(f"- 10:{index:02d} β€” @worker β€” entry {index}", content)
- self.assertEqual(content.count("@worker β€” entry"), 12)
-
- def test_redact_text_removes_secret_like_assignments(self):
- self.assertEqual(redact_text("api_key=abc token: xyz password = qwerty"), "api_key=[REDACTED] token: [REDACTED] password = [REDACTED]")
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_hermes_plugin.py b/tests/test_hermes_plugin.py
deleted file mode 100644
index 9542d799..00000000
--- a/tests/test_hermes_plugin.py
+++ /dev/null
@@ -1,136 +0,0 @@
-import importlib.util
-import os
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-
-from plugins.hermes import check_health, health, on_pre_llm_call, register
-
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-class HermesPluginTests(unittest.TestCase):
- def test_health_report_checks_repo_artifacts(self):
- report = health(ROOT)
- self.assertTrue(report["ok"], report)
- self.assertIn("claude_manifest", report["checks"])
- self.assertIn("codex_manifest", report["checks"])
- self.assertIn("openclaw_manifest", report["checks"])
- self.assertIn("o2b_script", report["checks"])
-
- def test_check_health_alias(self):
- self.assertEqual(check_health(ROOT)["name"], "open-second-brain")
-
- def test_root_plugin_entrypoint_loads_like_hermes_git_install(self):
- spec = importlib.util.spec_from_file_location(
- "open_second_brain_plugin_test",
- ROOT / "__init__.py",
- submodule_search_locations=[str(ROOT)],
- )
- self.assertIsNotNone(spec)
- self.assertIsNotNone(spec.loader)
- module = importlib.util.module_from_spec(spec)
- sys.modules[spec.name] = module
- try:
- spec.loader.exec_module(module)
- self.assertEqual(module.check_health(ROOT)["name"], "open-second-brain")
- finally:
- sys.modules.pop(spec.name, None)
-
- def test_register_attaches_to_method_context(self):
- calls = []
-
- class Context:
- def register_health_check(self, name, callback):
- calls.append((name, callback))
-
- register(Context())
- self.assertEqual(calls[0][0], "open-second-brain")
- self.assertTrue(calls[0][1](ROOT)["ok"])
-
- def test_register_attaches_to_dict_context(self):
- class Context:
- def __init__(self):
- self.health_checks = {}
-
- ctx = Context()
- register(ctx)
- self.assertIn("open-second-brain", ctx.health_checks)
-
- def test_register_calls_register_hook_for_pre_llm_call(self):
- registered: list[tuple[str, object]] = []
-
- class Context:
- def register_hook(self, name, callback):
- registered.append((name, callback))
-
- register(Context())
- self.assertEqual(len(registered), 1)
- name, callback = registered[0]
- self.assertEqual(name, "pre_llm_call")
- self.assertIs(callback, on_pre_llm_call)
-
-
-class PreLlmCallTests(unittest.TestCase):
- """Verify the pre_llm_call hook contract toward Hermes.
-
- The hook fires every turn and must:
- - return ``{"context": "..."}`` when identity is configured
- - return ``None`` (no inject) when identity is unresolved
- - never raise
- """
-
- def setUp(self):
- self._prev_env = os.environ.pop("VAULT_AGENT_NAME", None)
- self._prev_cfg = os.environ.pop("OPEN_SECOND_BRAIN_CONFIG", None)
-
- def tearDown(self):
- os.environ.pop("VAULT_AGENT_NAME", None)
- os.environ.pop("OPEN_SECOND_BRAIN_CONFIG", None)
- if self._prev_env is not None:
- os.environ["VAULT_AGENT_NAME"] = self._prev_env
- if self._prev_cfg is not None:
- os.environ["OPEN_SECOND_BRAIN_CONFIG"] = self._prev_cfg
-
- def test_pre_llm_call_returns_context_when_env_identity_set(self):
- os.environ["VAULT_AGENT_NAME"] = "hermes-vps-agent"
- result = on_pre_llm_call(
- session_id="test",
- user_message="hello",
- conversation_history=[],
- is_first_turn=True,
- model="combo",
- platform="cli",
- sender_id="",
- )
- self.assertIsInstance(result, dict)
- self.assertIn("context", result)
- ctx = result["context"]
- self.assertIn("@hermes-vps-agent", ctx)
- self.assertIn("event_log_append", ctx)
-
- def test_pre_llm_call_returns_context_from_persisted_config(self):
- with tempfile.TemporaryDirectory() as tmp:
- cfg = Path(tmp) / "config.yaml"
- cfg.write_text('agent_name: "openclaw-main"\n', encoding="utf-8")
- os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg)
- result = on_pre_llm_call()
- self.assertIsInstance(result, dict)
- self.assertIn("@openclaw-main", result["context"])
-
- def test_pre_llm_call_returns_none_when_identity_unresolved(self):
- # No env, no config β†’ fallback hits the literal "agent" placeholder.
- # The hook must skip injection instead of telling the LLM "you are
- # @agent", which would be misleading.
- with tempfile.TemporaryDirectory() as tmp:
- os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(
- Path(tmp) / "missing.yaml"
- )
- result = on_pre_llm_call()
- self.assertIsNone(result)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_init.py b/tests/test_init.py
deleted file mode 100644
index 2267e21e..00000000
--- a/tests/test_init.py
+++ /dev/null
@@ -1,139 +0,0 @@
-import tempfile
-import unittest
-from pathlib import Path
-
-from open_second_brain.init import AGENTS_PLACEHOLDER, bootstrap_vault, VAULT_FILES
-
-
-class InitTests(unittest.TestCase):
- def test_bootstrap_vault_creates_structure(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- created = bootstrap_vault(vault, name="Test Brain")
- self.assertGreater(len(created), 0)
- self.assertIn(Path("AI Wiki") / "_OPEN_SECOND_BRAIN.md", created)
- self.assertIn(Path("AI Wiki") / "_open-second-brain.yaml", created)
- self.assertIn(Path("AI Wiki") / "index.md", created)
- self.assertIn(Path("AI Wiki") / "hot.md", created)
- self.assertIn(Path("AI Wiki") / "log.md", created)
- self.assertIn(Path("AI Wiki") / "identity" / "user.md", created)
- self.assertIn(Path("AI Wiki") / "identity" / "agents.md", created)
-
- # Verify all files exist
- for rel_path in VAULT_FILES:
- self.assertTrue((vault / rel_path).is_file(), f"Missing {rel_path}")
-
- # Check content has the name
- manual = (vault / "AI Wiki" / "_OPEN_SECOND_BRAIN.md").read_text(encoding="utf-8")
- self.assertIn("Test Brain", manual)
-
- def test_bootstrap_vault_writes_agent_name(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- bootstrap_vault(vault, name="Test", agent_name="openclaw-main")
- agents_md = (vault / "AI Wiki" / "identity" / "agents.md").read_text(
- encoding="utf-8"
- )
- self.assertIn("- openclaw-main: primary agent on this server", agents_md)
- self.assertNotIn(AGENTS_PLACEHOLDER, agents_md)
-
- def test_bootstrap_vault_without_agent_name_keeps_placeholder(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- bootstrap_vault(vault, name="Test")
- agents_md = (vault / "AI Wiki" / "identity" / "agents.md").read_text(
- encoding="utf-8"
- )
- self.assertIn(AGENTS_PLACEHOLDER, agents_md)
-
- def test_bootstrap_vault_registers_second_agent_when_first_already_present(self):
- # Multi-runtime install: a previous `o2b init --agent-name X`
- # already replaced the placeholder, so this run's agent name
- # has to be APPENDED to the existing list, not skipped. Before
- # this fix the second invocation was a silent no-op: the
- # plugin config got the new identity but the vault registry
- # never learned about it. Both Codex and Claude install
- # sessions hit this in practice.
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- bootstrap_vault(vault, name="Test", agent_name="hermes-vps-agent")
- agents_path = vault / "AI Wiki" / "identity" / "agents.md"
- first_text = agents_path.read_text(encoding="utf-8")
- self.assertIn("- hermes-vps-agent: primary agent on this server", first_text)
- self.assertNotIn(AGENTS_PLACEHOLDER, first_text)
-
- created = bootstrap_vault(vault, name="Test", agent_name="codex-vps-agent")
- self.assertIn(Path("AI Wiki") / "identity" / "agents.md", created)
- text = agents_path.read_text(encoding="utf-8")
- # Both agents are present, in registration order.
- self.assertIn("- hermes-vps-agent: primary agent on this server", text)
- self.assertIn("- codex-vps-agent: primary agent on this server", text)
- self.assertLess(
- text.index("hermes-vps-agent"),
- text.index("codex-vps-agent"),
- "first-registered agent must come first",
- )
- # The "## Scopes" section that follows must still be intact.
- self.assertIn("## Scopes", text)
- self.assertLess(
- text.index("codex-vps-agent"),
- text.index("## Scopes"),
- "new agent must be inserted under '## Registered agents', "
- "not after the next section header",
- )
-
- # A third register of an already-present name is a no-op.
- created_again = bootstrap_vault(vault, name="Test", agent_name="codex-vps-agent")
- self.assertNotIn(Path("AI Wiki") / "identity" / "agents.md", created_again)
- text_after = agents_path.read_text(encoding="utf-8")
- self.assertEqual(
- text_after.count("- codex-vps-agent: primary agent on this server"),
- 1,
- "re-registering an existing agent must not duplicate the entry",
- )
-
- def test_bootstrap_vault_upgrades_existing_placeholder_in_place(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- # First init without agent name leaves placeholder.
- bootstrap_vault(vault, name="Test")
- agents_path = vault / "AI Wiki" / "identity" / "agents.md"
- self.assertIn(AGENTS_PLACEHOLDER, agents_path.read_text(encoding="utf-8"))
-
- # Second init with agent_name (no --force) must rewrite the placeholder.
- created = bootstrap_vault(vault, name="Test", agent_name="hermes-main")
- self.assertIn(Path("AI Wiki") / "identity" / "agents.md", created)
- text = agents_path.read_text(encoding="utf-8")
- self.assertIn("- hermes-main: primary agent on this server", text)
- self.assertNotIn(AGENTS_PLACEHOLDER, text)
-
- def test_bootstrap_vault_does_not_overwrite_by_default(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- index_path = vault / "AI Wiki" / "index.md"
- index_path.parent.mkdir(parents=True)
- index_path.write_text("custom content", encoding="utf-8")
-
- created = bootstrap_vault(vault, name="Test")
- # index.md should NOT be in created (already exists)
- self.assertNotIn(Path("AI Wiki") / "index.md", created)
- # But other files should be created
- self.assertIn(Path("AI Wiki") / "_OPEN_SECOND_BRAIN.md", created)
- # Original content preserved
- self.assertEqual(index_path.read_text(encoding="utf-8"), "custom content")
-
- def test_bootstrap_vault_force_overwrites(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- index_path = vault / "AI Wiki" / "index.md"
- index_path.parent.mkdir(parents=True)
- index_path.write_text("old", encoding="utf-8")
-
- created = bootstrap_vault(vault, name="Test", force=True)
- self.assertIn(Path("AI Wiki") / "index.md", created)
- # Content should be overwritten with template
- self.assertNotEqual(index_path.read_text(encoding="utf-8"), "old")
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_mcp.py b/tests/test_mcp.py
deleted file mode 100644
index d29727bf..00000000
--- a/tests/test_mcp.py
+++ /dev/null
@@ -1,663 +0,0 @@
-import io
-import json
-import os
-import subprocess
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[1]
-ENV = {**os.environ, "PYTHONPATH": str(ROOT / "src")}
-
-sys.path.insert(0, str(ROOT / "src"))
-
-from open_second_brain.mcp import ( # noqa: E402
- JSONRPC_VERSION,
- MCPServer,
- PROTOCOL_VERSION,
- SERVER_NAME,
- SERVER_VERSION,
- serve_stdio,
- slugify,
-)
-from tests.fixtures import create_plugin_repo, create_sandbox_vault # noqa: E402
-
-
-def _make_server(vault: Path, *, config: Path | None = None, repo: Path | None = None) -> MCPServer:
- return MCPServer(vault=vault, config_path=config, repo_root=repo)
-
-
-def _initialize(server: MCPServer) -> dict:
- response = server.handle_request(
- {
- "jsonrpc": JSONRPC_VERSION,
- "id": 1,
- "method": "initialize",
- "params": {
- "protocolVersion": PROTOCOL_VERSION,
- "capabilities": {},
- "clientInfo": {"name": "test-client", "version": "0"},
- },
- }
- )
- assert server.handle_request(
- {"jsonrpc": JSONRPC_VERSION, "method": "notifications/initialized"}
- ) is None
- return response
-
-
-def _call_tool(server: MCPServer, name: str, arguments: dict | None = None, request_id: int = 99) -> dict:
- return server.handle_request(
- {
- "jsonrpc": JSONRPC_VERSION,
- "id": request_id,
- "method": "tools/call",
- "params": {"name": name, "arguments": arguments or {}},
- }
- )
-
-
-class SlugifyTests(unittest.TestCase):
- def test_slugify_lowercases_and_replaces_punctuation(self):
- self.assertEqual(slugify("Hello, World!"), "hello-world")
-
- def test_slugify_handles_unicode_and_empty(self):
- self.assertEqual(slugify(" "), "note")
- self.assertEqual(slugify("---"), "note")
- self.assertEqual(slugify("КСйс / ВСст"), "note")
-
- def test_slugify_truncates_long_input(self):
- long = "a" * 200
- self.assertEqual(len(slugify(long)), 64)
-
-
-class HandshakeTests(unittest.TestCase):
- def test_initialize_returns_server_info_and_tools_capability(self):
- with tempfile.TemporaryDirectory() as tmp:
- server = _make_server(Path(tmp))
- response = _initialize(server)
- self.assertEqual(response["jsonrpc"], JSONRPC_VERSION)
- self.assertEqual(response["id"], 1)
- result = response["result"]
- self.assertEqual(result["serverInfo"]["name"], SERVER_NAME)
- self.assertEqual(result["serverInfo"]["version"], SERVER_VERSION)
- self.assertIn("tools", result["capabilities"])
- self.assertEqual(result["protocolVersion"], PROTOCOL_VERSION)
-
- def test_initialize_instructions_embed_resolved_agent_identity(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- config = Path(tmp) / "config.yaml"
- config.write_text("agent_name: hermes-vps-agent\n", encoding="utf-8")
- prior_env = os.environ.pop("VAULT_AGENT_NAME", None)
- try:
- server = _make_server(vault, config=config)
- response = _initialize(server)
- finally:
- if prior_env is not None:
- os.environ["VAULT_AGENT_NAME"] = prior_env
- instructions = response["result"]["instructions"]
- self.assertIn("@hermes-vps-agent", instructions)
- self.assertIn("event_log_append", instructions)
- self.assertIn("DO NOT", instructions)
-
- def test_initialize_negotiates_alternate_client_version(self):
- with tempfile.TemporaryDirectory() as tmp:
- server = _make_server(Path(tmp))
- response = server.handle_request(
- {
- "jsonrpc": JSONRPC_VERSION,
- "id": 1,
- "method": "initialize",
- "params": {
- "protocolVersion": "2024-11-05",
- "capabilities": {},
- "clientInfo": {"name": "old", "version": "0"},
- },
- }
- )
- self.assertEqual(response["result"]["protocolVersion"], "2024-11-05")
-
- def test_initialized_notification_is_silent(self):
- with tempfile.TemporaryDirectory() as tmp:
- server = _make_server(Path(tmp))
- self.assertIsNone(
- server.handle_request(
- {"jsonrpc": JSONRPC_VERSION, "method": "notifications/initialized"}
- )
- )
-
- def test_unknown_method_returns_method_not_found(self):
- with tempfile.TemporaryDirectory() as tmp:
- server = _make_server(Path(tmp))
- response = server.handle_request(
- {"jsonrpc": JSONRPC_VERSION, "id": 7, "method": "does/not/exist"}
- )
- self.assertEqual(response["error"]["code"], -32601)
-
-
-class ToolListingTests(unittest.TestCase):
- def test_tools_list_advertises_all_roadmap_tools(self):
- with tempfile.TemporaryDirectory() as tmp:
- server = _make_server(Path(tmp))
- _initialize(server)
- response = server.handle_request(
- {"jsonrpc": JSONRPC_VERSION, "id": 2, "method": "tools/list"}
- )
- names = {tool["name"] for tool in response["result"]["tools"]}
- self.assertEqual(
- names,
- {
- "second_brain_status",
- "second_brain_query",
- "second_brain_capture",
- "event_log_append",
- "vault_health",
- },
- )
- for tool in response["result"]["tools"]:
- self.assertIn("inputSchema", tool)
- self.assertEqual(tool["inputSchema"]["type"], "object")
-
-
-class ToolCallTests(unittest.TestCase):
- def test_second_brain_status_reports_vault_and_config(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- config = Path(tmp) / "config.yaml"
- config.write_text("vault_path: /tmp/vault\napi_key: secret\n", encoding="utf-8")
- server = _make_server(vault, config=config)
- _initialize(server)
-
- response = _call_tool(server, "second_brain_status")
- structured = response["result"]["structuredContent"]
- self.assertEqual(structured["vault_path"], str(vault))
- self.assertTrue(structured["vault_exists"])
- self.assertEqual(structured["config"]["api_key"], "[REDACTED]")
- self.assertIn("vault_path", structured["config_keys"])
-
- def test_second_brain_query_filters_and_limits(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = create_sandbox_vault(Path(tmp))
- server = _make_server(vault)
- _initialize(server)
-
- response = _call_tool(
- server,
- "second_brain_query",
- {"pattern": "Sandbox", "limit": 5},
- )
- structured = response["result"]["structuredContent"]
- self.assertEqual(structured["limit"], 5)
- self.assertGreaterEqual(structured["total_pages"], 1)
- self.assertTrue(any("Sandbox" in p["title"] for p in structured["pages"]))
-
- def test_second_brain_capture_writes_note_with_frontmatter(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- server = _make_server(vault)
- _initialize(server)
-
- response = _call_tool(
- server,
- "second_brain_capture",
- {
- "title": "Hello World",
- "content": "# Body\n\ntext",
- "tags": ["draft", "demo"],
- },
- )
- structured = response["result"]["structuredContent"]
- note = vault / "AI Wiki" / "notes" / "hello-world.md"
- self.assertTrue(note.is_file())
- text = note.read_text(encoding="utf-8")
- self.assertIn("title: Hello World", text)
- self.assertIn("tags: [draft, demo]", text)
- self.assertIn("# Body", text)
- self.assertEqual(structured["slug"], "hello-world")
-
- def test_second_brain_capture_rejects_existing_note_without_overwrite(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- server = _make_server(vault)
- _initialize(server)
-
- args = {"title": "Same Title", "content": "first"}
- response = _call_tool(server, "second_brain_capture", args)
- self.assertFalse(response["result"]["isError"])
-
- response = _call_tool(server, "second_brain_capture", args, request_id=100)
- self.assertTrue(response["result"]["isError"])
- self.assertIn("already exists", response["result"]["content"][0]["text"])
-
- def test_second_brain_capture_rejects_empty_title(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- server = _make_server(vault)
- _initialize(server)
-
- response = _call_tool(
- server,
- "second_brain_capture",
- {"title": " ", "content": "body"},
- )
- self.assertEqual(response["error"]["code"], -32602)
-
- def test_event_log_append_writes_daily_note(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- server = _make_server(vault)
- _initialize(server)
-
- response = _call_tool(
- server,
- "event_log_append",
- {
- "message": "via mcp",
- "agent": "mcp-test",
- "date": "2026.05.06",
- "time": "11:42",
- },
- )
- self.assertFalse(response["result"]["isError"])
- structured = response["result"]["structuredContent"]
- self.assertEqual(structured["agent"], "mcp-test")
- daily = vault / "Daily" / "2026.05.06.md"
- self.assertIn("- 11:42 β€” @mcp-test β€” via mcp", daily.read_text(encoding="utf-8"))
-
- def test_event_log_append_strips_leading_at_in_agent(self):
- # LLMs frequently echo the @-prefixed identity from the prompt back as
- # the `agent` argument. The server must strip the leading @ so the
- # final entry doesn't double up to `@@name`.
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- server = _make_server(vault)
- _initialize(server)
-
- response = _call_tool(
- server,
- "event_log_append",
- {
- "message": "with-at-prefix",
- "agent": "@hermes-vps-agent",
- "date": "2026.05.06",
- "time": "11:55",
- },
- )
- self.assertFalse(response["result"]["isError"])
- structured = response["result"]["structuredContent"]
- self.assertEqual(structured["agent"], "hermes-vps-agent")
- daily = vault / "Daily" / "2026.05.06.md"
- text = daily.read_text(encoding="utf-8")
- self.assertIn("- 11:55 β€” @hermes-vps-agent β€” with-at-prefix", text)
- self.assertNotIn("@@", text)
-
- def test_event_log_append_placeholder_agent_falls_back_to_default(self):
- # When the LLM hallucinates a placeholder/self-name (`agent`,
- # `assistant`, `claude`, ...) into the call, the server must treat it
- # as "no value" and fall back to the resolved default identity instead
- # of writing the guess verbatim into Daily.
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- config = Path(tmp) / "config.yaml"
- config.write_text("agent_name: hermes-vps-agent\n", encoding="utf-8")
- server = _make_server(vault, config=config)
- _initialize(server)
-
- prior_env = os.environ.pop("VAULT_AGENT_NAME", None)
- try:
- cases = (
- "agent", "@agent", "AGENT", " @agent ",
- "assistant", "@assistant", "Assistant",
- "claude", "GPT", "gpt-5", "ai", "Bot", "model",
- )
- for trash in cases:
- response = _call_tool(
- server,
- "event_log_append",
- {
- "message": f"trash:{trash}",
- "agent": trash,
- "date": "2026.05.06",
- "time": "12:30",
- },
- )
- self.assertFalse(response["result"]["isError"])
- self.assertEqual(
- response["result"]["structuredContent"]["agent"],
- "hermes-vps-agent",
- msg=f"placeholder {trash!r} should fall back to default",
- )
- finally:
- if prior_env is not None:
- os.environ["VAULT_AGENT_NAME"] = prior_env
-
- def test_event_log_append_empty_optional_strings_treated_as_missing(self):
- # LLMs in tool-use mode often pass empty strings for optional fields
- # they want to skip (e.g. `time=""`, `date=""`) instead of omitting
- # them. The server must treat empty-string optional args the same as
- # omitted, not pass `""` through to validators.
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- server = _make_server(vault)
- _initialize(server)
-
- response = _call_tool(
- server,
- "event_log_append",
- {
- "message": "with-empty-optionals",
- "agent": "",
- "date": "",
- "time": "",
- },
- )
- self.assertFalse(
- response["result"]["isError"],
- msg=f"empty optional strings should not error: {response}",
- )
- structured = response["result"]["structuredContent"]
- # date/time were empty β†’ server filled in current values, not ""
- self.assertIsNone(structured["date"])
- self.assertIsNone(structured["time"])
-
- def test_event_log_append_uses_configured_timezone(self):
- # The plugin config stores an IANA timezone alongside agent_name. When
- # set, event_log_append must stamp Daily entries in that timezone, so
- # that user-local clock time appears regardless of where the host is.
- # Cross-checked with `datetime.now(ZoneInfo(...))` to avoid asserting
- # against a wall-clock value that flips between test runs around the
- # minute boundary.
- from datetime import datetime
- from zoneinfo import ZoneInfo
-
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- config = Path(tmp) / "config.yaml"
- config.write_text(
- 'agent_name: "hermes-vps-agent"\ntimezone: "Europe/Belgrade"\n',
- encoding="utf-8",
- )
- server = _make_server(vault, config=config)
- _initialize(server)
-
- prior = {k: os.environ.pop(k, None) for k in ("VAULT_AGENT_NAME", "VAULT_TIMEZONE")}
- try:
- # Capture the local-tz wall clock immediately *before* the
- # tool runs, so the assertion's expected date/hour are
- # derived from an instant strictly earlier than the one
- # the tool stamps. Capturing it after introduces a
- # midnight-rollover race (tool stamps day N, assertion
- # computes day N+1, mismatched filename).
- expected_at_call = datetime.now(ZoneInfo("Europe/Belgrade"))
- response = _call_tool(
- server,
- "event_log_append",
- {"message": "tz-test"},
- )
- finally:
- for k, v in prior.items():
- if v is not None:
- os.environ[k] = v
-
- self.assertFalse(response["result"]["isError"], response)
- expected_file = vault / "Daily" / f"{expected_at_call.strftime('%Y.%m.%d')}.md"
- self.assertTrue(expected_file.is_file(), f"missing: {expected_file}")
- text = expected_file.read_text(encoding="utf-8")
- self.assertIn(f"β€” @hermes-vps-agent β€” tz-test", text)
- self.assertIn(f"- {expected_at_call.strftime('%H')}", text)
-
- def test_event_log_append_uses_vault_timezone_env(self):
- # Env var takes precedence over config. Useful for runtime overrides
- # (Hermes mcp_servers env block) without touching the plugin config.
- from datetime import datetime
- from zoneinfo import ZoneInfo
-
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- config = Path(tmp) / "config.yaml"
- # Config says one zone; env says another β€” env must win.
- config.write_text('timezone: "UTC"\n', encoding="utf-8")
- server = _make_server(vault, config=config)
- _initialize(server)
-
- prior = os.environ.get("VAULT_TIMEZONE")
- os.environ["VAULT_TIMEZONE"] = "Europe/Belgrade"
- try:
- # Capture before the tool call so a midnight rollover
- # between the call and the assertion can't mismatch
- # the expected filename.
- expected_at_call = datetime.now(ZoneInfo("Europe/Belgrade"))
- response = _call_tool(
- server,
- "event_log_append",
- {"message": "env-tz-test", "agent": "tester"},
- )
- finally:
- if prior is None:
- os.environ.pop("VAULT_TIMEZONE", None)
- else:
- os.environ["VAULT_TIMEZONE"] = prior
-
- self.assertFalse(response["result"]["isError"], response)
- expected_file = vault / "Daily" / f"{expected_at_call.strftime('%Y.%m.%d')}.md"
- self.assertTrue(expected_file.is_file())
-
- def test_event_log_append_invalid_config_timezone_falls_back_silently(self):
- # A typo in the config timezone must NOT break logging β€” we silently
- # fall back to system-local time. The entry still lands; only its
- # stamp is in server time instead of user-intended time.
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- config = Path(tmp) / "config.yaml"
- config.write_text('timezone: "Not/A/Real/Zone"\n', encoding="utf-8")
- server = _make_server(vault, config=config)
- _initialize(server)
-
- prior = os.environ.pop("VAULT_TIMEZONE", None)
- try:
- response = _call_tool(
- server,
- "event_log_append",
- {"message": "fallback", "agent": "tester"},
- )
- finally:
- if prior is not None:
- os.environ["VAULT_TIMEZONE"] = prior
-
- self.assertFalse(response["result"]["isError"], response)
-
- def test_event_log_append_uses_config_agent_name_default(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- config = Path(tmp) / "config.yaml"
- config.write_text("agent_name: openclaw-main\n", encoding="utf-8")
- server = _make_server(vault, config=config)
- _initialize(server)
-
- # Ensure environment variable does not shadow the config default
- prior_env = os.environ.pop("VAULT_AGENT_NAME", None)
- try:
- response = _call_tool(
- server,
- "event_log_append",
- {
- "message": "from-config-default",
- "date": "2026.05.06",
- "time": "12:00",
- },
- )
- finally:
- if prior_env is not None:
- os.environ["VAULT_AGENT_NAME"] = prior_env
-
- self.assertFalse(response["result"]["isError"])
- structured = response["result"]["structuredContent"]
- self.assertEqual(structured["agent"], "openclaw-main")
- daily = vault / "Daily" / "2026.05.06.md"
- self.assertIn(
- "- 12:00 β€” @openclaw-main β€” from-config-default",
- daily.read_text(encoding="utf-8"),
- )
-
- def test_event_log_append_rejects_invalid_time(self):
- with tempfile.TemporaryDirectory() as tmp:
- server = _make_server(Path(tmp))
- _initialize(server)
- response = _call_tool(
- server,
- "event_log_append",
- {"message": "x", "time": "99:99"},
- )
- self.assertTrue(response["result"]["isError"])
- self.assertIn("HH:MM", response["result"]["content"][0]["text"])
-
- def test_vault_health_runs_doctor(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = create_sandbox_vault(Path(tmp))
- repo = create_plugin_repo(Path(tmp), valid=True)
- server = _make_server(vault, repo=repo)
- _initialize(server)
-
- response = _call_tool(server, "vault_health", {})
- structured = response["result"]["structuredContent"]
- self.assertTrue(structured["ok"])
- check_names = {check["name"] for check in structured["checks"]}
- self.assertIn("vault_writeable", check_names)
- self.assertIn("claude_manifest", check_names)
- self.assertIn("hermes_manifest", check_names)
-
- def test_unknown_tool_returns_method_not_found(self):
- with tempfile.TemporaryDirectory() as tmp:
- server = _make_server(Path(tmp))
- _initialize(server)
- response = _call_tool(server, "not_a_tool")
- self.assertEqual(response["error"]["code"], -32601)
-
-
-class StdioLoopTests(unittest.TestCase):
- def test_serve_stdio_processes_initialize_and_tools_list(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- server = MCPServer(vault=vault)
- payload = "\n".join(
- [
- json.dumps(
- {
- "jsonrpc": JSONRPC_VERSION,
- "id": 1,
- "method": "initialize",
- "params": {
- "protocolVersion": PROTOCOL_VERSION,
- "capabilities": {},
- "clientInfo": {"name": "t", "version": "0"},
- },
- }
- ),
- json.dumps({"jsonrpc": JSONRPC_VERSION, "method": "notifications/initialized"}),
- json.dumps({"jsonrpc": JSONRPC_VERSION, "id": 2, "method": "tools/list"}),
- ]
- ) + "\n"
- stdin = io.StringIO(payload)
- stdout = io.StringIO()
- stderr = io.StringIO()
- self.assertEqual(serve_stdio(server, stdin=stdin, stdout=stdout, stderr=stderr), 0)
- lines = [line for line in stdout.getvalue().splitlines() if line]
- self.assertEqual(len(lines), 2)
- init_response = json.loads(lines[0])
- list_response = json.loads(lines[1])
- self.assertEqual(init_response["id"], 1)
- self.assertEqual(list_response["id"], 2)
- self.assertEqual(len(list_response["result"]["tools"]), 5)
-
- def test_serve_stdio_returns_parse_error_for_invalid_json(self):
- with tempfile.TemporaryDirectory() as tmp:
- server = MCPServer(vault=Path(tmp))
- stdin = io.StringIO("{not json}\n")
- stdout = io.StringIO()
- self.assertEqual(serve_stdio(server, stdin=stdin, stdout=stdout, stderr=io.StringIO()), 0)
- response = json.loads(stdout.getvalue().splitlines()[0])
- self.assertEqual(response["error"]["code"], -32700)
-
- def test_serve_stdio_returns_invalid_request_for_batch_request(self):
- with tempfile.TemporaryDirectory() as tmp:
- server = MCPServer(vault=Path(tmp))
- batch = json.dumps(
- [
- {"jsonrpc": JSONRPC_VERSION, "id": 1, "method": "ping"},
- {"jsonrpc": JSONRPC_VERSION, "id": 2, "method": "ping"},
- ]
- )
- stdin = io.StringIO(batch + "\n")
- stdout = io.StringIO()
- self.assertEqual(serve_stdio(server, stdin=stdin, stdout=stdout, stderr=io.StringIO()), 0)
- response = json.loads(stdout.getvalue().splitlines()[0])
- self.assertEqual(response["error"]["code"], -32600)
- self.assertIn("batch", response["error"]["message"].lower())
-
-
-class CliIntegrationTests(unittest.TestCase):
- def test_o2b_mcp_subcommand_serves_stdio(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp) / "vault"
- vault.mkdir()
- payload = "\n".join(
- [
- json.dumps(
- {
- "jsonrpc": JSONRPC_VERSION,
- "id": 1,
- "method": "initialize",
- "params": {
- "protocolVersion": PROTOCOL_VERSION,
- "capabilities": {},
- "clientInfo": {"name": "t", "version": "0"},
- },
- }
- ),
- json.dumps({"jsonrpc": JSONRPC_VERSION, "method": "notifications/initialized"}),
- json.dumps({"jsonrpc": JSONRPC_VERSION, "id": 2, "method": "tools/list"}),
- ]
- ) + "\n"
- result = subprocess.run(
- [
- sys.executable,
- "-m",
- "open_second_brain.cli",
- "mcp",
- "--vault",
- str(vault),
- ],
- cwd=ROOT,
- input=payload,
- env=ENV,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=15,
- )
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("listening on stdio", result.stderr)
- lines = [line for line in result.stdout.splitlines() if line]
- self.assertEqual(len(lines), 2)
- tools_response = json.loads(lines[1])
- self.assertEqual(tools_response["id"], 2)
- tool_names = {tool["name"] for tool in tools_response["result"]["tools"]}
- self.assertIn("second_brain_status", tool_names)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_openclaw_plugin.py b/tests/test_openclaw_plugin.py
deleted file mode 100644
index ece41166..00000000
--- a/tests/test_openclaw_plugin.py
+++ /dev/null
@@ -1,308 +0,0 @@
-"""Tests for OpenClaw plugin compatibility (openclaw.plugin.json and package.json)."""
-
-import json
-import tempfile
-import unittest
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[1]
-
-from open_second_brain.doctor import check_openclaw_manifest, check_openclaw_installability
-from open_second_brain.mcp import MCPServer
-
-from tests.fixtures import create_plugin_repo
-
-
-class OpenClawManifestValidityTests(unittest.TestCase):
- """Validate the shipped openclaw.plugin.json."""
-
- @classmethod
- def setUpClass(cls):
- cls.manifest_path = ROOT / "openclaw.plugin.json"
- with cls.manifest_path.open("r", encoding="utf-8") as f:
- cls.manifest = json.load(f)
-
- def test_manifest_is_valid_json(self):
- self.assertIsInstance(self.manifest, dict)
-
- def test_manifest_has_required_id(self):
- self.assertEqual(self.manifest["id"], "open-second-brain")
-
- def test_manifest_has_config_schema(self):
- schema = self.manifest["configSchema"]
- self.assertIsInstance(schema, dict)
- self.assertEqual(schema["type"], "object")
-
- def test_manifest_has_version(self):
- from open_second_brain import __version__
-
- self.assertEqual(self.manifest["version"], __version__)
-
- def test_manifest_declares_tools(self):
- tools = self.manifest["contracts"]["tools"]
- self.assertIsInstance(tools, list)
- expected = {
- "second_brain_status",
- "second_brain_query",
- "second_brain_capture",
- "event_log_append",
- "vault_health",
- }
- self.assertEqual(set(tools), expected)
-
- def test_manifest_tool_names_match_mcp_server(self):
- """Every tool declared in openclaw.plugin.json must exist in the MCP server."""
- with tempfile.TemporaryDirectory() as tmp:
- server = MCPServer(vault=Path(tmp))
- mcp_tools = set(server._tools.keys())
- manifest_tools = set(self.manifest["contracts"]["tools"])
- self.assertEqual(
- manifest_tools,
- mcp_tools,
- f"OpenClaw manifest tools {manifest_tools} do not match MCP tools {mcp_tools}",
- )
-
- def test_manifest_has_activation(self):
- self.assertIn("activation", self.manifest)
- self.assertTrue(self.manifest["activation"].get("onStartup"))
-
- def test_manifest_has_skills(self):
- self.assertIn("skills", self.manifest)
- self.assertIsInstance(self.manifest["skills"], list)
-
- def test_manifest_has_ui_hints(self):
- self.assertIn("uiHints", self.manifest)
- self.assertIn("vault", self.manifest["uiHints"])
-
- def test_manifest_mcp_enabled_default_false(self):
- mcp_prop = self.manifest["configSchema"]["properties"]["mcpEnabled"]
- self.assertFalse(mcp_prop.get("default", True))
-
- def test_manifest_declares_timezone_field(self):
- # OpenClaw's native plugin entry reads timezone from
- # api.pluginConfig.timezone (set via openclaw config set), with
- # fallback to VAULT_TIMEZONE env. The configSchema must declare
- # the field as a string so OpenClaw accepts it as a settable
- # value, and uiHints must label it so the field surfaces in the
- # config UI alongside agentName / vault.
- tz_prop = self.manifest["configSchema"]["properties"].get("timezone")
- self.assertIsNotNone(tz_prop, "configSchema is missing timezone field")
- self.assertEqual(tz_prop["type"], "string")
- tz_hint = self.manifest["uiHints"].get("timezone")
- self.assertIsNotNone(tz_hint, "uiHints is missing timezone entry")
- self.assertIn("label", tz_hint)
- self.assertIn("help", tz_hint)
-
-
-class OpenClawManifestDoctorTests(unittest.TestCase):
- """Test the doctor check for openclaw.plugin.json."""
-
- def test_doctor_passes_on_valid_manifest(self):
- with tempfile.TemporaryDirectory() as tmp:
- repo = create_plugin_repo(Path(tmp), valid=True)
- result = check_openclaw_manifest(repo / "openclaw.plugin.json")
- self.assertTrue(result.ok, result.message)
- self.assertEqual(result.name, "openclaw_manifest")
-
- def test_doctor_fails_on_missing_manifest(self):
- with tempfile.TemporaryDirectory() as tmp:
- result = check_openclaw_manifest(Path(tmp) / "missing.json")
- self.assertFalse(result.ok)
- self.assertEqual(result.name, "openclaw_manifest")
-
- def test_doctor_fails_on_empty_manifest(self):
- with tempfile.TemporaryDirectory() as tmp:
- manifest = Path(tmp) / "openclaw.plugin.json"
- manifest.write_text("{}", encoding="utf-8")
- result = check_openclaw_manifest(manifest)
- self.assertFalse(result.ok)
- self.assertIn("field 'id'", result.message)
-
- def test_doctor_fails_on_missing_config_schema(self):
- with tempfile.TemporaryDirectory() as tmp:
- manifest = Path(tmp) / "openclaw.plugin.json"
- manifest.write_text(
- json.dumps({"id": "test-plugin"}),
- encoding="utf-8",
- )
- result = check_openclaw_manifest(manifest)
- self.assertFalse(result.ok)
- self.assertIn("configSchema", result.message)
-
- def test_doctor_passes_on_real_repo_manifest(self):
- result = check_openclaw_manifest(ROOT / "openclaw.plugin.json")
- self.assertTrue(result.ok, result.message)
-
-
-class OpenClawPackageJsonTests(unittest.TestCase):
- """Validate the shipped package.json for OpenClaw native plugin compatibility."""
-
- @classmethod
- def setUpClass(cls):
- cls.pkg_path = ROOT / "package.json"
- with cls.pkg_path.open("r", encoding="utf-8") as f:
- cls.pkg = json.load(f)
-
- def test_package_json_is_valid_json(self):
- self.assertIsInstance(self.pkg, dict)
-
- def test_package_json_has_name(self):
- self.assertEqual(self.pkg["name"], "open-second-brain")
-
- def test_package_json_has_version(self):
- from open_second_brain import __version__
-
- self.assertEqual(self.pkg["version"], __version__)
-
- def test_package_json_has_type_module(self):
- self.assertEqual(self.pkg["type"], "module")
-
- def test_package_json_has_openclaw_extensions(self):
- extensions = self.pkg["openclaw"]["extensions"]
- self.assertIsInstance(extensions, list)
- self.assertGreater(len(extensions), 0)
-
- def test_package_json_extension_entries_exist(self):
- for entry in self.pkg["openclaw"]["extensions"]:
- entry_path = ROOT / entry
- self.assertTrue(entry_path.is_file(), f"Missing extension entry: {entry}")
-
- def test_package_json_has_no_dependencies(self):
- """The package must not declare dependencies β€” it imports from the host at runtime."""
- self.assertNotIn("dependencies", self.pkg)
-
-
-class OpenClawInstallabilityDoctorTests(unittest.TestCase):
- """Test check_openclaw_installability doctor checks."""
-
- def test_passes_on_real_repo(self):
- results = check_openclaw_installability(ROOT)
- for r in results:
- self.assertTrue(r.ok, f"{r.name}: {r.message}")
-
- def test_fails_on_missing_package_json(self):
- with tempfile.TemporaryDirectory() as tmp:
- repo = Path(tmp)
- # No package.json
- results = check_openclaw_installability(repo)
- self.assertFalse(results[0].ok)
- self.assertEqual(results[0].name, "openclaw_package_json")
-
- def test_fails_on_package_json_without_extensions(self):
- with tempfile.TemporaryDirectory() as tmp:
- repo = Path(tmp)
- (repo / "package.json").write_text(
- json.dumps({"name": "test"}),
- encoding="utf-8",
- )
- results = check_openclaw_installability(repo)
- # First check (package.json exists) passes
- self.assertTrue(results[0].ok)
- # Second check (extensions) fails
- self.assertFalse(results[1].ok)
- self.assertIn("extensions", results[1].message)
-
- def test_fails_on_missing_extension_file(self):
- with tempfile.TemporaryDirectory() as tmp:
- repo = Path(tmp)
- (repo / "package.json").write_text(
- json.dumps({"openclaw": {"extensions": ["./nonexistent.js"]}}),
- encoding="utf-8",
- )
- results = check_openclaw_installability(repo)
- # First two checks pass
- self.assertTrue(results[0].ok)
- self.assertTrue(results[1].ok)
- # Entry file check fails
- self.assertFalse(results[2].ok)
- self.assertIn("nonexistent.js", results[2].message)
-
-
-class OpenClawInstallabilityTests(unittest.TestCase):
- """Invariants required for `openclaw plugins install` to succeed."""
-
- @classmethod
- def setUpClass(cls):
- cls.manifest_path = ROOT / "openclaw.plugin.json"
-
- def test_manifest_file_exists_at_project_root(self):
- self.assertTrue(self.manifest_path.is_file())
-
- def test_manifest_is_parseable_json(self):
- data = json.loads(self.manifest_path.read_text(encoding="utf-8"))
- self.assertIn("id", data)
-
- def test_package_json_exists_at_project_root(self):
- self.assertTrue((ROOT / "package.json").is_file())
-
- def test_bundle_adapter_claude_exists(self):
- """OpenClaw Bundle format auto-detects .claude-plugin/."""
- self.assertTrue((ROOT / ".claude-plugin" / "plugin.json").is_file())
-
- def test_bundle_adapter_codex_exists(self):
- """OpenClaw Bundle format auto-detects .codex-plugin/."""
- self.assertTrue((ROOT / ".codex-plugin" / "plugin.json").is_file())
-
- def test_openclaw_entry_js_exists(self):
- """The JS entry declared in package.json must exist."""
- self.assertTrue((ROOT / "openclaw" / "index.js").is_file())
-
- def test_openclaw_vault_js_exists(self):
- """The pure JS vault module must exist."""
- self.assertTrue((ROOT / "openclaw" / "vault.js").is_file())
-
- def test_openclaw_event_log_js_exists(self):
- """The pure JS event-log module must exist."""
- self.assertTrue((ROOT / "openclaw" / "event-log.js").is_file())
-
-
-class OpenClawSecurityTests(unittest.TestCase):
- """Verify that the OpenClaw JS entry contains no subprocess calls."""
-
- @classmethod
- def setUpClass(cls):
- cls.index_js = (ROOT / "openclaw" / "index.js").read_text(encoding="utf-8")
- cls.vault_js = (ROOT / "openclaw" / "vault.js").read_text(encoding="utf-8")
- cls.event_log_js = (ROOT / "openclaw" / "event-log.js").read_text(encoding="utf-8")
-
- def test_index_js_no_child_process_import(self):
- """index.js must not import child_process."""
- self.assertNotIn("child_process", self.index_js)
-
- def test_index_js_no_exec_file(self):
- """index.js must not call execFile."""
- self.assertNotIn("execFile", self.index_js)
-
- def test_index_js_no_exec(self):
- """index.js must not call exec (subprocess)."""
- for line in self.index_js.splitlines():
- stripped = line.strip()
- # Skip method definitions like "async execute()" and "async execute(_id, params)"
- if stripped.startswith("async execute("):
- continue
- # Look for standalone exec calls (not .exec() on regex)
- if "exec" in stripped.lower() and ".exec(" not in stripped:
- self.fail(f"Found subprocess-like 'exec' in index.js: {stripped}")
-
- def test_index_js_no_spawn(self):
- """index.js must not call spawn."""
- self.assertNotIn("spawn", self.index_js)
-
- def test_vault_js_no_child_process(self):
- """vault.js must not import child_process."""
- self.assertNotIn("child_process", self.vault_js)
-
- def test_event_log_js_no_child_process(self):
- """event-log.js must not import child_process."""
- self.assertNotIn("child_process", self.event_log_js)
-
- def test_runner_js_deleted(self):
- """o2b-runner.js must no longer exist."""
- self.assertFalse(
- (ROOT / "openclaw" / "o2b-runner.js").exists(),
- "openclaw/o2b-runner.js should have been deleted",
- )
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_uninstall.py b/tests/test_uninstall.py
deleted file mode 100644
index ccd41b09..00000000
--- a/tests/test_uninstall.py
+++ /dev/null
@@ -1,328 +0,0 @@
-import os
-import re
-import sys
-import tempfile
-import textwrap
-import unittest
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(ROOT / "src"))
-
-from open_second_brain.uninstall import (
- HERMES_COMMANDS,
- PLUGIN_NAME,
- SAFE_CONFIG_DIR_NAMES,
- plan_uninstall,
- render_plan,
-)
-from tests.test_cli import run_cli
-
-
-class HermesCommandsTests(unittest.TestCase):
- def test_hermes_commands_match_documented_form(self):
- self.assertEqual(
- HERMES_COMMANDS,
- (
- f"hermes mcp remove {PLUGIN_NAME}",
- f"hermes plugins remove {PLUGIN_NAME}",
- "hermes gateway restart",
- ),
- )
-
- def test_hermes_commands_do_not_use_quoted_args_blob(self):
- for cmd in HERMES_COMMANDS:
- self.assertNotIn("'", cmd)
- self.assertNotIn('"', cmd)
- self.assertNotIn("--args ", cmd)
-
-
-class PlanUninstallTests(unittest.TestCase):
- def test_dry_run_does_not_remove_config_directory(self):
- with tempfile.TemporaryDirectory() as tmp:
- config_dir = Path(tmp) / "open-second-brain"
- config_dir.mkdir()
- config = config_dir / "config.yaml"
- config.write_text("vault_path: /vault/example\n", encoding="utf-8")
- other = config_dir / "snapshot.json"
- other.write_text("{}", encoding="utf-8")
-
- plan = plan_uninstall(config_path=config, apply_local=False)
-
- self.assertFalse(plan.apply_local)
- self.assertTrue(config.exists())
- self.assertTrue(other.exists())
- self.assertTrue(config_dir.is_dir())
- self.assertEqual(plan.removed_paths, ())
- self.assertEqual(plan.skipped_paths, ())
- self.assertEqual(plan.config_dir, config_dir)
- self.assertTrue(plan.config_dir_exists)
- self.assertEqual(plan.vault_path, Path("/vault/example"))
-
- def test_dry_run_records_missing_config(self):
- with tempfile.TemporaryDirectory() as tmp:
- config = Path(tmp) / "open-second-brain" / "missing.yaml"
-
- plan = plan_uninstall(config_path=config, apply_local=False)
-
- self.assertFalse(plan.config_exists)
- self.assertFalse(plan.config_dir_exists)
- self.assertEqual(plan.removed_paths, ())
-
- def test_apply_local_removes_only_named_config_directory(self):
- with tempfile.TemporaryDirectory() as tmp:
- config_dir = Path(tmp) / "open-second-brain"
- config_dir.mkdir()
- (config_dir / "config.yaml").write_text("instance: x\n", encoding="utf-8")
- (config_dir / "snapshots").mkdir()
- (config_dir / "snapshots" / "old.json").write_text("{}", encoding="utf-8")
-
- plan = plan_uninstall(config_path=config_dir / "config.yaml", apply_local=True)
-
- self.assertTrue(plan.apply_local)
- self.assertFalse(config_dir.exists())
- self.assertEqual(plan.removed_paths, (config_dir,))
- self.assertEqual(plan.skipped_paths, ())
- self.assertEqual(plan.errors, ())
-
- def test_apply_local_refuses_unknown_directory_name(self):
- with tempfile.TemporaryDirectory() as tmp:
- config_dir = Path(tmp) / "etc"
- config_dir.mkdir()
- payload = config_dir / "important.yaml"
- payload.write_text("vault_path: /vault\n", encoding="utf-8")
-
- plan = plan_uninstall(config_path=payload, apply_local=True)
-
- self.assertTrue(config_dir.exists())
- self.assertTrue(payload.exists())
- self.assertEqual(plan.removed_paths, ())
- self.assertEqual(len(plan.skipped_paths), 1)
- skipped_path, reason = plan.skipped_paths[0]
- self.assertEqual(skipped_path, config_dir)
- self.assertIn("not a recognized", reason)
-
- def test_apply_local_refuses_paths_inside_hermes(self):
- with tempfile.TemporaryDirectory() as tmp:
- hermes_root = Path(tmp) / ".hermes"
- config_dir = hermes_root / "open-second-brain"
- config_dir.mkdir(parents=True)
- payload = config_dir / "config.yaml"
- payload.write_text("vault_path: /vault\n", encoding="utf-8")
-
- plan = plan_uninstall(config_path=payload, apply_local=True)
-
- self.assertTrue(config_dir.exists())
- self.assertTrue(payload.exists())
- self.assertEqual(plan.removed_paths, ())
- self.assertEqual(len(plan.skipped_paths), 1)
- _, reason = plan.skipped_paths[0]
- self.assertIn("Hermes", reason)
-
- def test_apply_local_refuses_git_repository(self):
- with tempfile.TemporaryDirectory() as tmp:
- config_dir = Path(tmp) / "open-second-brain"
- config_dir.mkdir()
- (config_dir / ".git").mkdir()
- payload = config_dir / "config.yaml"
- payload.write_text("instance: x\n", encoding="utf-8")
-
- plan = plan_uninstall(config_path=payload, apply_local=True)
-
- self.assertTrue(config_dir.exists())
- self.assertEqual(plan.removed_paths, ())
- self.assertEqual(len(plan.skipped_paths), 1)
- _, reason = plan.skipped_paths[0]
- self.assertIn("git", reason)
-
- def test_apply_local_skips_when_config_dir_missing(self):
- with tempfile.TemporaryDirectory() as tmp:
- payload = Path(tmp) / "open-second-brain" / "config.yaml"
-
- plan = plan_uninstall(config_path=payload, apply_local=True)
-
- self.assertEqual(plan.removed_paths, ())
- self.assertEqual(len(plan.skipped_paths), 1)
- _, reason = plan.skipped_paths[0]
- self.assertIn("does not exist", reason)
-
-
-class VaultSafetyTests(unittest.TestCase):
- def test_apply_local_never_touches_vault(self):
- with tempfile.TemporaryDirectory() as tmp:
- tmp_path = Path(tmp)
- vault = tmp_path / "vault"
- (vault / "AI Wiki").mkdir(parents=True)
- (vault / "Daily").mkdir(parents=True)
- (vault / "AI Wiki" / "page.md").write_text("# Page\n", encoding="utf-8")
- (vault / "Daily" / "2026.05.06.md").write_text("# Daily\n", encoding="utf-8")
-
- config_dir = tmp_path / "open-second-brain"
- config_dir.mkdir()
- config = config_dir / "config.yaml"
- config.write_text(f"vault_path: {vault}\n", encoding="utf-8")
-
- plan_uninstall(config_path=config, apply_local=True)
-
- self.assertTrue(vault.is_dir())
- self.assertTrue((vault / "AI Wiki" / "page.md").is_file())
- self.assertTrue((vault / "Daily" / "2026.05.06.md").is_file())
-
- def test_apply_local_never_touches_hermes_config_file(self):
- with tempfile.TemporaryDirectory() as tmp:
- tmp_path = Path(tmp)
- hermes_dir = tmp_path / ".hermes"
- hermes_dir.mkdir()
- hermes_config = hermes_dir / "config.yaml"
- hermes_payload = textwrap.dedent(
- """
- mcp_servers:
- open-second-brain:
- command: o2b
- args: ["mcp", "--vault", "/vault"]
- """
- ).strip() + "\n"
- hermes_config.write_text(hermes_payload, encoding="utf-8")
-
- config_dir = tmp_path / "open-second-brain"
- config_dir.mkdir()
- config = config_dir / "config.yaml"
- config.write_text("vault_path: /vault\n", encoding="utf-8")
-
- plan_uninstall(config_path=config, apply_local=True)
-
- self.assertTrue(hermes_config.is_file())
- self.assertEqual(hermes_config.read_text(encoding="utf-8"), hermes_payload)
-
-
-class RenderPlanTests(unittest.TestCase):
- def _basic_plan(self, *, apply_local: bool, tmp_path: Path) -> str:
- config_dir = tmp_path / "open-second-brain"
- config_dir.mkdir()
- config = config_dir / "config.yaml"
- config.write_text("vault_path: /vault/here\n", encoding="utf-8")
-
- plan = plan_uninstall(config_path=config, apply_local=apply_local)
- return render_plan(plan)
-
- def test_rendered_plan_includes_hermes_commands(self):
- with tempfile.TemporaryDirectory() as tmp:
- text = self._basic_plan(apply_local=False, tmp_path=Path(tmp))
- for cmd in HERMES_COMMANDS:
- self.assertIn(cmd, text)
-
- def test_rendered_plan_states_vault_is_preserved(self):
- with tempfile.TemporaryDirectory() as tmp:
- text = self._basic_plan(apply_local=False, tmp_path=Path(tmp))
- self.assertRegex(text, r"Vault \(NEVER removed by this tool\)")
- self.assertIn("Daily/", text)
- self.assertIn("AI Wiki/", text)
-
- def test_rendered_plan_states_hermes_config_is_not_edited(self):
- with tempfile.TemporaryDirectory() as tmp:
- text = self._basic_plan(apply_local=False, tmp_path=Path(tmp))
- self.assertIn("~/.hermes/config.yaml", text)
- self.assertIn("never edits", text)
-
- def test_rendered_plan_marks_dry_run(self):
- with tempfile.TemporaryDirectory() as tmp:
- text = self._basic_plan(apply_local=False, tmp_path=Path(tmp))
- self.assertIn("dry-run", text)
-
- def test_rendered_plan_marks_apply_local(self):
- with tempfile.TemporaryDirectory() as tmp:
- text = self._basic_plan(apply_local=True, tmp_path=Path(tmp))
- self.assertIn("apply-local", text)
-
-
-class CliUninstallTests(unittest.TestCase):
- def test_cli_dry_run_does_not_modify_filesystem(self):
- with tempfile.TemporaryDirectory() as tmp:
- tmp_path = Path(tmp)
- config_dir = tmp_path / "open-second-brain"
- config_dir.mkdir()
- config = config_dir / "config.yaml"
- config.write_text("vault_path: /vault\n", encoding="utf-8")
-
- result = run_cli("uninstall", "--config", str(config))
-
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("Uninstall plan", result.stdout)
- self.assertIn("dry-run", result.stdout)
- self.assertIn("hermes mcp remove open-second-brain", result.stdout)
- self.assertIn("hermes plugins remove open-second-brain", result.stdout)
- self.assertIn("hermes gateway restart", result.stdout)
- self.assertIn("NEVER removed by this tool", result.stdout)
- self.assertTrue(config.exists())
- self.assertTrue(config_dir.is_dir())
-
- def test_cli_apply_local_removes_only_local_config_dir(self):
- with tempfile.TemporaryDirectory() as tmp:
- tmp_path = Path(tmp)
- vault = tmp_path / "vault"
- (vault / "Daily").mkdir(parents=True)
- (vault / "Daily" / "2026.05.06.md").write_text("vault content", encoding="utf-8")
-
- config_dir = tmp_path / "open-second-brain"
- config_dir.mkdir()
- config = config_dir / "config.yaml"
- config.write_text(f"vault_path: {vault}\n", encoding="utf-8")
-
- result = run_cli("uninstall", "--config", str(config), "--apply-local")
-
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("apply-local", result.stdout)
- self.assertFalse(config_dir.exists())
- self.assertTrue(vault.is_dir())
- self.assertTrue((vault / "Daily" / "2026.05.06.md").is_file())
-
- def test_cli_apply_local_refuses_when_config_dir_name_unknown(self):
- with tempfile.TemporaryDirectory() as tmp:
- tmp_path = Path(tmp)
- config_dir = tmp_path / "etc"
- config_dir.mkdir()
- (config_dir / "very-important.yaml").write_text("keep-me\n", encoding="utf-8")
- config = config_dir / "config.yaml"
- config.write_text("vault_path: /vault\n", encoding="utf-8")
-
- result = run_cli("uninstall", "--config", str(config), "--apply-local")
-
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("skipped", result.stdout)
- self.assertTrue(config_dir.is_dir())
- self.assertTrue((config_dir / "very-important.yaml").is_file())
-
- def test_cli_uses_open_second_brain_config_env(self):
- with tempfile.TemporaryDirectory() as tmp:
- tmp_path = Path(tmp)
- config_dir = tmp_path / "open-second-brain"
- config_dir.mkdir()
- config = config_dir / "config.yaml"
- config.write_text("vault_path: /env/vault\n", encoding="utf-8")
-
- result = run_cli(
- "uninstall",
- env={"OPEN_SECOND_BRAIN_CONFIG": str(config)},
- )
-
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn(str(config), result.stdout)
- self.assertIn("/env/vault", result.stdout)
-
- def test_cli_help_documents_safety_invariants(self):
- result = run_cli("uninstall", "--help")
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertIn("never touches", result.stdout)
- self.assertIn("vault", result.stdout.lower())
-
-
-class SafeNamesTests(unittest.TestCase):
- def test_safe_names_only_contain_canonical_open_second_brain_names(self):
- self.assertEqual(
- SAFE_CONFIG_DIR_NAMES,
- frozenset({"open-second-brain", "open_second_brain"}),
- )
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_vault.py b/tests/test_vault.py
deleted file mode 100644
index 846f30e7..00000000
--- a/tests/test_vault.py
+++ /dev/null
@@ -1,134 +0,0 @@
-import tempfile
-import unittest
-from pathlib import Path
-
-from open_second_brain.vault import (
- extract_wikilinks,
- list_vault_pages,
- parse_frontmatter,
- write_frontmatter,
-)
-
-
-class VaultTests(unittest.TestCase):
- def test_parse_frontmatter_extracts_fields(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "note.md"
- path.write_text(
- "---\ntitle: Hello World\ntags: test, example\n---\n\nBody text.\n",
- encoding="utf-8",
- )
- meta, body = parse_frontmatter(path)
- self.assertEqual(meta["title"], "Hello World")
- self.assertEqual(meta["tags"], "test, example")
- self.assertEqual(body, "Body text.")
-
- def test_parse_frontmatter_no_frontmatter(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "note.md"
- path.write_text("Just a note.", encoding="utf-8")
- meta, body = parse_frontmatter(path)
- self.assertEqual(meta, {})
- self.assertEqual(body, "Just a note.")
-
- def test_parse_frontmatter_missing_file(self):
- meta, body = parse_frontmatter(Path("/nonexistent/file.md"))
- self.assertEqual(meta, {})
- self.assertEqual(body, "")
-
- def test_write_frontmatter_roundtrip(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "note.md"
- write_frontmatter(path, {"title": "Roundtrip"}, "The body.")
- meta, body = parse_frontmatter(path)
- self.assertEqual(meta["title"], "Roundtrip")
- self.assertEqual(body, "The body.")
-
- def test_write_frontmatter_serializes_list_values_as_inline_array(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "note.md"
- write_frontmatter(
- path,
- {"title": "Tagged", "tags": ["draft", "demo"]},
- "Body.",
- )
- text = path.read_text(encoding="utf-8")
- self.assertIn("tags: [draft, demo]", text)
-
- def test_write_frontmatter_quotes_list_values_with_special_chars(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "note.md"
- write_frontmatter(
- path,
- {"tags": ["plain", "needs, comma"]},
- "Body.",
- )
- text = path.read_text(encoding="utf-8")
- self.assertIn('tags: [plain, "needs, comma"]', text)
-
- def test_write_frontmatter_quotes_scalar_with_colon_space(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "note.md"
- write_frontmatter(path, {"title": "Hello: world"}, "Body.")
- text = path.read_text(encoding="utf-8")
- self.assertIn('title: "Hello: world"', text)
-
- def test_write_frontmatter_escapes_control_characters(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "note.md"
- write_frontmatter(path, {"summary": "line one\nline two"}, "Body.")
- text = path.read_text(encoding="utf-8")
- self.assertIn(r'summary: "line one\nline two"', text)
-
- def test_extract_wikilinks_simple(self):
- content = "See [[Target]] and [[Other]] for details."
- links = extract_wikilinks(content)
- self.assertEqual(links, ["Target", "Other"])
-
- def test_extract_wikilinks_ignores_media(self):
- content = "Look at ![[photo.png]] and [[concept]]."
- links = extract_wikilinks(content)
- self.assertEqual(links, ["concept"])
-
- def test_extract_wikilinks_ignores_code_blocks(self):
- content = "```\n[[not-a-link]]\n```\nReal: [[real-link]]"
- links = extract_wikilinks(content)
- self.assertEqual(links, ["real-link"])
-
- def test_extract_wikilinks_deduplicates(self):
- content = "[[A]] [[A]] [[B]]"
- links = extract_wikilinks(content)
- self.assertEqual(links, ["A", "B"])
-
- def test_list_vault_pages_discovers_markdown(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- (vault / "page1.md").write_text("---\ntitle: Alpha\n---\n\nContent.", encoding="utf-8")
- (vault / "page2.md").write_text("Beta content without frontmatter.", encoding="utf-8")
- pages = list_vault_pages(vault)
- self.assertEqual(len(pages), 2)
- titles = [t for t, _, _ in pages]
- self.assertIn("Alpha", titles)
- self.assertIn("page2", titles) # stem, no frontmatter title
-
- def test_list_vault_pages_skips_excluded_dirs(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- (vault / "page.md").write_text("Content.", encoding="utf-8")
- (vault / ".obsidian").mkdir()
- (vault / ".obsidian" / "hidden.md").write_text("Hidden.", encoding="utf-8")
- pages = list_vault_pages(vault)
- self.assertEqual(len(pages), 1)
-
- def test_list_vault_pages_skips_excluded_files(self):
- with tempfile.TemporaryDirectory() as tmp:
- vault = Path(tmp)
- (vault / "page.md").write_text("Content.", encoding="utf-8")
- (vault / "index.md").write_text("Index.", encoding="utf-8")
- pages = list_vault_pages(vault)
- self.assertEqual(len(pages), 1)
- self.assertEqual(pages[0][0], "page")
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/test_version.py b/tests/test_version.py
deleted file mode 100644
index 786b6015..00000000
--- a/tests/test_version.py
+++ /dev/null
@@ -1,83 +0,0 @@
-"""Lock the contract that ``__version__`` reads from ``pyproject.toml``.
-
-The package version is the single source of truth in ``pyproject.toml``.
-Several other files (manifests, package.json) carry a synced copy and are
-kept aligned by ``scripts/sync-version.py``. These tests guard the two
-properties that matter:
-
- - ``open_second_brain.__version__`` matches the canonical value in
- ``pyproject.toml`` (so a bump there is visible at runtime without a
- pip reinstall).
- - ``MCPServer`` advertises the same value in its ``serverInfo.version``.
- - The synced manifests (root ``plugin.yaml`` etc.) all carry the same
- string β€” i.e. nothing has drifted in the working tree.
-"""
-
-import json
-import re
-import tomllib
-import unittest
-from pathlib import Path
-
-from open_second_brain import __version__
-from open_second_brain.mcp import SERVER_VERSION
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-def _canonical_version() -> str:
- with (ROOT / "pyproject.toml").open("rb") as fh:
- return tomllib.load(fh)["project"]["version"]
-
-
-class VersionResolutionTests(unittest.TestCase):
- def test_package_version_matches_pyproject(self):
- self.assertEqual(__version__, _canonical_version())
-
- def test_mcp_server_version_matches_package(self):
- self.assertEqual(SERVER_VERSION, __version__)
-
-
-class ManifestVersionSyncTests(unittest.TestCase):
- """Re-implement the read part of ``scripts/sync-version.py`` to assert
- that every manifest in the working tree currently equals the canonical
- version. If this fails, ``python3 scripts/sync-version.py`` from the
- repo root will fix it.
- """
-
- def setUp(self):
- self.canonical = _canonical_version()
-
- def _read_yaml_version(self, rel: str) -> str:
- text = (ROOT / rel).read_text(encoding="utf-8")
- match = re.search(r'^version:\s*"([^"]+)"', text, re.MULTILINE)
- self.assertIsNotNone(match, f"no version line in {rel}")
- return match.group(1)
-
- def _read_json_version(self, rel: str) -> str:
- data = json.loads((ROOT / rel).read_text(encoding="utf-8"))
- version = data.get("version")
- self.assertIsInstance(version, str, f"no version key in {rel}")
- return version
-
- def test_root_plugin_yaml(self):
- self.assertEqual(self._read_yaml_version("plugin.yaml"), self.canonical)
-
- def test_inner_plugins_hermes_yaml(self):
- self.assertEqual(self._read_yaml_version("plugins/hermes/plugin.yaml"), self.canonical)
-
- def test_package_json(self):
- self.assertEqual(self._read_json_version("package.json"), self.canonical)
-
- def test_claude_plugin_json(self):
- self.assertEqual(self._read_json_version(".claude-plugin/plugin.json"), self.canonical)
-
- def test_codex_plugin_json(self):
- self.assertEqual(self._read_json_version(".codex-plugin/plugin.json"), self.canonical)
-
- def test_openclaw_plugin_json(self):
- self.assertEqual(self._read_json_version("openclaw.plugin.json"), self.canonical)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/version.test.ts b/tests/version.test.ts
new file mode 100644
index 00000000..7c270fb7
--- /dev/null
+++ b/tests/version.test.ts
@@ -0,0 +1,66 @@
+/**
+ * Lock the contract that all manifests carry the same version.
+ *
+ * Single source of truth: `package.json` `version`. Other files (Hermes
+ * plugin.yaml, OpenClaw manifest, Claude/Codex plugin manifests, pyproject.toml)
+ * carry a synced copy and are kept aligned by `scripts/sync-version.ts`.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { SERVER_VERSION } from "../src/mcp/protocol.ts";
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+
+function canonicalVersion(): string {
+ return JSON.parse(readFileSync(`${ROOT}/package.json`, "utf8")).version;
+}
+
+function readYamlVersion(rel: string): string {
+ const text = readFileSync(`${ROOT}/${rel}`, "utf8");
+ const m = text.match(/^version:\s*"([^"]+)"/m);
+ expect(m).not.toBeNull();
+ return m![1]!;
+}
+
+function readJsonVersion(rel: string): string {
+ return JSON.parse(readFileSync(`${ROOT}/${rel}`, "utf8")).version;
+}
+
+function readPyprojectVersion(rel: string): string {
+ const text = readFileSync(`${ROOT}/${rel}`, "utf8");
+ const m = text.match(/^version\s*=\s*"([^"]+)"/m);
+ expect(m).not.toBeNull();
+ return m![1]!;
+}
+
+describe("version resolution", () => {
+ test("MCP SERVER_VERSION matches package.json", () => {
+ expect(SERVER_VERSION).toBe(canonicalVersion());
+ });
+});
+
+describe("manifest version sync", () => {
+ const cases = [
+ { kind: "yaml", rel: "plugin.yaml" },
+ { kind: "yaml", rel: "plugins/hermes/plugin.yaml" },
+ { kind: "json", rel: ".claude-plugin/plugin.json" },
+ { kind: "json", rel: ".codex-plugin/plugin.json" },
+ { kind: "json", rel: "openclaw.plugin.json" },
+ { kind: "pyproject", rel: "pyproject.toml" },
+ ] as const;
+
+ for (const { kind, rel } of cases) {
+ test(`${rel} matches canonical`, () => {
+ const expected = canonicalVersion();
+ let actual: string;
+ if (kind === "yaml") actual = readYamlVersion(rel);
+ else if (kind === "json") actual = readJsonVersion(rel);
+ else actual = readPyprojectVersion(rel);
+ expect(actual).toBe(expected);
+ });
+ }
+});
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 00000000..c15eadbc
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,23 @@
+{
+ "compilerOptions": {
+ "lib": ["ES2023"],
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "moduleDetection": "force",
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": true,
+ "noEmit": true,
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "noImplicitOverride": true,
+ "noFallthroughCasesInSwitch": true,
+ "skipLibCheck": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "esModuleInterop": true,
+ "forceConsistentCasingInFileNames": true,
+ "types": ["bun"]
+ },
+ "include": ["src/**/*.ts", "src/**/*.d.ts", "tests/**/*.ts", "scripts/**/*.ts"]
+}