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
feat: timezone support, marketplace manifests, hardened vault resolution, Claude/Codex 2.x compatibility (v0.6.1)
Sol Aitken212c823e1f0d
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.jsonnew file mode 100644index 00000000..61b17977--- /dev/null+++ b/.agents/plugins/marketplace.json@@ -0,0 +1,19 @@+{+ "name": "open-second-brain",+ "interface": {+ "displayName": "Open Second Brain"+ },+ "plugins": [+ {+ "name": "open-second-brain",+ "source": {+ "source": "local",+ "path": "."+ },+ "policy": {+ "installation": "AVAILABLE"+ },+ "category": "Productivity"+ }+ ]+}diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonnew file mode 100644index 00000000..4f250da0--- /dev/null+++ b/.claude-plugin/marketplace.json@@ -0,0 +1,27 @@+{+ "name": "open-second-brain",+ "owner": {+ "name": "itechmeat",+ "url": "https://github.com/itechmeat"+ },+ "metadata": {+ "description": "Open Second Brain marketplace (single self-hosted plugin).",+ "version": "1.0.0"+ },+ "plugins": [+ {+ "name": "open-second-brain",+ "source": "./",+ "description": "Plugin-first second brain for AI agents and humans (Obsidian-compatible Markdown vaults).",+ "category": "knowledge",+ "tags": [+ "second-brain",+ "obsidian",+ "agents",+ "skills",+ "event-log",+ "mcp"+ ]+ }+ ]+}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 77cbe812..72b57019 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,66 +1,19 @@{"name": "open-second-brain",- "version": "0.6.0",+ "version": "0.6.1","description": "Plugin-first second brain package for AI agents and humans.",- "author": "Open Second Brain contributors",+ "author": {+ "name": "Open Second Brain contributors"+ },"license": "MIT","homepage": "https://github.com/itechmeat/open-second-brain","repository": "https://github.com/itechmeat/open-second-brain",- "keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"],- "commands": [- {- "name": "status",- "description": "Show Open Second Brain configuration status.",- "command": "scripts/o2b",- "args": ["status"]- },- {- "name": "doctor",- "description": "Run vault, config, and plugin manifest health checks.",- "command": "scripts/o2b",- "args": ["doctor"]- },- {- "name": "init",- "description": "Initialize a sandbox or production vault profile.",- "command": "scripts/o2b",- "args": ["init"]- },- {- "name": "index",- "description": "Regenerate the vault wiki index from Markdown pages.",- "command": "scripts/o2b",- "args": ["index"]- },- {- "name": "append-event",- "description": "Append an agent event to the daily Markdown event log.",- "command": "scripts/o2b",- "args": ["append-event"]- },- {- "name": "export-config",- "description": "Write a redacted configuration snapshot as JSON.",- "command": "scripts/o2b",- "args": ["export-config"]- },- {- "name": "mcp",- "description": "Run the optional MCP tool server over stdio (JSON-RPC 2.0).",- "command": "scripts/o2b",- "args": ["mcp"]- },- {- "name": "uninstall",- "description": "Print an uninstall plan; --apply-local removes only the machine-local config directory.",- "command": "scripts/o2b",- "args": ["uninstall"]- },- {- "name": "vault-log",- "description": "Compatibility wrapper for appending event log entries.",- "command": "scripts/vault-log",- "args": []- }+ "keywords": [+ "second-brain",+ "obsidian",+ "agents",+ "skills",+ "event-log",+ "mcp"]}diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 51cdde13..059f06ab 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.6.0",+ "version": "0.6.1","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/.mcp.json b/.mcp.jsonnew file mode 100644index 00000000..f9b03c70--- /dev/null+++ b/.mcp.json@@ -0,0 +1,8 @@+{+ "mcpServers": {+ "open-second-brain": {+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",+ "args": ["mcp"]+ }+ }+}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5be2ca0e..9f34301e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,264 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+## [0.6.1] - 2026-05-08++### Added++- `pre_llm_call` hook in the Hermes-side adapter. Each turn the plugin+ injects a compact identity + workflow nudge into the user message β+ the LLM learns its `@agentName` and the contract for+ `event_log_append` (plain message text; the server prepends timestamp+ and identity). Skips injection silently when the agent identity is+ not configured, so the literal `@agent` placeholder never reaches+ the LLM.+- `.claude-plugin/marketplace.json` β single-plugin Claude Code+ marketplace manifest. Claude Code 2.x install flow is+ `claude plugin marketplace add` β `claude plugin install <plugin>@<marketplace>`,+ and the marketplace step expects this catalog file. Without it, the+ install fails with `Marketplace file not found`. Manifest declares+ the repository as a one-plugin marketplace pointing at itself+ (`source: "./"`), so the same Git URL works for every other runtime+ without restructuring.+- `.mcp.json` at the repo root β Claude auto-registers MCP servers+ declared here when the plugin is installed, so users never run+ `claude mcp add` manually. The entry uses `${CLAUDE_PLUGIN_ROOT}` to+ stay portable, and intentionally carries no `--vault` arg or env+ vars: the MCP server reads vault/agent/timezone from the persisted+ plugin config (see `vault` field below). Same `.mcp.json` works on+ every user's machine without per-host customization.+- `o2b init --vault <path>` now also persists the vault path into the+ plugin config (`vault` field, alongside `agent_name` and `timezone`).+ `o2b mcp` invoked without `--vault` (Claude `.mcp.json`+ auto-register, Hermes/Codex MCP entries that omit the flag) reads+ from this field β falling back to `VAULT_DIR` env, then to a clear+ error referencing `o2b init`.+- `config.resolve_vault(config_path)` β public helper, mirroring the+ existing `resolve_agent_name` and `resolve_timezone` shape.+- install.md Branch D is rewritten end-to-end against current Claude+ Code CLI (2.x): step 2 uses `claude plugin marketplace add` plus+ `claude plugin install <plugin>@<marketplace>` (the legacy+ `claude plugins install <git-ref>` form was removed in 2.x); step 5+ collapses to a no-op because Claude auto-registers MCP servers from+ the bundled `.mcp.json`; step 6 verifies via `claude plugin list` and+ `claude mcp list`; step 7 uses the marketplace + plugin update+ commands; step 8 uses the matching uninstall/remove pair.++- `.agents/plugins/marketplace.json` β single-plugin Codex marketplace+ manifest at the repo root. Codex 0.129+ has dropped the legacy+ `codex plugins install <git-ref>` command; the only documented install+ path is `codex plugin marketplace add <source>`, which validates a+ marketplace catalog at this exact location. Without this file the+ install fails with `marketplace root does not contain a supported+ manifest`. The manifest declares the repository as a one-plugin+ marketplace pointing at itself (`path: "."`), so the same Git URL+ that worked for `hermes plugins install` works for the new Codex+ flow without restructuring the repo.+- install.md Branch C is rewritten end-to-end against current Codex CLI+ (0.129+): step 2 uses `codex plugin marketplace add` plus a manual+ `[plugins."open-second-brain@open-second-brain"] enabled = true`+ stanza in `~/.codex/config.toml` (Codex has no `plugin enable`+ subcommand); step 5 uses `codex mcp add ... -- o2b mcp --vault ...`+ with both `VAULT_AGENT_NAME` and `VAULT_TIMEZONE` env vars; step 7+ uses `codex plugin marketplace upgrade`; step 8 uses+ `codex mcp remove` + `codex plugin marketplace remove`. The previous+ text referenced commands (`codex plugins install/update/uninstall`)+ that simply do not exist on current Codex.+- Timezone support for Daily event log entries. The plugin now stamps+ `HH:MM` and the day-file selection in the user's local timezone+ instead of the host's clock β important when the host runs in UTC+ but the user lives in a different zone, or when Daily entries+ straddle midnight in the user's local time. Resolution order:+ `VAULT_TIMEZONE` env var β `timezone` field in the plugin config β+ fallback to system local. Invalid names are silently treated as not+ configured (entries still land, just stamped in server time) so a+ typo never breaks logging.+- `o2b init --timezone <iana-name>` validates the IANA name via stdlib+ `zoneinfo` and persists it to the plugin config alongside+ `agent_name`. Invalid input is rejected before any vault scaffolding+ is written, so a typo cannot leave the install in a half-configured+ state.+- `open_second_brain.config.resolve_agent_name()` and+ `resolve_timezone()` β public helpers used by both the MCP server+ and the Hermes hook so identity and timezone reads stay consistent+ across every runtime / CLI surface.+- `scripts/sync-version.py` β propagates the canonical version from+ `pyproject.toml` into every runtime manifest (`plugin.yaml` Γ 2,+ `package.json`, `.claude-plugin/plugin.json`,+ `.codex-plugin/plugin.json`, `openclaw.plugin.json`). Idempotent;+ ships a `--check` mode for CI drift detection.++### Changed++- `.claude-plugin/plugin.json` modernized to current Claude 2.x schema:+ `author` is now an object (`{ "name": "..." }`) per the docs (Claude+ 2.1.x rejected the legacy string form with `author: Invalid input`),+ and the embedded `commands` array is removed (Claude no longer+ parses in-manifest slash command definitions; they are authored as+ Markdown files under `commands/` at the plugin root if needed).+- `o2b doctor` `claude_manifest` check rewritten to validate the new+ schema. It accepts the modern `author` object form and reports a+ clear error when an old-style `commands` array is present.+- OpenClaw native plugin entry brought to parity with the Python /+ MCP side for the features added in this release. `openclaw/index.js`+ now uses `resolveTimezone(api)` (reads `api.pluginConfig.timezone`,+ falls back to `VAULT_TIMEZONE` env) and a `normalizeAgentArgument`+ helper (strips leading `@`, treats common LLM self-name guesses+ like `agent` / `assistant` / `claude` / `gpt` as "no value" so the+ resolved default identity is used instead). `openclaw/event-log.js`+ `currentDate(tz)` / `currentTime(tz)` use `Intl.DateTimeFormat` so+ Daily entries are stamped in the user's local timezone instead of+ the host's clock β matching the Python `current_date(tz)` /+ `current_time(tz)` behavior. The `appendEvent(...)` signature gains+ a trailing optional `tz` argument; backward-compatible.+ `openclaw.plugin.json` `configSchema` and `uiHints` now declare a+ `timezone` field so OpenClaw users can set it via+ `openclaw config set plugins.entries.open-second-brain.config.timezone "..."`.+- install.md Branch B step 1 corrected: previously claimed the+ OpenClaw native plugin reads timezone from+ `~/.config/open-second-brain/config.yaml`. It does not β the JS+ plugin reads exclusively from `api.pluginConfig` (OpenClaw's own+ per-plugin store, populated by `openclaw config set`). Step 5 now+ includes a fourth `openclaw config set` line for the timezone, and+ the worked example JSON shows `timezone` alongside `agentName`.+- Removed the unused, drifting `PLUGIN_VERSION = "0.6.0"` constant+ from `openclaw/index.js`. The two unused local helpers+ `currentDate()` / `currentTime()` in the same file were also+ deleted (the active versions live in `openclaw/event-log.js` and+ are now timezone-aware).+- Hardened vault resolution across every write-mode CLI entry point.+ Previously `vault-log`, `o2b append-event`, `o2b doctor`,+ `o2b index`, `o2b tool-call`, and `o2b mcp` (the standalone+ `open_second_brain.mcp:main` console script) all fell back to the+ current working directory (`Path(os.environ.get("VAULT_DIR", "."))`)+ when neither `--vault` nor `VAULT_DIR` was set. That fallback was+ silent: an agent invoking `vault-log "..."` from `$HOME` would+ write `~/Daily/<date>.md` instead of the user's actual vault, and+ the success line `appended: Daily/...` gave no signal that the+ entry had landed in the wrong place. Now every one of these entry+ points resolves the vault via `--vault β VAULT_DIR β persisted+ plugin config (vault field)`, and exits with a clear+ `error: no vault configured. Pass --vault ... or run o2b init ...`+ if none of those is set. The shared resolver lives in+ `cli._require_vault`; the `vault-log` and standalone-`o2b mcp`+ paths use the same logic inline because they don't share the cli+ module's argparse setup.+- `vault-log` and `o2b append-event` now print the **absolute** path+ of the appended Daily file (`appended: /abs/.../Daily/<date>.md`),+ not a relative `Daily/<date>.md`. The relative form was the visual+ disguise that hid the silent-cwd-fallback bug above.+- install.md step 1 in every branch is now "Collect installation+ parameters (vault path + agent name + timezone)" β three values+ instead of two. The new "Vault path" subsection tells the+ installer agent how to discover the user's Obsidian vault on the+ target machine: scan common roots (`~/`, `~/Documents/`,+ `~/Sync/`, iCloud paths, Syncthing mounts), look for the+ `.obsidian/` marker subdirectory, list candidates and ask the user+ to pick one, or ask for a path if none are found. The agent must+ confirm the resolved absolute path with the user before passing it+ to `o2b init`. No vault location is hard-coded in the docs β the+ example `/path/to/vault` placeholder remains generic.+- `docs/architecture.md` example config snippet no longer hard-codes+ `/root/vault` / `hermes-vps-agent` / `vps-techmeat`. Replaced with+ generic placeholders so the doc reads correctly on any machine.+- `set_config_value` (`config.py`) is now atomic and stricter:+ contents go through a sibling temp file with `fsync` + `os.replace`,+ so an interrupt during the write leaves either the previous config+ or the new one intact β never a half-written hybrid. Values+ containing characters that the simple parser cannot round-trip+ (`"`, `\\`, `\n`, `\r`) are rejected with a clear `ValueError`+ instead of being silently corrupted on the next read. The fields+ this helper persists (`vault` paths, IANA timezone names, agent+ identifiers) never legitimately contain those characters; the+ rejection is a guardrail against future callers passing arbitrary+ strings through. Surfaced by an autonomous CodeRabbit review pass.+- OpenClaw `resolveTimezone(api)` now validates the candidate against+ `Intl.DateTimeFormat` before returning it. An invalid IANA name in+ `api.pluginConfig.timezone` or `VAULT_TIMEZONE` would otherwise+ crash every `event_log_append` call inside `Intl.DateTimeFormat`+ with `RangeError`. The Python side already had this fallback+ (`config.resolve_timezone` swallows `ZoneInfoNotFoundError`); the+ JS side now matches.+- `o2b doctor`'s `claude_manifest` author check rejects an empty+ `name` (e.g. `{"author": {"name": ""}}`) with the same error+ message used for missing or wrong-typed `author`. Previously+ ``isinstance(author.get("name"), str)`` accepted the empty string.+- The two timezone-aware MCP tests now capture the local-tz wall+ clock **before** invoking the tool. The previous order computed+ `now_local` after the tool returned, which around midnight could+ flake: tool stamps day N, assertion looks for day N+1. Tightened.+- New install.md **Branch E β Generic adapter (other runtimes)**. For+ any runtime not covered by branches AβD (a new MCP-aware client, a+ different agent platform, or a supported runtime after a breaking+ CLI rename), Branch E describes the install **contract** the+ plugin needs β directory layout, `o2b` on PATH, `o2b mcp` registered+ as stdio MCP server, persisted plugin config β instead of literal+ commands. It instructs the installer agent to consult the target+ runtime's own plugin / MCP documentation and translate each step+ into the runtime-specific equivalent, asking the user before+ guessing on any step that has no obvious analogue. The document+ prelude was updated to list E as the fallback option alongside+ AβD.+- "When to log" criteria broadened in both surfaces the LLM sees:+ the per-turn `pre_llm_call` nudge and the MCP server's+ `serverInfo.instructions`. The previous wording only listed concrete+ artifacts (feature/fix/config/instruction-file/content) and instructed+ the LLM to skip "exploration, planning, or pure discussion". This+ caused agents to refuse logging substantial-but-non-tangible work β+ research findings, design decisions, investigations that surfaced+ facts worth recalling. The rules now treat any **durable artifact**+ as loggable, including research outcomes, design decisions, and+ external-fact discoveries (CLI behaviour change, API quirk, etc.),+ and end with a self-test prompt: *"would future-me want to find this+ in the log by searching for it later?"*. Skip-list is unchanged in+ spirit but reworded around "did not produce an artifact" rather+ than against specific activity types.+- `tests/test_cli.py` `run_cli` helper now isolates+ `OPEN_SECOND_BRAIN_CONFIG` per call by default. With `o2b init` now+ unconditionally persisting `vault` / `agent_name` / `timezone` into+ the config file, init-tests without explicit isolation were silently+ writing to the developer's real `~/.config/open-second-brain/config.yaml`.+ Tests that specifically exercise the default-config path can still+ pass `env={"OPEN_SECOND_BRAIN_CONFIG": ...}` to override the guard.+- The package version is now a single source of truth in+ `pyproject.toml`. `open_second_brain.__version__` reads it+ dynamically (live `pyproject.toml` first, `importlib.metadata`+ fallback) so a version bump shows up at runtime without a pip+ reinstall. `mcp.SERVER_VERSION` re-exports the same value.+- `event_log.append_event(..., tz=...)` accepts an optional+ `datetime.tzinfo` parameter; `current_date` and `current_time` are+ likewise tz-aware. Backward-compatible: omitting `tz` keeps the+ previous server-local behavior.+- install.md step 1 in every branch is now "Collect identity (agent+ name + timezone)" β a single up-front step that asks the user for+ both values before any commands run. The instructions tell the+ installer agent to accept free-form timezone input (city, country,+ abbreviation) and translate it to canonical IANA before passing to+ `o2b init`.+- `event_log_append` accepts and normalizes a wider set of LLM-supplied+ values for the optional `agent` argument: leading `@` is stripped+ (so `@hermes-vps-agent` no longer becomes `@@hermes-vps-agent`), and+ common placeholder/self-name guesses (`agent`, `assistant`, `claude`,+ `gpt`, β¦) fall back to the server-resolved default identity instead+ of being written verbatim into Daily.+- `event_log_append` and other tools that take optional string+ arguments now treat empty strings the same as omitted arguments.+ LLMs in tool-use mode frequently emit `""` for fields they want to+ skip; the previous behavior rejected `time=""` / `date=""` with a+ validator error.+- `o2b init --agent-name <name>` now also persists the chosen identity+ into the plugin config (`~/.config/open-second-brain/config.yaml` by+ default), not only into `AI Wiki/identity/agents.md`. Resolution+ order in `event_log_append` is unchanged+ (`VAULT_AGENT_NAME` env β plugin config β literal `agent`+ placeholder), but persistence now survives runtimes that do not+ propagate the env into the MCP subprocess.+- The MCP `initialize` response's `serverInfo.instructions` field now+ carries an identity + workflow block (you-are-@<agent>, when to+ call `event_log_append`, message format rules) rather than a plain+ list of tool names. Clients that surface MCP `instructions` to the+ LLM benefit immediately; clients that ignore the field are unaffected.+## [0.6.0] - 2026-05-08### Added@@ -256,7 +514,8 @@ 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.0...HEAD+[unreleased]: https://github.com/itechmeat/open-second-brain/compare/v0.6.1...HEAD+[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[0.5.5]: https://github.com/itechmeat/open-second-brain/compare/v0.5.4...v0.5.5[0.5.2]: https://github.com/itechmeat/open-second-brain/compare/v0.5.1...v0.5.2diff --git a/README.md b/README.mdindex 4865feee..409aa9c1 100644--- a/README.md+++ b/README.md@@ -19,10 +19,10 @@ OpenSecondBrain does not run a daemon, replace your vault, or write hidden backg## Installation-> **Agent-assisted install (recommended):** The easiest way to install this plugin is to send your agent the following prompt with a link to the installation guide:+> **Agent-assisted install (recommended):** The easiest way to install this plugin is to send your agent the following prompt with a link to the installation guide. <ins>Replace `[your_agent_name, Hermes for example]` with the runtime you are installing into</ins> β for example `Hermes`, `Claude Code`, `Codex`, or `OpenClaw`. The agent uses that name to pick the correct branch in the install guide.>> ```-> Install the open-second-brain plugin following the instructions at https://raw.githubusercontent.com/itechmeat/open-second-brain/main/install.md+> Install the open-second-brain plugin for [your_agent_name, Hermes for example] following the instructions at https://raw.githubusercontent.com/itechmeat/open-second-brain/main/install.md> ```>> The guide at `install.md` contains exact commands for both Hermes and OpenClaw runtimes. Below are the same instructions for manual installation.@@ -63,10 +63,10 @@ o2b doctor --vault /path/to/vault --repo .OpenClaw supports this project through the **Native plugin format**: a root `package.json` with `openclaw.extensions` pointing to a JS entry that registers tools natively inside OpenClaw's Node.js process. The JS entry spawns the Python CLI as a subprocess, so no MCP server is needed for basic operation.-Install from Git:+Install from Git (always installs the latest from `main`; do not append `@v...`):```bash-openclaw plugins install git:github.com/itechmeat/[email protected]+openclaw plugins install git:github.com/itechmeat/open-second-brain```Or from a local checkout:diff --git a/docs/architecture.md b/docs/architecture.mdindex af836f76..e9c44b19 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -103,10 +103,10 @@ The integration flow:The Python CLI (`o2b`) and MCP server (`o2b mcp`) remain available for Hermes and standalone usage, but the OpenClaw runtime is self-contained JavaScript.-Installation:+Installation (always installs the latest from `main`; do not append `@v...`):```bash-openclaw plugins install git:github.com/itechmeat/[email protected]+openclaw plugins install git:github.com/itechmeat/open-second-brain```The OpenClaw adapter must remain compatible with the Hermes, Claude Code, and Codex adapters. The `o2b mcp` MCP server is still available for runtimes that prefer the MCP protocol.@@ -130,15 +130,15 @@ Example:```yamlversion: 1-instance_name: Hermes Second Brain+instance_name: My Second Brainruntime: hermes-environment_name: vps-techmeat+environment_name: <hostname>vault:- path: /root/vault+ path: <absolute-path-to-Obsidian-vault>agent_dir: AI Wikiidentity:- agent_name: hermes-vps-agent- user_language: ru+ agent_name: <chosen-agent-name>+ user_language: <BCP-47 tag, e.g. en or ru>policy:write_mode: agent-owned-dir```diff --git a/install.md b/install.mdindex 9f561cf6..4a1de099 100644--- a/install.md+++ b/install.md@@ -1,9 +1,12 @@# open-second-brain β Agent Installation Guide-> **Version 0.6.0**> Repository: https://github.com/itechmeat/open-second-brain-This guide is written for an **AI agent**, not a human. It contains the exact commands and decision logic needed to install and configure the **open-second-brain** plugin autonomously. Follow exactly one of the branches below based on the target runtime (Hermes, OpenClaw, Codex, or Claude). Complete every step in the chosen branch.+This guide is written for an **AI agent**, not a human. It contains the exact commands and decision logic needed to install and configure the **open-second-brain** plugin autonomously. Follow exactly one of the branches below based on the target runtime: **A β Hermes**, **B β OpenClaw**, **C β Codex**, **D β Claude Code**, or **E β generic adapter** (any other runtime not covered by AβD). Complete every step in the chosen branch.++**Always install the latest version.** Every install command in this guide pulls the current state of the `main` branch β there are no version pins. Do **NOT** add `@vX.Y.Z`, `@<tag>`, or any other version specifier to the install commands below, even if you happen to know the most recent release number; the project ships fixes between releases and the canonical install always tracks `main`. After install, the agent's effective version is reported by `o2b status` / `o2b doctor` and by the runtime's plugin listing β read it from there if you need it, do not hard-code it anywhere.++**`o2b init` is idempotent.** Re-running it on an already-initialized vault only fills in missing scaffolding (`AI Wiki/identity/agents.md`, etc.) and never rewrites the user's notes or templates. Re-running with `--agent-name <name>` is the supported way to switch identities: it rewrites the entry in `AI Wiki/identity/agents.md` and updates the persisted `agent_name` in the plugin config (`~/.config/open-second-brain/config.yaml`). Use `--force` only when the user explicitly asks for a reset of the scaffolding files.If at any point you are missing information β for example, the vault path is unknown, a required tool is not installed, or the runtime version is unclear β stop and ask the user for clarification. Offer concrete options where possible (e.g. suggest a default vault path, list supported Python versions, or propose an alternative runtime).@@ -11,7 +14,77 @@ If at any point you are missing information β for example, the vault path is u## Branch A β Hermes-### 1. Install the plugin+### 1. Collect installation parameters (vault path + agent name + timezone)++Collect all three values before running any commands β step 4+(`o2b init`) and step 5 (MCP `env`) both depend on them.++**Vault path.** Locate (or have the user create) the directory that+will hold the Obsidian-compatible Markdown vault. Do **not** hard-code+a path; vault locations vary per user and per OS. Discover candidates+on the target machine in this order:++ 1. Look for an existing Obsidian vault: any directory containing a+ `.obsidian/` subdirectory is a vault. Common roots to scan:+ `~/`, `~/Documents/`, `~/Sync/`, `~/Dropbox/`,+ `~/Library/Mobile Documents/iCloud~md~obsidian/Documents/`+ (macOS iCloud), or β on this server β wherever Syncthing has+ mounted a shared `vault` folder.+ 2. If multiple candidates exist, list them and ask the user to pick+ one.+ 3. If none found, ask the user for a path (or for permission to+ create a new vault directory at a sensible default like+ `~/vault/`).++Confirm the chosen path with the user before passing it to `o2b init`:+show them the absolute path you resolved and wait for explicit+agreement. The plugin will refuse to write to the wrong place β but+catching a misclick at this step is much cheaper than after entries+have started accumulating.++**Agent name.** Ask the user to choose the agent name that will appear+as the `@agent-name` prefix in Daily event log entries. Offer these+defaults plus a custom value:++- `hermes-main`+- `hermes-vps-agent`+- `hermes-server`+- `second-brain-agent`+- `<hostname>-hermes`++Resolve `<hostname>` from the `hostname` command on the target system+before showing the list (e.g. `vps-techmeat-hermes`).++**Timezone.** Ask the user for their local timezone. Accept a free-form+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`+- `New York` / `EST` / `eastern` β `America/New_York`+- `UTC` / `none` / `server time` β `UTC`+- `Tokyo` / `JST` β `Asia/Tokyo`++If the answer is ambiguous, ask one clarifying question (e.g. "Belgrade+or somewhere else in Central Europe?"). If validation fails on the+chosen name, ask again β do not silently fall back.++Explain that the daily entry format is++```+- HH:MM β @agent-name β event message+```++β¦and that the `HH:MM` will be stamped in the timezone you collect here,+not in the host's clock. Do not continue until all three values+(vault path, agent name, timezone) are known. The vault path goes into+`o2b init --vault` (step 4) and the MCP entry `args` (step 5). The+agent name goes into `o2b init --agent-name` (step 4) **and** the MCP+server `env.VAULT_AGENT_NAME` block (step 5) β the two must match.+The timezone goes into `o2b init --timezone` (step 4) and is persisted+to the plugin config; the MCP server reads it from there.++### 2. Install the plugin```bashhermes plugins install itechmeat/open-second-brain --enable@@ -29,7 +102,7 @@ After install, restart the gateway:hermes gateway restart```-### 2. Publish CLI commands to PATH+### 3. Publish CLI commands to PATH`hermes plugins install` clones the repository but does not pip-install the package, so the `o2b` and `vault-log` commands are not on PATH yet. Run this step to create symlinks:@@ -41,52 +114,69 @@ This creates symlinks in `~/.local/bin` pointing to `scripts/o2b` and `scripts/vAfter this step, the bare commands `o2b` and `vault-log` will be available on PATH.-### 3. Choose Daily log agent name--Ask the user to choose the agent name used in Daily event log entries.-Offer these defaults plus a custom value:--- `hermes-main`-- `hermes-vps-agent`-- `hermes-server`-- `second-brain-agent`-- `<hostname>-hermes`--Resolve `<hostname>` from `hostname` on the target system before showing the-list (e.g. `vps-techmeat-hermes`).+### 4. Initialize the vault-Explain that this name appears in `Daily/*.md` as+Replace `/path/to/vault`, `<chosen-agent-name>`, and `<chosen-timezone>`+with the values collected in step 1.-```-- HH:MM β @agent-name β event message+```bash+o2b init --vault /path/to/vault --name "My Second Brain" \+ --agent-name "<chosen-agent-name>" \+ --timezone "<chosen-timezone>"```-Do not continue until the value is known. Pass it as `--agent-name` to-`o2b init` in the next step.+`--agent-name` writes the chosen name into `AI Wiki/identity/agents.md`+and persists `agent_name` into the plugin config+(`~/.config/open-second-brain/config.yaml`). `--timezone` validates the+IANA name via stdlib `zoneinfo` and persists it to the same config; from+that moment on, every `event_log_append` call stamps Daily entries in+that timezone regardless of the host's clock.-### 4. Initialize the vault+### 5. Register the MCP server-Replace `/path/to/vault` and `<chosen-agent-name>` with the actual values.+**Recommended path β edit `~/.hermes/config.yaml` directly.** Add the+following entry under `mcp_servers:` (create the section if it does not+exist), then restart the gateway. Substitute `/path/to/vault` and+`<chosen-agent-name>` with the real values you collected in step 3 and+will use again in step 4.++```yaml+mcp_servers:+ open-second-brain:+ command: o2b+ args: [mcp, --vault, /path/to/vault]+ env:+ VAULT_AGENT_NAME: <chosen-agent-name>+ enabled: true+``````bash-o2b init --vault /path/to/vault --name "My Second Brain" --agent-name "<chosen-agent-name>"+hermes gateway restart```-`--agent-name` writes the chosen name into `AI Wiki/identity/agents.md` and-removes the template placeholder.+The `env.VAULT_AGENT_NAME` value is what `event_log_append` falls back to+when the LLM omits the explicit `agent` argument. **It must be set in+this block** β without it, Daily entries will be written under the+literal `@agent` placeholder (or an unrelated value inherited from the+gateway's own environment), and the daily-identity check in step 6 will+fail.-### 5. Register the MCP server+**Alternative β `hermes mcp add` (CLI).** On older Hermes builds the+following one-liner is equivalent and may work:```bash-hermes mcp add open-second-brain --command o2b --args mcp --vault /path/to/vault+hermes mcp add open-second-brain \+ --command o2b --args mcp --vault /path/to/vault \+ --env VAULT_AGENT_NAME=<chosen-agent-name>hermes gateway restart```-Set the agent name in the environment passed to the MCP server so-`event_log_append` can default to it when no explicit `agent` argument is-given. The simplest way is to add `VAULT_AGENT_NAME=<chosen-agent-name>` to-the gateway environment (or to the MCP server entry in-`~/.hermes/config.yaml`).+On the current Hermes release argparse stops collecting `--args [...]` as+soon as it sees a token starting with `--`, so `--vault /path/to/vault`+is rejected as an unknown top-level flag and the command fails with+`unrecognized arguments: --vault ...`. Use the YAML path above if that+happens. Do **not** also pass `--vault` as a top-level CLI flag β that+will not be forwarded to the `o2b mcp` subprocess.### 6. Verify the installation@@ -131,12 +221,76 @@ The vault and its Markdown files are never deleted by the uninstall process.## Branch B β OpenClaw-### 1. Install the plugin+### 1. Collect installation parameters (vault path + agent name + timezone)++Collect all three values before running any commands β step 4+(`o2b init`) and step 5 (OpenClaw config) both depend on them.++**Vault path.** Locate (or have the user create) the directory that+will hold the Obsidian-compatible Markdown vault. Do **not** hard-code+a path; vault locations vary per user and per OS. Discover candidates+on the target machine in this order:++ 1. Look for an existing Obsidian vault: any directory containing a+ `.obsidian/` subdirectory is a vault. Common roots to scan:+ `~/`, `~/Documents/`, `~/Sync/`, `~/Dropbox/`,+ `~/Library/Mobile Documents/iCloud~md~obsidian/Documents/`+ (macOS iCloud), or any Syncthing-mounted shared `vault` folder.+ 2. If multiple candidates exist, list them and ask the user to pick+ one.+ 3. If none found, ask the user for a path (or for permission to+ create a new vault directory at a sensible default like+ `~/vault/`).++Confirm the chosen path with the user (show them the absolute path you+resolved) before passing it to `o2b init` and `openclaw config set`.-From Git (pin to a version tag):+**Agent name.** Ask the user to choose the agent name that will appear+as the `@agent-name` prefix in Daily event log entries. Offer these+defaults plus a custom value:++- `openclaw-main`+- `openclaw-server`+- `server-agent`+- `second-brain-agent`+- `<hostname>-openclaw`++Resolve `<hostname>` from the `hostname` command on the target system+before showing the list (e.g. `vps-techmeat-openclaw`).++**Timezone.** Ask the user for their local timezone. Accept a free-form+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: `Belgrade` β `Europe/Belgrade`,+`New York` / `EST` β `America/New_York`, `UTC` / `none` β `UTC`,+`Tokyo` β `Asia/Tokyo`. If the answer is ambiguous, ask one clarifying+question. If validation fails on the chosen name, ask again β do not+silently fall back.++Explain that the daily entry format is++```+- HH:MM β @agent-name β event message+```++β¦and that the `HH:MM` will be stamped in the timezone you collect here,+not in the host's clock. Do not continue until all three values+(vault path, agent name, timezone) are known. On OpenClaw, the native+JS plugin entry reads its config exclusively from OpenClaw's own+per-plugin config store (`api.pluginConfig`, populated by+`openclaw config set`), **not** from+`~/.config/open-second-brain/config.yaml`. So vault path, agent name,+and timezone must all be set via `openclaw config set` in step 5; the+`o2b init` invocation in step 4 still runs (to scaffold the vault) but+the values it persists into the Python-side config there are read only+by the optional `o2b mcp` server, not by the OpenClaw plugin runtime.++### 2. Install the plugin++From Git (always installs the latest from `main`; do not append `@v...`):```bash-openclaw plugins install git:github.com/itechmeat/[email protected]+openclaw plugins install git:github.com/itechmeat/open-second-brain```Or from a local checkout:@@ -151,7 +305,7 @@ After install, restart the gateway:openclaw gateway restart```-### 2. Publish CLI commands to PATH+### 3. Publish CLI commands to PATHThe `o2b` and `vault-log` commands are not on PATH after OpenClaw plugininstall. Run this step to create symlinks:@@ -163,52 +317,39 @@ install. Run this step to create symlinks:This creates symlinks in `~/.local/bin`. After this, bare `o2b` and`vault-log` work on PATH.-### 3. Choose Daily log agent name--Ask the user to choose the agent name used in Daily event log entries.-Offer these defaults plus a custom value:--- `openclaw-main`-- `openclaw-server`-- `server-agent`-- `second-brain-agent`-- `<hostname>-openclaw`--Resolve `<hostname>` from `hostname` on the target system before showing the-list (e.g. `vps-techmeat-openclaw`).--Explain that this name appears in `Daily/*.md` as--```-- HH:MM β @agent-name β event message-```--Do not continue until the value is known. The chosen name is stored in the-plugin config in step 5 as `agentName` and is written into-`AI Wiki/identity/agents.md` by `o2b init` in step 4.-### 4. Initialize the vault-Replace `/path/to/vault` and `<chosen-agent-name>` with the actual values.+Replace `/path/to/vault`, `<chosen-agent-name>`, and `<chosen-timezone>`+with the values collected in step 1.```bash-o2b init --vault /path/to/vault --name "My Second Brain" --agent-name "<chosen-agent-name>"+o2b init --vault /path/to/vault --name "My Second Brain" \+ --agent-name "<chosen-agent-name>" \+ --timezone "<chosen-timezone>"```-### 5. Configure the vault path and agent name+`--agent-name` writes the chosen name into `AI Wiki/identity/agents.md`+and persists `agent_name` into the plugin config+(`~/.config/open-second-brain/config.yaml`). `--timezone` validates the+IANA name via stdlib `zoneinfo` and persists it to the same config; from+that moment on, every Daily entry is stamped in that timezone regardless+of the host's clock.++### 5. Configure the vault path, agent name, and timezone-Tools are registered natively by the JS plugin entry β no MCP registration-is needed. Set the vault path, instance name, and agent name in the-OpenClaw plugin config:+Tools are registered natively by the JS plugin entry β no MCP+registration is needed. Set the vault path, instance name, agent name,+and timezone in the OpenClaw plugin config:```bashopenclaw config set plugins.entries.open-second-brain.config.vault '"/path/to/vault"'openclaw config set plugins.entries.open-second-brain.config.instanceName '"My Second Brain"'openclaw config set plugins.entries.open-second-brain.config.agentName '"<chosen-agent-name>"'+openclaw config set plugins.entries.open-second-brain.config.timezone '"<chosen-timezone>"'```-The resulting plugin entry must contain `agentName` as a separate field-alongside `instanceName` (do not merge the two):+The resulting plugin entry must contain `agentName` and `timezone` as+separate fields alongside `instanceName` (do not merge them):```json{@@ -217,11 +358,18 @@ alongside `instanceName` (do not merge the two):"vault": "/path/to/vault","instanceName": "My Second Brain","agentName": "<chosen-agent-name>",+ "timezone": "<chosen-timezone>","mcpEnabled": false}}```+`agentName` and `timezone` are read by the native JS plugin from+`api.pluginConfig` on every `event_log_append` call (with+`VAULT_AGENT_NAME` / `VAULT_TIMEZONE` env vars as fallbacks). Without+`timezone` set here, Daily entries fall back to the host's local+clock β which is rarely what the user wants.+### 6. Verify the installation```bash@@ -264,25 +412,33 @@ The vault and its Markdown files are never deleted by the uninstall process.## Branch C β Codex-### 1. Install the plugin--Codex consumes the bundled `.codex-plugin/plugin.json` manifest. Install-the plugin from Git through the Codex CLI:+### 1. Collect installation parameters (vault path + agent name + timezone)-```bash-codex plugins install git:github.com/itechmeat/[email protected]-```+Collect all three values before running any commands β step 4+(`o2b init`) and step 5 (Codex MCP `env`) both depend on them.-### 2. Publish CLI commands to PATH+**Vault path.** Locate (or have the user create) the directory that+will hold the Obsidian-compatible Markdown vault. Do **not** hard-code+a path; vault locations vary per user and per OS. Discover candidates+on the target machine in this order:-```bash-./scripts/o2b install-cli-```+ 1. Look for an existing Obsidian vault: any directory containing a+ `.obsidian/` subdirectory is a vault. Common roots to scan:+ `~/`, `~/Documents/`, `~/Sync/`, `~/Dropbox/`,+ `~/Library/Mobile Documents/iCloud~md~obsidian/Documents/`+ (macOS iCloud).+ 2. If multiple candidates exist, list them and ask the user to pick+ one.+ 3. If none found, ask the user for a path (or for permission to+ create a new vault directory at a sensible default like+ `~/vault/`).-### 3. Choose Daily log agent name+Confirm the chosen path with the user (show them the absolute path you+resolved) before passing it to `o2b init` and the Codex MCP entry.-Ask the user to choose the agent name used in Daily event log entries.-Offer these defaults plus a custom value:+**Agent name.** Ask the user to choose the agent name that will appear+as the `@agent-name` prefix in Daily event log entries. Offer these+defaults plus a custom value:- `codex-main`- `codex-vps-agent`@@ -290,149 +446,461 @@ Offer these defaults plus a custom value:- `second-brain-agent`- `<hostname>-codex`-Resolve `<hostname>` from `hostname` on the target system before showing-the list. Explain that this name appears in `Daily/*.md` as-`- HH:MM β @agent-name β event message`. Do not continue until the value-is known.+Resolve `<hostname>` from the `hostname` command on the target system+before showing the list.++**Timezone.** Ask the user for their local timezone. Accept a free-form+answer and translate it to a canonical IANA name yourself before passing+it to `o2b init` β the plugin only accepts IANA. Examples: `Belgrade`+β `Europe/Belgrade`, `New York` / `EST` β `America/New_York`, `UTC` /+`none` β `UTC`, `Tokyo` β `Asia/Tokyo`. If the answer is ambiguous, ask+one clarifying question. If validation fails on the chosen name, ask+again β do not silently fall back.++Explain that this name and timezone appear in `Daily/*.md` as+`- HH:MM β @agent-name β event message` (HH:MM in the chosen timezone,+not the host's clock). Do not continue until all three values+(vault path, agent name, timezone) are known. The vault path goes+into `o2b init --vault` (step 4) and the Codex MCP entry's `args`+(step 5). The agent name goes into `o2b init --agent-name` (step 4)+and the `env.VAULT_AGENT_NAME` of the Codex MCP entry (step 5) β the+two must match. The timezone goes into `o2b init --timezone` (step 4)+and is persisted to the plugin config; the MCP server reads it from+there.++### 2. Install the plugin++Codex 0.129 and later install plugins via the **marketplace** subsystem.+This repository ships a single-plugin marketplace manifest at+`.agents/plugins/marketplace.json`, so the official command is:++```bash+codex plugin marketplace add itechmeat/open-second-brain+```++(Always pulls the latest commit on `main`; do not append `@v...`.) Codex+clones the repo into `~/.codex/plugins/cache/open-second-brain/<plugin>/<hash>/`+and registers a `[marketplaces.open-second-brain]` entry in+`~/.codex/config.toml`.++Then enable the plugin so its bundled skills/agents/commands become+available β there is no `codex plugin enable` subcommand on current+Codex, this is done by adding one stanza to `~/.codex/config.toml`:++```toml+[plugins."open-second-brain@open-second-brain"]+enabled = true+```++(The `<plugin>@<marketplace>` form here resolves to plugin+`open-second-brain` from marketplace `open-second-brain` β both names+come from the manifest.) The plugin's MCP tools (`event_log_append`,+`second_brain_capture`, `second_brain_query`, `second_brain_status`,+`vault_health`) become available **only** after step 5 below β Codex+treats MCP server registration as a separate concern from plugin+enablement.++### 3. Publish CLI commands to PATH++The `o2b` and `vault-log` scripts ship inside the plugin checkout; this+step symlinks them into `~/.local/bin` so they are usable on PATH.++```bash+~/.codex/plugins/cache/open-second-brain/open-second-brain/*/scripts/o2b install-cli+```++(The glob handles the version hash that Codex assigns to the cached+clone. If you installed the marketplace from a local path, run+`<that-path>/scripts/o2b install-cli` instead.)### 4. Initialize the vault+Replace `/path/to/vault`, `<chosen-agent-name>`, and `<chosen-timezone>`+with the values collected in step 1.+```bash-o2b init --vault /path/to/vault --name "My Second Brain" --agent-name "<chosen-agent-name>"+o2b init --vault /path/to/vault --name "My Second Brain" \+ --agent-name "<chosen-agent-name>" \+ --timezone "<chosen-timezone>"```-### 5. Wire up the agent name for the Codex runtime+`--timezone` validates the IANA name via stdlib `zoneinfo` and persists+it to the plugin config. From this moment on, every Daily entry is+stamped in that timezone regardless of the host's clock.-Codex consumes Open Second Brain through the optional MCP stdio server.-Export `VAULT_AGENT_NAME=<chosen-agent-name>` in the environment that-launches the MCP server so `event_log_append` defaults to that name when-called without an explicit `agent` argument.+### 5. Register the MCP server-A minimal Codex `mcp_servers` entry:+Codex consumes Open Second Brain's MCP tools through a stdio server+configured in `~/.codex/config.toml`. The official command is:-```yaml-mcp_servers:- open-second-brain:- command: o2b- args: ["mcp", "--vault", "/path/to/vault"]- env:- VAULT_AGENT_NAME: "<chosen-agent-name>"+```bash+codex mcp add open-second-brain \+ --env VAULT_AGENT_NAME=<chosen-agent-name> \+ --env VAULT_TIMEZONE=<chosen-timezone> \+ -- o2b mcp --vault /path/to/vault```+Note the `--` separator: everything before it is parsed by Codex,+everything after is passed verbatim to the MCP subprocess as+`command + args`. Codex writes the resulting block to `config.toml` in+the form++```toml+[mcp_servers.open-second-brain]+command = "o2b"+args = ["mcp", "--vault", "/path/to/vault"]++[mcp_servers.open-second-brain.env]+VAULT_AGENT_NAME = "<chosen-agent-name>"+VAULT_TIMEZONE = "<chosen-timezone>"+```++Both env vars are required for the daily-identity check in step 6 to+succeed under the chosen identity and the user's local timezone β the+MCP server reads them as the in-process default for `event_log_append`.+### 6. Verify the installation```basho2b doctor --vault /path/to/vault --repo .+codex mcp list```-Then run the **daily identity** check (see Β§ Verification β daily identity-below). Installation is incomplete until that check passes.+The `codex mcp list` output must show `open-second-brain` with+`Status: enabled`. Then run the **daily identity** check (see+Β§ Verification β daily identity below). Installation is incomplete+until that check passes.### 7. Update```bash-codex plugins update open-second-brain+codex plugin marketplace upgrade open-second-brain```-The CLI symlinks created in step 2 do not need to be recreated after an-update β they point into the git checkout, which the plugin updater-refreshes.+(Works only when the marketplace was added from a Git source. For a+local source, the marketplace tracks the path live β pulling latest+from upstream is up to whatever Git workflow you use on that path.)++The CLI symlinks created in step 3 do not need to be recreated after an+update β they point into the cached plugin checkout, which the+upgrade refreshes via `git fetch + reset`.### 8. Uninstall```bash-codex plugins uninstall open-second-brain+codex mcp remove open-second-brain+codex plugin marketplace remove open-second-braino2b uninstall --apply-local --remove-cli```-The vault and its Markdown files are never deleted by the uninstall process.+Then remove the `[plugins."open-second-brain@open-second-brain"]`+stanza from `~/.codex/config.toml` if you added one in step 2. The+vault and its Markdown files are never deleted by the uninstall+process.---## Branch D β Claude Code-### 1. Install the plugin+### 1. Collect installation parameters (vault path + agent name + timezone)++Collect all three values before running any commands β step 4+(`o2b init`) is the single point where they enter the system on Claude+Code. The plugin's bundled `.mcp.json` auto-registers the MCP server+with no flags or env vars, and the server reads vault path, agent+name, and timezone from the persisted plugin config that `o2b init`+writes β so there is no second place to keep in sync.++**Vault path.** Locate (or have the user create) the directory that+will hold the Obsidian-compatible Markdown vault. Do **not** hard-code+a path; vault locations vary per user and per OS. Discover candidates+on the target machine in this order:++ 1. Look for an existing Obsidian vault: any directory containing a+ `.obsidian/` subdirectory is a vault. Common roots to scan:+ `~/`, `~/Documents/`, `~/Sync/`, `~/Dropbox/`,+ `~/Library/Mobile Documents/iCloud~md~obsidian/Documents/`+ (macOS iCloud).+ 2. If multiple candidates exist, list them and ask the user to pick+ one.+ 3. If none found, ask the user for a path (or for permission to+ create a new vault directory at a sensible default like+ `~/vault/`).++Confirm the chosen path with the user (show them the absolute path+you resolved) before passing it to `o2b init`.++**Agent name.** Ask the user to choose the agent name that will appear+as the `@agent-name` prefix in Daily event log entries. Offer these+defaults plus a custom value:++- `claude-main`+- `claude-vps-agent`+- `claude-server`+- `second-brain-agent`+- `<hostname>-claude`++Resolve `<hostname>` from the `hostname` command on the target system+before showing the list.++**Timezone.** Ask the user for their local timezone. Accept a free-form+answer and translate it to a canonical IANA name yourself before passing+it to `o2b init` β the plugin only accepts IANA. Examples: `Belgrade`+β `Europe/Belgrade`, `New York` / `EST` β `America/New_York`, `UTC` /+`none` β `UTC`, `Tokyo` β `Asia/Tokyo`. If the answer is ambiguous, ask+one clarifying question. If validation fails on the chosen name, ask+again β do not silently fall back.++Explain that this name and timezone appear in `Daily/*.md` as+`- HH:MM β @agent-name β event message` (HH:MM in the chosen timezone,+not the host's clock). Do not continue until all three values+(vault path, agent name, timezone) are known. All three go into the+single `o2b init` call in step 4; the bundled `.mcp.json`+auto-registers the MCP server, and the server reads everything from+the persisted plugin config β no second config to set.-Claude Code consumes the bundled `.claude-plugin/plugin.json` manifest.-Install the plugin from Git:+### 2. Install the plugin++Claude Code 2.x installs plugins through its **marketplace** subsystem.+This repository ships a single-plugin marketplace manifest at+`.claude-plugin/marketplace.json` plus the plugin manifest at+`.claude-plugin/plugin.json`, so the official two-step install is:```bash-claude plugins install git:github.com/itechmeat/[email protected]+claude plugin marketplace add itechmeat/open-second-brain+claude plugin install open-second-brain@open-second-brain```-### 2. Publish CLI commands to PATH+(The marketplace step always pulls the latest commit on `main`; do not+append `@v...`.) After install, `claude plugin list` shows the plugin+under user scope with `Status: β enabled`. Claude clones the repo into+`~/.claude/plugins/cache/open-second-brain/<plugin-name>/` and tracks+the source via the `claude-plugins` config block.++The plugin auto-registers its MCP server through the bundled `.mcp.json`+file at the repo root β **no `claude mcp add` step is needed**. After+step 4 below (vault init), `claude mcp list` will show+`open-second-brain` with `β Connected`.++### 3. Publish CLI commands to PATH++The `o2b` and `vault-log` scripts ship inside the plugin checkout; this+step symlinks them into `~/.local/bin` so they are usable on PATH.```bash-./scripts/o2b install-cli+~/.claude/plugins/cache/open-second-brain/open-second-brain/scripts/o2b install-cli```-### 3. Choose Daily log agent name+### 4. Initialize the vault-Ask the user to choose the agent name used in Daily event log entries.-Offer these defaults plus a custom value:+Replace `/path/to/vault`, `<chosen-agent-name>`, and `<chosen-timezone>`+with the values collected in step 1.-- `claude-main`-- `claude-vps-agent`-- `claude-server`-- `second-brain-agent`-- `<hostname>-claude`+```bash+o2b init --vault /path/to/vault --name "My Second Brain" \+ --agent-name "<chosen-agent-name>" \+ --timezone "<chosen-timezone>"+```++`o2b init` persists all three values (`vault`, `agent_name`, `timezone`)+into `~/.config/open-second-brain/config.yaml`. The `.mcp.json` that+Claude auto-registered is intentionally minimal β it points only at+`o2b mcp` with no flags, no env vars, no vault path. The MCP server+discovers everything it needs from the persisted config when it+spawns. This means the same `.mcp.json` works on every user's machine+without per-user customization.++### 5. (No separate MCP wiring step on Claude Code)++Skipped on this runtime β see step 2. Claude's `.mcp.json` auto-register+already covers what Hermes does in `mcp_servers:` and Codex does via+`codex mcp add`.++### 6. Verify the installation++```bash+o2b doctor --vault /path/to/vault --repo .+claude plugin list+claude mcp list+```-Resolve `<hostname>` from `hostname` on the target system before showing-the list. Explain that this name appears in `Daily/*.md` as-`- HH:MM β @agent-name β event message`. Do not continue until the value-is known.+`claude plugin list` must show `open-second-brain@open-second-brain`+with `Status: β enabled`. `claude mcp list` must show+`plugin:open-second-brain:open-second-brain` with `β Connected`. Then+run the **daily identity** check (see Β§ Verification β daily identity+below). Installation is incomplete until that check passes.++### 7. Update++```bash+claude plugin marketplace update open-second-brain+claude plugin update open-second-brain@open-second-brain+```++The CLI symlinks created in step 3 do not need to be recreated after+an update β they point into the cached plugin checkout, which the+update step refreshes via `git fetch + reset`.++### 8. Uninstall++```bash+claude plugin uninstall open-second-brain@open-second-brain+claude plugin marketplace remove open-second-brain+o2b uninstall --apply-local --remove-cli+```++Claude removes the plugin's MCP server registration automatically when+the plugin is uninstalled. The vault and its Markdown files are never+deleted by the uninstall process.++---++## Branch E β Generic adapter (other runtimes)++If the target runtime is **not** Hermes, OpenClaw, Codex, or Claude+Code β for example a new MCP-aware client, a different agent platform,+or one of the supported runtimes after a breaking CLI rename β use+this branch. It describes the install **contract** the plugin needs,+not literal commands. The agent doing the install must consult the+target runtime's own plugin / MCP documentation and translate each+step below into the equivalent runtime-specific operation. Where the+runtime has no equivalent for a step, ask the user before proceeding+rather than guessing.++The plugin's runtime contract is small:++- A directory tree on disk containing `scripts/o2b` (Python CLI) and+ `src/open_second_brain/` (the package). This is what the runtime's+ plugin install delivers.+- The `o2b` CLI on PATH (used for vault scaffolding, status, and+ doctor checks).+- The `o2b mcp` stdio server registered with the runtime as an MCP+ server (used by the LLM at runtime via the five tools+ `event_log_append` / `second_brain_capture` / `second_brain_query` /+ `second_brain_status` / `vault_health`).+- A persisted plugin config at `~/.config/open-second-brain/config.yaml`+ holding `vault` / `agent_name` / `timezone` (written by `o2b init`,+ read by `o2b mcp` when its CLI flags / env vars are absent).++### 1. Collect installation parameters (vault path + agent name + timezone)++Same three values as branches AβD collect, same discovery rules. Read+the "Collect installation parameters" subsection of any other branch+above and apply it as-is β the questions and defaults are runtime-+agnostic. For agent name, derive a runtime-appropriate prefix+(`<runtime>-main`, `<runtime>-vps-agent`, etc.) so multi-runtime users+can tell entries apart in Daily.++### 2. Install the plugin++Get the plugin source onto the target machine via whatever channel the+runtime supports. The repo ships several manifest formats so most+runtimes will find one they understand:++- `.claude-plugin/plugin.json` + `.claude-plugin/marketplace.json`+- `.codex-plugin/plugin.json` + `.agents/plugins/marketplace.json`+- `openclaw.plugin.json` + `package.json` `openclaw.extensions`+- Hermes `plugin.yaml` (root)+- A vanilla Git checkout (every runtime can clone a repo)++Pick whichever your runtime documents. Do **not** add a version pin+(`@v...`) β the canonical install always tracks the `main` branch.++### 3. Publish CLI commands to PATH++Run `<plugin-checkout>/scripts/o2b install-cli`. It symlinks `o2b` and+`vault-log` into `~/.local/bin`. If your runtime caches plugins under+a content-addressed path with a version hash, glob it:+`<runtime-cache>/.../scripts/o2b install-cli`.### 4. Initialize the vault```bash-o2b init --vault /path/to/vault --name "My Second Brain" --agent-name "<chosen-agent-name>"+o2b init --vault /path/to/vault --name "My Second Brain" \+ --agent-name "<chosen-agent-name>" \+ --timezone "<chosen-timezone>"```-### 5. Wire up the agent name for the Claude runtime+This is identical across runtimes β the values are persisted into+`~/.config/open-second-brain/config.yaml` and read back by the MCP+server with no further wiring required.++### 5. Register the MCP server with your runtime-Claude Code talks to Open Second Brain over the optional MCP stdio server.-Export `VAULT_AGENT_NAME=<chosen-agent-name>` in the environment that-launches the MCP server so `event_log_append` defaults to that name when-called without an explicit `agent` argument.+The exact mechanism depends on the runtime. The minimum spec the+plugin expects is a stdio MCP server invocation:-A minimal Claude Code `mcp_servers` entry:+| field | value |+|---|---|+| `command` | `o2b` |+| `args` | `["mcp"]` (vault / agent / timezone resolved from the persisted plugin config; no flags needed) |+| `env` | optional. Set `VAULT_AGENT_NAME=<chosen-agent-name>` and `VAULT_TIMEZONE=<chosen-tz>` if your runtime cannot read the plugin config (e.g. a per-runtime override is desired); otherwise leave empty. |++If your runtime's MCP config is YAML (Hermes-style):```yamlmcp_servers:open-second-brain:command: o2b- args: ["mcp", "--vault", "/path/to/vault"]+ args: [mcp]env:VAULT_AGENT_NAME: "<chosen-agent-name>"+ VAULT_TIMEZONE: "<chosen-timezone>"+ enabled: true```-### 6. Verify the installation+If TOML (Codex-style):-```bash-o2b doctor --vault /path/to/vault --repo .+```toml+[mcp_servers.open-second-brain]+command = "o2b"+args = ["mcp"]++[mcp_servers.open-second-brain.env]+VAULT_AGENT_NAME = "<chosen-agent-name>"+VAULT_TIMEZONE = "<chosen-timezone>"```-Then run the **daily identity** check (see Β§ Verification β daily identity-below). Installation is incomplete until that check passes.+If the runtime auto-registers MCP servers from a manifest at the+plugin root (Claude Code's `.mcp.json`-style), use that β the plugin+already ships `.mcp.json` with `${CLAUDE_PLUGIN_ROOT}/scripts/o2b mcp`+and no env, which auto-resolves everything from the persisted plugin+config at runtime.-### 7. Update+If the runtime does **not** support stdio MCP servers at all, the+plugin's tools will not be available to that runtime; the user can+still run `o2b` / `vault-log` manually from the shell, but agent-side+integration is the runtime's missing capability, not the plugin's.++### 6. Verify the installation```bash-claude plugins update open-second-brain+o2b doctor --vault /path/to/vault --repo <plugin-checkout>```-The CLI symlinks created in step 2 do not need to be recreated after an-update β they point into the git checkout, which the plugin updater-refreshes.+All checks must pass. Then run the **daily identity** check (see+Β§ Verification β daily identity below). Installation is incomplete+until that check passes.-### 8. Uninstall+### 7. Optional β surface plugin guidance to the LLM-```bash-claude plugins uninstall open-second-brain-o2b uninstall --apply-local --remove-cli-```+The plugin's MCP `initialize` response carries a full identity ++workflow block in `serverInfo.instructions` (resolved per the+configured agent name). Runtimes that respect the MCP `instructions`+field show this to the LLM automatically. If yours does not β and the+runtime has a "system prompt injection" or "per-turn context" hook+analogous to Hermes's `pre_llm_call` β consider wiring the same+content (or a paraphrase) through that channel. Without it, the LLM+will still see the five tools but won't know when to call+`event_log_append`.-The vault and its Markdown files are never deleted by the uninstall process.+### 8. Update / Uninstall++Use the runtime's native plugin update / uninstall commands. The+plugin keeps no state outside the vault and+`~/.config/open-second-brain/config.yaml`; `o2b uninstall+--apply-local --remove-cli` cleans the latter and the PATH symlinks+created in step 3. Vault Markdown files are never deleted.---diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 40b230e1..78d51434 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.0",+ "version": "0.6.1","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {@@ -28,7 +28,11 @@},"agentName": {"type": "string",- "description": "Identity used in Daily/*.md event log entries (e.g. 'openclaw-main'). Falls back to VAULT_AGENT_NAME, then to '@agent'."+ "description": "Identity used in Daily/*.md event log entries (e.g. 'openclaw-main'). Falls back to VAULT_AGENT_NAME env, then to '@agent'."+ },+ "timezone": {+ "type": "string",+ "description": "IANA timezone name (e.g. 'Europe/Belgrade', 'America/New_York', 'UTC') used to stamp Daily/*.md entries in the user's local time. Falls back to VAULT_TIMEZONE env, then to the host's local clock."},"mcpEnabled": {"type": "boolean",@@ -50,6 +54,10 @@"label": "Agent Name","help": "Identity used in Daily/*.md as @agent-name for event log entries."},+ "timezone": {+ "label": "Timezone",+ "help": "IANA timezone name (e.g. Europe/Belgrade) for HH:MM stamps in Daily/*.md."+ },"mcpEnabled": {"label": "Enable MCP Server","help": "Expose Open Second Brain as an MCP stdio server (optional)."diff --git a/openclaw/event-log.js b/openclaw/event-log.jsindex 4653a892..3ce77091 100644--- a/openclaw/event-log.js+++ b/openclaw/event-log.js@@ -38,23 +38,37 @@ function redactText(text) {/*** 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() {- const now = new Date();- const y = now.getFullYear();- const m = String(now.getMonth() + 1).padStart(2, "0");- const d = String(now.getDate()).padStart(2, "0");- return `${y}.${m}.${d}`;+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.+ * Get current time in HH:MM 24-hour format, optionally in ``tz``.*/-function currentTime() {- const now = new Date();- const h = String(now.getHours()).padStart(2, "0");- const m = String(now.getMinutes()).padStart(2, "0");- return `${h}:${m}`;+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")}`;}/**@@ -135,11 +149,13 @@ function insertEventEntry(content, entry) {* @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) {- const eventDate = date || currentDate();- const eventTime = validateEventTime(time || currentTime());+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`);diff --git a/openclaw/index.js b/openclaw/index.jsindex 53183ec1..776dfe2f 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -36,10 +36,32 @@ import { existsSync } from "node:fs";// ββ Constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-const PLUGIN_VERSION = "0.6.0";-const SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"];+// 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",+]);+// ββ Config helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ/**@@ -87,24 +109,55 @@ function resolveVaultPath(api) {}/**- * Get current date in YYYY.MM.DD format.+ * 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 currentDate() {- const now = new Date();- const y = now.getFullYear();- const m = String(now.getMonth() + 1).padStart(2, "0");- const d = String(now.getDate()).padStart(2, "0");- return `${y}.${m}.${d}`;+function resolveTimezone(api) {+ const config = api.pluginConfig || {};+ const candidate = config.timezone || process.env.VAULT_TIMEZONE || null;+ if (!candidate) return null;+ try {+ new Intl.DateTimeFormat("en-US", { timeZone: candidate });+ } catch {+ return null;+ }+ return candidate;}/**- * Get current time in HH:MM 24-hour format.+ * 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 currentTime() {- const now = new Date();- const h = String(now.getHours()).padStart(2, "0");- const m = String(now.getMinutes()).padStart(2, "0");- return `${h}:${m}`;+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;}/**@@ -414,15 +467,17 @@ export default definePluginEntry({const pluginConfig = api.pluginConfig || {};const configuredAgent = pluginConfig.agentName || null;+ const normalizedAgent = normalizeAgentArgument(params.agent);const agent =- params.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);+ const result = await appendEvent(vault, agent, message, date, time, tz);return {content: [diff --git a/package.json b/package.jsonindex 114420c4..d73b5d3f 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.6.0",+ "version": "0.6.1","type": "module","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",diff --git a/plugin.yaml b/plugin.yamlindex 440255dd..a9aef722 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,9 +1,10 @@name: open-second-brain-version: "0.6.0"+version: "0.6.1"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalone-provides_hooks: []+provides_hooks:+ - pre_llm_callmcp_server:command: scripts/o2bargs: ["mcp"]diff --git a/plugins/hermes/__init__.py b/plugins/hermes/__init__.pyindex ca590177..6769346d 100644--- a/plugins/hermes/__init__.py+++ b/plugins/hermes/__init__.py@@ -111,15 +111,57 @@ def _attach_health(ctx: Any, callback: Callable[[], HealthReport]) -> bool: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 register(ctx: Any) -> None:- """Register the Hermes plugin health check when the context supports it.+ """Register Hermes-side hooks when the context supports them.- This remains safe/no-op-ish: unsupported context objects are ignored and no- exception is raised for registration incompatibilities.+ Best-effort: 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:- return None+ pass++ register_hook = getattr(ctx, "register_hook", None)+ if callable(register_hook):+ try:+ register_hook("pre_llm_call", on_pre_llm_call)+ except Exception:+ passreturn Nonediff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex a3123451..2aaf0931 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,9 +1,10 @@name: open-second-brain-version: "0.6.0"+version: "0.6.1"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalone-provides_hooks: []+provides_hooks:+ - pre_llm_callmcp_server:command: scripts/o2bargs: ["mcp"]diff --git a/pyproject.toml b/pyproject.tomlindex 14624cb5..dc996d48 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "open-second-brain"-version = "0.6.0"+version = "0.6.1"description = "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw."readme = "README.md"requires-python = ">=3.11"diff --git a/scripts/sync-version.py b/scripts/sync-version.pynew file mode 100755index 00000000..8e86b184--- /dev/null+++ b/scripts/sync-version.py@@ -0,0 +1,153 @@+#!/usr/bin/env python3+"""Propagate the version from ``pyproject.toml`` to runtime manifests.++The single source of truth for the Open Second Brain version is the+``[project] version`` field in ``pyproject.toml``. Python code resolves it+dynamically (see ``src/open_second_brain/__init__.py``).++Manifests consumed by external runtimes (Hermes, OpenClaw, Claude Code,+Codex, npm) are read raw without templating, so they have to carry a copy+of the version on disk. This script propagates the canonical value into+every such file. It is idempotent: rerunning when nothing changed exits+cleanly with no writes.++Files NOT touched by design:++ - ``CHANGELOG.md`` β historical record, edited by hand on release.+ - ``install.md`` β install commands MUST NOT pin a specific version+ (``@vX.Y.Z``); they always pull the latest from the default branch.+ - ``docs/architecture.md`` β same rule as ``install.md`` for example+ commands inside the doc.+ - ``tests/`` β fixtures may reference specific historical versions.++Usage::++ python3 scripts/sync-version.py # write changes+ python3 scripts/sync-version.py --check # exit 1 if any drift+"""++from __future__ import annotations++import argparse+import re+import sys+import tomllib+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]++# ---------------------------------------------------------------------------+# Targets+# ---------------------------------------------------------------------------++# Files where ``version: "X.Y.Z"`` appears once, on its own line (YAML).+YAML_TARGETS: tuple[str, ...] = (+ "plugin.yaml",+ "plugins/hermes/plugin.yaml",+)++# Files where ``"version": "X.Y.Z"`` appears once at the top level (JSON).+# We do NOT round-trip through ``json.loads``/``json.dumps`` because that+# rewrites whitespace, key order, and trailing newlines. Regex replacement+# preserves the file byte-for-byte except for the version string itself.+JSON_TARGETS: tuple[str, ...] = (+ "package.json",+ ".claude-plugin/plugin.json",+ ".codex-plugin/plugin.json",+ "openclaw.plugin.json",+)++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++_YAML_RE = re.compile(r'^(version:\s*)"[^"]*"', re.MULTILINE)+_JSON_RE = re.compile(r'("version"\s*:\s*)"[^"]*"')+++def canonical_version() -> str:+ pyproject = ROOT / "pyproject.toml"+ with pyproject.open("rb") as fh:+ data = tomllib.load(fh)+ project = data.get("project") or {}+ version = project.get("version")+ if not isinstance(version, str) or not version:+ raise SystemExit(f"{pyproject} is missing [project].version")+ return version+++def _replace(text: str, regex: re.Pattern[str], version: str) -> str:+ return regex.sub(rf'\g<1>"{version}"', text, count=1)+++def update_file(path: Path, regex: re.Pattern[str], version: str, *, write: bool) -> tuple[bool, bool]:+ """Return ``(matched, would_change)``.++ ``matched`` β the regex found a version line in this file at all.+ ``would_change`` β the current value differs from ``version``.+ """+ text = path.read_text(encoding="utf-8")+ new = _replace(text, regex, version)+ if not regex.search(text):+ return False, False+ if new == text:+ return True, False+ if write:+ path.write_text(new, encoding="utf-8")+ return True, True+++# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])+ parser.add_argument(+ "--check",+ action="store_true",+ help="Exit 1 if any manifest drifts from pyproject.toml; do not write.",+ )+ args = parser.parse_args(argv)++ version = canonical_version()+ print(f"canonical version: {version}")++ drifted: list[str] = []+ for rel in YAML_TARGETS:+ path = ROOT / rel+ matched, would_change = update_file(path, _YAML_RE, version, write=not args.check)+ if not matched:+ print(f" WARN no version line in {rel}", file=sys.stderr)+ continue+ if would_change:+ drifted.append(rel)+ print(f" {'DRIFT' if args.check else 'wrote'}: {rel}")+ else:+ print(f" ok: {rel}")++ for rel in JSON_TARGETS:+ path = ROOT / rel+ matched, would_change = update_file(path, _JSON_RE, version, write=not args.check)+ if not matched:+ print(f" WARN no version line in {rel}", file=sys.stderr)+ continue+ if would_change:+ drifted.append(rel)+ print(f" {'DRIFT' if args.check else 'wrote'}: {rel}")+ else:+ print(f" ok: {rel}")++ if args.check and drifted:+ print(+ f"\n{len(drifted)} file(s) out of sync with pyproject.toml; "+ "run scripts/sync-version.py to fix.",+ file=sys.stderr,+ )+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/open_second_brain/__init__.py b/src/open_second_brain/__init__.pyindex 3b943d38..015a71d0 100644--- a/src/open_second_brain/__init__.py+++ b/src/open_second_brain/__init__.py@@ -1,3 +1,65 @@"""Open Second Brain core package."""-__version__ = "0.6.0"+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.pyindex 18d02cf6..24e0435b 100644--- a/src/open_second_brain/cli.py+++ b/src/open_second_brain/cli.py@@ -8,7 +8,14 @@ from pathlib import Pathimport json as _json-from open_second_brain.config import default_config_path, discover_config, redact_mapping+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 doctorfrom open_second_brain.event_log import append_eventfrom open_second_brain.init import bootstrap_vault@@ -45,6 +52,18 @@ def build_parser() -> argparse.ArgumentParser:"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")@@ -144,6 +163,29 @@ def build_parser() -> argparse.ArgumentParser: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):@@ -170,6 +212,20 @@ def command_status(args: argparse.Namespace) -> int:def command_init(args: argparse.Namespace) -> int:vault = args.vaultagent_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,@@ -180,21 +236,29 @@ def command_init(args: argparse.Namespace) -> int:except OSError as exc:print(f"error: failed to initialize vault: {exc}", file=sys.stderr)return 1- if not created:+ 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")- return 0- print(f"initialized vault: {vault}")- for path in created:- print(f" created: {path}")+ 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 0def command_doctor(args: argparse.Namespace) -> int:- vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))config = args.config or default_config_path()+ vault = _require_vault(args, config)repo_root: Path | None = args.repotry:@@ -212,13 +276,18 @@ def command_doctor(args: argparse.Namespace) -> int:def command_append_event(args: argparse.Namespace) -> int:- vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))+ 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)+ 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- print(f"appended: {path}")+ # 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@@ -240,7 +309,7 @@ def command_export_config(args: argparse.Namespace) -> int:def command_index(args: argparse.Namespace) -> int:- vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))+ vault = _require_vault(args, default_config_path())try:pages = list_vault_pages(vault)except OSError as exc:@@ -274,8 +343,8 @@ def command_index(args: argparse.Namespace) -> int:def command_mcp(args: argparse.Namespace) -> int:- vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))config = args.config or default_config_path()+ vault = _require_vault(args, config)repo_root: Path | None = args.repotry:return run_mcp_server(vault=vault, config_path=config, repo_root=repo_root)@@ -312,8 +381,8 @@ def command_install_cli(args: argparse.Namespace) -> int:def command_tool_call(args: argparse.Namespace) -> int:"""Bridge: invoke an MCP tool handler from the CLI and print JSON to stdout."""- vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))config = default_config_path()+ vault = _require_vault(args, config)repo_root: Path | None = Noneserver = MCPServer(vault=vault, config_path=config, repo_root=repo_root)diff --git a/src/open_second_brain/config.py b/src/open_second_brain/config.pyindex 6c9e6cb6..2017224c 100644--- a/src/open_second_brain/config.py+++ b/src/open_second_brain/config.py@@ -54,6 +54,152 @@ def discover_config(path: Path | None = None) -> ConfigDiscovery: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():diff --git a/src/open_second_brain/doctor.py b/src/open_second_brain/doctor.pyindex f50ee1e5..c0aeed12 100644--- a/src/open_second_brain/doctor.py+++ b/src/open_second_brain/doctor.py@@ -99,30 +99,51 @@ 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,- "author": str,- "license": str,- "repository": str,- "keywords": list,- "commands": list,}problems = _validate_required_fields(data, required)- commands = data.get("commands")- if isinstance(commands, list):- for index, command in enumerate(commands):- if not isinstance(command, dict):- problems.append(f"commands[{index}] must be object")- continue- for field in ("name", "description", "command"):- value = command.get(field)- if not isinstance(value, str) or not value.strip():- problems.append(f"commands[{index}].{field} must be non-empty string")- args = command.get("args")- if args is not None and not (isinstance(args, list) and all(isinstance(arg, str) for arg in args)):- problems.append(f"commands[{index}].args must be list of strings")+ 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}")diff --git a/src/open_second_brain/event_log.py b/src/open_second_brain/event_log.pyindex a012d54f..a320a783 100644--- a/src/open_second_brain/event_log.py+++ b/src/open_second_brain/event_log.py@@ -4,7 +4,7 @@ import fcntlimport osimport reimport tempfile-from datetime import datetime+from datetime import datetime, tzinfofrom pathlib import PathSECRET_ASSIGNMENT_RE = re.compile(@@ -19,12 +19,20 @@ 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() -> str:- return datetime.now().strftime("%Y.%m.%d")+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() -> str:- return datetime.now().strftime("%H:%M")++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:@@ -53,9 +61,10 @@ def append_event(*,date: str | None = None,time: str | None = None,+ tz: tzinfo | None = None,) -> Path:- event_date = date or current_date()- event_time = validate_event_time(time or current_time())+ 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")diff --git a/src/open_second_brain/mcp.py b/src/open_second_brain/mcp.pyindex 38d8f2fc..f8585668 100644--- a/src/open_second_brain/mcp.py+++ b/src/open_second_brain/mcp.py@@ -22,14 +22,22 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Callable, IO-from open_second_brain.config import default_config_path, discover_config, redact_mapping+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 doctorfrom open_second_brain.event_log import append_event, validate_event_timefrom 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"-SERVER_VERSION = "0.6.0"JSONRPC_VERSION = "2.0"# JSON-RPC 2.0 error codes used by the MCP server.@@ -168,12 +176,7 @@ class MCPServer:"protocolVersion": negotiated,"capabilities": {"tools": {"listChanged": False}},"serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},- "instructions": (- "Open Second Brain MCP server. Tools are deterministic wrappers around the o2b CLI. "- "Use second_brain_status before writes, vault_health to verify the vault, "- "second_brain_query to look up notes, second_brain_capture to add wiki pages, "- "and event_log_append for daily operational events."- ),+ "instructions": _build_instructions(_resolve_default_agent(self)),}def _handle_tools_list(self) -> dict[str, Any]:@@ -235,7 +238,11 @@ def _tool_error(message: str) -> dict[str, Any]: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:+ 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@@ -354,15 +361,87 @@ def _tool_second_brain_capture(server: MCPServer, arguments: dict[str, Any]) ->}+# 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:- env_value = os.environ.get("VAULT_AGENT_NAME")- if env_value:- return env_value- discovery = discover_config(server.config_path)- config_value = discovery.data.get("agent_name") or discovery.data.get("agentName")- if config_value:- return config_value- return "agent"+ 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]:@@ -375,8 +454,9 @@ def _tool_event_log_append(server: MCPServer, arguments: dict[str, Any]) -> dictif time is not None:validate_event_time(time)- effective_agent = agent or _resolve_default_agent(server)- path = append_event(server.vault, effective_agent, message, date=date, 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),@@ -585,10 +665,18 @@ def main(argv: list[str] | None = None) -> int:parser.add_argument("--repo", type=Path, default=None, help="Repository root for plugin checks")args = parser.parse_args(argv)- vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))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 1repo_root = args.repo- return run_cli_command(vault=vault, config_path=config, repo_root=repo_root)+ return run_cli_command(vault=Path(vault), config_path=config, repo_root=repo_root)if __name__ == "__main__":diff --git a/src/open_second_brain/vault_log.py b/src/open_second_brain/vault_log.pyindex 860dec5b..806e2236 100644--- a/src/open_second_brain/vault_log.py+++ b/src/open_second_brain/vault_log.py@@ -2,8 +2,10 @@ from __future__ import annotationsimport argparseimport os+import sysfrom pathlib import Path+from open_second_brain.config import resolve_timezone, resolve_vaultfrom open_second_brain.event_log import append_event@@ -19,9 +21,25 @@ def build_parser() -> argparse.ArgumentParser:def main(argv: list[str] | None = None) -> int:args = build_parser().parse_args(argv)- vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))- path = append_event(vault, args.agent, args.message, date=args.date, time=args.time)- print(f"appended: {path}")+ # 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 0diff --git a/tests/fixtures.py b/tests/fixtures.pyindex 1a3ffb04..eeaea56a 100644--- a/tests/fixtures.py+++ b/tests/fixtures.py@@ -34,13 +34,10 @@ def create_plugin_repo(root: Path, *, valid: bool = True) -> Path:"name": "test","version": "1.0.0","description": "test manifest",- "author": "tests",+ "author": { "name": "tests" },"license": "MIT","repository": "https://example.invalid/test",- "keywords": ["test"],- "commands": [- {"name": "status", "description": "status", "command": "scripts/o2b", "args": ["status"]}- ]+ "keywords": ["test"]}""",encoding="utf-8",diff --git a/tests/test_claude_marketplace.py b/tests/test_claude_marketplace.pynew file mode 100644index 00000000..b58d5402--- /dev/null+++ b/tests/test_claude_marketplace.py@@ -0,0 +1,130 @@+"""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.pyindex 34a99c4a..84f5d98a 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -26,7 +26,24 @@ def run_module(module, *args, env=None):def run_cli(*args, env=None):- return run_module("open_second_brain.cli", *args, env=env)+ # 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):@@ -49,7 +66,8 @@ class CliTests(unittest.TestCase):def test_init_with_agent_name_writes_identity_entry(self):with tempfile.TemporaryDirectory() as tmp:- vault = Path(tmp)+ vault = Path(tmp) / "vault"+ config = Path(tmp) / "config.yaml"result = run_cli("init","--vault",@@ -58,6 +76,7 @@ class CliTests(unittest.TestCase):"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)@@ -67,6 +86,255 @@ class CliTests(unittest.TestCase):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)diff --git a/tests/test_codex_marketplace.py b/tests/test_codex_marketplace.pynew file mode 100644index 00000000..69cde05b--- /dev/null+++ b/tests/test_codex_marketplace.py@@ -0,0 +1,84 @@+"""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.pyindex 6af80074..0f46b8b6 100644--- a/tests/test_config.py+++ b/tests/test_config.py@@ -4,7 +4,14 @@ import unittestfrom pathlib import Pathfrom unittest.mock import patch-from open_second_brain.config import default_config_path, discover_config, redact_mapping+from open_second_brain.config import (+ default_config_path,+ discover_config,+ redact_mapping,+ resolve_agent_name,+ resolve_timezone,+ resolve_vault,+)class ConfigTests(unittest.TestCase):@@ -60,5 +67,54 @@ class ConfigTests(unittest.TestCase):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_hermes_plugin.py b/tests/test_hermes_plugin.pyindex 28f8b0b6..9542d799 100644--- a/tests/test_hermes_plugin.py+++ b/tests/test_hermes_plugin.py@@ -1,9 +1,11 @@import importlib.util+import osimport sys+import tempfileimport unittestfrom pathlib import Path-from plugins.hermes import check_health, health, register+from plugins.hermes import check_health, health, on_pre_llm_call, registerROOT = Path(__file__).resolve().parents[1]@@ -57,6 +59,78 @@ class HermesPluginTests(unittest.TestCase):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_mcp.py b/tests/test_mcp.pyindex a7ec44fc..d29727bf 100644--- a/tests/test_mcp.py+++ b/tests/test_mcp.py@@ -85,6 +85,24 @@ class HandshakeTests(unittest.TestCase):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))@@ -253,6 +271,214 @@ class ToolCallTests(unittest.TestCase):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"diff --git a/tests/test_openclaw_plugin.py b/tests/test_openclaw_plugin.pyindex 3d360887..ece41166 100644--- a/tests/test_openclaw_plugin.py+++ b/tests/test_openclaw_plugin.py@@ -34,7 +34,9 @@ class OpenClawManifestValidityTests(unittest.TestCase):self.assertEqual(schema["type"], "object")def test_manifest_has_version(self):- self.assertEqual(self.manifest["version"], "0.6.0")+ from open_second_brain import __version__++ self.assertEqual(self.manifest["version"], __version__)def test_manifest_declares_tools(self):tools = self.manifest["contracts"]["tools"]@@ -76,6 +78,21 @@ class OpenClawManifestValidityTests(unittest.TestCase):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."""@@ -133,7 +150,9 @@ class OpenClawPackageJsonTests(unittest.TestCase):self.assertEqual(self.pkg["name"], "open-second-brain")def test_package_json_has_version(self):- self.assertEqual(self.pkg["version"], "0.6.0")+ 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")diff --git a/tests/test_version.py b/tests/test_version.pynew file mode 100644index 00000000..786b6015--- /dev/null+++ b/tests/test_version.py@@ -0,0 +1,83 @@+"""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()