Local-first π§ memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly π΄ dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
v0.10.11: Multi-runtime install orchestrator + Most-applied in digest
Sol Aitkenf819f32b2517
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 383cfcaa..2d1abf34 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.10",+ "version": "0.10.11","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex b3884629..30003129 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.10",+ "version": "0.10.11","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 57b7d13d..816e13a0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,76 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [0.10.11] - 2026-05-20++Multi-runtime install orchestrator plus a configurable+`Most-applied (Nd)` block surfaced to operators alongside the+existing lifetime-top section. One PR delivers seven new install+targets, a wizard, a runtime-install health check, and a partial+uptake of session-transcript awareness in the discipline report.+Companion design and impl plan at+`docs/plans/2026-05-20-multi-runtime-install-design.md` and+`docs/plans/2026-05-20-multi-runtime-install-impl.md`.++### Added++- `o2b install --target <name>` for seven additional runtimes+ alongside the existing Hermes / OpenClaw / Codex / Claude Code+ paths: `cursor`, `aider`, `opencode`, `kiro`, `copilot-cli`,+ `gemini-cli`, `pi`, plus a `generic` printout target for the+ long tail. Default invocation (no `--target`) is detect-only;+ `--apply` is required for any file writes, `--dry-run` /+ `--check` cover the other read-only modes. JSON-merge runtimes+ preserve user-authored keys; Aider uses a marker-fenced managed+ block plus a sidecar context file; Pi uses a symlink; generic+ prints to stdout or `--out <path>`.+- `o2b uninstall --target <name>` paired with the new+ `<vault>/.open-second-brain/install.lock.json` sidecar manifest.+ Removes exactly what install wrote and never user-authored+ config; refuses without `--force-from-snippet` when no manifest+ entry exists.+- `o2b init --interactive` first-time-setup wizard. Composes+ `o2b init`, `o2b brain init`, and per-target `o2b install`+ behind a single linear flow. Stdin-driven; safe-by-default+ confirmation gate before any side effects.+- `o2b install --check [--target X]` runtime health check.+ Reports per-runtime status (`ok` / `drift` / `not-installed` /+ `mcp-unreachable`) and prints the exact repair command. Exit+ code 3 on drift, 0 otherwise.+- `o2b mcp --writer-only` flag β alias for `--scope writer`,+ used by every JSON-merge adapter when it writes the second of+ the two registered MCP servers.+- `o2b mcp --probe` flag β in-process MCP handshake used by+ `o2b install --check` to confirm the server starts cleanly.+- `_brain.yaml` block `active.{most_applied_window_days,+ most_applied_limit}` (defaults 30 / 10; bounds 1..365 / 1..50).+ Both `Brain/active.md` and `brain_digest` honour the values;+ defaults unchanged from prior behaviour.+- `Most-applied (Nd)` section in `brain_digest` Markdown plus a+ mirrored `most_applied` field in the JSON form. Rendered only+ when the window contains at least one applied event; JSON form+ always carries the shape (with empty `entries` when applicable).+- Per-runtime session-transcript awareness in the daily discipline+ report. Resolvers for Claude Code, Codex, and Cursor surface a+ `transcript-confirmed` sub-reason on `alert` rows when the proxy+ signal lines up with runtime transcripts dated to the same day.+ Remaining runtimes (opencode / kiro / Copilot CLI / Gemini CLI /+ Aider / Pi) stay deferred.+- Bundled Aider context template+ `templates/install/aider-context.md.tmpl`.++### Notes++- Design closes `_summary.md` Β§4 second half (full installer with+ auto-detect + managed block + dry-run) and Β§15 second half+ (interactive `o2b init` wizard). Project-scope MCP config and+ Pi path auto-detect remain deferred.+- The `_brain.yaml` schema accepts the new `active:` block as flat+ keys (`most_applied_window_days`, `most_applied_limit`). The+ two-level YAML parser drove the choice; the in-memory+ `BrainActiveConfig.most_applied` still groups them so consumers+ pass one struct around.+## [0.10.10] - 2026-05-20Pull channels for runtimes without `SessionStart`. Adds an MCPdiff --git a/README.md b/README.mdindex 75dfd994..954adc66 100644--- a/README.md+++ b/README.md@@ -57,7 +57,8 @@ safety invariants are in [`docs/how-it-works.md`](docs/how-it-works.md).| Claude Code | Marketplace plugin + bundled `.mcp.json` + lifecycle hooks | `hooks/hooks.json` registers a `PostToolUse` reminder that points the agent at `brain_feedback` / `brain_apply_evidence` after every Write/Edit. See [`hooks/`](hooks/). || OpenAI Codex | Marketplace plugin + MCP server + lifecycle hooks | Same hook bundle as Claude Code. || OpenClaw | Native JS plugin (`openclaw.extensions`) β no MCP needed | Core query/status/health tools are registered directly inside OpenClaw's Node.js process. Native parity with the `brain_*` tools is tracked separately in the post-v0.9 roadmap. |-| Other MCP hosts | Generic adapter (stdio MCP server, persisted plugin config) | See `install.md` branch E for the contract. |+| Cursor / Aider / opencode / kiro / Copilot CLI / Gemini CLI / Pi | One-shot `o2b install --target <name> --apply` | v0.10.11 multi-runtime orchestrator with idempotent managed block and sidecar manifest. See `install/<name>.md` and `install.md`. |+| Other MCP hosts | Generic adapter (stdio MCP server, persisted plugin config) | `o2b install --target generic --apply --out -` prints the payload; see `install/generic.md`. |## What it does@@ -81,31 +82,34 @@ safety invariants are in [`docs/how-it-works.md`](docs/how-it-works.md).## Install-`install.md` is the canonical install guide. It is written so an-agent can read it directly and pick the right branch by runtime-name. The recommended way to install is to send your agent the-prompt below β replace `[runtime]` with `Hermes`, `Claude Code`,-`Codex`, or `OpenClaw`:+`install.md` is a short router. Pick the matching per-runtime page+under [`install/`](install/) and follow it end-to-end. The+MCP-aware runtimes share one CLI orchestrator:-```text-Install the open-second-brain plugin for [runtime] following the-instructions at-https://raw.githubusercontent.com/itechmeat/open-second-brain/main/install.md+```bash+o2b install --target <name> --apply+o2b install --check```-For manual installs, follow the matching branch in-[`install.md`](install.md) directly:+Supported `--target` values: `cursor`, `aider`, `opencode`, `kiro`,+`copilot-cli`, `gemini-cli`, `pi`, `generic`. Each writes a sidecar+manifest at `<vault>/.open-second-brain/install.lock.json` so+`o2b uninstall --target <name> --apply` removes exactly what was+added.++For runtimes that ship their own plugin/MCP install pipeline+(Hermes, Claude Code, Codex, OpenClaw) the corresponding+`install/<runtime>.md` walks through the runtime-native flow.-- Branch A β Hermes-- Branch B β OpenClaw-- Branch C β Codex-- Branch D β Claude Code-- Branch E β generic adapter (other runtimes)+First-time-setup users can also run a guided wizard:++```bash+o2b init --interactive+```-Each branch covers the same six steps: collect vault path, install-plugin, publish CLI to PATH (`o2b install-cli`), initialise the-vault (`o2b init`), register the MCP server (where needed), and-verify with `o2b doctor` + a daily-identity check.+The wizard composes `o2b init`, optional `o2b brain init`, and+per-target `o2b install` behind a single linear question/answer+flow with an explicit confirmation gate.## CLIdiff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 3bc95af3..80b4a0d1 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -320,13 +320,16 @@ flowchart LR```- **`Brain/active.md`** is a derived Markdown digest: confirmed- preferences (id, scope, confidence, principle), a `Most-applied- (30d)` section ranking up to ten confirmed/quarantine rules by- `apply-evidence (result: applied)` events in the trailing- 30-day window, quarantined preferences with their applied /+ preferences (id, scope, confidence, principle), a+ `Most-applied (Nd)` section ranking confirmed/quarantine rules+ by `apply-evidence (result: applied)` events in the trailing+ window (defaults to 30 days / top-10; configurable via+ `active.most_applied_window_days` and `active.most_applied_limit`+ in `_brain.yaml`), quarantined preferences with their applied /violated counters, and the three most recently retired entries.The writer is idempotent β if the rendered body matches the file- on disk, no I/O happens.+ on disk, no I/O happens. The same window / limit drive a mirrored+ `Most-applied (Nd)` section in `brain_digest` output.- **SessionStart hook** (`startup | resume | clear`) and**PostCompact hook** (`manual | auto`) inject the body as`additionalContext` so the agent sees current rules at the start ofdiff --git a/docs/plans/2026-05-20-multi-runtime-install-design.md b/docs/plans/2026-05-20-multi-runtime-install-design.mdnew file mode 100644index 00000000..e487d4c2--- /dev/null+++ b/docs/plans/2026-05-20-multi-runtime-install-design.md@@ -0,0 +1,945 @@+# Multi-runtime install orchestrator + Most-applied in digest β design++Status: design+Target release: v0.10.11 (additive; no breaking CLI contract)+Closes / advances:++- `_summary.md` Β§4 second half (Deferred work) β full `o2b install --target X`+ orchestrator with auto-detect, idempotent managed-block / JSON-merge,+ `--dry-run` and `--check`.+- `_summary.md` Β§15 second half (Deferred work) β interactive+ `o2b init --interactive` wizard.+- `_summary.md` Β§13 cousin β `Most-applied (Nd)` block in `brain_digest`+ mirroring `active.md`, with `_brain.yaml`-driven window and limit.+- New companion lint surface β `o2b install --check` covers the+ "I installed it but it doesn't run" reports.+- `_summary.md` Deferred Β§D non-bash-runtime activity sources β partial+ uptake (Claude Code / Codex / Cursor session-transcript adapters land+ with this change; opencode / kiro / Copilot CLI / Gemini CLI / Aider /+ Pi stay deferred).++---++## 1. Scope and motivation++### 1.1 What this change delivers++Two themes plus three companions, all wired through a single new+abstraction layer (`InstallAdapter`).++**Theme 1 β single-command install across runtimes.** Today, installing+OSB on a new runtime requires walking `install.md` (1350 lines, five+hand-maintained branches AβE) and translating each step into the+runtime's native plugin / MCP machinery. The supported set is+{Hermes, OpenClaw, Codex, Claude Code, generic}; everything else β Cursor,+Aider, opencode, kiro, GitHub Copilot CLI, Google Gemini CLI, Pi β is+manual. After this change:++```+o2b install # detect-only; prints a table of detected+ # runtimes + the exact command to install+o2b install --target X # plan-only; prints what would be written+o2b install --target X --apply # apply the plan; idempotent+o2b install --target X --check # post-install verify: managed block on+ # disk + MCP server responds+o2b uninstall --target X --apply # remove exactly what install wrote,+ # never user-authored config+o2b init --interactive # wizard that composes the commands+ # above into the first-time setup path+```++The seven new targets ship together: `cursor`, `aider`, `opencode`,+`kiro`, `copilot-cli`, `gemini-cli`, `pi`, `generic`. Existing targets+(`claudecode`, `codex`, `hermes`, `openclaw`) are not changed in this+PR β they keep their current install paths (documented in+`install/claudecode.md`, etc., after the doc restructure).++**Theme 2 β Most-applied surfaced to operators, not only agents.**+`Brain/active.md` already carries a `## Most-applied (30d)` block since+v0.10.10. `brain_digest` carries `## Top applied` (lifetime), but no+windowed equivalent. Operators reading the daily digest cannot tell+which rules are firing _now_ versus _ever_. After this change, both+`active.md` and `brain_digest` share one computer and one config block+(`active.most_applied.{window_days, limit}` in `Brain/_brain.yaml`).++**Companion 1 β `o2b install --check`.** Adapter-driven runtime health+check that catches the most common operator complaint ("I installed+it but the agent doesn't see it"). Not in `brain doctor` β that command+stays scoped to vault invariants.++**Companion 2 β partial uptake of per-runtime session-transcript+parsing in `o2b discipline report`.** The current "agent worked but did+not record" detector is runtime-agnostic (git + mtime + vault delta).+With install-time runtime detection in place, we can cheaply ask each+adapter "where do your session transcripts live?" and confirm activity+from the runtime's own logs. First round: Claude Code, Codex, Cursor+(transcript paths are documented and stable). Other runtimes stay on+the agnostic proxy until their transcript story stabilises.++**Companion 3 β `install/` documentation split.** `install.md` becomes+a short router pointing at `install/<target>.md`. Each per-runtime+file is the runtime-specific one-liner plus its caveats β terse enough+for an agent to consume verbatim, still readable for a human.++### 1.2 Out of scope for this PR++- Refactor of existing `claudecode` / `codex` / `hermes` / `openclaw`+ install flows. Those work today and have their own per-runtime+ branches. After this PR they live behind the same `InstallAdapter`+ interface for consistency, but the on-disk effect is unchanged.+- Pi runtime path resolution beyond the documented `~/.pi/skills/`+ default. If Pi stabilises a different convention, we add detection+ in a follow-up.+- Auto-merge of session-transcript signals into Brain (e.g. extracting+ user preferences from Cursor chat). Discipline-report only counts+ activity from transcripts; it does not _import_ them.+- New permission / sandbox features. Install never edits anything+ outside the runtime's documented config location and the vault's+ sidecar.++---++## 2. Architecture++### 2.1 Module layout++```+src/+ core/+ install/+ types.ts # InstallAdapter, InstallPlan, ManifestEntry, ...+ registry.ts # Map<target, InstallAdapter>, detectAll()+ manifest.ts # sidecar I/O (<vault>/.open-second-brain/install.lock.json)+ managed-block.ts # marker-fenced editor for text/YAML/TOML+ json-merge.ts # safe mcpServers merge (preserves user keys)+ payload.ts # builds the MCP-server payload from current config+ session-paths.ts # per-target session-transcript globs+ adapters/+ cursor.ts+ aider.ts+ opencode.ts+ kiro.ts+ copilot-cli.ts+ gemini-cli.ts+ pi.ts+ generic.ts+ brain/+ most-applied.ts # extended: windowDays/limit options+ digest.ts # extended: most_applied block (text + JSON)+ active.ts # uses computeMostApplied with config values+ policy.ts # _brain.yaml loader extended for active.* block+ cli/+ install/+ install.ts # `o2b install [--target X] [--apply|--check]`+ uninstall.ts # `o2b uninstall --target X [--apply]`+ init-interactive.ts # `o2b init --interactive` wizard+ render.ts # table / plan / verify renderers+docs/+ install.md # router/index+ install/+ prerequisites.md+ cursor.md+ aider.md+ opencode.md+ kiro.md+ copilot-cli.md+ gemini-cli.md+ pi.md+ claudecode.md # current Branch D, restructured+ codex.md # current Branch C, restructured+ hermes.md # current Branch A, restructured+ openclaw.md # current Branch B, restructured+ generic.md # current Branch E + stdout/file format+templates/+ install/+ aider-context.md.tmpl # Aider's read-list payload (skill summary)+tests/+ fixtures/install/<target>/+ before.{json|yml|txt}+ after.{json|yml|txt}+ manifest.json+```++### 2.2 InstallAdapter interface++```typescript+export interface InstallEnv {+ readonly vault: string;+ readonly home: string;+ readonly cwd: string;+ readonly env: Readonly<Record<string, string>>;+ readonly now: Date;+}++export type AdapterStatus =+ | "not-installed"+ | "installed"+ | "drift"+ | "unsupported-on-this-platform";++export interface DetectResult {+ readonly target: string;+ readonly status: AdapterStatus;+ readonly configPath: string | null;+ readonly notes: ReadonlyArray<string>;+}++export interface InstallStep {+ readonly kind:+ | "json-merge"+ | "managed-block"+ | "subprocess"+ | "file-copy"+ | "symlink"+ | "print";+ readonly path: string | null; // null for print / subprocess+ readonly preview: string; // human-readable diff or command+}++export interface InstallPlan {+ readonly target: string;+ readonly steps: ReadonlyArray<InstallStep>;+ readonly postNotes: ReadonlyArray<string>;+}++export interface ApplyOpts {+ readonly dryRun: boolean;+ readonly stdout: NodeJS.WriteStream;+ readonly stderr: NodeJS.WriteStream;+}++export interface ManifestEntry {+ readonly target: string;+ readonly applied_at: string; // ISO+ readonly operation: InstallStep["kind"];+ readonly config_path: string | null;+ readonly owned_keys?: ReadonlyArray<string>; // JSON pointer paths+ readonly owned_paths?: ReadonlyArray<string>; // absolute fs paths+ readonly owned_block_marker?: string; // marker text for managed-block+}++export interface ApplyResult {+ readonly target: string;+ readonly manifest: ManifestEntry;+ readonly steps_executed: number;+}++export interface UninstallResult {+ readonly target: string;+ readonly removed_keys: ReadonlyArray<string>;+ readonly removed_paths: ReadonlyArray<string>;+ readonly skipped: ReadonlyArray<readonly [string, string]>; // (what, reason)+}++export interface VerifyResult {+ readonly target: string;+ readonly status: "ok" | "drift" | "not-installed" | "mcp-unreachable";+ readonly details: ReadonlyArray<string>;+ readonly fix_hint: string | null; // exact command to repair+}++export interface SessionPathsResult {+ readonly target: string;+ readonly paths: ReadonlyArray<string>;+ readonly format: "claude-jsonl" | "codex-json" | "cursor-sqlite" | "unknown";+}++export interface InstallAdapter {+ readonly target: string;+ readonly label: string;+ detect(env: InstallEnv): DetectResult;+ plan(payload: McpPayload, env: InstallEnv): InstallPlan;+ apply(plan: InstallPlan, env: InstallEnv, opts: ApplyOpts): ApplyResult;+ uninstall(env: InstallEnv, opts: ApplyOpts): UninstallResult;+ verify(env: InstallEnv): VerifyResult;+ sessionPaths?(env: InstallEnv): SessionPathsResult | null;+}+```++`InstallAdapter` is the single seam everything else hangs off:++- `install.ts` CLI verb calls `detect β plan β apply β verify`.+- `uninstall.ts` calls `uninstall` (which reads sidecar manifest).+- `o2b install --check` calls `verify` per target.+- `o2b init --interactive` calls `registry.detectAll()` and then+ delegates to per-target `plan / apply` for the chosen targets.+- `o2b discipline report` calls `sessionPaths` for targets that+ implement it.++### 2.3 Idempotency model++Two patterns, picked per target by the adapter:++**JSON-merge (Cursor / opencode / kiro / Gemini CLI / Copilot CLI+fallback file).** The adapter parses the existing JSON, replaces or+inserts exactly two well-known keys (`mcpServers.open-second-brain`,+`mcpServers.open-second-brain-writer`), writes back with the same+indentation if detectable. Re-running `--apply` overwrites those two+keys verbatim and leaves every other key unchanged. `uninstall`+removes exactly those two keys based on the sidecar manifest.++**Marker-fenced block (Aider, generic-text-fallback).** The adapter+wraps its payload between `# >>> open-second-brain managed >>>` and+`# <<< open-second-brain managed <<<` markers (mirroring the existing+`o2b brain protect --target codex` convention). The block is the unit+of overwrite β content between markers is replaced atomically;+content outside is never touched. `uninstall` removes both markers+and everything between them.++In both cases the sidecar manifest records the exact intent. The+uninstall path is **manifest-driven**, not heuristic. Without a+sidecar entry, `uninstall` refuses unless `--force-from-snippet` is+passed (which then performs an exact-match check on the current OSB+payload signature, and removes only on full match).++### 2.4 Sidecar manifest++Path: `<vault>/.open-second-brain/install.lock.json`. Shared+directory with `protect.lock.json`, schema is independent.++```json+{+ "schema_version": 1,+ "installs": {+ "cursor": {+ "applied_at": "...Z",+ "operation": "json-merge",+ "config_path": "/home/user/.cursor/mcp.json",+ "owned_keys": [+ "mcpServers.open-second-brain",+ "mcpServers.open-second-brain-writer"+ ]+ },+ "aider": {+ "applied_at": "...Z",+ "operation": "managed-block",+ "config_path": "/home/user/.aider.conf.yml",+ "owned_block_marker": "# >>> open-second-brain managed >>>"+ },+ "pi": {+ "applied_at": "...Z",+ "operation": "symlink",+ "owned_paths": ["/home/user/.pi/skills/brain-memory"]+ }+ }+}+```++Atomic writes via the existing `atomicWriteFileSync` helper. Reads+tolerate missing file (returns `{ schema_version: 1, installs: {} }`)+and forward-compat unknown keys (logged as warnings, not errors).++---++## 3. Per-target adapters++### 3.1 `cursor`++- Operation: JSON-merge.+- Detect:+ - Default scope is user-global. Config path:+ `${XDG_CONFIG_HOME:-$HOME}/.cursor/mcp.json`. macOS fallback:+ `~/.cursor/mcp.json`.+ - `--scope project` (`<cwd>/.cursor/mcp.json`) is deferred β see Β§12.+- Plan: insert/replace two keys in `mcpServers`.+- Apply: write JSON, record manifest with both `owned_keys`.+- Verify: file parses as JSON, both keys present, optional MCP ping via+ `o2b mcp --probe`. Cursor needs an app-restart to reload β `verify`+ surfaces "MCP server registered on disk; restart Cursor to load"+ rather than treating "no ping yet" as failure.+- Uninstall: remove both `owned_keys`. If `mcpServers` is now empty,+ drop the empty object too.++### 3.2 `aider`++- Operation: managed-block in YAML config + sidecar context file.+- Detect:+ - Config path candidates (first wins): `<cwd>/.aider.conf.yml`,+ `$AIDER_CONFIG`, `~/.aider.conf.yml`.+- Plan:+ 1. Generate `<vault>/.open-second-brain/aider-context.md` from+ `templates/install/aider-context.md.tmpl` (one render per+ install; idempotent overwrite).+ 2. Add managed-block to `~/.aider.conf.yml` under the `read:` list,+ adding the generated context file path.+- Apply: write both files; manifest records `owned_block_marker` and+ `owned_paths: ['<vault>/.open-second-brain/aider-context.md']`.+- Verify: managed-block present, generated file exists, generated+ file is non-empty.+- Uninstall: remove managed-block; remove generated file.+- Open question for impl: confirm via WebFetch whether Aider has+ native MCP at impl time. If yes, switch to JSON-merge against+ Aider's MCP config; if no, the managed-block path stays. The+ adapter is structured to allow either without rewriting callers.++### 3.3 `opencode`++- Operation: JSON-merge.+- Detect: `${XDG_CONFIG_HOME:-$HOME/.config}/opencode/mcp.json`.+- Plan / apply / verify / uninstall: identical pattern to `cursor`.+- Impl note: confirm config path via opencode upstream docs at impl+ time; the path above is the documented default but may move.++### 3.4 `kiro`++- Operation: JSON-merge.+- Detect: `~/.kiro/settings.json` (verify at impl time).+- Plan / apply / verify / uninstall: identical pattern.++### 3.5 `copilot-cli`++- Operation: subprocess, with JSON-merge fallback.+- Detect: `command -v copilot` (or `gh copilot` per upstream docs).+- Plan:+ 1. If `copilot` CLI is on PATH: `copilot mcp remove open-second-brain`+ then `copilot mcp add open-second-brain ...` (twice β once per+ name). The CLI is the official path per+ `docs.github.com/copilot/how-tos/copilot-cli/customize-copilot/add-mcp-servers`.+ 2. Else: JSON-merge fallback at the documented file location.+- Apply: execute subprocess sequence or JSON-merge; manifest records+ `operation: "subprocess"` plus a `fallback_file` field when the+ fallback path was used.+- Verify: `copilot mcp list` shows both names (subprocess form) or+ config file parses with both keys (fallback form), plus MCP ping.+- Uninstall: `copilot mcp remove` per name, or remove JSON keys.++### 3.6 `gemini-cli`++- Operation: JSON-merge in `~/.gemini/settings.json` under `mcpServers`.+ Anchored in `github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md`.+- Plan / apply / verify / uninstall: standard JSON-merge.+- Verify ping: `gemini --help` exit-code 0 (cheap liveness),+ `gemini --version` for runtime version, and `o2b mcp --probe`+ for the MCP-side handshake.++### 3.7 `pi`++- Operation: symlink, no config edit.+- Detect: `${PI_HOME:-$HOME/.pi}`. Adapter creates the `skills/`+ subdir if missing.+- Plan: `ln -s <plugin-checkout>/skills/brain-memory $PI_HOME/skills/brain-memory`.+- Apply: create symlink; manifest records `owned_paths`.+- Verify: symlink exists, target resolves to a readable+ `brain-memory/SKILL.md`.+- Uninstall: remove symlink only (never the source).+- Open question for impl: confirm Pi's actual skills directory+ convention. If pi.dev / pi-mono stabilises a different layout,+ the adapter accepts `--pi-skill-dir <path>` as an override and+ records the chosen path in the manifest.++### 3.8 `generic`++- Operation: print.+- Detect: always `not-installed` (no canonical config to detect).+- Plan: build the MCP server payload (`o2b mcp` command + env) and+ render as JSON or YAML.+- Apply: write to `--out <path>` (or stdout if `--out -` or absent).+ Never edits any other file. Manifest records the output path so+ uninstall can report "you wrote it to /path/X; remove it yourself".+- Verify: if `--out <path>` was used, check the file still exists+ and parses. Else `not-installed`.+- Uninstall: print the path; do not delete (the operator chose+ where to put it; the runtime that consumed it may not know about+ our manifest).++### 3.9 Shared helpers++**`payload.ts`** builds the canonical MCP server payload from+`~/.config/open-second-brain/config.yaml`:++```json+{+ "command": "o2b",+ "args": ["mcp", "--vault", "<vault>"],+ "env": { "VAULT_AGENT_NAME": "...", "VAULT_TIMEZONE": "..." }+}+```++Two variants: full server (`open-second-brain`) and writer-only+(`open-second-brain-writer`, `args: ["mcp", "--writer-only"]`). The+writer-only path adds a new `--writer-only` flag to `o2b mcp` that+filters `buildToolTable()` to the three writer tools + `brain_context`+(consistent with the existing `alwaysLoad` writer-MCP server+introduced in v0.10.7).++**`json-merge.ts`** loads JSON5-tolerant (BOM, trailing newline),+records original indentation when detectable, replaces exactly the+two named keys under `mcpServers`, writes back with the original+indentation. No reformatting of unrelated content. If `mcpServers`+is missing, creates it; if the file is missing, creates it with+both keys only.++**`managed-block.ts`** matches the existing `protect.ts` marker+convention. Replaces the block atomically; rejects nested markers;+preserves surrounding content byte-for-byte.++**`manifest.ts`** is a thin sidecar I/O helper. The manifest schema+is independent of the rest of Brain β it lives under+`<vault>/.open-second-brain/` rather than `<vault>/Brain/` because+it tracks runtime-side state, not Brain memory state.++---++## 4. `o2b install` CLI surface++### 4.1 Verbs and flags++```+o2b install # detect-only; table output+o2b install --json # same, JSON++o2b install --target X # plan-only; prints what would change+o2b install --target X --apply # execute the plan+o2b install --target X --apply --json # apply + machine output++o2b install --target generic --out <path> # write payload to file+o2b install --target generic --out - # write payload to stdout+o2b install --target generic --format json # default+o2b install --target generic --format yaml++o2b install --check # verify all known runtimes+o2b install --check --target X # verify one+o2b install --check --json # machine output++o2b uninstall --target X # dry-run+o2b uninstall --target X --apply # remove what install wrote+o2b uninstall --target X --force-from-snippet+ # uninstall without sidecar entry,+ # using exact-payload match+```++The default `o2b install` (no flag) is **detect-only by design**.+This is the safest entry-point for the active user (the Hermes agent+on this VPS): zero side effects until `--apply` is named. Plan-mode+(`--target X` without `--apply`) is the second-safest: human-readable+diff per step, still no writes.++### 4.2 Exit codes++| code | meaning |+|------|---------|+| 0 | success (or `--check` reports all-ok / not-installed) |+| 1 | I/O error, parse error, subprocess failure |+| 2 | usage error (unknown target, missing flag) |+| 3 | `--check` found drift |+| 4 | `--apply` would have touched a file modified outside our managed-block / outside our owned JSON keys; aborted to avoid clobbering user changes |++Exit-code 4 is the safety net: when re-applying, the adapter builds+the canonical payload it would write right now (from the current+plugin config), reads the current on-disk content of the owned keys+or marker block, and compares them. If they differ **and** the+target file's mtime is newer than the manifest's `applied_at`, the+adapter refuses to overwrite without `--force`. This catches "user+hand-edited our block; don't blow it away on next `--apply`". No+content hash is stored in the manifest β the canonical payload is+fully determined by the plugin config plus a fixed payload template,+so it can be regenerated deterministically.++### 4.3 Output format++Default text output is operator-facing. Same data renders as JSON+under `--json` for the Hermes agent. Both formats include enough+detail for the agent to produce a follow-up command without needing+a second probe.++Detect-only table (excerpt):++```+o2b install β detected runtimes+-------------------------------+ cursor installed ~/.cursor/mcp.json (2 OSB keys present)+ aider not-installed ~/.aider.conf.yml exists (no managed block)+ opencode not-installed (config file missing)+ pi installed ~/.pi/skills/brain-memory (symlink ok)+ gemini-cli drift ~/.gemini/settings.json: writer key missing+ fix: o2b install --target gemini-cli --apply++5 runtimes in registry; 2 installed, 1 drift, 2 not-installed.+```++---++## 5. `o2b init --interactive` wizard++Plain linear script β no TUI library. The wizard is a thin composer+over already-existing commands; no parallel implementation of+"what `o2b init` does".++Flow:++1. Vault path β scan `~/`, `~/Documents/`, `~/Sync/`, `~/Dropbox/`,+ `~/Library/Mobile Documents/.../Documents/` for `.obsidian/`.+ Numbered list + "other path" option.+2. Agent name β check `~/.config/open-second-brain/config.yaml` and+ `<vault>/AI Wiki/identity/agents.md` first. If found, offer to+ reuse; else propose `<hostname>-<runtime>` defaults + custom.+3. Timezone β free-form input; local IANA normalisation; one retry+ on invalid.+4. Language β optional; ISO 639-1 code; defaults to `en`. Recorded+ in plugin config for future language-aware behaviour.+5. Runtime selection β `registry.detectAll()` numbered list ++ "select multiple as comma-separated".+6. Optional `o2b brain init [--starter]`.+7. Summary plan β print the entire action list. Default answer:+ no. Require explicit `yes`.+8. Apply β `o2b init ...`, `o2b brain init ...`, then for each+ chosen runtime `o2b install --target X --apply`.+9. Verify β final `o2b install --check`.++Implementation: `src/cli/install/init-interactive.ts`. Tested via+mock-stdin / mock-stdout (`Bun.stdin` rewriting in test setup).++---++## 6. `o2b install --check` design++Per-target verifier driven by `adapter.verify()`:++1. **Sidecar manifest probe.** Look up the target's entry. Missing β+ status `not-installed`.+2. **Disk state.** For `json-merge`: file parses; both `owned_keys`+ present and match the canonical payload. For `managed-block`:+ marker pair found; content between markers matches canonical+ payload. For `symlink`: link exists and target resolves.+3. **MCP probe (where applicable).** Spawn `o2b mcp --probe`. The+ `--probe` flag is a new sub-flag on `o2b mcp`: it performs the+ MCP `initialize` handshake, reports tool count, and exits 0.+ Non-MCP targets (Pi, generic) skip the probe.+4. **Side-channel hint.** Cursor needs an app restart for MCP+ reload; the verifier surfaces this rather than treating "no+ ping" as failure when disk state is otherwise ok.++Output (text):++```+o2b install --check+-------------------+ cursor ok managed: ~/.cursor/mcp.json (2/2 keys; restart Cursor to load)+ gemini-cli drift managed: ~/.gemini/settings.json β writer key missing+ fix: o2b install --target gemini-cli --apply+ pi ok symlink: ~/.pi/skills/brain-memory β <repo>/skills/brain-memory+ copilot-cli not-installed+```++Exit code: 0 on all-ok-or-not-installed, 3 on any drift, 1 on I/O+error. JSON form mirrors text form field-for-field.++---++## 7. `brain_digest` extension (Theme 2)++### 7.1 Config block++`Brain/_brain.yaml` gains an optional top-level `active` block:++```yaml+schema_version: 1+active:+ most_applied:+ window_days: 30 # int 1..365; default 30+ limit: 10 # int 1..50; default 10+```++Loader (`policy.ts`) returns `BrainActiveConfig | undefined`.+Validator rejects out-of-range and non-integer values with+`BrainConfigError` carrying the offending value and the accepted+range. Default values are not back-filled into the config object β+consumers read `cfg.active?.most_applied?.window_days ?? 30`.++`o2b brain upgrade` (additive deep-merge, v0.10.6) carries the new+block forward for existing vaults without user action; the starter+bundle ships the block populated at defaults so new vaults document+the knob.++### 7.2 Computer++`computeMostApplied(vault, prefs, opts)` already exists. Signature+change is additive:++```typescript+interface ComputeMostAppliedOptions {+ readonly now?: Date;+ readonly windowDays?: number; // default 30+ readonly limit?: number; // default 10+}+```++Internal `WINDOW_MS` is replaced with `windowDaysToMs(windowDays)`.+Day-level fence (`earliestDayPrefix`) still subtracts one day from+window start for UTC drift; that fence is independent of+`windowDays`.++### 7.3 Digest output++JSON (additive β `top_applied` lifetime block stays):++```json+{+ "top_applied": [...],+ "most_applied": {+ "window_days": 30,+ "limit": 10,+ "entries": [+ { "id": "pref-no-em-dashes", "principle": "...", "applied_in_window": 12 },+ ...+ ]+ }+}+```++Markdown (new section, rendered only when `entries.length > 0`):++```markdown+## Most-applied (30d)++- [[pref-no-em-dashes|No em-dashes in Russian prose]] β 12 applied+- [[pref-no-simply-word|Never use "simply"]] β 8 applied+```++Header text uses the actual `window_days` value (`(30d)`, `(14d)`,+`(7d)`). Empty-window markdown skips the section entirely; empty-+window JSON still emits the block with `entries: []` so machine+consumers see the shape.++### 7.4 `active.md`++`regenerateActive` now reads `cfg.active?.most_applied`. The+`active.md` header still says `Most-applied (30d)` when the config+holds the default; for non-default windows the header reflects the+actual value. Hash-stability for golden tests is preserved by+threading `now` through.++---++## 8. `o2b discipline report` extension (Companion 2)++`adapter.sessionPaths(env)` is optional. First-round implementers:++- `claudecode` β Claude Code project transcripts (`~/.claude/projects/`+ layout). Adapter reuses the path resolver from+ `src/core/brain/claude-memory-paths.ts`; format `claude-jsonl`.+- `codex` β Codex per-session transcripts under `~/.codex/`.+ Adapter resolves the exact subdirectory at impl time from the+ current Codex CLI version (the location has moved at least once+ upstream); format `codex-json`.+- `cursor` β Cursor workspace storage SQLite files+ (`~/.cursor/.../state.vscdb` on Linux, `~/Library/Application+ Support/Cursor/User/workspaceStorage/<hash>/state.vscdb` on+ macOS). Adapter resolves the exact path at impl time; format+ `cursor-sqlite`. Reader uses `bun:sqlite` (already in our stack).++For each path glob, the report:++1. Lists files modified inside the report window.+2. Reads each file, counts "agent-active turns" (tool calls+ detected: Claude `assistant.message.content[*].input` for+ `Write|Edit|MultiEdit|apply_patch`; Codex equivalent; Cursor+ reads from `aiServer.*` rows).+3. Computes per-agent activity-with-no-brain-events: an agent name+ appears in transcripts inside the window, but no `feedback` /+ `apply-evidence` / `note` event in `Brain/log/<date>.jsonl`+ carries the same agent for that day.++Status taxonomy adds a sub-reason in alert: `transcript-confirmed`+when the transcript glob confirms activity that the existing+proxy (git + mtime + vault-delta) also flagged. This reduces false+positives where activity was inferred from mtime but the agent+genuinely did read-only work.++Adapters without a `sessionPaths` implementation return `null`;+the report falls back to the existing proxy for those agents.++---++## 9. Documentation restructure (Companion 3)++### 9.1 New layout++```+docs/+ install.md # router; ~80 lines+ install/+ prerequisites.md # Bun, common preconditions+ cursor.md # ~50 lines: command + caveats + verify+ aider.md+ opencode.md+ kiro.md+ copilot-cli.md+ gemini-cli.md+ pi.md+ claudecode.md # current Branch D content, restructured+ codex.md # current Branch C+ hermes.md # current Branch A+ openclaw.md # current Branch B+ generic.md # current Branch E + stdout/file format+```++`install.md` (router) holds:++- One-paragraph intro to what OSB is.+- Link to `install/prerequisites.md`.+- Table of supported runtimes with one-liner command and link to+ per-runtime detail.+- Two paragraphs: `o2b init --interactive` and uninstall.+- Pointer to `install/generic.md` for runtimes outside the supported+ list.++Per-runtime files are terse β operator-readable, agent-consumable,+no historical context. Anything that needed two paragraphs of+rationale stays in the design doc, not the install guide.++### 9.2 README++Add a "Quick install" section above existing content:++```markdown+## Quick install++```+o2b install --target <name> --apply+```++| runtime | target name |+|---|---|+| Cursor | `cursor` |+| Aider | `aider` |+| opencode | `opencode` |+| kiro | `kiro` |+| GitHub Copilot CLI | `copilot-cli` |+| Google Gemini CLI | `gemini-cli` |+| Pi (pi.dev) | `pi` |+| Claude Code | `claudecode` |+| Codex | `codex` |+| Hermes | `hermes` |+| OpenClaw | `openclaw` |+| any other (printout) | `generic` |++See `docs/install.md` for per-runtime detail.+```++---++## 10. Testing strategy++### 10.1 Unit++- `managed-block.ts`: clean insert, idempotent overwrite, rejection+ of nested markers, byte-preservation of surrounding content,+ LF/CRLF tolerance.+- `json-merge.ts`: insert-into-empty, replace-existing-keys,+ preserve-unrelated-keys, preserve-indentation, BOM tolerance,+ trailing-newline preservation.+- `manifest.ts`: missing file β empty manifest, forward-compat+ unknown keys, atomic write, concurrent-write safety (mtime+ monotonicity).+- `payload.ts`: full server vs writer-only payloads;+ config-missing vs config-present; env-var override.++### 10.2 Per-adapter++Each adapter has a `tests/fixtures/install/<target>/` directory:++- `before.{json|yml|txt}` β config file contents before install+ (with realistic user keys mixed in).+- `after.{json|yml|txt}` β expected contents after install.+- `manifest.json` β expected sidecar manifest entry.+- Test cases per adapter:+ - clean install (`before.json` doesn't have OSB keys)+ - re-apply (apply twice; second is no-op; manifest `applied_at`+ is updated, file bytes do not change unless the canonical+ payload changed)+ - drift detection (manually mutate the file, run `--check`,+ expect drift status)+ - uninstall (apply then uninstall; expect exact pre-install+ state, except for the trailing newline)+ - uninstall without manifest (`--force-from-snippet`)+ - user-modified block (mtime newer than `applied_at`, content+ differs from canonical; expect exit 4 without `--force`)++### 10.3 Integration++- `o2b init --interactive` wizard with mock-stdin scripted answers.+ Covers: clean vault, vault with prior identity, vault with+ prior Brain layer, two runtimes selected, all runtimes selected,+ user cancels at summary.+- `o2b install --check` against a tmpdir vault with mock adapters+ in all four states (`ok`, `drift`, `not-installed`, `mcp-unreachable`).++### 10.4 Brain digest tests++- Default config (no `active` block) renders 30d/10.+- Custom config (`window_days: 7, limit: 3`) renders 7d/3.+- Empty window: markdown skips the section; JSON emits empty+ `entries`.+- Invalid config: validator rejects with the offending value and+ range; loader returns the error path; `brain doctor` surfaces it.++---++## 11. Versioning, migration, rollout++- **Version:** v0.10.11. Additive: new `_brain.yaml` block (optional;+ loader returns undefined when absent), new CLI verbs, new docs+ files. No CLI flag removed, no env var renamed.+- **Schema migration:** `o2b brain upgrade --apply` adds the+ `active.most_applied` block at defaults to existing+ `_brain.yaml`. No data migration required.+- **CHANGELOG:** one entry under `v0.10.11` covering both themes+ and the three companions. Per the project convention, single PR+ β single version entry; expanded scope grows the entry, never+ bumps version mid-PR.++---++## 12. Deferred work++After this PR ships, `_summary.md` Deferred section gets these+adjustments:++- Strike: `_summary.md` Β§4 second half (closed by this PR).+- Strike: `_summary.md` Β§15 second half (closed by this PR).+- Update Companion 2 entry: "shipped partial uptake (Claude Code /+ Codex / Cursor); remaining runtimes (opencode / kiro / Copilot+ CLI / Gemini CLI / Aider / Pi) stay deferred. Trigger for+ uptake: each runtime documents a stable session-transcript path+ and we have a user actively running that runtime."++New deferred items introduced by this PR:++- `--scope project` for Cursor / opencode (and any other runtime+ that supports project-scope configs). v0.10.11 defaults to+ user-scope only. Trigger: an operator reports a vault used from+ multiple project trees, or two runtime installs on the same+ machine collide on user-scope.+- Pi path auto-detection beyond `~/.pi/skills/`. Trigger: pi.dev+ stabilises a different convention, or `--pi-skill-dir` becomes+ the common case.+- `o2b install --apply --interactive`: confirm-each-step prompt+ for users who want the wizard's safety without running the full+ `o2b init --interactive`. Trigger: explicit operator request.+- Per-target restart hooks (kill old MCP server processes after+ install). Right now we rely on the runtime's own restart cadence.+ Trigger: drift reports where the file is correct but the runtime+ did not pick up the change.++---++## 13. Open questions for impl++Each is testable at impl time with WebFetch or a one-liner probe;+not blocking design approval.++1. Aider MCP support status at impl time. If native MCP exists,+ switch the `aider` adapter from managed-block-in-YAML to+ JSON-merge against Aider's own MCP config. Adapter structure+ admits either backend.+2. opencode / kiro / Copilot CLI / Gemini CLI exact config-file+ paths and any required env vars beyond `VAULT_AGENT_NAME` /+ `VAULT_TIMEZONE`.+3. Pi's documented skills directory convention. If `~/.pi/skills/`+ is wrong, the adapter accepts `--pi-skill-dir <path>` and the+ wizard surfaces the override.+4. Cursor restart automation. Right now `verify` surfaces "restart+ to load" as a hint; we do not kill the Cursor process. Confirm+ no IPC channel exists for graceful reload before declaring this+ a closed question.diff --git a/docs/plans/2026-05-20-multi-runtime-install-impl.md b/docs/plans/2026-05-20-multi-runtime-install-impl.mdnew file mode 100644index 00000000..e4824e90--- /dev/null+++ b/docs/plans/2026-05-20-multi-runtime-install-impl.md@@ -0,0 +1,1669 @@+# v0.10.11 β multi-runtime install + Most-applied in digest: Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use+> `superpowers:subagent-driven-development` (recommended) or+> `superpowers:executing-plans` to implement this plan task-by-task.+> Steps use checkbox (`- [ ]`) syntax for tracking.+>+> **Git policy for this project (operator-imposed):** the executing+> agent MUST NOT run `git commit`, `git push`, branch creation, or any+> other state-changing git command without an explicit per-action+> confirmation from the operator. Every "Commit" step below ends with+> `Pause: ask operator for permission to run the git command, paste+> the exact command, wait for an explicit yes`. Do not auto-stage and+> do not piggyback unrelated changes.++**Goal:** Ship `o2b install --target X [--apply|--check]` for seven+new runtimes (Cursor, Aider, opencode, kiro, Copilot CLI, Gemini CLI,+Pi) plus a `generic` printout fallback; ship `o2b init --interactive`+wizard on top of that; surface `Most-applied (Nd)` in `brain_digest`+with `_brain.yaml`-driven window and limit; add per-runtime session-+transcript awareness to `o2b discipline report` for Claude Code,+Codex, and Cursor; restructure `docs/install.md` into a router plus+per-runtime files.++**Architecture:** One `InstallAdapter` interface lives at+`src/core/install/types.ts`. Each runtime is a single file under+`src/core/install/adapters/`. Shared helpers (`json-merge.ts`,+`managed-block.ts`, `manifest.ts`, `payload.ts`) live next to the+registry. The CLI layer (`src/cli/install/*`) is thin and composes+adapters. Theme 2 reuses the existing `computeMostApplied` β+signature gains optional `windowDays` and `limit`, and both+consumers (`active.md` and `digest.ts`) read the new+`active.most_applied` block from `Brain/_brain.yaml`.++**Tech Stack:** TypeScript (Bun-native), `bun test`, `bun:sqlite`+(only for Cursor session-transcript reader; already in the stack),+no new runtime dependencies. Tests live under `tests/` mirroring+`src/`. Full suite: `bun test`. Typecheck: `bun run typecheck`.++**Spec:** `docs/plans/2026-05-20-multi-runtime-install-design.md`.+Read it before starting β every section number below (`Β§3.1`,+`Β§7.2`, ...) refers to that document.++---++## Pre-flight++These run once before Task 1.++- [ ] **Verify the working tree is clean.**++```bash+cd /srv/projects/open-second-brain+git status+```++Expected: branch is `master` or a feature branch, no unstaged+changes, no untracked files in `src/` or `tests/`. If dirty: stop+and ask the operator how to proceed.++- [ ] **Verify baseline tests pass.**++```bash+cd /srv/projects/open-second-brain+bun test+```++Expected: full suite green.++- [ ] **Verify typecheck passes.**++```bash+cd /srv/projects/open-second-brain+bun run typecheck+```++Expected: zero errors.++- [ ] **Read the spec.**++Read `docs/plans/2026-05-20-multi-runtime-install-design.md` end-to-end.++- [ ] **Resolve open questions from Β§13 of the spec via WebFetch.**++The spec leaves four questions to verify at impl time. Resolve before+Task 7 (Cursor) and before Task 12 (Aider). For each, record findings+in a scratch file under `/tmp/install-impl-notes.md` (gitignored) so+later tasks reference the same evidence.++```+1. Aider β does upstream support a native MCP client at impl time?+ WebFetch: https://github.com/Aider-AI/aider/blob/main/CHANGELOG.md+ WebFetch: https://aider.chat/docs/config/dotenv.html+2. opencode β exact MCP config file path.+ WebFetch: https://github.com/sst/opencode#mcp+3. kiro β exact MCP config file path.+ WebFetch: https://kiro.dev/docs/mcp (or the project's README)+4. Copilot CLI β exact `copilot mcp add` syntax + fallback file path.+ WebFetch: https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/add-mcp-servers+5. Gemini CLI β settings.json layout.+ WebFetch: https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md+6. Pi β skills directory convention.+ WebFetch: https://pi.dev/docs (if available) or+ https://mariozechner.at/posts/2025-11-30-pi-coding-agent/+```++If any WebFetch returns conflicting or stale information, stop and+ask the operator. Do not guess.++---++## Task 1: Shared install types++**Objective:** Land the `InstallAdapter` interface and supporting+types so subsequent tasks have a stable seam.++**Files:**++- Create: `src/core/install/types.ts`+- Create: `tests/core/install/types.test.ts`++**Step 1: Write failing test.**++```typescript+// tests/core/install/types.test.ts+import { describe, expect, test } from "bun:test";+import {+ ADAPTER_STATUSES,+ INSTALL_STEP_KINDS,+ VERIFY_STATUSES,+} from "../../../src/core/install/types.ts";++describe("install types", () => {+ test("ADAPTER_STATUSES covers the four documented states", () => {+ expect(ADAPTER_STATUSES).toEqual(+ new Set([+ "not-installed",+ "installed",+ "drift",+ "unsupported-on-this-platform",+ ]),+ );+ });++ test("INSTALL_STEP_KINDS covers the five operation kinds", () => {+ expect(INSTALL_STEP_KINDS).toEqual(+ new Set([+ "json-merge",+ "managed-block",+ "subprocess",+ "file-copy",+ "symlink",+ "print",+ ]),+ );+ });++ test("VERIFY_STATUSES covers the four documented states", () => {+ expect(VERIFY_STATUSES).toEqual(+ new Set(["ok", "drift", "not-installed", "mcp-unreachable"]),+ );+ });+});+```++**Step 2: Run test to verify failure.**++```bash+bun test tests/core/install/types.test.ts+```++Expected: FAIL β module not found.++**Step 3: Write minimal implementation.**++Create `src/core/install/types.ts` with the interfaces listed in+Β§2.2 of the spec, plus the runtime-checkable sets above. Pure+type-only file (no I/O, no side effects, no runtime deps).++Key exports:++```typescript+export const ADAPTER_STATUSES = new Set([+ "not-installed", "installed", "drift", "unsupported-on-this-platform",+] as const);+export const INSTALL_STEP_KINDS = new Set([+ "json-merge", "managed-block", "subprocess", "file-copy", "symlink", "print",+] as const);+export const VERIFY_STATUSES = new Set([+ "ok", "drift", "not-installed", "mcp-unreachable",+] as const);++export type AdapterStatus = ...; // union over ADAPTER_STATUSES+export type InstallStepKind = ...;+export type VerifyStatus = ...;++export interface InstallEnv { ... }+export interface DetectResult { ... }+export interface InstallStep { ... }+export interface InstallPlan { ... }+export interface ApplyOpts { ... }+export interface ManifestEntry { ... }+export interface ApplyResult { ... }+export interface UninstallResult { ... }+export interface VerifyResult { ... }+export interface SessionPathsResult { ... }+export interface InstallAdapter { ... }+export interface McpPayload { ... } // shape of the canonical MCP server entry+```++Full field list per the spec Β§2.2.++**Step 4: Run test to verify pass.**++```bash+bun test tests/core/install/types.test.ts+bun run typecheck+```++Expected: PASS, zero typecheck errors.++**Step 5: Commit.**++Stage and prepare:++```bash+git status+git diff --stat src/core/install/types.ts tests/core/install/types.test.ts+git add src/core/install/types.ts tests/core/install/types.test.ts+```++Pause: ask operator for permission to run the git command, paste+the exact command, wait for an explicit yes:++```bash+git commit -m "feat(install): InstallAdapter interface and supporting types"+```++---++## Task 2: `manifest.ts` sidecar I/O helper++**Objective:** Land the read/write helper for+`<vault>/.open-second-brain/install.lock.json` per Β§2.4 of the spec.++**Files:**++- Create: `src/core/install/manifest.ts`+- Create: `tests/core/install/manifest.test.ts`++**Step 1: Write failing tests.**++```typescript+// tests/core/install/manifest.test.ts+import { describe, expect, test, beforeEach } from "bun:test";+import { mkdtempSync, rmSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import {+ readManifest,+ recordEntry,+ removeEntry,+ manifestPath,+ type ManifestEntry,+} from "../../../src/core/install/manifest.ts";++let vault: string;+beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-manifest-"));+});++describe("install manifest", () => {+ test("readManifest returns empty shell when file is missing", () => {+ const m = readManifest(vault);+ expect(m.schema_version).toBe(1);+ expect(m.installs).toEqual({});+ });++ test("recordEntry creates sidecar dir + file atomically", () => {+ const entry: ManifestEntry = {+ target: "cursor",+ applied_at: "2026-05-20T12:00:00.000Z",+ operation: "json-merge",+ config_path: "/home/u/.cursor/mcp.json",+ owned_keys: ["mcpServers.open-second-brain"],+ };+ recordEntry(vault, entry);+ const m = readManifest(vault);+ expect(m.installs.cursor).toEqual(entry);+ const raw = readFileSync(manifestPath(vault), "utf8");+ expect(raw.endsWith("\n")).toBe(true);+ });++ test("recordEntry overwrites existing entry for the same target", () => {+ recordEntry(vault, {+ target: "cursor", applied_at: "2026-05-20T12:00:00.000Z",+ operation: "json-merge", config_path: "/a",+ owned_keys: ["mcpServers.open-second-brain"],+ });+ recordEntry(vault, {+ target: "cursor", applied_at: "2026-05-20T12:05:00.000Z",+ operation: "json-merge", config_path: "/b",+ owned_keys: ["mcpServers.open-second-brain"],+ });+ const m = readManifest(vault);+ expect(m.installs.cursor!.applied_at).toBe("2026-05-20T12:05:00.000Z");+ expect(m.installs.cursor!.config_path).toBe("/b");+ });++ test("removeEntry deletes the named target only", () => {+ recordEntry(vault, {+ target: "cursor", applied_at: "...Z",+ operation: "json-merge", config_path: "/a",+ owned_keys: ["mcpServers.open-second-brain"],+ });+ recordEntry(vault, {+ target: "pi", applied_at: "...Z",+ operation: "symlink", config_path: null,+ owned_paths: ["/p"],+ });+ removeEntry(vault, "cursor");+ const m = readManifest(vault);+ expect(m.installs.cursor).toBeUndefined();+ expect(m.installs.pi).toBeDefined();+ });++ test("removeEntry on missing target is a no-op", () => {+ removeEntry(vault, "cursor");+ expect(readManifest(vault).installs).toEqual({});+ });++ test("readManifest tolerates forward-compat unknown top-level keys", () => {+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ writeFileSync(+ manifestPath(vault),+ JSON.stringify({ schema_version: 1, installs: {}, future_thing: 42 }),+ );+ const m = readManifest(vault);+ expect(m.schema_version).toBe(1);+ });++ test("readManifest rejects unknown schema_version", () => {+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ writeFileSync(+ manifestPath(vault),+ JSON.stringify({ schema_version: 999, installs: {} }),+ );+ expect(() => readManifest(vault)).toThrow(/schema_version/);+ });++ afterEach(() => {+ try { rmSync(vault, { recursive: true, force: true }); } catch {}+ });+});+```++**Step 2: Run test to verify failure.**++```bash+bun test tests/core/install/manifest.test.ts+```++Expected: FAIL β module not found.++**Step 3: Write minimal implementation.**++`src/core/install/manifest.ts` exports `manifestPath(vault)`,+`readManifest(vault)`, `recordEntry(vault, entry)`,+`removeEntry(vault, target)`. Use the existing+`atomicWriteFileSync` from `src/core/fs-atomic.ts` for writes.+JSON output: 2-space indent, trailing newline.++Reject unknown `schema_version`. Tolerate unknown top-level keys+(forward-compat per spec Β§2.4). Missing file = empty shell.++**Step 4: Run test to verify pass.**++```bash+bun test tests/core/install/manifest.test.ts+bun run typecheck+```++Expected: all 7 tests PASS, zero typecheck errors.++**Step 5: Commit.**++```bash+git add src/core/install/manifest.ts tests/core/install/manifest.test.ts+```++Pause for operator yes, then:++```bash+git commit -m "feat(install): sidecar manifest read/write"+```++---++## Task 3: `json-merge.ts` helper++**Objective:** Safe merge of OSB's two `mcpServers` keys into an+existing JSON file, preserving user-authored content and+indentation.++**Files:**++- Create: `src/core/install/json-merge.ts`+- Create: `tests/core/install/json-merge.test.ts`+- Create fixtures: `tests/fixtures/install/json-merge/{empty,user-keys-present,osb-already,bom}.{before,after}.json`++**Step 1: Write failing tests.**++Cover six cases:++1. Empty file (or missing) β write a new file with both OSB keys+ under `mcpServers`, 2-space indent, trailing newline.+2. User has unrelated `mcpServers` keys (e.g. `mcpServers.other`)+ β keep them, add two OSB keys, preserve key order+ (user keys before OSB keys, OSB keys in insertion order).+3. User has older OSB keys with different command/args+ β overwrite both with canonical payload, byte-equal to expected+ output.+4. File has 4-space indent β preserve 4-space indent on write.+5. File has BOM at start β preserve BOM.+6. File is invalid JSON β throw `JsonMergeError` with file path+ and parse error.++```typescript+// tests/core/install/json-merge.test.ts+// see full code under tests/ folder; here is the test of case 2:+test("preserves unrelated mcpServers keys", () => {+ const before = `{+ "mcpServers": {+ "other": { "command": "x", "args": [] }+ }+}\n`;+ const after = mergeMcpServers(before, OSB_PAYLOAD);+ const parsed = JSON.parse(after);+ expect(Object.keys(parsed.mcpServers)).toEqual([+ "other",+ "open-second-brain",+ "open-second-brain-writer",+ ]);+ expect(parsed.mcpServers.other).toEqual({ command: "x", args: [] });+});+```++(Detail similar for the other 5 cases; refer to fixtures.)++**Step 2: Run test to verify failure.**++```bash+bun test tests/core/install/json-merge.test.ts+```++Expected: FAIL β module not found.++**Step 3: Write minimal implementation.**++`src/core/install/json-merge.ts` exports:++- `mergeMcpServers(currentJson: string, payload: { full: McpServerEntry; writer: McpServerEntry }): string`+- `removeMcpServers(currentJson: string): string` β removes both OSB keys; empty `mcpServers` object kept (we don't dictate user's parent shape).+- `JsonMergeError extends Error` β carries path.++Implementation hints:++- Detect indentation by scanning the first indented line; default to 2 spaces if file has no nesting.+- Detect BOM by inspecting first three bytes (`ο»Ώ`); preserve verbatim.+- Use `JSON.parse` for read; manual stringify with `JSON.stringify(..., null, indent)` for write.+- Don't sort keys; preserve insertion order. JS objects retain insertion order for non-integer keys, so build the merged `mcpServers` by iterating original keys (skipping OSB names if present) then appending OSB names.++**Step 4: Run test to verify pass.**++```bash+bun test tests/core/install/json-merge.test.ts+bun run typecheck+```++Expected: all 6 tests PASS.++**Step 5: Commit.**++```bash+git add src/core/install/json-merge.ts tests/core/install/json-merge.test.ts tests/fixtures/install/json-merge/+```++Pause for operator, then:++```bash+git commit -m "feat(install): JSON-merge helper for mcpServers"+```++---++## Task 4: `managed-block.ts` helper++**Objective:** Insert / replace / remove a marker-fenced block in a+text file (used by Aider adapter and the future text-fallback+adapter).++**Files:**++- Create: `src/core/install/managed-block.ts`+- Create: `tests/core/install/managed-block.test.ts`+- Create fixtures: `tests/fixtures/install/managed-block/{insert,replace,remove}.{before,after}.txt`++**Step 1: Write failing tests.**++Cover:++1. Insert into file that has no marker block β append at end with a+ leading blank line; preserve all preceding content byte-for-byte.+2. Replace existing block β content between markers fully replaced;+ surrounding lines unchanged.+3. Remove block β both markers and everything between them removed;+ preceding and trailing blank lines normalised to one.+4. Nested markers β reject with `ManagedBlockError`.+5. Single marker without closing β reject with `ManagedBlockError`.+6. CRLF input β preserve CRLF on write (don't normalise to LF).+7. Custom marker text β markers are parametrised; default uses the+ `# >>> open-second-brain managed >>>` / `<<<` pair from+ `protect.ts`.++**Step 2-4: Standard TDD cycle.**++Implementation hints:++- Markers are parametrised so the adapter chooses (Aider uses YAML+ comment markers; generic-text-fallback uses the same).+- Use a precompiled RegExp with `^...$` and `m` flag to find the+ pair; reject if more than one of either marker appears.+- Detect line ending (CRLF vs LF) by scanning first 1KB; preserve.++**Step 5: Commit.**++```bash+git add src/core/install/managed-block.ts tests/core/install/managed-block.test.ts tests/fixtures/install/managed-block/+```++Pause, then:++```bash+git commit -m "feat(install): managed-block editor for text/YAML configs"+```++---++## Task 5: `payload.ts` builder++**Objective:** Build the canonical MCP server entries from the+plugin config β same input, deterministic output, used by every+adapter that emits MCP config.++**Files:**++- Create: `src/core/install/payload.ts`+- Create: `tests/core/install/payload.test.ts`++**Step 1: Write failing tests.**++```typescript+test("buildPayload returns full + writer entries with vault + env vars", () => {+ const cfg = {+ vault: "/home/u/vault",+ agent_name: "claude-vps-agent",+ timezone: "Europe/Belgrade",+ };+ const { full, writer } = buildPayload(cfg);+ expect(full.command).toBe("o2b");+ expect(full.args).toEqual(["mcp", "--vault", "/home/u/vault"]);+ expect(full.env).toEqual({+ VAULT_AGENT_NAME: "claude-vps-agent",+ VAULT_TIMEZONE: "Europe/Belgrade",+ });+ expect(writer.args).toEqual(["mcp", "--writer-only", "--vault", "/home/u/vault"]);+});++test("buildPayload omits env when agent_name / timezone missing", () => {+ const cfg = { vault: "/v", agent_name: null, timezone: null };+ const { full } = buildPayload(cfg);+ expect(full.env).toBeUndefined();+});++test("buildPayload throws on missing vault", () => {+ expect(() => buildPayload({ vault: null } as any)).toThrow(/vault/);+});+```++**Step 2-4: TDD cycle.**++Pure function; reads no I/O; takes the loaded plugin config as+argument. Adapters that need it call `discoverConfig` themselves+upstream.++**Step 5: Commit.**++```bash+git add src/core/install/payload.ts tests/core/install/payload.test.ts+```++Pause:++```bash+git commit -m "feat(install): canonical MCP payload builder"+```++---++## Task 6: Adapter registry++**Objective:** A `Map<target, InstallAdapter>` + `detectAll(env)`+helper. Empty in this commit (adapters land in later tasks).++**Files:**++- Create: `src/core/install/registry.ts`+- Create: `tests/core/install/registry.test.ts`++**Step 1: Write failing tests.**++```typescript+test("registry is empty initially", () => {+ const reg = createRegistry();+ expect(reg.list()).toEqual([]);+ expect(reg.get("cursor")).toBeUndefined();+});++test("register + get round-trip", () => {+ const reg = createRegistry();+ const fake: InstallAdapter = makeFakeAdapter("test");+ reg.register(fake);+ expect(reg.get("test")).toBe(fake);+ expect(reg.list().map((a) => a.target)).toEqual(["test"]);+});++test("register rejects duplicate target", () => {+ const reg = createRegistry();+ reg.register(makeFakeAdapter("cursor"));+ expect(() => reg.register(makeFakeAdapter("cursor"))).toThrow(/duplicate/);+});++test("detectAll returns one entry per registered adapter", () => {+ const reg = createRegistry();+ reg.register(makeFakeAdapter("a"));+ reg.register(makeFakeAdapter("b"));+ const env = makeEnv({});+ expect(reg.detectAll(env).map((d) => d.target)).toEqual(["a", "b"]);+});+```++**Step 2-4: TDD cycle.**++Provide a `createRegistry()` factory plus a module-level default+registry (`defaultRegistry`) that adapter files mutate via+`defaultRegistry.register(...)` at import time. Test-friendly:+`createRegistry()` returns a fresh isolated instance.++**Step 5: Commit.**++```bash+git add src/core/install/registry.ts tests/core/install/registry.test.ts+```++Pause:++```bash+git commit -m "feat(install): adapter registry"+```++---++## Task 7: `cursor` adapter++**Objective:** First real adapter β canonical JSON-merge case.++**Files:**++- Create: `src/core/install/adapters/cursor.ts`+- Create: `tests/core/install/adapters/cursor.test.ts`+- Create fixtures: `tests/fixtures/install/cursor/{clean,user-keys,osb-old,drift}.before.json` and matching `.after.json`++**Step 1: Write failing tests.**++Cover the six scenarios listed in spec Β§10.2:++1. Clean install on empty config β `apply` writes file; `verify` returns `ok`.+2. Re-apply β second `apply` is a byte-no-op; manifest `applied_at` is updated only if content changed.+3. Drift detection β manually mutate the file post-install; `verify` returns `drift` with the missing/extra keys.+4. Uninstall β `uninstall` removes both keys; manifest entry gone; surrounding keys preserved.+5. Uninstall without manifest entry β fails with code path message; `--force-from-snippet` succeeds when payload matches.+6. User-modified block β file mtime newer than `applied_at`, content differs from canonical; `apply` without `--force` throws exit-4 (the adapter signals via thrown error; the CLI layer converts).++```typescript+test("apply on empty config installs both keys", () => {+ const env = makeEnv({ home: TMP_HOME, configPath: join(TMP_HOME, ".cursor/mcp.json") });+ const adapter = cursorAdapter;+ const payload = buildPayload(loadFakeConfig());+ const plan = adapter.plan(payload, env);+ const result = adapter.apply(plan, env, { dryRun: false, stdout: ..., stderr: ... });+ const raw = JSON.parse(readFileSync(env.configPath, "utf8"));+ expect(Object.keys(raw.mcpServers)).toEqual([+ "open-second-brain",+ "open-second-brain-writer",+ ]);+ expect(result.manifest.owned_keys).toEqual([+ "mcpServers.open-second-brain",+ "mcpServers.open-second-brain-writer",+ ]);+});+```++**Step 2: Run test to verify failure.**++```bash+bun test tests/core/install/adapters/cursor.test.ts+```++Expected: FAIL β module not found.++**Step 3: Write minimal implementation.**++`src/core/install/adapters/cursor.ts`:++- `detect(env)`: check `${XDG_CONFIG_HOME:-$HOME}/.cursor/mcp.json`;+ report `installed` if both OSB keys present and match, `drift`+ if file exists with partial or mismatched OSB keys,+ `not-installed` otherwise.+- `plan(payload, env)`: emit one `json-merge` step with preview+ (deterministic diff text).+- `apply(plan, env, opts)`: build current canonical payload from+ `payload.ts`, call `mergeMcpServers` from `json-merge.ts`, write+ atomically. Record manifest. Honor `dryRun`.+- `uninstall(env, opts)`: read manifest, call `removeMcpServers`,+ remove manifest entry. If manifest absent and not `--force-from-snippet`,+ throw `ManifestMissingError`.+- `verify(env)`: parse file, compare current key values to canonical+ payload. If file mtime is newer than `applied_at` and content+ differs from canonical β `drift`.++Auto-register: `defaultRegistry.register(cursorAdapter)` at the+bottom of the file. The default registry is imported by every CLI+verb.++**Step 4: Run test to verify pass.**++```bash+bun test tests/core/install/adapters/cursor.test.ts+bun run typecheck+```++Expected: all six scenarios PASS.++**Step 5: Commit.**++```bash+git add src/core/install/adapters/cursor.ts tests/core/install/adapters/cursor.test.ts tests/fixtures/install/cursor/+```++Pause:++```bash+git commit -m "feat(install): cursor adapter"+```++---++## Task 8: `opencode` adapter++**Objective:** Same JSON-merge pattern as Cursor; different config+path.++**Files:**++- Create: `src/core/install/adapters/opencode.ts`+- Create: `tests/core/install/adapters/opencode.test.ts`+- Fixtures: `tests/fixtures/install/opencode/`++**Pattern:** Replicate Task 7 structure. The body of the adapter+shares 90% of the code with Cursor β extract the common JSON-merge+adapter body to `adapters/_json-mcp.ts` if and only if the third+JSON-merge adapter (Task 9 or Task 10) doesn't introduce a third+shape difference. Otherwise keep them as three independent files+to avoid premature abstraction.++**Detect path:** `${XDG_CONFIG_HOME:-$HOME/.config}/opencode/mcp.json`+(confirm via WebFetch resolved in Pre-flight).++**TDD cycle + fixtures + commit.** Brief commit message:+`feat(install): opencode adapter`.++---++## Task 9: `kiro` adapter++Same shape as Cursor / opencode. Config path `~/.kiro/settings.json`+(confirm via WebFetch). If kiro stores MCP entries under a+different top-level key than `mcpServers`, override the key in+`json-merge` call.++After this task, decide whether to extract the shared JSON-merge+adapter body into `adapters/_json-mcp.ts`. If yes, do it as a+no-op refactor (existing tests must still pass) and commit+separately:++```+git commit -m "refactor(install): extract shared JSON-merge adapter body"+```++---++## Task 10: `gemini-cli` adapter++Same shape as Cursor. Config path `~/.gemini/settings.json` under+key `mcpServers` (per+`github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md`).++**Verify hint:** `gemini --version` exit 0 is the cheap liveness+check; `o2b mcp --probe` is the MCP-side check.++TDD cycle + fixtures + commit. Message:+`feat(install): gemini-cli adapter`.++---++## Task 11: `copilot-cli` adapter (subprocess + fallback)++**Objective:** First adapter that calls a subprocess. Adds the+`subprocess` operation kind in practice.++**Files:**++- Create: `src/core/install/adapters/copilot-cli.ts`+- Create: `tests/core/install/adapters/copilot-cli.test.ts`+- Mocked subprocess fixtures.++**Step 1: Write failing tests.**++Test cases:++1. Happy path β `copilot` CLI on PATH; `apply` calls `copilot mcp+ remove open-second-brain` then `copilot mcp add ...` (twice, once per name).+2. CLI missing β `apply` falls back to JSON-merge at the documented+ fallback file path; stderr emits "copilot CLI not found; using+ file fallback".+3. CLI returns non-zero on `add` β `apply` falls back to file mode,+ stderr describes the CLI error.+4. Uninstall via subprocess β calls `copilot mcp remove` once per+ name.+5. Uninstall via file fallback β same path as Cursor uninstall.+6. Verify via `copilot mcp list` parsing β both names present β+ `ok`.++Subprocess mocking: use `Bun.spawn` injection point. The adapter+takes an injectable `spawn` function in its options (defaults to+`Bun.spawn`); tests pass a fake.++**Step 2-4: TDD cycle.**++Adapter records `operation: "subprocess"` plus optional+`fallback_file` field in manifest when fallback path was used.++**Step 5: Commit.**++```+git commit -m "feat(install): copilot-cli adapter with subprocess + file fallback"+```++---++## Task 12: `aider` adapter++**Objective:** Managed-block in `~/.aider.conf.yml` + sidecar+context file.++**Files:**++- Create: `src/core/install/adapters/aider.ts`+- Create: `templates/install/aider-context.md.tmpl`+- Create: `tests/core/install/adapters/aider.test.ts`+- Fixtures.++**Pre-task check.** Re-read Pre-flight finding #1. If upstream Aider+shipped native MCP at impl time, switch to JSON-merge against+Aider's MCP config and document the change in a one-line comment+at top of `aider.ts`. The rest of this task assumes no native MCP.++**Step 1: Write failing tests.**++Cases:++1. Clean install β creates `~/.aider.conf.yml` if missing; adds+ managed block under `read:`; generates+ `<vault>/.open-second-brain/aider-context.md` from template.+2. Pre-existing `~/.aider.conf.yml` with user's own `read:` list β+ preserves user's list; appends managed block as additional list+ entries between markers.+3. Re-apply β byte no-op when canonical payload hasn't changed.+4. Uninstall β removes managed block AND sidecar context file+ (path from manifest).+5. Template render β the sidecar context file contains a brief+ summary of `skills/brain-memory/SKILL.md` plus the current+ `Brain/active.md` body. Regeneration on each apply.+6. Verify β managed block present + sidecar file exists + non-empty.++**Step 2-4: TDD cycle.**++Template uses simple `{{var}}` substitution (no jinja). Template+content drafted as part of this task.++**Step 5: Commit.**++```+git commit -m "feat(install): aider adapter (managed-block + sidecar context)"+```++---++## Task 13: `pi` adapter++**Objective:** Symlink-only adapter; no JSON, no managed block.++**Files:**++- Create: `src/core/install/adapters/pi.ts`+- Create: `tests/core/install/adapters/pi.test.ts`++**Cases:**++1. Clean install β creates `~/.pi/skills/brain-memory` symlink+ pointing at `<repo>/skills/brain-memory`.+2. `--pi-skill-dir <path>` override β symlink at custom location.+3. Re-apply on existing valid symlink β no-op.+4. Re-apply on existing broken symlink (target gone) β replaces.+5. Re-apply on existing non-symlink at target path β refuses+ without `--force` (don't clobber a user-authored directory).+6. Uninstall β removes symlink only, never the source.+7. Verify β symlink valid + target readable.++**Step 5: Commit.**++```+git commit -m "feat(install): pi adapter (symlink-based)"+```++---++## Task 14: `generic` adapter++**Objective:** Print-only fallback; never edits any runtime config.++**Files:**++- Create: `src/core/install/adapters/generic.ts`+- Create: `tests/core/install/adapters/generic.test.ts`++**Cases:**++1. Default β prints canonical JSON payload to stdout.+2. `--format yaml` β YAML rendering.+3. `--out <path>` β writes to file; manifest records path.+4. `--out -` β explicit stdout.+5. `detect` β always returns `not-installed`.+6. `uninstall` β prints the path that the operator must remove+ manually; no file deletion.++**Step 5: Commit.**++```+git commit -m "feat(install): generic adapter (print-only fallback)"+```++---++## Task 15: `o2b mcp --writer-only` flag++**Objective:** The Payload builder emits args+`["mcp", "--writer-only", ...]`. Land the matching flag in+`o2b mcp`.++**Files:**++- Modify: `src/mcp/main.ts` (or wherever `o2b mcp` argv parsing+ lives β search for `mcpMain` or `cmdMcp`).+- Modify: `src/mcp/tools.ts:buildToolTable` to accept a+ `writerOnly: boolean` option.+- Test: `tests/mcp/writer-only.test.ts`.++**Step 1: Test.**++```typescript+test("writer-only tool table contains only the three writer tools + brain_context", () => {+ const table = buildToolTable({ writerOnly: true, ... });+ const names = table.tools.map((t) => t.name);+ expect(names.sort()).toEqual([+ "brain_apply_evidence",+ "brain_context",+ "brain_feedback",+ "brain_note",+ ]);+});++test("full tool table contains everything", () => {+ const table = buildToolTable({ writerOnly: false, ... });+ expect(table.tools.length).toBeGreaterThan(15);+});+```++**Step 2-4: TDD cycle.**++Add `--writer-only` to argv parsing. When set, pass to+`buildToolTable`. The writer-server in `.mcp.json` already+filters this way via a different mechanism (per v0.10.7); reuse+the filter logic if it lives in a helper, else extract.++**Step 5: Commit.**++```+git commit -m "feat(mcp): --writer-only flag for o2b mcp"+```++---++## Task 16: `o2b mcp --probe` flag++**Objective:** Used by `o2b install --check` to validate that the+MCP server starts and responds to `initialize`.++**Files:**++- Modify: `src/mcp/main.ts`+- Create: `src/mcp/probe.ts`+- Test: `tests/mcp/probe.test.ts`++**Behavior:** `o2b mcp --probe`:++1. Sets up an in-process pipe instead of stdio.+2. Sends an MCP `initialize` request.+3. Reads the response; checks `tools` array is non-empty.+4. Writes one line to stdout: `mcp probe ok (N tools)` or+ `mcp probe FAIL: <reason>`.+5. Exits 0 on success, non-zero on failure.++**Cases:**++1. Happy path β returns 0, prints tool count.+2. Probe with vault flag missing in plugin config β exits non-zero+ with "vault not configured".+3. Probe with vault path invalid (does not exist) β exits non-zero+ with reason.++**Step 5: Commit.**++```+git commit -m "feat(mcp): --probe flag for in-process MCP handshake"+```++---++## Task 17: `o2b install` CLI verb++**Objective:** Main entry-point. Glues registry + adapters.++**Files:**++- Create: `src/cli/install/install.ts`+- Create: `src/cli/install/render.ts`+- Modify: `src/cli/main.ts` to route `o2b install`.+- Test: `tests/cli/install/install.test.ts`.++**Step 1: Tests (organised by subcommand path).**++```typescript+describe("o2b install", () => {+ test("no args β detect-only table (text)", async () => {+ const out = await runCli(["install"], env);+ expect(out.stdout).toContain("detected runtimes");+ expect(out.exitCode).toBe(0);+ // No file writes+ expect(existsSync(env.cursorConfig)).toBe(false);+ });++ test("--json β machine output", async () => {+ const out = await runCli(["install", "--json"], env);+ const parsed = JSON.parse(out.stdout);+ expect(parsed.targets).toBeInstanceOf(Array);+ });++ test("--target cursor (no --apply) β plan-only", async () => {+ const out = await runCli(["install", "--target", "cursor"], env);+ expect(out.stdout).toContain("json-merge");+ expect(existsSync(env.cursorConfig)).toBe(false);+ });++ test("--target cursor --apply β writes file", async () => {+ const out = await runCli(["install", "--target", "cursor", "--apply"], env);+ expect(out.exitCode).toBe(0);+ expect(existsSync(env.cursorConfig)).toBe(true);+ });++ test("--target unknown β exit 2", async () => {+ const out = await runCli(["install", "--target", "nope"], env);+ expect(out.exitCode).toBe(2);+ });++ test("--target generic --out - β stdout", async () => {+ const out = await runCli(+ ["install", "--target", "generic", "--out", "-"], env,+ );+ expect(JSON.parse(out.stdout).command).toBe("o2b");+ });++ test("apply on user-modified block exits 4", async () => {+ // setup: install once, then hand-edit, advance mtime+ await runCli(["install", "--target", "cursor", "--apply"], env);+ writeFileSync(env.cursorConfig, '{ "mcpServers": { "open-second-brain": { "command": "TAMPERED" } } }');+ advanceFileMtime(env.cursorConfig, 60); // make mtime newer than manifest applied_at+ const out = await runCli(["install", "--target", "cursor", "--apply"], env);+ expect(out.exitCode).toBe(4);+ expect(out.stderr).toContain("hand-edited");+ });+});+```++**Step 2-4: TDD cycle.**++The verb resolves `defaultRegistry`, parses argv, dispatches:++- no `--target` β `registry.detectAll(env)` β `renderDetectTable(...)` or JSON.+- `--target X` without `--apply` β `adapter.plan(...)` β `renderPlan(...)`.+- `--target X --apply` β `adapter.detect(...)` + `adapter.plan(...)` + `adapter.apply(...)`.+- `--target generic` with `--out` / `--format` β passthrough.++Use existing `parseArgs` helper from `src/cli/argparse.ts`.++**Step 5: Commit.**++```+git commit -m "feat(cli): o2b install verb (detect + plan + apply)"+```++---++## Task 18: `o2b uninstall --target X` CLI verb++**Objective:** Sibling of `install` β reads manifest, calls+`adapter.uninstall`.++**Files:**++- Modify: `src/cli/uninstall.ts` (existing β extend with+ `--target` mode; current `--apply-local` mode stays).+- Test: `tests/cli/uninstall-target.test.ts`.++**Cases:**++1. Dry-run (`--target X`, no `--apply`) β prints what would be+ removed; no file changes.+2. `--apply` β removes per manifest; manifest entry deleted.+3. Manifest missing β exits non-zero with hint; `--force-from-snippet`+ path documented in the error message.+4. `--target X` with no manifest entry β exit 0 with "nothing+ recorded".++**Step 5: Commit.**++```+git commit -m "feat(cli): o2b uninstall --target X"+```++---++## Task 19: `o2b install --check` CLI verb++**Objective:** Runtime install health check.++**Files:**++- Modify: `src/cli/install/install.ts`+- Test: `tests/cli/install/check.test.ts`.++**Cases:**++1. All-ok β exit 0; table shows each target with status.+2. One drift β exit 3; drift row carries `fix` hint pointing at+ the exact apply command.+3. Not-installed everywhere β exit 0 (`not-installed` is not an+ error).+4. MCP probe failure on Cursor (probe spawn returns non-zero) β+ row status `mcp-unreachable` with restart hint.+5. `--json` β mirror of text output, exit code identical.++**Step 5: Commit.**++```+git commit -m "feat(cli): o2b install --check"+```++---++## Task 20: `o2b init --interactive` wizard++**Objective:** First-time setup wizard that composes+`o2b init` + optional `o2b brain init` + per-target install.++**Files:**++- Create: `src/cli/install/init-interactive.ts`+- Modify: `src/cli/main.ts` to route `o2b init --interactive`.+- Test: `tests/cli/init-interactive.test.ts`.++**Step 1: Test.**++The wizard takes an injectable `prompt(question, options)`+function. Tests pass a fake that returns scripted answers; the+wizard's output is asserted exactly.++```typescript+test("wizard happy path: clean vault, two targets selected", async () => {+ const answers = [+ "1", // vault: first candidate+ "claude-vps", // agent name+ "Europe/Belgrade",+ "ru",+ "1,3", // pick targets 1 and 3 from list+ "y", // brain init?+ "n", // starter?+ "yes", // confirm summary+ ];+ const result = await runWizard(makeFakePrompt(answers), env);+ expect(result.exitCode).toBe(0);+ expect(result.actions).toContain("o2b init --vault ...");+ expect(result.actions).toContain("o2b install --target cursor --apply");+});++test("wizard aborts at summary on 'no'", async () => {+ const answers = [..., "no"];+ const result = await runWizard(makeFakePrompt(answers), env);+ expect(result.exitCode).toBe(0);+ expect(result.actions).toEqual([]); // nothing executed+});+```++**Step 2-4: TDD cycle.**++Implement nine steps per spec Β§5. Each step is a small private+function; the top-level wizard glues them together with the+injected prompt.++**Step 5: Commit.**++```+git commit -m "feat(cli): o2b init --interactive wizard"+```++---++## Task 21: Theme 2 β `active.most_applied` config block++**Objective:** Land the new block in `_brain.yaml` schema + loader++ validator.++**Files:**++- Modify: `src/core/brain/types.ts` (add `BrainActiveConfig`,+ `BrainMostAppliedConfig` interfaces; add `active?:` field to+ `BrainConfig`).+- Modify: `src/core/brain/policy.ts` (loader pulls the block;+ validator rejects out-of-range values).+- Test: `tests/core/brain/policy-active.test.ts`.++**Cases:**++1. `_brain.yaml` without `active` block β loader returns+ `cfg.active === undefined`; consumers use defaults.+2. `_brain.yaml` with `active.most_applied: { window_days: 7, limit: 3 }` β loaded values.+3. `window_days: 0` β `BrainConfigError("active.most_applied.window_days must be between 1 and 365, got 0")`.+4. `window_days: "thirty"` β `BrainConfigError`.+5. `limit: -1` β `BrainConfigError`.+6. `limit: 100` β `BrainConfigError("between 1 and 50")`.++**Step 5: Commit.**++```+git commit -m "feat(brain): _brain.yaml active.most_applied config block"+```++---++## Task 22: Theme 2 β extend `computeMostApplied`++**Objective:** Make `windowDays` and `limit` parameters; keep+defaults for back-compat.++**Files:**++- Modify: `src/core/brain/most-applied.ts`+- Modify: `tests/core/brain/most-applied.test.ts` (add cases for+ custom values; existing cases must still pass).++**Cases (new ones to add to the existing test file):**++1. `windowDays: 7` β events older than 7 days excluded.+2. `windowDays: 7, limit: 2` β top 2 within 7-day window.+3. `windowDays: 365` β events from up to one year ago count.+4. Day-level fence preserved regardless of `windowDays`.++**Step 5: Commit.**++```+git commit -m "feat(brain): computeMostApplied windowDays + limit params"+```++---++## Task 23: Theme 2 β `active.md` uses configured window++**Objective:** `regenerateActive` reads+`cfg.active?.most_applied?.{window_days, limit}` and passes them+through.++**Files:**++- Modify: `src/core/brain/active.ts`+- Modify: `tests/core/brain/active.test.ts` (one new case).++**Case:**++`_brain.yaml` has `active.most_applied.window_days: 7` β+`active.md` header reads `## Most-applied (7d)` and only counts+events within the last 7 days.++**Golden test note:** existing golden fixtures used default 30/10;+verify they still pass byte-for-byte.++**Step 5: Commit.**++```+git commit -m "feat(brain): active.md honours active.most_applied config"+```++---++## Task 24: Theme 2 β digest most_applied JSON field++**Objective:** Add `most_applied` to `DigestJson` and the data+collector.++**Files:**++- Modify: `src/core/brain/digest.ts`+- Modify: `tests/core/brain/digest.test.ts`.++**Cases:**++1. Default config β `digest.most_applied.window_days === 30`,+ `limit === 10`, `entries: [...]`.+2. Custom config β values reflected in JSON.+3. Empty window β `entries: []`, block present.++**Step 5: Commit.**++```+git commit -m "feat(brain): digest JSON most_applied block"+```++---++## Task 25: Theme 2 β digest most_applied Markdown section++**Objective:** Render `## Most-applied (Nd)` between existing+sections.++**Files:**++- Modify: `src/core/brain/digest.ts:renderMarkdown`+- Modify golden Markdown fixtures: add new section for windows+ with entries; absent for empty-window cases.++**Cases:**++1. Default config + non-empty window β section rendered.+2. Empty window β section omitted entirely.+3. Custom window (`14d`) β header text reflects it.++**Step 5: Commit.**++```+git commit -m "feat(brain): digest Markdown Most-applied section"+```++---++## Task 26: Companion 2 β `sessionPaths` for claudecode/codex/cursor++**Objective:** Land the three transcript-path resolvers.++**Files:**++- Modify: existing claudecode adapter (created in earlier task or+ located via `find src/core/install/adapters/ -name '*claude*'`)+ β add `sessionPaths`. If no Claude Code adapter exists yet, the+ resolver lives standalone at+ `src/core/install/session-paths-claudecode.ts`.+- Create: `src/core/install/session-paths-codex.ts`+- Create: `src/core/install/session-paths-cursor.ts`+- Tests: `tests/core/install/session-paths-{claudecode,codex,cursor}.test.ts`++**Cases per resolver:**++1. Standard path resolves on Linux fixtures.+2. macOS layout resolves (Cursor).+3. Missing files β returns `{ paths: [] }`, not an error.++**Step 5: Commit.**++```+git commit -m "feat(install): sessionPaths for claudecode/codex/cursor"+```++---++## Task 27: Companion 2 β `o2b discipline report` transcript adapter++**Objective:** Plug session-path resolvers into the report; surface+`transcript-confirmed` sub-reason in alert rows.++**Files:**++- Modify: `scripts/discipline-report.ts` (the actual implementation+ behind `bin/o2b-discipline-report`).+- Test: `tests/scripts/discipline-report-transcripts.test.ts`.++**Cases:**++1. Claude Code transcript shows activity + zero brain events for+ the same agent that day β alert with `transcript-confirmed`.+2. Transcript empty + git/mtime activity β existing proxy result+ (no `transcript-confirmed` flag).+3. Multiple runtimes simultaneously β each evaluated independently.++**Step 5: Commit.**++```+git commit -m "feat(discipline): per-runtime transcript-confirmed signal"+```++---++## Task 28: Docs β `install/` folder restructure++**Objective:** Split `install.md` into router + per-runtime files.++**Files:**++- Modify: `install.md` (root) β reduce to router; preserve a+ pointer at the top to the per-runtime files.+- Create: `install/prerequisites.md`+- Create: `install/cursor.md`, `install/aider.md`, `install/opencode.md`,+ `install/kiro.md`, `install/copilot-cli.md`,+ `install/gemini-cli.md`, `install/pi.md`, `install/generic.md`+- Create (migrate content from existing branches): `install/claudecode.md`,+ `install/codex.md`, `install/hermes.md`, `install/openclaw.md`.++**Pattern per file:**++1. One-paragraph intro.+2. Command block: `o2b install --target X --apply` (or other+ per-runtime command).+3. Verify section: `o2b install --check --target X`.+4. Caveats (one or two paragraphs at most).+5. Uninstall command.++**Step 5: Commit.**++```+git commit -m "docs(install): split install.md into router + per-runtime files"+```++---++## Task 29: Docs β README quick install++**Objective:** Surface the one-liner up front.++**Files:**++- Modify: `README.md` β add a "Quick install" section above+ existing content.++**Step 5: Commit.**++```+git commit -m "docs: README quick-install section"+```++---++## Task 30: CHANGELOG + version bump++**Objective:** Land the v0.10.11 entry and bump+`package.json` / `pyproject.toml`.++**Files:**++- Modify: `CHANGELOG.md`+- Modify: `package.json` (`version` field)+- Modify: `pyproject.toml` (if it carries a version field)+- Modify: any other version-bearing file (search:+ `grep -rn "0\\.10\\.10" --include='*.{json,toml,md,ts}' .`)++**Per project convention:** one PR β one CHANGELOG version. No+`[Unreleased]` placeholder.++Sample entry (operator confirms the date on ship day):++```markdown+## [0.10.11] - <YYYY-MM-DD set on the day the release ships>++### Added+- `o2b install --target X [--apply|--check]` for Cursor, Aider,+ opencode, kiro, GitHub Copilot CLI, Google Gemini CLI, Pi, and+ generic printout.+- `o2b uninstall --target X` driven by the new sidecar manifest at+ `<vault>/.open-second-brain/install.lock.json`.+- `o2b init --interactive` first-time-setup wizard.+- `o2b mcp --writer-only` and `o2b mcp --probe` subflags.+- `Brain/_brain.yaml` `active.most_applied.{window_days, limit}`+ block. `brain_digest` and `Brain/active.md` honour the values;+ default 30/10 unchanged.+- `Most-applied (Nd)` section in `brain_digest` Markdown and a+ mirrored `most_applied` field in the JSON form.+- Per-runtime session-transcript awareness in `o2b discipline+ report` for Claude Code, Codex, and Cursor.+- Documentation restructured into `install.md` router plus+ `install/<target>.md` per-runtime files.+```++**Step 5: Commit.**++```+git commit -m "chore: release v0.10.11"+```++---++## Task 31: Vault summary update (operator-coordinated)++**Objective:** Keep `Projects/OpenSecondBrain/Features/_summary.md`+in sync with what shipped.++**This task does not run autonomously.** The vault lives outside the+repo and the operator decides what to write there. The executing+agent prepares a draft snippet and presents it to the operator for+manual application.++**Draft to present:**++- Β§4 β strike "second half deferred" and mark the line that closes+ it. Note PR + release tag.+- Β§15 β same for the wizard half.+- Deferred section Β§D non-bash-runtime activity sources β replace+ with "partial uptake shipped in v0.10.11; remaining runtimes+ (opencode / kiro / Copilot CLI / Gemini CLI / Aider / Pi) stay+ deferred. Trigger: stable upstream transcript paths and operator+ use."+- Add new deferred items per spec Β§12 (project-scope, Pi path+ auto-detect, interactive apply, restart hooks).++Pause: print the snippet to the operator, ask them to drop it into+the vault file. The executing agent does not edit+`/root/vault/Projects/...` directly.++---++## Final pass++- [ ] **Full test suite green.**++```bash+bun test+```++- [ ] **Typecheck clean.**++```bash+bun run typecheck+```++- [ ] **Lint clean** (if the repo wires one β verify+ `package.json scripts`).++```bash+bun run lint+```++- [ ] **Spec compliance walk-through.** Re-read+ `docs/plans/2026-05-20-multi-runtime-install-design.md` and tick+ each Β§1.1 deliverable against shipped code. If any deliverable+ is missing, list it in the operator handoff message.++- [ ] **CHANGELOG matches reality.** Run `git log+ v0.10.10..HEAD --oneline` and verify every commit subject maps+ to a CHANGELOG bullet.++- [ ] **Hermes preview restart (operator-coordinated, if Hermes+ is the active runtime on this server).** After the operator+ confirms the work is shippable:++ ```bash+ hermes gateway restart+ ```++ Wait for the new `Plugin discovery complete` line in+ `~/.hermes/logs/agent.log` before testing live.++- [ ] **Operator handoff.** Summary message to operator:++ > v0.10.11 ready. Seven new install targets land; Most-applied+ > now configurable. Reviewed against design doc, all tasks+ > checked off. Suggest reviewing the seven new adapter files+ > and the new CLI verbs before tag and release. The vault+ > summary draft is in Task 31 β apply when ready.++---++## Implementation order recap++| # | Task | Depends on |+|---|---|---|+| 1 | `types.ts` interfaces | β |+| 2 | `manifest.ts` | 1 |+| 3 | `json-merge.ts` | β (independent helper) |+| 4 | `managed-block.ts` | β |+| 5 | `payload.ts` | β |+| 6 | Registry | 1 |+| 7 | `cursor` adapter | 2, 3, 5, 6 |+| 8 | `opencode` adapter | 7 |+| 9 | `kiro` adapter | 7 |+| 10 | `gemini-cli` adapter | 7 |+| 11 | `copilot-cli` adapter | 6, 3 |+| 12 | `aider` adapter | 4, 6 |+| 13 | `pi` adapter | 6 |+| 14 | `generic` adapter | 6 |+| 15 | `o2b mcp --writer-only` | β |+| 16 | `o2b mcp --probe` | β |+| 17 | `o2b install` CLI | 7-14, 15 |+| 18 | `o2b uninstall --target X` | 17 |+| 19 | `o2b install --check` | 16, 17 |+| 20 | `o2b init --interactive` | 17 |+| 21 | `active.most_applied` config | β |+| 22 | `computeMostApplied` params | 21 |+| 23 | `active.md` honours config | 22 |+| 24 | digest JSON most_applied | 22 |+| 25 | digest Markdown section | 24 |+| 26 | sessionPaths resolvers | β |+| 27 | discipline-report transcripts | 26 |+| 28 | docs restructure | 17-20 |+| 29 | README quick install | 28 |+| 30 | CHANGELOG + version | every preceding task |+| 31 | vault summary | 30 |++Tasks 1-6 are setup; they can land as one feature branch. Tasks+7-14 (adapters) are independent of each other once 1-6 are done+β they can land in any order. Tasks 15-16 land in parallel with+adapters. Tasks 17-20 (CLI verbs) gate on adapters being done.+Tasks 21-25 (Theme 2) are entirely independent of Theme 1 and+can land in parallel. Tasks 26-27 (Companion 2) are independent+of both. Tasks 28-31 are the wrap.diff --git a/install.md b/install.mdindex 4123f22a..d0382aec 100644--- a/install.md+++ b/install.md@@ -1,1350 +1,102 @@-# open-second-brain β Agent Installation Guide+# Open Second Brain β Installation-> Repository: https://github.com/itechmeat/open-second-brain+Open Second Brain ships one CLI (`o2b`), one always-loaded MCP+writer server, one full MCP server, and a runtime-specific install+adapter per supported runtime. This file is a router β pick the+runtime you use and read the corresponding `install/<runtime>.md`.-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 released version.** The runtime CLIs+> resolve `latest` from a bare `owner/repo` identifier by default.+> Do not append `@v...` β that freezes the install at a specific+> tag, including back to an older release if you happen to know an+> outdated number.-**Always install the latest released version.** When the user installs the plugin, they expect to receive the newest published release β for example, if `v0.6.1` is the most recent tag and `v0.6.0` was the previous one, the install **must** end up at `v0.6.1`, not at `v0.6.0`. Each runtime CLI in branches AβD below already resolves "latest" by default when handed a bare `owner/repo` identifier (or the runtime-specific equivalent). Manually appending a version specifier β `@v0.6.0`, `@v1.2.3`, `@<some-tag>`, `--ref v...`, etc. β **bypasses** that resolution and freezes the install at the literal value you typed, including back to an older release if you happen to know an outdated tag number. Do **NOT** add any version specifier to the install commands below; rely on the CLI's default-latest behavior. After install, the effective version is reported by `o2b status` / `o2b doctor` and by the runtime's own plugin listing β read it from there if you need to know what got installed, do not pre-suppose it.+## Prerequisites-**`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 appends the new agent's entry to `AI Wiki/identity/agents.md` (without removing existing ones, so the registry grows correctly across multi-runtime installs) 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.+Read **`install/prerequisites.md`** first β Bun runtime, vault+discovery, identity (agent name + timezone), and the verification+pattern that every install path ends with.-**The `o2b` CLI on PATH is shared across runtimes.** The first runtime to run `o2b install-cli` wires `~/.local/bin/o2b` (and `vault-log`) at its own checkout; subsequent runtimes' `install-cli` invocations detect the existing symlink and **deliberately refuse to overwrite it** (printing `warning: already points to ..., not overwriting`). This is by design: the `o2b` script is byte-identical across all runtime checkouts (they all clone the same repo at the same version), so a single symlink serves every runtime correctly, and overwriting silently would risk pointing at a stale-and-uninstalled checkout when one runtime updates faster than another. If you have a deliberate reason to point `o2b` at a specific runtime's checkout (e.g. you want CLI behavior to track that runtime's plugin update cycle), repoint with `ln -sfn <path> ~/.local/bin/o2b` manually β the plugin won't second-guess you. But the default state, with `o2b` pointing at whichever runtime got there first, is correct and does not need fixing.+## Quick install-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).+For MCP-aware runtimes the v0.10.11 orchestrator handles install+in one command:----+| Runtime | Command | Notes |+|----------------------|----------------------------------------------------|-----------------------------------------------------------------------|+| Cursor | `o2b install --target cursor --apply` | `install/cursor.md` β JSON-merge; restart Cursor after apply |+| Aider | `o2b install --target aider --apply` | `install/aider.md` β managed block + sidecar context; no native MCP |+| opencode | `o2b install --target opencode --apply` | `install/opencode.md` β JSON-merge |+| kiro | `o2b install --target kiro --apply` | `install/kiro.md` β JSON-merge |+| GitHub Copilot CLI | `o2b install --target copilot-cli --apply` | `install/copilot-cli.md` β `copilot mcp add` with JSON fallback |+| Google Gemini CLI | `o2b install --target gemini-cli --apply` | `install/gemini-cli.md` β JSON-merge in `~/.gemini/settings.json` |+| Pi (pi.dev) | `o2b install --target pi --apply` | `install/pi.md` β skill symlink, not MCP |+| Generic / other | `o2b install --target generic --apply --out -` | `install/generic.md` β prints payload; never edits external config |-## Prerequisites β Bun runtime (all branches)+For runtimes that ship their own plugin/MCP install pipeline, OSB+hooks into that pipeline instead of `o2b install --target`:-**Open Second Brain runs on the [Bun](https://bun.sh) JavaScript runtime.** The `o2b` CLI, the MCP server (`o2b mcp`), and the OpenClaw native plugin all execute under Bun. Hermes still loads a small Python shim for the per-turn `pre_llm_call` hook, but every other runtime path is Bun-only.+| Runtime | Doc |+|----------------------|---------------------------|+| Hermes Agent | `install/hermes.md` |+| OpenClaw | `install/openclaw.md` |+| Codex | `install/codex.md` |+| Claude Code | `install/claudecode.md` |-**Before running any branch below, verify Bun is on PATH:**+## Interactive setup-```bash-command -v bun >/dev/null 2>&1 || curl -fsSL https://bun.sh/install | bash-```--If the install runs, re-source your shell so `~/.bun/bin` lands on PATH:--```bash-export PATH="$HOME/.bun/bin:$PATH"-bun --version-```--`bun --version` must report **1.1.0 or newer**. If it does not, stop and ask the user to upgrade Bun before continuing β older versions miss APIs the plugin relies on.--If the user is on a system where they cannot install Bun (locked-down environment, unsupported architecture), abort the install and tell them so explicitly. There is no Python fallback for the CLI; do **not** try to work around the missing runtime by hand-rolling one.-------## Branch A β Hermes--### 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.** You **MUST ask the user** to choose this. Do **not**-silently pick a default value, do **not** assume the user wants-whichever runtime-prefixed name looks reasonable. The value will-appear as the `@agent-name` prefix in every single Daily event log-entry written from this runtime; it has to be the user's deliberate-choice, not the agent's guess.--**Before asking, check for a previously-set identity.** If the user-has installed Open Second Brain before β under another runtime, in a-prior session, or after a reset β there are likely traces on disk:--- `~/.config/open-second-brain/config.yaml` `agent_name` field β the- authoritative persisted identity (written by any past- `o2b init --agent-name` invocation, regardless of runtime).-- `<vault>/AI Wiki/identity/agents.md` β usually has a line like- `- <name>: primary agent on this server`.-- `<vault>/Daily/*.md` β recurring `@<name>` lines hint at past- identities the user has been writing under.--If any of these surfaces a name, **show it to the user first** with a-question like Β«This vault is already configured with `@<found-name>`.-Should I reuse that name for the Hermes runtime, or do you want a-different one for this runtime specifically?Β». Wait for an explicit-answer β do not assume "reuse" or "change" on the user's behalf.--Only when no prior identity is found, 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` / `Serbia` β `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--```bash-hermes plugins install itechmeat/open-second-brain --enable-```--Alternatively, use the Hermes Dashboard: open **Plugins β Install from GitHub URL** and paste:--```-https://github.com/itechmeat/open-second-brain-```--After install, restart the gateway:--```bash-hermes gateway restart-```--### 3. Publish CLI commands to PATH--`hermes plugins install` clones the repository but does not pip-install the package, so the `o2b`, `vault-log`, and `o2b-hook` commands are not on PATH yet. Run this step to create symlinks:--```bash-~/.hermes/plugins/open-second-brain/scripts/o2b install-cli-```--This creates symlinks in `~/.local/bin` pointing to `scripts/o2b`,-`scripts/vault-log`, and `scripts/o2b-hook` inside the plugin-checkout. The symlinks survive `hermes plugins update` because they-point into the git-managed checkout.--After this step, the bare commands `o2b`, `vault-log`, and-`o2b-hook` will be available on PATH. (`o2b-hook` is the launcher-that Claude Code and Codex use for lifecycle hooks; it is not used-by Hermes itself but installing it costs nothing.)--### 4. Initialize the vault--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>" \- --timezone "<chosen-timezone>"--# Recommended on v0.9.0+: bootstrap the Brain observing-memory layer-# next to AI Wiki/. Idempotent; safe to skip on first install if the-# user explicitly opts out of Brain.-o2b brain init --vault /path/to/vault \- --primary-agent "<chosen-agent-name>"-```--**Optional β append `--starter` to bootstrap with a worked example-set.** `o2b brain init --vault /path/to/vault --starter` drops a curated-bundle (8 preferences, 3 retired entries, 1 inbox signal, 6 log days)-into the fresh `Brain/`. The bundle is byte-stable, passes-`o2b brain doctor` cleanly, and is a no-op under `o2b brain dream`-at install time. The starter refuses to run on a non-empty Brain β-it is for the first-init experience only.--`--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.--**Declare this Hermes install as the vault's primary dream-running-agent.** When the vault is shared with other devices through-Syncthing, exactly one runtime should run `hermes cron` for-`o2b brain dream`; the typical choice is the Hermes install on the-always-on host. Passing `--primary-agent <chosen-agent-name>` writes-the value into `Brain/_brain.yaml`. Subsequent dream invocations from-a different agent emit a stderr warning and tag the log entry with-`non_primary_agent: <caller>`. You can change or clear the primary-later with `o2b brain set-primary <name>` or-`o2b brain set-primary --clear`. The flag is ignored on re-runs-against an already-initialised `_brain.yaml`; use `set-primary`-there.--**Wire the `brain-memory` skill into the default Hermes profile.** The-plugin ships `skills/brain-memory/SKILL.md`, which tells the agent when-to call `brain_feedback` / `brain_apply_evidence` in conversation β-without it the MCP tools are registered but the agent does not know to-proactively use them. If the user has a `hermes-skills-sync` helper-configured (typical on systems following the `/root/.agents/` skill-convention), enable the skill once:--```bash-ln -sfn "$(hermes plugins inspect open-second-brain --plugin-root)/skills/brain-memory" \- /root/.agents/hermes-skills-pool/.agents/skills/brain-memory-/root/.agents/hermes-skills-sync enable <profile-name> brain-memory-hermes gateway restart-```--`<profile-name>` is the Hermes profile your default gateway inherits-(commonly `product-tech-lead` per local convention). If the system does-not use that convention, simply expose the skill anywhere Hermes scans-(`/root/.agents/skills/` is global; per-profile views live under-`/root/.agents/hermes-skillsets/<profile>/`). After `hermes skills list`-shows `brain-memory β enabled`, the agent will start recognising-preference signals in conversation and writing them through-`brain_feedback`.--### 5. Register the MCP server--**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-hermes gateway restart-```--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.--**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 \- --env VAULT_AGENT_NAME=<chosen-agent-name>-hermes gateway restart-```--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--```bash-o2b doctor --vault /path/to/vault --repo .-```--All checks must pass. If any check fails, report the failure output to the-user before continuing.--Then run the **daily identity** check (see Β§ Verification β daily identity-below). Installation is incomplete until that check passes.--### 7. Update--```bash-hermes plugins update open-second-brain-hermes gateway restart-o2b doctor --vault /path/to/vault --repo .-```--The CLI symlinks created in step 2 do not need to be recreated after an update β they point into the git checkout, which `hermes plugins update` refreshes via `git pull`.--### 8. Uninstall--Run in this order:--```bash-# Step 1 β dry-run review-o2b uninstall--# Step 2 β deregister MCP, clean up CLI symlinks, remove plugin-hermes mcp remove open-second-brain-o2b uninstall --apply-local --remove-cli-hermes plugins remove open-second-brain-hermes gateway restart-```--The vault and its Markdown files are never deleted by the uninstall process.-------## Branch B β OpenClaw--### 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`.--**Agent name.** You **MUST ask the user** to choose this. Do **not**-silently pick a default value, do **not** assume the user wants-whichever runtime-prefixed name looks reasonable. The value will-appear as the `@agent-name` prefix in every single Daily event log-entry written from this runtime; it has to be the user's deliberate-choice, not the agent's guess.--**Before asking, check for a previously-set identity.** If the user-has installed Open Second Brain before β under another runtime, in a-prior session, or after a reset β there are likely traces on disk:--- `~/.config/open-second-brain/config.yaml` `agent_name` field β the- authoritative persisted identity (written by any past- `o2b init --agent-name` invocation, regardless of runtime).-- `<vault>/AI Wiki/identity/agents.md` β usually has a line like- `- <name>: primary agent on this server`.-- `<vault>/Daily/*.md` β recurring `@<name>` lines hint at past- identities the user has been writing under.--If any of these surfaces a name, **show it to the user first** with a-question like Β«This vault is already configured with `@<found-name>`.-Should I reuse that name for the OpenClaw runtime, or do you want a-different one for this runtime specifically?Β». Wait for an explicit-answer β do not assume "reuse" or "change" on the user's behalf.--Only when no prior identity is found, 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 (let the CLI resolve to the latest released version on its-own; do not append `@v...` β see the prelude on why pinning a tag-manually is the wrong move):--```bash-openclaw plugins install git:github.com/itechmeat/open-second-brain-```--Or from a local checkout:--```bash-openclaw plugins install ./open-second-brain-```--After install, restart the gateway:--```bash-openclaw gateway restart-```--### 3. Publish CLI commands to PATH--The `o2b` and `vault-log` commands are not on PATH after OpenClaw plugin-install (and `o2b-hook`, even though OpenClaw doesn't use it).-Run this step to create symlinks:--```bash-./scripts/o2b install-cli-```--This creates symlinks in `~/.local/bin` for `o2b`, `vault-log`, and-`o2b-hook`. After this, the bare commands work on PATH.--### 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>" \- --timezone "<chosen-timezone>"--# Recommended on v0.9.0+: bootstrap the Brain observing-memory layer-# next to AI Wiki/. Idempotent; safe to skip on first install if the-# user explicitly opts out of Brain.-o2b brain init --vault /path/to/vault-```--Append `--starter` to drop the bundled example set (8 preferences,-3 retired entries, 1 inbox signal, 6 log days) into the fresh-`Brain/`. The bundle passes `o2b brain doctor` cleanly and is a-no-op under `o2b brain dream` at install time; it refuses to run-on a non-empty Brain.--`--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, agent name,-and timezone in the OpenClaw plugin config:--```bash-openclaw config set plugins.entries.open-second-brain.config.vault '"/path/to/vault"'-openclaw config set plugins.entries.open-second-brain.config.instanceName '"My Second Brain"'-openclaw config set plugins.entries.open-second-brain.config.agentName '"<chosen-agent-name>"'-openclaw config set plugins.entries.open-second-brain.config.timezone '"<chosen-timezone>"'-```--The resulting plugin entry must contain `agentName` and `timezone` as-separate fields alongside `instanceName` (do not merge them):--```json-{- "enabled": true,- "config": {- "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-o2b doctor --vault /path/to/vault --repo .-openclaw plugins inspect open-second-brain --runtime --json-```--Both commands must succeed. If any check fails, report the failure output-to the user before continuing.--Then run the **daily identity** check (see Β§ Verification β daily identity-below). Installation is incomplete until that check passes.--### 7. Update--```bash-openclaw plugins update open-second-brain-openclaw gateway restart-o2b doctor --vault /path/to/vault --repo .-```--The CLI symlinks created in step 2 do not need to be recreated after an update.--### 8. Uninstall--```bash-openclaw plugins uninstall open-second-brain-openclaw gateway restart-```--Optionally remove the local config directory and CLI symlinks:--```bash-o2b uninstall --apply-local --remove-cli-```--The vault and its Markdown files are never deleted by the uninstall process.-------## Branch C β Codex--### 1. Collect installation parameters (vault path + agent name + timezone)--Collect all three values before running any commands β step 4-(`o2b init`) and step 5 (Codex 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).- 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 the Codex MCP entry.--**Agent name.** You **MUST ask the user** to choose this. Do **not**-silently pick a default value, do **not** assume the user wants-whichever runtime-prefixed name looks reasonable. The value will-appear as the `@agent-name` prefix in every single Daily event log-entry written from this runtime; it has to be the user's deliberate-choice, not the agent's guess.--**Before asking, check for a previously-set identity.** If the user-has installed Open Second Brain before β under another runtime, in a-prior session, or after a reset β there are likely traces on disk:--- `~/.config/open-second-brain/config.yaml` `agent_name` field β the- authoritative persisted identity (written by any past- `o2b init --agent-name` invocation, regardless of runtime).-- `<vault>/AI Wiki/identity/agents.md` β usually has a line like- `- <name>: primary agent on this server`.-- `<vault>/Daily/*.md` β recurring `@<name>` lines hint at past- identities the user has been writing under.--If any of these surfaces a name, **show it to the user first** with a-question like Β«This vault is already configured with `@<found-name>`.-Should I reuse that name for the Codex runtime, or do you want a-different one for this runtime specifically?Β». Wait for an explicit-answer β do not assume "reuse" or "change" on the user's behalf.--Only when no prior identity is found, offer these defaults plus a-custom value:--- `codex-main`-- `codex-vps-agent`-- `codex-server`-- `second-brain-agent`-- `<hostname>-codex`--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-```--(The CLI resolves to the latest released version by default; do-**not** append `@v...` β see the prelude.) Codex clones the repo-somewhere under `~/.codex/`. The exact path varies by-CLI version: older builds use `~/.codex/plugins/cache/<marketplace>/<plugin>/<hash>/`;-Codex 0.129 stores it under `~/.codex/.tmp/marketplaces/<marketplace>/`.-Step 3 below uses a `find` to locate the plugin scripts regardless of-layout, so this difference is not user-visible. A-`[marketplaces.open-second-brain]` entry is added to-`~/.codex/config.toml`; the printed `Installed marketplace root: ...`-line shows the absolute path of the install for that run.--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 advertised MCP tools become-available **only** after step 5 below β Codex treats MCP server-registration as a separate concern from plugin enablement. The-advertised set is:--- **Core (3):** `second_brain_status`, `second_brain_query`,- `vault_health`.-- **Brain (6):** `brain_feedback`, `brain_dream`,- `brain_apply_evidence`, `brain_digest`, `brain_query`,- `brain_doctor`.-- **Pay Memory (8):** `payment_memory_init`, `payment_receipt_append`,- `asset_capture`, `payment_report_generate`, `payment_policy_check`,- `payment_request_approval`, `payment_request_status`,- `payment_request_consume`.--### 3. Publish CLI commands to PATH--The `o2b`, `vault-log`, and `o2b-hook` scripts ship inside the plugin-checkout; this step symlinks them into `~/.local/bin` so they are-usable on PATH. (`o2b-hook` is the launcher that lifecycle hooks-invoke β see step 6b.)--The cached path differs across Codex versions (see step 2), so locate-the script by searching under `~/.codex/`:+For a guided first-time setup that composes `o2b init`, optional+`o2b brain init`, and per-target `o2b install`:```bash-"$(find ~/.codex -path '*open-second-brain*/scripts/o2b' -type f 2>/dev/null | head -1)" install-cli+o2b init --interactive```-If you installed the marketplace from a local path, run-`<that-path>/scripts/o2b install-cli` directly instead.+The wizard reads from stdin, prints the full action plan, and+requires an explicit `yes` before any side effects.-### 4. Initialize the vault+## Verify-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>" \- --timezone "<chosen-timezone>"--# Recommended on v0.9.0+: bootstrap the Brain observing-memory layer-# next to AI Wiki/. Idempotent; safe to skip on first install if the-# user explicitly opts out of Brain.-o2b brain init --vault /path/to/vault-```--Append `--starter` to drop the bundled example set (8 preferences,-3 retired entries, 1 inbox signal, 6 log days) into the fresh-`Brain/`. The bundle passes `o2b brain doctor` cleanly and is a-no-op under `o2b brain dream` at install time; it refuses to run-on a non-empty Brain.--`--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.--### 5. Register the MCP server--Codex consumes Open Second Brain's MCP tools through a stdio server-configured in `~/.codex/config.toml`. The official command is:--```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+After any install:```basho2b doctor --vault /path/to/vault --repo .-codex mcp list+o2b install --check```-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.+`o2b install --check` is the runtime-install health check+(per-target managed-block / MCP-ping verification). Exit code is+`0` for ok / not-installed, `3` if any target reports drift.-### 6b. Lifecycle hooks (auto-enabled)+## Uninstall-The plugin ships a `hooks/hooks.json` that Codex loads automatically-from the bundled plugin tree. One hook fires per turn:--- `PostToolUse` (matcher `Write|Edit|MultiEdit|apply_patch`) β after- a file-mutating tool succeeds, injects a short reminder pointing- the agent at `brain_feedback` (when the turn contained a user- preference or correction) and `brain_apply_evidence` (when an- active preference in `Brain/preferences/` scopes to the artifact- just produced).--The hook invokes `o2b-hook` from PATH. That CLI was symlinked into-`~/.local/bin` by step 3, so no extra wiring is needed. If-`o2b-hook` is missing from PATH the hook fails closed (turn proceeds-normally with a stderr trace) β re-run step 3 to fix.--### 6c. Optional β machine-enforce write protection on `Brain/`--OSB defends `Brain/preferences/`, `retired/`, `log/`, `.snapshots/`,-and `Brain/_brain.yaml` against accidental writes by the agent-through Codex's native `[permissions.osb_protected.filesystem]`-table. `Brain/inbox/` stays writable β that is where-`brain_feedback` legitimately drops signals.--Preview the snippet without touching disk:+For MCP-aware runtimes:```bash-o2b brain protect --target codex --vault /path/to/vault+o2b uninstall --target <name> --apply```-Apply when satisfied:--```bash-o2b brain protect --target codex --vault /path/to/vault --apply-```--`o2b brain unprotect --target codex --vault /path/to/vault` removes-the OSB-managed block (a `# >>> open-second-brain managed >>>`-fence in `~/.codex/config.toml`). A sidecar manifest at-`<vault>/.open-second-brain/protect.lock.json` records what was-added, so `unprotect` removes exactly the OSB rules and never-touches user-authored config.--### 7. Update--```bash-codex plugin marketplace upgrade open-second-brain-```--(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 mcp remove open-second-brain-codex plugin marketplace remove open-second-brain-o2b uninstall --apply-local --remove-cli-```--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. 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.** You **MUST ask the user** to choose this. Do **not**-silently pick a default value, do **not** assume the user wants-whichever runtime-prefixed name looks reasonable. The value will-appear as the `@agent-name` prefix in every single Daily event log-entry written from this runtime; it has to be the user's deliberate-choice, not the agent's guess.--**Before asking, check for a previously-set identity.** If the user-has installed Open Second Brain before β under another runtime, in a-prior session, or after a reset β there are likely traces on disk:--- `~/.config/open-second-brain/config.yaml` `agent_name` field β the- authoritative persisted identity (written by any past- `o2b init --agent-name` invocation, regardless of runtime). On- Claude Code specifically this field is what the bundled- `.mcp.json` resolves at runtime, so a stale value here will- silently become Claude's identity unless step 4 overwrites it.-- `<vault>/AI Wiki/identity/agents.md` β usually has a line like- `- <name>: primary agent on this server`.-- `<vault>/Daily/*.md` β recurring `@<name>` lines hint at past- identities the user has been writing under.--If any of these surfaces a name, **show it to the user first** with a-question like Β«This vault is already configured with `@<found-name>`.-Should I reuse that name for the Claude Code runtime, or do you want-a different one for this runtime specifically?Β». Wait for an explicit-answer β do not assume "reuse" or "change" on the user's behalf.--Only when no prior identity is found, 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.--### 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 plugin marketplace add itechmeat/open-second-brain-claude plugin install open-second-brain@open-second-brain-```--(The marketplace step resolves to the latest released version on its-own; do **not** append `@v...` β see the prelude.) After install,-`claude plugin list` shows the plugin under user scope with-`Status: β enabled`. Claude clones the repo-under `~/.claude/plugins/cache/<marketplace>/<plugin-name>/<version>/`-(the trailing `<version>` segment matches the installed plugin-manifest's `version`, e.g. `0.6.1`) 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`, `vault-log`, and `o2b-hook` scripts ship inside the plugin-checkout; this step symlinks them into `~/.local/bin` so they are-usable on PATH. (`o2b-hook` is the launcher that lifecycle hooks-invoke β see step 6b.)--The cached path includes the plugin version segment, so locate the-script by searching under the cache:--```bash-"$(find ~/.claude/plugins/cache -path '*open-second-brain*/scripts/o2b' -type f 2>/dev/null | head -1)" install-cli-```--### 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>" \- --timezone "<chosen-timezone>"--# Recommended on v0.9.0+: bootstrap the Brain observing-memory layer-# next to AI Wiki/. Idempotent; safe to skip on first install if the-# user explicitly opts out of Brain.-o2b brain init --vault /path/to/vault-```--Append `--starter` to drop the bundled example set (8 preferences,-3 retired entries, 1 inbox signal, 6 log days) into the fresh-`Brain/`. The bundle passes `o2b brain doctor` cleanly and is a-no-op under `o2b brain dream` at install time; it refuses to run-on a non-empty Brain.--`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-```--`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.--### 6b. Lifecycle hooks (auto-enabled)--The plugin ships a `hooks/hooks.json` that Claude Code loads-automatically from the cached plugin tree. One hook fires per turn:--- `PostToolUse` (matcher `Write|Edit|MultiEdit|apply_patch`) β after- a file-mutating tool succeeds, injects a short reminder pointing- the agent at `brain_feedback` (when the turn contained a user- preference or correction) and `brain_apply_evidence` (when an- active preference in `Brain/preferences/` scopes to the artifact- just produced).--The hook invokes `o2b-hook` from PATH. That CLI was symlinked into-`~/.local/bin` by step 3, so no extra wiring is needed. To watch the-hook fire end-to-end use `--output-format=stream-json --verbose---include-hook-events`; you should see `hook_started` /-`hook_response` events around each `Write` / `Edit`.--### 6c. Optional β machine-enforce write protection on `Brain/`--OSB defends `Brain/preferences/`, `retired/`, `log/`, `.snapshots/`,-and `Brain/_brain.yaml` against accidental writes by the agent-through Claude Code's native `permissions.deny` list. `Brain/inbox/`-stays writable β that is where `brain_feedback` legitimately drops-signals.--Preview the snippet without touching disk:--```bash-o2b brain protect --target claudecode --vault /path/to/vault-```--Apply when satisfied:--```bash-o2b brain protect --target claudecode --vault /path/to/vault --apply-```--`o2b brain unprotect --target claudecode --vault /path/to/vault`-removes the OSB-managed entries from `<vault>/.claude/settings.json`.-A sidecar manifest at-`<vault>/.open-second-brain/protect.lock.json` records exactly which-`permissions.deny` / `permissions.allow` strings OSB owns, so-`unprotect` removes only those and never touches user-authored-rules.--### 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. The advertised tool set is 17 tools across three groups- β Core (3: `second_brain_status` / `second_brain_query` /- `vault_health`), Brain (6: `brain_feedback` / `brain_dream` /- `brain_apply_evidence` / `brain_digest` / `brain_query` /- `brain_doctor`), and Pay Memory (8: `payment_*` and- `asset_capture`).-- 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...`) β let the runtime CLI resolve to the latest released-version on its own (see the prelude on why manual pinning freezes you-to a stale release).--### 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>" \- --timezone "<chosen-timezone>"--# Recommended on v0.9.0+: bootstrap the Brain observing-memory layer-# next to AI Wiki/. Idempotent; safe to skip on first install if the-# user explicitly opts out of Brain.-o2b brain init --vault /path/to/vault-```--Append `--starter` to drop the bundled example set (8 preferences,-3 retired entries, 1 inbox signal, 6 log days) into the fresh-`Brain/`. The bundle passes `o2b brain doctor` cleanly and is a-no-op under `o2b brain dream` at install time; it refuses to run-on a non-empty Brain.--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--The exact mechanism depends on the runtime. The minimum spec the-plugin expects is a stdio MCP server invocation:--| 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):--```yaml-mcp_servers:- open-second-brain:- command: o2b- args: [mcp]- env:- VAULT_AGENT_NAME: "<chosen-agent-name>"- VAULT_TIMEZONE: "<chosen-timezone>"- enabled: true-```--If TOML (Codex-style):--```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>"-```--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.--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-o2b doctor --vault /path/to/vault --repo <plugin-checkout>-```--All checks must pass. Then run the **daily identity** check (see-Β§ Verification β daily identity below). Installation is incomplete-until that check passes.--### 7. Optional β surface plugin guidance to the LLM--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`.--### 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.-------## Verification β identity registry--The plugin's MCP-side identity (what gets stamped in Daily as-`@<name>`) is one of two artifacts; the **vault's identity registry**-(the human-/agent-readable list of who is allowed to write) is the-other. Both must agree, and both must be checked. Past install-sessions have skipped this and silently ended up with the runtime-writing under one identity that the registry never recorded β the MCP-server happily logged events without complaint, and the gap only-surfaced later when someone audited the vault.--After step 4's `o2b init --agent-name <name>` finishes, open-`<vault>/AI Wiki/identity/agents.md` and confirm it contains a line-like:--```-- <chosen-agent-name>: primary agent on this server-```--Multi-runtime installs build this list incrementally: each-`o2b init --agent-name X` appends another entry under-`## Registered agents` if `X` isn't already there. So on a vault-that already has Hermes registered, a fresh Codex install should-result in **two** lines β one for `hermes-vps-agent`, one for-`codex-vps-agent` β not just one.--If your runtime's identity is missing from the registry after-`o2b init` ran without errors, treat the install as **incomplete**:-report it to the user, then either re-run `o2b init --agent-name <name>`-(it's idempotent and will append the missing entry), or add the line-by hand if you have a reason not to re-run init. Don't proceed to-the daily-identity check below without this in place.--## Verification β daily identity--`o2b doctor` and `vault_health` confirm that the vault is structurally-valid, but they do not verify that the agent will write under the chosen-identity. Run this extra check after every install:--1. Call `event_log_append` **without** an explicit `agent` argument.- Through the MCP server:-- ```bash- o2b tool-call event_log_append --vault /path/to/vault \- --tool-arg message="install verification"- ```--2. Open the daily note that was just written:-- ```- /path/to/vault/Daily/YYYY.MM.DD.md- ```--3. The newest entry must show `@<chosen-agent-name>`, **not** the- `@agent` placeholder. Example:-- ```- - 14:32 β @openclaw-main β install verification- ```--4. If `@agent` appears instead, stop and report the install as- **incomplete**: the runtime did not pick up the configured `agentName`.- Re-check step 5 of the chosen branch (plugin config or MCP env).+Removes exactly what `o2b install --target <name>` wrote (recorded+in `<vault>/.open-second-brain/install.lock.json`). For runtimes+that ship their own plugin uninstall command, see the+corresponding `install/<runtime>.md` for the full sequence.----+The vault and its Markdown files are never deleted by the+uninstall process.## Installation readiness criteria-The installation is complete **only** when **all** of the following hold:+The installation is complete only when all of the following hold:-- [ ] plugin installed;-- [ ] gateway restarted;-- [ ] plugin runtime status is `loaded`;-- [ ] all tools registered;+- [ ] plugin (or per-target managed block) installed;+- [ ] runtime restarted to pick up the change;+- [ ] all tools advertised by the runtime's MCP listing;- [ ] vault initialized (`o2b init` succeeded);-- [ ] `vault_health` (or `o2b doctor`) reports OK;-- [ ] for OpenClaw: `plugins.entries.open-second-brain.config.agentName` is- set to the chosen name;-- [ ] for Hermes / Codex: `VAULT_AGENT_NAME` is exported in the- environment that launches the MCP server (or set in the runtime's- MCP-config stanza);-- [ ] for Claude Code: `agent_name` is persisted in- `~/.config/open-second-brain/config.yaml` by `o2b init --agent-name`.- Claude Code's bundled `.mcp.json` reads from that config at server- spawn, so no `VAULT_AGENT_NAME` env var is required;-- [ ] `AI Wiki/identity/agents.md` contains the chosen agent name and no- longer contains the `(add your agents here, β¦)` template- placeholder;-- [ ] `event_log_append` called **without** an explicit `agent` argument- writes a `Daily/*.md` entry under the chosen name (see Verification- β daily identity above), not under `@agent`.+- [ ] `o2b doctor` reports OK;+- [ ] `o2b install --check` reports `ok` for the target;+- [ ] `AI Wiki/identity/agents.md` contains the chosen agent name;+- [ ] a test event written without an explicit `agent` argument+ stamps `@<chosen-agent-name>` in `Daily/`, not `@agent`.-If any single item is missing, the install is **incomplete** β report+If any single item is missing, the install is incomplete β reportthat to the user and do not mark the workflow as successful.diff --git a/install/aider.md b/install/aider.mdnew file mode 100644index 00000000..2eb9e301--- /dev/null+++ b/install/aider.md@@ -0,0 +1,55 @@+# Aider++Aider has no native MCP client at the time this file was written.+`o2b install --target aider --apply` instead writes a marker-fenced+managed block into `~/.aider.conf.yml` that points at a generated+context file under the vault. Aider auto-includes that file as+read-only context on every chat turn.++## Install++```bash+o2b install --target aider --apply+```++The command:++1. Renders `templates/install/aider-context.md.tmpl` to+ `<vault>/.open-second-brain/aider-context.md` with the current+ `@agent_name` and vault path substituted in.+2. Appends a managed block to `~/.aider.conf.yml` under `read:`+ listing the generated file.++The block is fenced by+`# >>> open-second-brain managed >>>` /+`# <<< open-second-brain managed <<<`. Anything outside those+markers is preserved byte-for-byte.++## Verify++```bash+o2b install --check --target aider+```++Confirms both the managed block and the sidecar context file are+on disk.++## Uninstall++```bash+o2b uninstall --target aider --apply+```++Removes the managed block plus the generated context file. Your+own `~/.aider.conf.yml` content above and below the block stays.++## Notes++- If you also set a project-local `read:` list elsewhere in+ `~/.aider.conf.yml`, Aider's YAML loader treats duplicate+ top-level keys as ambiguous. Merge the two `read:` lists by hand+ if you keep your own.+- Aider was tracked as a potential MCP host in the v0.10.11+ design. If a future Aider release ships native MCP, this adapter+ will switch to JSON-merge transparently β the CLI surface stays+ the same.diff --git a/install/claudecode.md b/install/claudecode.mdnew file mode 100644index 00000000..dca67ef0--- /dev/null+++ b/install/claudecode.md@@ -0,0 +1,78 @@+# Claude Code++Claude Code installs OSB through its marketplace subsystem. The+bundled `.mcp.json` auto-registers the MCP server so there is no+explicit `claude mcp add` step.++## 1. Install the plugin++```bash+claude plugin marketplace add itechmeat/open-second-brain+claude plugin install open-second-brain@open-second-brain+```++## 2. Publish the `o2b` CLI on PATH++Claude caches the plugin at a versioned path; locate the script:++```bash+"$(find ~/.claude/plugins/cache -path '*open-second-brain*/scripts/o2b' -type f 2>/dev/null | head -1)" install-cli+```++## 3. Initialize the vault++```bash+o2b init --vault /path/to/vault --name "My Second Brain" \+ --agent-name "<chosen-agent-name>" --timezone "<chosen-tz>"+o2b brain init --vault /path/to/vault+```++`o2b init` persists `vault`, `agent_name`, and `timezone` into+`~/.config/open-second-brain/config.yaml`. The auto-registered+`.mcp.json` calls `o2b mcp` with no flags; the server reads the+persisted config at spawn time.++## 4. Verify++```bash+o2b doctor --vault /path/to/vault --repo .+claude plugin list+claude mcp list+```++`claude mcp list` must show+`plugin:open-second-brain:open-second-brain` with `β Connected`.+Run the daily-identity check from `install/prerequisites.md`.++## Lifecycle hooks (auto-enabled)++The bundled `hooks/hooks.json` registers a `PostToolUse` hook+(matcher `Write|Edit|MultiEdit|apply_patch`). To watch the hook+fire end-to-end use+`--output-format=stream-json --verbose --include-hook-events`.++## Machine-enforce write protection (optional)++```bash+o2b brain protect --target claudecode --vault /path/to/vault --apply+o2b brain unprotect --target claudecode --vault /path/to/vault+```++The sidecar manifest at+`<vault>/.open-second-brain/protect.lock.json` records exactly the+`permissions.deny` / `permissions.allow` entries OSB owns.++## Update++```bash+claude plugin marketplace update open-second-brain+claude plugin update open-second-brain@open-second-brain+```++## Uninstall++```bash+claude plugin uninstall open-second-brain@open-second-brain+claude plugin marketplace remove open-second-brain+o2b uninstall --apply-local --remove-cli+```diff --git a/install/codex.md b/install/codex.mdnew file mode 100644index 00000000..2c2bf6f7--- /dev/null+++ b/install/codex.md@@ -0,0 +1,83 @@+# Codex++Codex installs OSB through its marketplace + MCP subsystems.++## 1. Install the plugin++```bash+codex plugin marketplace add itechmeat/open-second-brain+```++Then enable it by adding to `~/.codex/config.toml`:++```toml+[plugins."open-second-brain@open-second-brain"]+enabled = true+```++## 2. Publish the `o2b` CLI on PATH++Codex caches the plugin at a version-hashed path; locate the+script:++```bash+"$(find ~/.codex -path '*open-second-brain*/scripts/o2b' -type f 2>/dev/null | head -1)" install-cli+```++## 3. Initialize the vault++```bash+o2b init --vault /path/to/vault --name "My Second Brain" \+ --agent-name "<chosen-agent-name>" --timezone "<chosen-tz>"+o2b brain init --vault /path/to/vault+```++## 4. Register the MCP server++```bash+codex mcp add open-second-brain \+ --env VAULT_AGENT_NAME=<chosen-agent-name> \+ --env VAULT_TIMEZONE=<chosen-tz> \+ -- o2b mcp --vault /path/to/vault+```++## 5. Verify++```bash+o2b doctor --vault /path/to/vault --repo .+codex mcp list+```++Run the daily-identity check from `install/prerequisites.md`.++## Lifecycle hooks (auto-enabled)++The bundled `hooks/hooks.json` registers a `PostToolUse` hook+(matcher `Write|Edit|MultiEdit|apply_patch`) that invokes+`o2b-hook` from PATH after every file-mutating tool succeeds. Step+2 above wires it.++## Machine-enforce write protection (optional)++```bash+o2b brain protect --target codex --vault /path/to/vault --apply+o2b brain unprotect --target codex --vault /path/to/vault+```++The sidecar manifest at+`<vault>/.open-second-brain/protect.lock.json` records exactly+what was added; `unprotect` removes the same.++## Update++```bash+codex plugin marketplace upgrade open-second-brain+```++## Uninstall++```bash+codex mcp remove open-second-brain+codex plugin marketplace remove open-second-brain+o2b uninstall --apply-local --remove-cli+```diff --git a/install/copilot-cli.md b/install/copilot-cli.mdnew file mode 100644index 00000000..4eaffb91--- /dev/null+++ b/install/copilot-cli.md@@ -0,0 +1,43 @@+# GitHub Copilot CLI++`o2b install --target copilot-cli --apply` registers the two OSB+MCP servers with the GitHub Copilot CLI. The primary path calls+`copilot mcp add` per server name; if the CLI is missing or its+`add` step fails, the adapter falls back to writing+`${XDG_CONFIG_HOME:-$HOME/.config}/github-copilot/mcp.json`+directly and prints a stderr note.++## Install++```bash+o2b install --target copilot-cli --apply+```++The adapter records which mode it used (`subprocess` or+`json-merge` fallback) in the sidecar manifest so `uninstall`+mirrors the same path.++## Verify++```bash+o2b install --check --target copilot-cli+```++Verify queries `copilot mcp list` when the CLI is available, or+inspects the fallback file otherwise.++## Uninstall++```bash+o2b uninstall --target copilot-cli --apply+```++## Notes++- Upstream reference:+ `docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/add-mcp-servers`.+- The exact `copilot mcp add` flag names are pinned to the CLI+ version current at v0.10.11 implementation time. If a Copilot CLI+ release renames flags, expect the adapter to fall back to the+ file-merge path automatically β `o2b install --check` will+ surface the change.diff --git a/install/cursor.md b/install/cursor.mdnew file mode 100644index 00000000..9fb54d34--- /dev/null+++ b/install/cursor.md@@ -0,0 +1,46 @@+# Cursor++`o2b install --target cursor --apply` writes the OSB MCP servers+into `~/.cursor/mcp.json` via JSON-merge. The two registered names+are `open-second-brain` (full tool set) and `open-second-brain-writer`+(always-loaded writer / `brain_context` subset).++## Prerequisites++See `install/prerequisites.md`. Then run `o2b init --vault <path>+--agent-name <name> --timezone <tz>` to persist identity that the+MCP servers will pick up at spawn time.++## Install++```bash+o2b install --target cursor --apply+```++This preserves any pre-existing `mcpServers.*` keys; only+`mcpServers.open-second-brain` and `mcpServers.open-second-brain-writer`+are owned by OSB.++After install, **restart the Cursor app** for the new MCP servers+to load. `o2b install --check --target cursor` confirms the file+state regardless of whether Cursor has reloaded yet.++## Uninstall++```bash+o2b uninstall --target cursor --apply+```++Removes exactly the two OSB keys from `mcpServers` (the sidecar+manifest at `<vault>/.open-second-brain/install.lock.json` records+which keys to remove). User-authored entries stay intact.++## Notes++- `--scope project` (writing into `<cwd>/.cursor/mcp.json`) is+ deferred to a follow-up release. v0.10.11 always targets the+ user-scope path.+- If a previous OSB version wrote to `.cursor/mcp.json` without+ recording a manifest entry, use+ `o2b uninstall --target cursor --apply --force-from-snippet`+ for a one-time cleanup.diff --git a/install/gemini-cli.md b/install/gemini-cli.mdnew file mode 100644index 00000000..c948e685--- /dev/null+++ b/install/gemini-cli.md@@ -0,0 +1,30 @@+# Google Gemini CLI++`o2b install --target gemini-cli --apply` writes the two OSB MCP+servers into `~/.gemini/settings.json` under the `mcpServers` key+(documented at+`github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md`).+Existing entries are preserved.++## Install++```bash+o2b install --target gemini-cli --apply+```++## Verify++```bash+o2b install --check --target gemini-cli+```++## Uninstall++```bash+o2b uninstall --target gemini-cli --apply+```++## Notes++- A liveness check for the runtime itself is `gemini --version`+ exit-code 0. `o2b mcp --probe` covers the MCP-side handshake.diff --git a/install/generic.md b/install/generic.mdnew file mode 100644index 00000000..b37a55c7--- /dev/null+++ b/install/generic.md@@ -0,0 +1,57 @@+# Generic (printout)++Use this target when your runtime is not in the per-runtime list+above. `o2b install --target generic` never edits any external+config; it prints the canonical MCP server payload and leaves the+operator to wire it into whatever the runtime expects.++## Print to stdout++```bash+o2b install --target generic --apply --out -+```++Default format is JSON:++```json+{+ "mcpServers": {+ "open-second-brain": {+ "command": "o2b",+ "args": ["mcp", "--vault", "/path/to/vault"],+ "env": { "VAULT_AGENT_NAME": "...", "VAULT_TIMEZONE": "..." }+ },+ "open-second-brain-writer": {+ "command": "o2b",+ "args": ["mcp", "--writer-only", "--vault", "/path/to/vault"]+ }+ }+}+```++YAML is also available:++```bash+o2b install --target generic --apply --out - --format yaml+```++## Write to a file++```bash+o2b install --target generic --apply --out /path/to/snippet.json+```++The path is recorded in the sidecar manifest so `o2b install+--check --target generic` can confirm the file still exists.+`o2b uninstall --target generic --apply` will _not_ delete the+file β the consuming runtime may still depend on it. The+uninstall step prints the path so the operator can clean it up by+hand.++## Notes++- Detection always reports `not-installed` (there is no canonical+ config to probe for this target).+- The `generic` target is the right escape hatch when a new+ runtime appears between OSB releases. Per-runtime adapters land+ in subsequent releases as needed.diff --git a/install/hermes.md b/install/hermes.mdnew file mode 100644index 00000000..f59e502c--- /dev/null+++ b/install/hermes.md@@ -0,0 +1,86 @@+# Hermes++Hermes installs OSB through its native plugin / MCP machinery,+not through `o2b install --target hermes`. The flow below assumes+a working Hermes Agent with `hermes` on PATH.++## 1. Install the plugin++```bash+hermes plugins install itechmeat/open-second-brain --enable+hermes gateway restart+```++Or paste `https://github.com/itechmeat/open-second-brain` into the+Hermes Dashboard β Plugins β Install from GitHub URL. Do not pin+a tag β the CLI resolves to the latest released version on its+own.++## 2. Publish the `o2b` CLI on PATH++```bash+~/.hermes/plugins/open-second-brain/scripts/o2b install-cli+```++Creates symlinks for `o2b`, `vault-log`, and `o2b-hook` in+`~/.local/bin`. Survives `hermes plugins update`.++## 3. Initialize the vault++```bash+o2b init --vault /path/to/vault --name "My Second Brain" \+ --agent-name "<chosen-agent-name>" --timezone "<chosen-tz>"+o2b brain init --vault /path/to/vault \+ --primary-agent "<chosen-agent-name>"+```++`--primary-agent` declares this Hermes install as the vault's+dream-running host. Multi-device setups (Syncthing) benefit from+a single dream-runner.++## 4. Register the MCP server++Edit `~/.hermes/config.yaml`:++```yaml+mcp_servers:+ open-second-brain:+ command: o2b+ args: [mcp, --vault, /path/to/vault]+ env:+ VAULT_AGENT_NAME: <chosen-agent-name>+ enabled: true+```++Then restart the gateway:++```bash+hermes gateway restart+```++## 5. Verify++```bash+o2b doctor --vault /path/to/vault --repo .+```++Run the daily-identity check described in `install/prerequisites.md`.++## Update++```bash+hermes plugins update open-second-brain+hermes gateway restart+o2b doctor --vault /path/to/vault --repo .+```++## Uninstall++```bash+hermes mcp remove open-second-brain+o2b uninstall --apply-local --remove-cli+hermes plugins remove open-second-brain+hermes gateway restart+```++The vault and its Markdown files are never deleted.diff --git a/install/kiro.md b/install/kiro.mdnew file mode 100644index 00000000..0ec41329--- /dev/null+++ b/install/kiro.md@@ -0,0 +1,30 @@+# kiro++`o2b install --target kiro --apply` writes the two OSB MCP servers+into `~/.kiro/settings.json` via JSON-merge. User-authored entries+are preserved.++## Install++```bash+o2b install --target kiro --apply+```++Restart kiro to load the new servers.++## Verify++```bash+o2b install --check --target kiro+```++## Uninstall++```bash+o2b uninstall --target kiro --apply+```++## Notes++- Confirm the upstream kiro MCP config path against the project's+ current docs before adopting on a new release.diff --git a/install/openclaw.md b/install/openclaw.mdnew file mode 100644index 00000000..65c58f21--- /dev/null+++ b/install/openclaw.md@@ -0,0 +1,74 @@+# OpenClaw++OpenClaw installs OSB through its native plugin system. Tools are+registered by the bundled JS plugin entry, not via a separate MCP+server.++## 1. Install the plugin++From Git:++```bash+openclaw plugins install git:github.com/itechmeat/open-second-brain+```++Or from a local checkout:++```bash+openclaw plugins install ./open-second-brain+```++Then:++```bash+openclaw gateway restart+```++## 2. Publish the `o2b` CLI on PATH++```bash+./scripts/o2b install-cli+```++## 3. Initialize the vault++```bash+o2b init --vault /path/to/vault --name "My Second Brain" \+ --agent-name "<chosen-agent-name>" --timezone "<chosen-tz>"+o2b brain init --vault /path/to/vault+```++## 4. Configure vault path, agent name, timezone++OpenClaw reads from its own per-plugin config store:++```bash+openclaw config set plugins.entries.open-second-brain.config.vault '"/path/to/vault"'+openclaw config set plugins.entries.open-second-brain.config.instanceName '"My Second Brain"'+openclaw config set plugins.entries.open-second-brain.config.agentName '"<chosen-agent-name>"'+openclaw config set plugins.entries.open-second-brain.config.timezone '"<chosen-tz>"'+```++## 5. Verify++```bash+o2b doctor --vault /path/to/vault --repo .+openclaw plugins inspect open-second-brain --runtime --json+```++Run the daily-identity check from `install/prerequisites.md`.++## Update++```bash+openclaw plugins update open-second-brain+openclaw gateway restart+```++## Uninstall++```bash+openclaw plugins uninstall open-second-brain+openclaw gateway restart+o2b uninstall --apply-local --remove-cli+```diff --git a/install/opencode.md b/install/opencode.mdnew file mode 100644index 00000000..192356b3--- /dev/null+++ b/install/opencode.md@@ -0,0 +1,32 @@+# opencode++`o2b install --target opencode --apply` writes the two OSB MCP+servers into `${XDG_CONFIG_HOME:-$HOME/.config}/opencode/mcp.json`+via JSON-merge. User-authored entries in `mcpServers` are preserved.++## Install++```bash+o2b install --target opencode --apply+```++Restart `opencode` to load the new servers.++## Verify++```bash+o2b install --check --target opencode+```++## Uninstall++```bash+o2b uninstall --target opencode --apply+```++## Notes++- Confirm the upstream `sst/opencode` MCP config path against the+ current docs before adopting on a new release. The adapter+ defaults to `~/.config/opencode/mcp.json` but reads+ `XDG_CONFIG_HOME` when set.diff --git a/install/pi.md b/install/pi.mdnew file mode 100644index 00000000..d0a56d11--- /dev/null+++ b/install/pi.md@@ -0,0 +1,43 @@+# Pi (pi.dev)++Pi intentionally chose "CLI-tool + README + skill" over MCP. OSB+installs as a thin skill that points at the `o2b brain *` CLI+verbs.++## Install++```bash+o2b install --target pi --apply+```++Creates a symlink at `${PI_HOME:-$HOME/.pi}/skills/brain-memory`+pointing at the bundled `skills/brain-memory/` directory inside+this plugin checkout. Override the destination with+`--pi-skill-dir <path>`.++## Verify++```bash+o2b install --check --target pi+```++Confirms the symlink is valid and the source `SKILL.md` is+readable.++## Uninstall++```bash+o2b uninstall --target pi --apply+```++Removes the symlink only. The bundled source directory is never+deleted.++## Notes++- If the Pi runtime stabilises a different convention for its+ skill directory in the future, `--pi-skill-dir` is the override+ knob until the adapter picks up the new path automatically.+- An existing non-symlink directory at the target path is refused+ without `--force`. This guards a user-authored folder under+ `~/.pi/skills/brain-memory/`.diff --git a/install/prerequisites.md b/install/prerequisites.mdnew file mode 100644index 00000000..729a7e09--- /dev/null+++ b/install/prerequisites.md@@ -0,0 +1,62 @@+# Prerequisites++The `o2b` CLI runs on [Bun](https://bun.sh/). Every install path+expects `bun >= 1.1.0` on `PATH`.++```bash+command -v bun >/dev/null 2>&1 || curl -fsSL https://bun.sh/install | bash+export PATH="$HOME/.bun/bin:$PATH"+bun --version+```++If you cannot install Bun (locked-down environment, unsupported+architecture), the plugin will not function on that host. No Python+fallback exists.++## Identity (agent name + timezone)++`o2b init` persists two values into `~/.config/open-second-brain/config.yaml`:++- **`agent_name`** β prefix used in every `Daily/` entry and every+ `Brain/log/` event written by an MCP server pointing at this vault.+ Pick a deliberate value (`<runtime>-<host>` is a good default).+- **`timezone`** β IANA name (`Europe/Belgrade`, `America/New_York`,+ `UTC`). Used to stamp `Daily/` entries regardless of the host's+ local clock.++If the vault was initialized previously, check the registry first:++- `~/.config/open-second-brain/config.yaml` `agent_name` (authoritative)+- `<vault>/AI Wiki/identity/agents.md` (human-readable list)+- `<vault>/Daily/*.md` (recurring `@<name>` lines)++A repeat `o2b init --agent-name X` is safe: it appends `X` to the+registry without removing the previous agents.++## Vault path discovery++Vault locations vary per user. Discover candidates in this order:++1. Directories containing a `.obsidian/` subdirectory under `~/`,+ `~/Documents/`, `~/Sync/`, `~/Dropbox/`, or a Syncthing-shared+ `vault/` folder.+2. The user's choice when multiple candidates exist.+3. A new directory at `~/vault/` if none are found and the user+ agrees.++## Verification++After any install path completes, run:++```bash+o2b doctor --vault /path/to/vault --repo .+o2b install --check+```++`o2b install --check` is the v0.10.11 runtime-install health check+(per-target managed-block / MCP-ping verification). `o2b doctor`+covers vault invariants β they are complementary, not substitutes.++Then send one event without an explicit `agent` argument and confirm+that the new `Daily/YYYY.MM.DD.md` line begins with the chosen+`@<agent_name>` prefix, not the literal `@agent` placeholder.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex d2949dcb..09ec19f6 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.10.10",+ "version": "0.10.11","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 8e3c8b87..a955a224 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.10",+ "version": "0.10.11","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 f88e7660..79b749e1 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.10.10"+version: "0.10.11"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex c661d803..7e1f78f3 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.10",+ "version": "0.10.11","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 33fff83b..0ac03be7 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.10.10"+version: "0.10.11"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex ff43176c..d5e37ee1 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "0.10.10"+version = "0.10.11"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/install/init-interactive.ts b/src/cli/install/init-interactive.tsnew file mode 100644index 00000000..9c8c8f28--- /dev/null+++ b/src/cli/install/init-interactive.ts@@ -0,0 +1,295 @@+/**+ * `o2b init --interactive` first-time-setup wizard.+ *+ * Composes the existing `o2b init`, `o2b brain init`, and per-target+ * `o2b install --target X --apply` commands behind a linear question-+ * answer flow. Input comes from stdin (or an injected reader for+ * tests); commands are dispatched via the same `main()` entry as a+ * real CLI invocation.+ */++import { existsSync, readdirSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join } from "node:path";++import { defaultRegistry } from "../../core/install/registry.ts";+import "../../core/install/adapters/aider.ts";+import "../../core/install/adapters/copilot-cli.ts";+import "../../core/install/adapters/cursor.ts";+import "../../core/install/adapters/gemini-cli.ts";+import "../../core/install/adapters/generic.ts";+import "../../core/install/adapters/kiro.ts";+import "../../core/install/adapters/opencode.ts";+import "../../core/install/adapters/pi.ts";++export interface WizardReader {+ read(): Promise<string | null>;+}++export interface WizardRunner {+ (cmd: ReadonlyArray<string>): Promise<{ exitCode: number; stdout: string; stderr: string }>;+}++export interface WizardOpts {+ reader: WizardReader;+ stdout: NodeJS.WriteStream | NodeJS.WritableStream;+ stderr: NodeJS.WriteStream | NodeJS.WritableStream;+ runner: WizardRunner;+}++export interface WizardResult {+ readonly exitCode: number;+ readonly actions: ReadonlyArray<ReadonlyArray<string>>;+}++// ---------- Defaults ----------++function defaultVaultCandidates(): string[] {+ const home = homedir();+ const cands: string[] = [];+ const dirs = [+ home,+ join(home, "Documents"),+ join(home, "Sync"),+ join(home, "Dropbox"),+ join(home, "Library", "Mobile Documents", "iCloud~md~obsidian", "Documents"),+ "/root/vault",+ ];+ for (const d of dirs) {+ if (!existsSync(d)) continue;+ try {+ if (existsSync(join(d, ".obsidian"))) cands.push(d);+ // also probe immediate children β many users keep multiple vaults+ if (statSync(d).isDirectory()) {+ for (const child of readdirSync(d)) {+ const full = join(d, child);+ if (existsSync(join(full, ".obsidian"))) cands.push(full);+ }+ }+ } catch {+ // ignore+ }+ }+ return Array.from(new Set(cands));+}++function hostName(): string {+ try {+ return process.env["HOSTNAME"] ?? "agent";+ } catch {+ return "agent";+ }+}++function tryNormaliseTz(input: string): string | null {+ if (!input || input.trim().length === 0) return null;+ const trimmed = input.trim();+ try {+ new Intl.DateTimeFormat("en-US", { timeZone: trimmed });+ return trimmed;+ } catch {+ return null;+ }+}++// ---------- Default reader & runner ----------++export function makeStdinReader(stdin: NodeJS.ReadStream = process.stdin): WizardReader {+ // Naive line-buffered reader; sufficient for the wizard's terse Q/A.+ let buffer = "";+ let resolveNext: ((s: string | null) => void) | null = null;+ let ended = false;+ stdin.setEncoding?.("utf8");+ stdin.on?.("data", (chunk: string | Buffer) => {+ buffer += typeof chunk === "string" ? chunk : chunk.toString();+ while (resolveNext && buffer.includes("\n")) {+ const idx = buffer.indexOf("\n");+ const line = buffer.slice(0, idx).replace(/\r$/, "");+ buffer = buffer.slice(idx + 1);+ const r = resolveNext;+ resolveNext = null;+ r(line);+ }+ });+ stdin.on?.("end", () => {+ ended = true;+ if (resolveNext) {+ const r = resolveNext;+ resolveNext = null;+ r(buffer.length > 0 ? buffer : null);+ }+ });+ return {+ read(): Promise<string | null> {+ return new Promise((resolve) => {+ if (buffer.includes("\n")) {+ const idx = buffer.indexOf("\n");+ const line = buffer.slice(0, idx).replace(/\r$/, "");+ buffer = buffer.slice(idx + 1);+ resolve(line);+ return;+ }+ if (ended) {+ resolve(buffer.length > 0 ? buffer : null);+ buffer = "";+ return;+ }+ resolveNext = resolve;+ });+ },+ };+}++export function defaultRunner(): WizardRunner {+ return async (cmd) => {+ // Call back into `main()` to avoid spawning a subprocess.+ // Lazy-import to break the cycle between main.ts and this module.+ const { main } = await import("../main.ts");+ const exitCode = await main(cmd);+ return { exitCode, stdout: "", stderr: "" };+ };+}++// ---------- Wizard ----------++async function ask(opts: WizardOpts, label: string, defaultValue?: string): Promise<string> {+ const suffix = defaultValue !== undefined && defaultValue !== ""+ ? ` [${defaultValue}]: `+ : ": ";+ opts.stdout.write(`${label}${suffix}`);+ const line = await opts.reader.read();+ if (line === null || line.trim().length === 0) {+ return defaultValue ?? "";+ }+ return line.trim();+}++export async function runWizard(opts: WizardOpts): Promise<WizardResult> {+ const actions: ReadonlyArray<string>[] = [];++ opts.stdout.write("\nOpen Second Brain β interactive setup\n");+ opts.stdout.write("=".repeat(40) + "\n\n");++ // 1. Vault path+ const cands = defaultVaultCandidates();+ if (cands.length > 0) {+ opts.stdout.write("Detected vault candidates:\n");+ for (const [i, c] of cands.entries()) {+ opts.stdout.write(` ${i + 1}. ${c}\n`);+ }+ opts.stdout.write(" N. other path\n\n");+ }+ let vault = "";+ while (!vault) {+ const ans = await ask(opts, "Vault path (number or path)", cands[0]);+ if (/^\d+$/.test(ans)) {+ const idx = parseInt(ans, 10) - 1;+ if (idx >= 0 && idx < cands.length) vault = cands[idx]!;+ } else if (ans.length > 0) {+ vault = ans;+ }+ if (!vault) opts.stdout.write(" (enter a number or a path)\n");+ }++ // 2. Agent name+ const defaultAgent = `${hostName()}-agent`;+ const agentName = await ask(opts, "Agent name", defaultAgent);++ // 3. Timezone+ let tz: string | null = null;+ while (tz === null) {+ const ans = await ask(opts, "Timezone (IANA)", "UTC");+ tz = tryNormaliseTz(ans);+ if (tz === null) opts.stdout.write(" (invalid IANA name; try again, e.g. Europe/Belgrade)\n");+ }++ // 4. Language (optional)+ const lang = await ask(opts, "Language (ISO 639-1, optional)", "en");++ // 5. Runtimes+ const env = {+ vault,+ home: homedir(),+ cwd: process.cwd(),+ env: { ...process.env, VAULT_AGENT_NAME: agentName, VAULT_TIMEZONE: tz } as Record<string, string>,+ now: new Date(),+ };+ const detected = defaultRegistry.detectAll(env);+ opts.stdout.write("\nKnown runtimes:\n");+ for (const [i, d] of detected.entries()) {+ opts.stdout.write(` ${i + 1}. ${d.target.padEnd(14)} ${d.status}\n`);+ }+ opts.stdout.write("\n");+ const sel = await ask(+ opts,+ "Install for which runtimes? (comma-separated numbers, or 'none')",+ "none",+ );+ const selected: string[] = [];+ if (sel.toLowerCase() !== "none" && sel.length > 0) {+ for (const tok of sel.split(",").map((s) => s.trim()).filter((s) => s.length > 0)) {+ const idx = parseInt(tok, 10) - 1;+ if (idx >= 0 && idx < detected.length) selected.push(detected[idx]!.target);+ }+ }++ // 6. Brain init?+ const brainInit = (await ask(opts, "Scaffold Brain layer with `o2b brain init`?", "y"))+ .toLowerCase()+ .startsWith("y");+ const starter = brainInit+ ? (await ask(opts, "Include starter preferences (--starter)?", "n"))+ .toLowerCase()+ .startsWith("y")+ : false;++ // 7. Plan + confirm+ const initCmd = ["init", "--vault", vault, "--agent-name", agentName, "--timezone", tz];+ // language and name persisted via o2b init's --name? language isn't a real flag yet β record only.+ actions.push(initCmd);+ if (brainInit) {+ const cmd = ["brain", "init", "--vault", vault];+ if (starter) cmd.push("--starter");+ actions.push(cmd);+ }+ for (const t of selected) {+ actions.push(["install", "--target", t, "--apply"]);+ }+ actions.push(["install", "--check"]);++ opts.stdout.write("\nPlanned commands:\n");+ for (const c of actions) opts.stdout.write(` o2b ${c.join(" ")}\n`);+ if (lang && lang !== "en") {+ opts.stdout.write(` (language preference \`${lang}\` will be recorded after init)\n`);+ }+ opts.stdout.write("\n");+ const confirm = (await ask(opts, "Run these commands now? (yes/no)", "no")).toLowerCase();+ if (confirm !== "yes" && confirm !== "y") {+ opts.stdout.write("Aborted. No changes made.\n");+ return { exitCode: 0, actions: [] };+ }++ // 8. Execute+ for (const c of actions) {+ opts.stdout.write(`\n$ o2b ${c.join(" ")}\n`);+ const r = await opts.runner(c);+ if (r.exitCode !== 0) {+ opts.stderr.write(`error: command exited with code ${r.exitCode}\n`);+ return { exitCode: r.exitCode, actions };+ }+ }+ return { exitCode: 0, actions };+}++// ---------- CLI entry ----------++export async function cmdInitInteractive(_argv: string[]): Promise<number> {+ const opts: WizardOpts = {+ reader: makeStdinReader(process.stdin),+ stdout: process.stdout,+ stderr: process.stderr,+ runner: defaultRunner(),+ };+ const r = await runWizard(opts);+ return r.exitCode;+}diff --git a/src/cli/install/install.ts b/src/cli/install/install.tsnew file mode 100644index 00000000..6a9f5979--- /dev/null+++ b/src/cli/install/install.ts@@ -0,0 +1,282 @@+/**+ * `o2b install` CLI verb.+ *+ * o2b install # detect-only table+ * o2b install --json # detect-only as JSON+ * o2b install --target X # plan-only+ * o2b install --target X --apply # execute the plan+ * o2b install --target X --check # verify+ * o2b install --check # verify every known target+ * o2b install --target generic --out <p|-> # generic adapter only+ * o2b install --target generic --format json|yaml+ *+ * Exit codes:+ * 0 success / no drift+ * 1 I/O / runtime error+ * 2 usage error (unknown target, bad flag)+ * 3 --check found drift+ * 4 user-modified-block conflict on apply (use --force to override)+ */++import { homedir } from "node:os";++import { parseFlags } from "../argparse.ts";+import { defaultConfigPath, discoverConfig } from "../../core/config.ts";+import { defaultRegistry } from "../../core/install/registry.ts";+// Importing each adapter module triggers `defaultRegistry.register(...)`+// at module-load time. Keep the side-effect imports ordered alphabetically+// so the registry's iteration order is predictable.+import "../../core/install/adapters/aider.ts";+import "../../core/install/adapters/copilot-cli.ts";+import "../../core/install/adapters/cursor.ts";+import "../../core/install/adapters/gemini-cli.ts";+import "../../core/install/adapters/generic.ts";+import "../../core/install/adapters/kiro.ts";+import "../../core/install/adapters/opencode.ts";+import "../../core/install/adapters/pi.ts";++import { buildPayload, PayloadError } from "../../core/install/payload.ts";+import { InstallError } from "../../core/install/types.ts";+import type {+ ApplyOpts,+ InstallEnv,+ VerifyResult,+} from "../../core/install/types.ts";+import {+ renderApplyJson,+ renderApplyResult,+ renderDetectJson,+ renderDetectTable,+ renderPlan,+ renderVerifyJson,+ renderVerifyTable,+} from "./render.ts";++interface ParsedInstallArgs {+ readonly target: string | null;+ readonly apply: boolean;+ readonly check: boolean;+ readonly dryRun: boolean;+ readonly force: boolean;+ readonly json: boolean;+ readonly out: string | null;+ readonly format: "json" | "yaml" | null;+ readonly vault: string | null;+ readonly config: string;+}++function parseInstallArgs(argv: string[]): ParsedInstallArgs {+ const { flags } = parseFlags(argv, {+ target: { type: "string" },+ apply: { type: "boolean" },+ check: { type: "boolean" },+ "dry-run": { type: "boolean" },+ force: { type: "boolean" },+ json: { type: "boolean" },+ out: { type: "string" },+ format: { type: "string" },+ vault: { type: "string" },+ config: { type: "string" },+ });+ const fmtRaw = flags["format"] as string | undefined;+ let format: "json" | "yaml" | null = null;+ if (fmtRaw) {+ if (fmtRaw !== "json" && fmtRaw !== "yaml") {+ throw new UsageError(`--format must be json or yaml, got: ${fmtRaw}`);+ }+ format = fmtRaw;+ }+ return {+ target: (flags["target"] as string | undefined) ?? null,+ apply: Boolean(flags["apply"]),+ check: Boolean(flags["check"]),+ dryRun: Boolean(flags["dry-run"]),+ force: Boolean(flags["force"]),+ json: Boolean(flags["json"]),+ out: (flags["out"] as string | undefined) ?? null,+ format,+ vault: (flags["vault"] as string | undefined) ?? null,+ config: (flags["config"] as string | undefined) ?? defaultConfigPath(),+ };+}++class UsageError extends Error {}++function buildInstallEnv(args: ParsedInstallArgs): InstallEnv {+ const cfg = discoverConfig(args.config).data;+ const vault = args.vault ?? cfg["vault"] ?? process.env["VAULT_DIR"] ?? "";+ const env = { ...process.env } as Record<string, string>;+ if (cfg["agent_name"]) env["VAULT_AGENT_NAME"] = cfg["agent_name"];+ if (cfg["timezone"]) env["VAULT_TIMEZONE"] = cfg["timezone"];+ return {+ vault,+ home: homedir(),+ cwd: process.cwd(),+ env,+ now: new Date(),+ };+}++function buildApplyOpts(+ args: ParsedInstallArgs,+ stdout: NodeJS.WriteStream,+ stderr: NodeJS.WriteStream,+): ApplyOpts {+ return {+ dryRun: args.dryRun,+ force: args.force,+ stdout,+ stderr,+ ...(args.out !== null ? { outPath: args.out } : {}),+ ...(args.format !== null ? { format: args.format } : {}),+ };+}++function loadPayload(args: ParsedInstallArgs, env: InstallEnv) {+ const cfg = discoverConfig(args.config).data;+ const vault = env.vault || cfg["vault"];+ if (!vault) {+ throw new UsageError(+ "o2b install: vault not configured. Pass --vault <path>, set VAULT_DIR, or run `o2b init`.",+ );+ }+ return buildPayload({+ vault,+ agent_name: cfg["agent_name"] ?? process.env["VAULT_AGENT_NAME"] ?? null,+ timezone: cfg["timezone"] ?? process.env["VAULT_TIMEZONE"] ?? null,+ });+}++export async function cmdInstall(argv: string[]): Promise<number> {+ let args: ParsedInstallArgs;+ try {+ args = parseInstallArgs(argv);+ } catch (e) {+ if (e instanceof UsageError) {+ process.stderr.write(`error: ${e.message}\n`);+ return 2;+ }+ throw e;+ }++ // `--check` is its own mode β runs verify per target.+ if (args.check) return runCheck(args);++ // No --target β detect-only mode.+ if (!args.target) return runDetect(args);++ // --target X with or without --apply.+ return runTarget(args);+}++function runDetect(args: ParsedInstallArgs): number {+ const env = buildInstallEnv(args);+ const results = defaultRegistry.detectAll(env);+ if (args.json) {+ process.stdout.write(renderDetectJson(results));+ } else {+ process.stdout.write(renderDetectTable(results));+ }+ return 0;+}++function runTarget(args: ParsedInstallArgs): number {+ const adapter = defaultRegistry.get(args.target!);+ if (!adapter) {+ process.stderr.write(+ `error: unknown --target: ${args.target}. ` ++ `Available: ${defaultRegistry.targets().join(", ")}\n`,+ );+ return 2;+ }+ const env = buildInstallEnv(args);+ let payload;+ try {+ payload = loadPayload(args, env);+ } catch (e) {+ if (e instanceof UsageError) {+ process.stderr.write(`error: ${e.message}\n`);+ return 2;+ }+ if (e instanceof PayloadError) {+ process.stderr.write(`error: ${e.message}\n`);+ return 2;+ }+ throw e;+ }++ const opts = buildApplyOpts(+ args,+ process.stdout as NodeJS.WriteStream,+ process.stderr as NodeJS.WriteStream,+ );++ const plan = adapter.plan(payload, env);++ // Plan-only (no --apply, no --check) β print and return.+ if (!args.apply) {+ if (args.json) {+ process.stdout.write(JSON.stringify({ schema_version: 1, plan }, null, 2) + "\n");+ } else {+ process.stdout.write(renderPlan(plan));+ }+ return 0;+ }++ try {+ const result = adapter.apply(plan, payload, env, opts);+ if (args.json) {+ process.stdout.write(renderApplyJson(result));+ } else {+ process.stdout.write(renderApplyResult(result));+ }+ return 0;+ } catch (e) {+ if (e instanceof InstallError && e.kind === "user-modified-block") {+ process.stderr.write(`error: ${e.message}\n`);+ if (e.hint) process.stderr.write(`hint: ${e.hint}\n`);+ return 4;+ }+ if (e instanceof InstallError) {+ process.stderr.write(`error: ${e.message}\n`);+ if (e.hint) process.stderr.write(`hint: ${e.hint}\n`);+ return 1;+ }+ process.stderr.write(`error: ${(e as Error).message}\n`);+ return 1;+ }+}++function runCheck(args: ParsedInstallArgs): number {+ const env = buildInstallEnv(args);+ // `verify()` reads the per-vault sidecar manifest. With an unset vault,+ // every adapter would silently report "not-installed" off a bogus path+ // and the operator gets no signal that the vault is unconfigured.+ if (!env.vault) {+ process.stderr.write(+ "error: vault not configured. Pass --vault <path>, set VAULT_DIR, or run `o2b init`.\n",+ );+ return 2;+ }+ const targets = args.target+ ? defaultRegistry.get(args.target)+ ? [defaultRegistry.get(args.target)!]+ : []+ : defaultRegistry.list();+ if (args.target && targets.length === 0) {+ process.stderr.write(+ `error: unknown --target: ${args.target}. ` ++ `Available: ${defaultRegistry.targets().join(", ")}\n`,+ );+ return 2;+ }+ const results: VerifyResult[] = [];+ for (const a of targets) results.push(a.verify(env));+ if (args.json) {+ process.stdout.write(renderVerifyJson(results));+ } else {+ process.stdout.write(renderVerifyTable(results));+ }+ const drift = results.some((r) => r.status === "drift");+ return drift ? 3 : 0;+}diff --git a/src/cli/install/render.ts b/src/cli/install/render.tsnew file mode 100644index 00000000..d8caa08a--- /dev/null+++ b/src/cli/install/render.ts@@ -0,0 +1,134 @@+/**+ * Output renderers for `o2b install` / `o2b install --check`.+ *+ * Two surfaces: human-readable text (default) and JSON (`--json`).+ * Both forms describe the same data so the agent can switch on+ * `--json` without losing detail.+ */++import type {+ ApplyResult,+ DetectResult,+ InstallPlan,+ VerifyResult,+} from "../../core/install/types.ts";++export interface DetectTableRow {+ readonly target: string;+ readonly status: string;+ readonly configPath: string | null;+ readonly notes: ReadonlyArray<string>;+}++export function renderDetectTable(rows: ReadonlyArray<DetectResult>): string {+ if (rows.length === 0) return "o2b install β no adapters registered\n";+ const lines: string[] = [+ "o2b install β detected runtimes",+ "-".repeat(35),+ ];+ let installed = 0;+ let drift = 0;+ let notInstalled = 0;+ for (const r of rows) {+ const status = r.status.padEnd(14);+ const target = r.target.padEnd(14);+ const where = r.configPath ?? "";+ lines.push(` ${target}${status}${where}`);+ if (r.notes.length > 0) {+ for (const n of r.notes) lines.push(` ${n}`);+ }+ if (r.status === "installed") installed += 1;+ else if (r.status === "drift") drift += 1;+ else if (r.status === "not-installed") notInstalled += 1;+ }+ lines.push("");+ const summary =+ `${rows.length} runtime(s) in registry; ${installed} installed, ${drift} drift, ${notInstalled} not-installed.`;+ lines.push(summary);+ if (drift > 0 || notInstalled > 0) {+ lines.push("");+ lines.push("To install or repair, run:");+ for (const r of rows) {+ if (r.status === "drift" || r.status === "not-installed") {+ lines.push(` o2b install --target ${r.target} --apply`);+ }+ }+ }+ lines.push("");+ return lines.join("\n");+}++export function renderDetectJson(rows: ReadonlyArray<DetectResult>): string {+ const payload = {+ schema_version: 1,+ targets: rows.map((r) => ({+ target: r.target,+ status: r.status,+ config_path: r.configPath,+ notes: r.notes,+ })),+ };+ return JSON.stringify(payload, null, 2) + "\n";+}++export function renderPlan(plan: InstallPlan): string {+ const lines: string[] = [];+ lines.push(`o2b install --target ${plan.target} β plan (dry-run; pass --apply to execute)`);+ lines.push("-".repeat(60));+ for (const [i, step] of plan.steps.entries()) {+ lines.push(` step ${i + 1}: [${step.kind}] ${step.preview}`);+ if (step.path) lines.push(` path: ${step.path}`);+ }+ if (plan.postNotes.length > 0) {+ lines.push("");+ lines.push("Post-install notes:");+ for (const n of plan.postNotes) lines.push(` - ${n}`);+ }+ lines.push("");+ return lines.join("\n");+}++export function renderApplyResult(result: ApplyResult): string {+ const m = result.manifest;+ const lines: string[] = [];+ lines.push(`o2b install --target ${result.target} --apply β done`);+ lines.push(` operation: ${m.operation}`);+ lines.push(` config path: ${m.config_path ?? "(none)"}`);+ if (m.owned_keys?.length) {+ lines.push(` owned keys:`);+ for (const k of m.owned_keys) lines.push(` - ${k}`);+ }+ if (m.owned_paths?.length) {+ lines.push(` owned paths:`);+ for (const p of m.owned_paths) lines.push(` - ${p}`);+ }+ lines.push(` applied at: ${m.applied_at}`);+ lines.push(` steps: ${result.steps_executed}`);+ lines.push("");+ return lines.join("\n");+}++export function renderApplyJson(result: ApplyResult): string {+ return JSON.stringify(result, null, 2) + "\n";+}++export function renderVerifyTable(rows: ReadonlyArray<VerifyResult>): string {+ if (rows.length === 0) return "o2b install --check β no targets verified\n";+ const lines: string[] = [+ "o2b install --check",+ "-".repeat(20),+ ];+ for (const v of rows) {+ const status = v.status.padEnd(18);+ lines.push(` ${v.target.padEnd(14)}${status}${v.details.join("; ")}`);+ if (v.fix_hint) {+ lines.push(` fix: ${v.fix_hint}`);+ }+ }+ lines.push("");+ return lines.join("\n");+}++export function renderVerifyJson(rows: ReadonlyArray<VerifyResult>): string {+ return JSON.stringify({ schema_version: 1, targets: rows }, null, 2) + "\n";+}diff --git a/src/cli/install/uninstall-target.ts b/src/cli/install/uninstall-target.tsnew file mode 100644index 00000000..9e22b3fa--- /dev/null+++ b/src/cli/install/uninstall-target.ts@@ -0,0 +1,114 @@+/**+ * `o2b uninstall --target X` β remove what `o2b install --target X` wrote.+ *+ * o2b uninstall --target X # dry-run+ * o2b uninstall --target X --apply # remove per manifest+ * o2b uninstall --target X --apply --force-from-snippet+ * # remove without manifest+ * # (exact-payload match)+ */++import { homedir } from "node:os";++import { parseFlags } from "../argparse.ts";+import { defaultConfigPath, discoverConfig } from "../../core/config.ts";+import { defaultRegistry } from "../../core/install/registry.ts";+import "../../core/install/adapters/aider.ts";+import "../../core/install/adapters/copilot-cli.ts";+import "../../core/install/adapters/cursor.ts";+import "../../core/install/adapters/gemini-cli.ts";+import "../../core/install/adapters/generic.ts";+import "../../core/install/adapters/kiro.ts";+import "../../core/install/adapters/opencode.ts";+import "../../core/install/adapters/pi.ts";+import { InstallError, type InstallEnv } from "../../core/install/types.ts";++export async function cmdUninstallTarget(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ target: { type: "string", required: true },+ apply: { type: "boolean" },+ "force-from-snippet": { type: "boolean" },+ config: { type: "string" },+ vault: { type: "string" },+ json: { type: "boolean" },+ });++ const target = flags["target"] as string;+ const adapter = defaultRegistry.get(target);+ if (!adapter) {+ process.stderr.write(+ `error: unknown --target: ${target}. ` ++ `Available: ${defaultRegistry.targets().join(", ")}\n`,+ );+ return 2;+ }++ const dryRun = !flags["apply"];+ const cfgPath = (flags["config"] as string | undefined) ?? defaultConfigPath();+ const cfg = discoverConfig(cfgPath).data;+ const vault =+ (flags["vault"] as string | undefined) ?? cfg["vault"] ?? process.env["VAULT_DIR"] ?? "";+ if (!vault) {+ process.stderr.write(+ "error: vault not configured. Pass --vault <path>, set VAULT_DIR, or run `o2b init`.\n",+ );+ return 2;+ }++ const env: InstallEnv = {+ vault,+ home: homedir(),+ cwd: process.cwd(),+ env: { ...process.env } as Record<string, string>,+ now: new Date(),+ };+ const opts = {+ dryRun,+ force: false,+ stdout: process.stdout as NodeJS.WriteStream,+ stderr: process.stderr as NodeJS.WriteStream,+ fromSnippet: Boolean(flags["force-from-snippet"]),+ };++ try {+ const result = adapter.uninstall(env, opts);+ if (flags["json"]) {+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");+ return 0;+ }+ const lines: string[] = [];+ lines.push(+ `o2b uninstall --target ${target}` + (dryRun ? " (dry-run)" : " --apply"),+ );+ if (result.removed_keys.length > 0) {+ lines.push(" removed keys:");+ for (const k of result.removed_keys) lines.push(` - ${k}`);+ }+ if (result.removed_paths.length > 0) {+ lines.push(" removed paths:");+ for (const p of result.removed_paths) lines.push(` - ${p}`);+ }+ if (result.skipped.length > 0) {+ lines.push(" skipped:");+ for (const [what, why] of result.skipped) lines.push(` - ${what} (${why})`);+ }+ if (+ result.removed_keys.length === 0 &&+ result.removed_paths.length === 0 &&+ result.skipped.length === 0+ ) {+ lines.push(" (nothing to do)");+ }+ lines.push("");+ process.stdout.write(lines.join("\n"));+ return 0;+ } catch (e) {+ if (e instanceof InstallError) {+ process.stderr.write(`error: ${e.message}\n`);+ if (e.hint) process.stderr.write(`hint: ${e.hint}\n`);+ return e.kind === "manifest-missing" ? 2 : 1;+ }+ process.stderr.write(`error: ${(e as Error).message}\n`);+ return 1;+ }+}diff --git a/src/cli/main.ts b/src/cli/main.tsindex 767eb79d..f13ee919 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -55,9 +55,13 @@ import {uninstallCli,} from "./install-cli.ts";import { planUninstall, renderPlan } from "./uninstall.ts";+import { cmdInstall } from "./install/install.ts";+import { cmdUninstallTarget } from "./install/uninstall-target.ts";+import { cmdInitInteractive } from "./install/init-interactive.ts";import { MCPServer } from "../mcp/server.ts";import { serveStdio } from "../mcp/stdio.ts";import { SERVER_VERSION } from "../mcp/protocol.ts";+import { buildToolTable } from "../mcp/tools.ts";// ββ Subcommands βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -102,6 +106,11 @@ async function cmdStatus(argv: string[]): Promise<number> {}async function cmdInit(argv: string[]): Promise<number> {+ // `--interactive` is its own mode β composed of `init` + `brain init` ++ // per-target `install`. The non-interactive path below requires --vault.+ if (argv.includes("--interactive")) {+ return await cmdInitInteractive(argv.filter((a) => a !== "--interactive"));+ }const { flags } = parseFlags(argv, {vault: { type: "string", required: true },name: { type: "string", default: "Second Brain" },@@ -360,21 +369,44 @@ async function cmdMcp(argv: string[]): Promise<number> {config: { type: "string" },repo: { type: "string" },scope: { type: "string" },+ "writer-only": { type: "boolean" },+ probe: { type: "boolean" },});- // Validate --scope before doing anything that could fail for other reasons.- const rawScope = (flags["scope"] as string | undefined) ?? "full";+ // `--writer-only` is an alias for `--scope writer`. The two flags+ // are mutually consistent; if the user passes both, `--writer-only`+ // wins only when `--scope` is absent or already "writer". A+ // contradictory pair (e.g. `--scope full --writer-only`) is+ // rejected to avoid silent surprises.+ const writerOnly = Boolean(flags["writer-only"]);+ const rawScope = (flags["scope"] as string | undefined) ?? (writerOnly ? "writer" : "full");if (rawScope !== "full" && rawScope !== "writer") {process.stderr.write(`o2b mcp: invalid --scope value: ${rawScope}; expected one of: full, writer\n`,);return 2;}+ if (writerOnly && rawScope !== "writer") {+ process.stderr.write(+ `o2b mcp: --writer-only conflicts with --scope ${rawScope}\n`,+ );+ return 2;+ }const scope = rawScope;const serverName =scope === "writer" ? "open-second-brain-writer" : "open-second-brain";const config = (flags["config"] as string | undefined) ?? defaultConfigPath();++ if (flags["probe"]) {+ return await runMcpProbe({+ vault: flags["vault"] as string | undefined,+ config,+ scope,+ serverName,+ });+ }+const vault = requireVault(flags["vault"] as string | undefined, config);const repoRoot = (flags["repo"] as string | undefined) ?? null;@@ -384,6 +416,36 @@ async function cmdMcp(argv: string[]): Promise<number> {return await serveStdio({ vault, configPath: config, repoRoot }, {}, { scope, serverName });}+async function runMcpProbe(args: {+ vault: string | undefined;+ config: string;+ scope: "full" | "writer";+ serverName: string;+}): Promise<number> {+ // The probe is an in-process MCP handshake: it counts the tools the+ // server would advertise and exits. Used by `o2b install --check`+ // to verify the server starts cleanly.+ let vault: string;+ try {+ vault = requireVault(args.vault, args.config);+ } catch (e) {+ process.stdout.write(+ `mcp probe FAIL: vault not configured (${(e as Error).message})\n`,+ );+ return 1;+ }+ try {+ const tools = buildToolTable(args.scope);+ process.stdout.write(+ `mcp probe ok: ${args.serverName} (${tools.length} tools, vault=${vault})\n`,+ );+ return 0;+ } catch (e) {+ process.stdout.write(`mcp probe FAIL: ${(e as Error).message}\n`);+ return 1;+ }+}+async function cmdInstallCli(argv: string[]): Promise<number> {const { flags } = parseFlags(argv, { bindir: { type: "string" } });const result = installCli(flags["bindir"] as string | undefined);@@ -392,6 +454,11 @@ async function cmdInstallCli(argv: string[]): Promise<number> {}async function cmdUninstall(argv: string[]): Promise<number> {+ // `--target X` is its own mode β per-runtime uninstall, distinct from the+ // legacy `--apply-local` config-removal path.+ if (argv.includes("--target")) {+ return await cmdUninstallTarget(argv);+ }const { flags } = parseFlags(argv, {config: { type: "string" },"apply-local": { type: "boolean" },@@ -556,6 +623,8 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {return await cmdMcp(rest);case "install-cli":return await cmdInstallCli(rest);+ case "install":+ return await cmdInstall(rest);case "uninstall":return await cmdUninstall(rest);case "tool-call":diff --git a/src/core/brain/active.ts b/src/core/brain/active.tsindex 2ea94fa2..55b165ac 100644--- a/src/core/brain/active.ts+++ b/src/core/brain/active.ts@@ -37,6 +37,11 @@ import { join } from "node:path";import { atomicWriteFileSync } from "../fs-atomic.ts";import { parseFrontmatter } from "../vault.ts";import { computeMostApplied, type MostAppliedEntry } from "./most-applied.ts";+import {+ MOST_APPLIED_LIMIT_DEFAULT,+ MOST_APPLIED_WINDOW_DAYS_DEFAULT,+ loadBrainConfig,+} from "./policy.ts";import { parsePreference, parseRetired } from "./preference.ts";import { brainActivePath, brainDirs } from "./paths.ts";import { isoSecond } from "./time.ts";@@ -105,16 +110,36 @@ export function regenerateActive(.filter((p) => p.status === BRAIN_PREFERENCE_STATUS.quarantine).sort(sortByIdAscending);+ // Read window/limit from `_brain.yaml:active.most_applied_*`. The+ // loader throws on a malformed `_brain.yaml`; we fall back to+ // defaults so a corrupted config never blocks the active digest.+ let windowDays = MOST_APPLIED_WINDOW_DAYS_DEFAULT;+ let limit = MOST_APPLIED_LIMIT_DEFAULT;+ try {+ const cfg = loadBrainConfig(vault);+ if (cfg.active?.most_applied) {+ windowDays = cfg.active.most_applied.window_days;+ limit = cfg.active.most_applied.limit;+ }+ } catch {+ // intentional fallback β config error is doctor's job to surface+ }+// Most-applied draws from the active candidates (confirmed +// quarantine) only β retired preferences are reported in their own// section below and never resurrected through the hot list.- const mostApplied = computeMostApplied(vault, [...confirmed, ...quarantine], { now });+ const mostApplied = computeMostApplied(vault, [...confirmed, ...quarantine], {+ now,+ windowDays,+ limit,+ });const body = renderBody({confirmed,quarantine,retiredRecent,mostApplied,+ windowDays,});// `readExistingBody` returns the trimmed body (parseFrontmatter@@ -212,6 +237,7 @@ interface RenderInput {readonly quarantine: ReadonlyArray<BrainPreference>;readonly retiredRecent: ReadonlyArray<BrainRetired>;readonly mostApplied: ReadonlyArray<MostAppliedEntry>;+ readonly windowDays: number;}function renderBody(input: RenderInput): string {@@ -231,7 +257,7 @@ function renderBody(input: RenderInput): string {out.push("");if (input.mostApplied.length > 0) {- out.push(`## Most-applied (30d) (${input.mostApplied.length})`);+ out.push(`## Most-applied (${input.windowDays}d) (${input.mostApplied.length})`);out.push("");for (const m of input.mostApplied) out.push(renderMostAppliedLine(m));out.push("");diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.tsindex ab9bcb0d..87850875 100644--- a/src/core/brain/digest.ts+++ b/src/core/brain/digest.ts@@ -40,7 +40,13 @@ import { join } from "node:path";import { backlinkCount, buildBacklinkIndex } from "./backlinks.ts";import { findMergeCandidates } from "./merge-candidates.ts";+import { computeMostApplied } from "./most-applied.ts";import { brainDirs, vaultRelative } from "./paths.ts";+import {+ MOST_APPLIED_LIMIT_DEFAULT,+ MOST_APPLIED_WINDOW_DAYS_DEFAULT,+ loadBrainConfig,+} from "./policy.ts";import { normaliseWikilinkTarget, renderPrefLink } from "./wikilink.ts";import { parsePreference, parseRetired } from "./preference.ts";import { parseLogDay, type BrainLogEntry } from "./log.ts";@@ -165,6 +171,25 @@ export interface DigestJsonTopReferenced {readonly backlink_count: number;}+/**+ * Most-applied entry: one preference + its applied-in-window count.+ * Drives the `Most-applied (Nd)` section in `brain_digest` Markdown+ * and the mirrored block in the JSON output. The window length and+ * limit come from `_brain.yaml:active.most_applied_*`.+ */+export interface DigestJsonMostAppliedEntry {+ readonly id: string;+ readonly principle: string;+ readonly scope: string | null;+ readonly applied_in_window: number;+}++export interface DigestJsonMostApplied {+ readonly window_days: number;+ readonly limit: number;+ readonly entries: ReadonlyArray<DigestJsonMostAppliedEntry>;+}+/*** Near-duplicate pair surfaced for operator review. Detected by* `findMergeCandidates`. Reflects current vault state, not windowed@@ -200,6 +225,12 @@ export interface DigestJson {readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;+ /**+ * Window-scoped most-applied list (v0.10.11). Mirrors the+ * `Most-applied (Nd)` section of `Brain/active.md` and uses the+ * same `_brain.yaml:active.most_applied_*` settings.+ */+ readonly most_applied: DigestJsonMostApplied;}/**@@ -253,6 +284,7 @@ export function renderDigest(top_applied: data.top_applied,top_referenced: data.top_referenced,merge_suggestions: data.merge_suggestions,+ most_applied: data.most_applied,};return Object.freeze({content: JSON.stringify(payload, null, 2) + "\n",@@ -278,6 +310,7 @@ interface DigestData {readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;+ readonly most_applied: DigestJsonMostApplied;}function collectDigestData(@@ -383,6 +416,44 @@ function collectDigestData(jaccard: c.jaccard,}));+ // Most-applied (Nd) β mirrors the section in `Brain/active.md`.+ // The window length / limit come from `_brain.yaml`; a corrupted+ // config falls back to defaults so the digest never breaks on+ // operator-side schema drift.+ let mostAppliedWindowDays = MOST_APPLIED_WINDOW_DAYS_DEFAULT;+ let mostAppliedLimit = MOST_APPLIED_LIMIT_DEFAULT;+ try {+ const cfg = loadBrainConfig(vault);+ if (cfg.active?.most_applied) {+ mostAppliedWindowDays = cfg.active.most_applied.window_days;+ mostAppliedLimit = cfg.active.most_applied.limit;+ }+ } catch {+ // fall through to defaults+ }+ const activePrefs = preferences+ .filter(+ ({ pref }) =>+ pref.status === BRAIN_PREFERENCE_STATUS.confirmed ||+ pref.status === BRAIN_PREFERENCE_STATUS.quarantine,+ )+ .map(({ pref }) => pref);+ const mostAppliedEntries = computeMostApplied(vault, activePrefs, {+ now: until,+ windowDays: mostAppliedWindowDays,+ limit: mostAppliedLimit,+ }).map((e) => ({+ id: e.preference.id,+ principle: e.preference.principle,+ scope: e.preference.scope ?? null,+ applied_in_window: e.applied_30d,+ }));+ const most_applied: DigestJsonMostApplied = {+ window_days: mostAppliedWindowDays,+ limit: mostAppliedLimit,+ entries: mostAppliedEntries,+ };+return {new_unconfirmed,confirmed,@@ -392,6 +463,7 @@ function collectDigestData(top_applied,top_referenced,merge_suggestions,+ most_applied,};}@@ -454,7 +526,11 @@ function isEmpty(data: DigestData): boolean {data.confirmed.length === 0 &&data.retired.length === 0 &&data.confidence_shifts.length === 0 &&- data.contradictions.length === 0+ data.contradictions.length === 0 &&+ // most_applied is windowed β entries imply real activity that the+ // operator wants to see in the daily digest even when nothing else+ // changed (v0.10.11).+ data.most_applied.entries.length === 0);}@@ -763,6 +839,19 @@ function renderMarkdown(}lines.push("");}+ if (data.most_applied.entries.length > 0) {+ lines.push(+ `## Most-applied (${data.most_applied.window_days}d) (${data.most_applied.entries.length})`,+ "",+ );+ for (const item of data.most_applied.entries) {+ const scope = item.scope ?? "β";+ lines.push(+ `- ${renderPrefLink({ id: item.id, principle: item.principle })} β ${scope}, ${item.applied_in_window} applied`,+ );+ }+ lines.push("");+ }if (data.top_applied.length > 0) {lines.push(`## Top applied (${data.top_applied.length})`, "");for (const item of data.top_applied) {diff --git a/src/core/brain/most-applied.ts b/src/core/brain/most-applied.tsindex ffbe8916..4780baec 100644--- a/src/core/brain/most-applied.ts+++ b/src/core/brain/most-applied.ts@@ -11,6 +11,10 @@ import { existsSync, readdirSync } from "node:fs";import { brainDirs } from "./paths.ts";import { readLogDay } from "./log-jsonl.ts";+import {+ MOST_APPLIED_LIMIT_DEFAULT,+ MOST_APPLIED_WINDOW_DAYS_DEFAULT,+} from "./policy.ts";import { isoDate } from "./time.ts";import { normaliseWikilinkTarget } from "./wikilink.ts";import {@@ -20,9 +24,7 @@ import {type BrainPreference,} from "./types.ts";-const WINDOW_MS = 30 * 24 * 3600 * 1000;const DAY_MS = 24 * 3600 * 1000;-const DEFAULT_LIMIT = 10;const LOG_FILENAME_RE = /^(\d{4}-\d{2}-\d{2})\.md$/;export interface MostAppliedEntry {@@ -33,6 +35,8 @@ export interface MostAppliedEntry {export interface ComputeMostAppliedOptions {/** Window anchor. Defaults to `new Date()`. */readonly now?: Date;+ /** Window length in days. Defaults to 30. */+ readonly windowDays?: number;/** Max entries returned. Defaults to 10. */readonly limit?: number;}@@ -52,7 +56,8 @@ export function computeMostApplied(opts: ComputeMostAppliedOptions = {},): ReadonlyArray<MostAppliedEntry> {const now = opts.now ?? new Date();- const limit = opts.limit ?? DEFAULT_LIMIT;+ const windowDays = opts.windowDays ?? MOST_APPLIED_WINDOW_DAYS_DEFAULT;+ const limit = opts.limit ?? MOST_APPLIED_LIMIT_DEFAULT;const dirs = brainDirs(vault);if (!existsSync(dirs.log)) return [];@@ -73,7 +78,7 @@ export function computeMostApplied(if (prefByKey.size === 0) return [];const windowEndMs = now.getTime();- const windowStartMs = windowEndMs - WINDOW_MS;+ const windowStartMs = windowEndMs - windowDays * DAY_MS;// Day-level fence: include the day before window start to absorb// UTC drift between the event timestamp and the file's date prefix.const earliestDayPrefix = isoDate(new Date(windowStartMs - DAY_MS));diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex 0e87b5af..1aa412d3 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -21,7 +21,13 @@import { existsSync, readFileSync } from "node:fs";-import type { BrainConfig, BrainVaultConfig, DisciplineReportConfig } from "./types.ts";+import type {+ BrainActiveConfig,+ BrainConfig,+ BrainMostAppliedConfig,+ BrainVaultConfig,+ DisciplineReportConfig,+} from "./types.ts";// Imported from `defaults.ts` (not from `vault-scope/index.ts`) to// break the module-init cycle: the resolver lives in `index.ts` and// itself imports `loadBrainConfig` from this file. See the@@ -35,6 +41,20 @@ import { brainConfigPath } from "./paths.ts";/** Schema versions this build understands. Bump on incompatible changes. */export const BRAIN_CONFIG_SUPPORTED_VERSIONS: ReadonlyArray<number> = [1];+/**+ * Bounds applied to `active.most_applied.{window_days, limit}` at load+ * time. Values outside these ranges are hard errors β clamping silently+ * would mask the operator's intent.+ */+export const MOST_APPLIED_WINDOW_DAYS_MIN = 1;+export const MOST_APPLIED_WINDOW_DAYS_MAX = 365;+export const MOST_APPLIED_LIMIT_MIN = 1;+export const MOST_APPLIED_LIMIT_MAX = 50;+/** Default window when `_brain.yaml` lacks `active.most_applied.window_days`. */+export const MOST_APPLIED_WINDOW_DAYS_DEFAULT = 30;+/** Default top-N limit when `_brain.yaml` lacks `active.most_applied.limit`. */+export const MOST_APPLIED_LIMIT_DEFAULT = 10;+/*** Default `_brain.yaml` content. Mirrors Β§10 of the design doc. Used by* `brain init` and as the fallback inside `loadBrainConfig` when callers@@ -508,6 +528,73 @@ export function validateBrainConfigDetailed(}}+ // Optional `active.{most_applied_window_days, most_applied_limit}`+ // block (v0.10.11). Hard-error on shape problems β operator-tunable+ // knobs should never silently fall back to defaults.+ //+ // The YAML keys are flat at level 2 to fit the existing two-level+ // parser; the in-memory shape `BrainActiveConfig.most_applied` still+ // groups them so downstream consumers (`active.md`, `brain_digest`)+ // can pass one struct around.+ let active: BrainActiveConfig | undefined;+ if ("active" in obj) {+ const rawActive = obj["active"];+ if (typeof rawActive !== "object" || rawActive === null || Array.isArray(rawActive)) {+ throw new BrainConfigError(+ `block must be a map of keys; got ${describe(rawActive)}`,+ "active",+ source,+ );+ }+ const activeMap = rawActive as Record<string, unknown>;+ const hasWindow = "most_applied_window_days" in activeMap;+ const hasLimit = "most_applied_limit" in activeMap;+ let mostApplied: BrainMostAppliedConfig | undefined;+ if (hasWindow || hasLimit) {+ const windowDays = hasWindow+ ? activeMap["most_applied_window_days"]+ : MOST_APPLIED_WINDOW_DAYS_DEFAULT;+ const limit = hasLimit ? activeMap["most_applied_limit"] : MOST_APPLIED_LIMIT_DEFAULT;+ if (+ typeof windowDays !== "number" ||+ !Number.isInteger(windowDays) ||+ windowDays < MOST_APPLIED_WINDOW_DAYS_MIN ||+ windowDays > MOST_APPLIED_WINDOW_DAYS_MAX+ ) {+ throw new BrainConfigError(+ `must be an integer between ${MOST_APPLIED_WINDOW_DAYS_MIN} and ` ++ `${MOST_APPLIED_WINDOW_DAYS_MAX}; got ${describe(windowDays)}`,+ "active.most_applied_window_days",+ source,+ );+ }+ if (+ typeof limit !== "number" ||+ !Number.isInteger(limit) ||+ limit < MOST_APPLIED_LIMIT_MIN ||+ limit > MOST_APPLIED_LIMIT_MAX+ ) {+ throw new BrainConfigError(+ `must be an integer between ${MOST_APPLIED_LIMIT_MIN} and ` ++ `${MOST_APPLIED_LIMIT_MAX}; got ${describe(limit)}`,+ "active.most_applied_limit",+ source,+ );+ }+ mostApplied = { window_days: windowDays, limit };+ }+ // Forward-compat: unknown sub-keys under `active:` β warning.+ for (const k of Object.keys(activeMap)) {+ if (k !== "most_applied_window_days" && k !== "most_applied_limit") {+ warnings.push({+ path: source ?? "<config>",+ message: `active.${k}: unknown field ignored (forward-compat)`,+ });+ }+ }+ active = mostApplied !== undefined ? { most_applied: mostApplied } : {};+ }+// Optional `discipline_report` section. On any type mismatch, emit a// warning and drop the section (return undefined) rather than throwing β// the rest of the CLI surface must keep working.@@ -601,6 +688,7 @@ export function validateBrainConfigDetailed("confidence","snapshots","vault",+ "active","discipline_report",]);for (const key of Object.keys(obj)) {@@ -634,6 +722,7 @@ export function validateBrainConfigDetailed(retention_count: snapshots.retention_count as number,},...(vault !== undefined ? { vault } : {}),+ ...(active !== undefined ? { active } : {}),...(disciplineReport !== undefined ? { discipline_report: disciplineReport } : {}),};diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 9a99aeb8..4bfa3105 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -660,6 +660,24 @@ export interface BrainVaultConfig {readonly ignore_paths: ReadonlyArray<string>;}+/**+ * Configuration for the `Most-applied (Nd)` block surfaced both in+ * `Brain/active.md` and the `brain_digest` output (v0.10.11).+ *+ * Both fields are optional in `_brain.yaml`; absence means consumers+ * fall back to `MOST_APPLIED_WINDOW_DAYS_DEFAULT` (30) and+ * `MOST_APPLIED_LIMIT_DEFAULT` (10).+ */+export interface BrainMostAppliedConfig {+ readonly window_days: number;+ readonly limit: number;+}++/** Container for the `active:` block of `_brain.yaml`. */+export interface BrainActiveConfig {+ readonly most_applied?: BrainMostAppliedConfig;+}+/*** Optional configuration for the daily discipline report (Β§D of the* agent-discipline-tail design). Absent on vaults that have not opted@@ -701,6 +719,12 @@ export interface BrainConfig {* user explicitly wants no exclusions".*/readonly vault?: BrainVaultConfig;+ /**+ * Optional `active.most_applied` block (v0.10.11). Drives both the+ * `Most-applied (Nd)` section in `Brain/active.md` and the+ * mirrored `most_applied` block in `brain_digest`.+ */+ readonly active?: BrainActiveConfig;/** Optional daily discipline-report configuration (Β§D). Absent when not configured. */readonly discipline_report?: DisciplineReportConfig;}diff --git a/src/core/discipline/decision.ts b/src/core/discipline/decision.tsindex d5fbf724..913888d1 100644--- a/src/core/discipline/decision.ts+++ b/src/core/discipline/decision.ts@@ -1,6 +1,7 @@import type { BrainEventCounts } from "./log-counts.ts";import type { GitActivity } from "./activity-git.ts";import type { VaultDelta } from "./vault-delta.ts";+import type { TranscriptActivity } from "./transcripts/types.ts";export interface RepoActivityRow {readonly path: string;@@ -15,6 +16,22 @@ export interface ActivitySummary {readonly repo: ReadonlyArray<RepoActivityRow>;readonly nonRepo: ReadonlyArray<NonRepoActivityRow>;readonly vaultDelta: VaultDelta;+ /**+ * Per-runtime session-transcript activity (v0.10.11). Optional so+ * the type is back-compat with callers / tests that have not been+ * migrated yet. When present and non-empty it adds a+ * `transcript-confirmed` sub-reason to an `alert` row.+ */+ readonly transcripts?: TranscriptActivity;+}++/**+ * Did at least one per-runtime transcript surface activity in the+ * report window? Used by the renderer to add a `transcript-confirmed`+ * hint to an `alert` row.+ */+export function transcriptConfirmed(activity: ActivitySummary): boolean {+ return (activity.transcripts?.totalFiles ?? 0) > 0;}export type DisciplineStatus = "ok" | "info" | "alert";diff --git a/src/core/discipline/render.ts b/src/core/discipline/render.tsindex fbe518a3..7b542762 100644--- a/src/core/discipline/render.ts+++ b/src/core/discipline/render.ts@@ -1,6 +1,10 @@import { escapeMarkdownV2 as e } from "./telegram.ts";import type { BrainEventCounts } from "./log-counts.ts";-import type { ActivitySummary, DisciplineStatus } from "./decision.ts";+import {+ transcriptConfirmed,+ type ActivitySummary,+ type DisciplineStatus,+} from "./decision.ts";export interface RenderInput {readonly localDate: string;@@ -48,6 +52,15 @@ export function renderReport(r: RenderInput): string {lines.push(`\\- vault β ${vd.newSignals} new signals, ${vd.newPreferences} new preferences, ${vd.newRetired} new retired`,);+ const transcripts = r.activity.transcripts;+ if (transcripts && transcripts.byRuntime.length > 0) {+ const parts = transcripts.byRuntime+ .filter((b) => b.fileCount > 0)+ .map((b) => `${e(b.runtime)}: ${b.fileCount}`);+ if (parts.length > 0) {+ lines.push(`\\- transcripts β ${parts.join(", ")}`);+ }+ }if (r.status === "alert") {lines.push("");@@ -58,6 +71,11 @@ export function renderReport(r: RenderInput): string {lines.push("_Activity present; zero brain events recorded\\. Stop guardrail likely bypassed or hook regressed\\._",);+ if (transcriptConfirmed(r.activity)) {+ lines.push(+ "_Sub\\-reason: transcript\\-confirmed β runtime session files dated to this window\\._",+ );+ }}return lines.join("\n");}diff --git a/src/core/discipline/report.ts b/src/core/discipline/report.tsindex 6a7edc69..cf2e0835 100644--- a/src/core/discipline/report.ts+++ b/src/core/discipline/report.ts@@ -1,13 +1,21 @@import { existsSync } from "node:fs";-import { BrainConfigError, loadBrainConfig } from "../brain/policy.ts";+import { loadBrainConfig } from "../brain/policy.ts";+import { brainConfigPath } from "../brain/paths.ts";import { countBrainEvents, type BrainEventCounts } from "./log-counts.ts";import { gitActivity } from "./activity-git.ts";import { mtimeActivity } from "./activity-mtime.ts";import { vaultDelta } from "./vault-delta.ts";-import { decideStatus, type ActivitySummary, type DisciplineStatus, type RepoActivityRow, type NonRepoActivityRow } from "./decision.ts";+import {+ decideStatus,+ type ActivitySummary,+ type DisciplineStatus,+ type NonRepoActivityRow,+ type RepoActivityRow,+} from "./decision.ts";import { renderReport } from "./render.ts";import { yesterdayWindow } from "./window.ts";+import { collectTranscriptActivity } from "./transcripts/index.ts";export interface RunDisciplineReportOpts {readonly vault: string;@@ -28,15 +36,10 @@ export function runDisciplineReport(opts: RunDisciplineReportOpts): DisciplineRe// Downgrade to the `disabled` shape β same as an explicit `enabled:// false` β so the Hermes cron stays silent instead of posting empty// messages on every tick.- let cfg;- try {- cfg = loadBrainConfig(opts.vault);- } catch (e) {- if (e instanceof BrainConfigError) {- return { status: "disabled", text: "", localDate: null, events: null, activity: null };- }- throw e;+ if (!existsSync(brainConfigPath(opts.vault))) {+ return { status: "disabled", text: "", localDate: null, events: null, activity: null };}+ const cfg = loadBrainConfig(opts.vault);const d = cfg.discipline_report;if (!d || !d.enabled) {return { status: "disabled", text: "", localDate: null, events: null, activity: null };@@ -58,7 +61,20 @@ export function runDisciplineReport(opts: RunDisciplineReportOpts): DisciplineRe}const vd = vaultDelta(opts.vault, win);- const activity: ActivitySummary = { repo, nonRepo, vaultDelta: vd };+ // Per-runtime session-transcript activity (v0.10.11). Hardened: if+ // a resolver throws (unreadable home, missing perms), we degrade+ // to zero counts rather than failing the whole report.+ let transcripts;+ try {+ transcripts = collectTranscriptActivity({+ dayStartMs: win.startUtc.getTime(),+ dayEndMs: win.endUtc.getTime(),+ });+ } catch {+ transcripts = { byRuntime: [], totalFiles: 0 };+ }++ const activity: ActivitySummary = { repo, nonRepo, vaultDelta: vd, transcripts };const status = decideStatus(events, activity);const text = renderReport({localDate: win.localDate,diff --git a/src/core/discipline/transcripts/claude-code.ts b/src/core/discipline/transcripts/claude-code.tsnew file mode 100644index 00000000..47d54672--- /dev/null+++ b/src/core/discipline/transcripts/claude-code.ts@@ -0,0 +1,51 @@+/**+ * Claude Code session-transcript paths for the discipline report.+ *+ * Reuses the same `~/.claude/projects/*` layout that+ * `o2b brain import-claude-memory` walks. We treat any `.jsonl`+ * session file as evidence of agent activity on the day matching+ * its mtime.+ */++import { existsSync, readdirSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++import type { TranscriptRuntime } from "./types.ts";++export const claudeCodeTranscript: TranscriptRuntime = {+ runtime: "claudecode",+ agentHint: "claude-vps-agent",+ collect(dayStartMs, dayEndMs, home = homedir()): string[] {+ const base = join(home, ".claude", "projects");+ if (!existsSync(base)) return [];+ const out: string[] = [];+ let entries: string[];+ try {+ entries = readdirSync(base);+ } catch {+ return [];+ }+ for (const e of entries) {+ const projectDir = join(base, e);+ let files: string[];+ try {+ files = readdirSync(projectDir);+ } catch {+ continue;+ }+ for (const f of files) {+ if (!f.endsWith(".jsonl")) continue;+ const full = join(projectDir, f);+ try {+ const st = statSync(full);+ const ms = st.mtimeMs;+ if (ms >= dayStartMs && ms < dayEndMs) out.push(full);+ } catch {+ // unreadable file β ignore+ }+ }+ }+ return out;+ },+};diff --git a/src/core/discipline/transcripts/codex.ts b/src/core/discipline/transcripts/codex.tsnew file mode 100644index 00000000..d583dc33--- /dev/null+++ b/src/core/discipline/transcripts/codex.ts@@ -0,0 +1,61 @@+/**+ * Codex session-transcript paths for the discipline report.+ *+ * Codex stores per-session JSON files under `~/.codex/`. The exact+ * subdirectory has moved between CLI releases (`sessions/`, `.tmp/`,+ * etc.); we walk every immediate subdirectory of `~/.codex/` and look+ * for `.json` files whose mtime falls in the day window.+ */++import { existsSync, readdirSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++import type { TranscriptRuntime } from "./types.ts";++export const codexTranscript: TranscriptRuntime = {+ runtime: "codex",+ agentHint: "codex-vps-agent",+ collect(dayStartMs, dayEndMs, home = homedir()): string[] {+ const base = join(home, ".codex");+ if (!existsSync(base)) return [];+ const candidates = ["sessions", "session", "history", ".tmp"];+ const out: string[] = [];+ for (const sub of candidates) {+ const dir = join(base, sub);+ if (!existsSync(dir)) continue;+ pushJsonInRange(dir, dayStartMs, dayEndMs, out, 3);+ }+ return out;+ },+};++function pushJsonInRange(+ dir: string,+ dayStartMs: number,+ dayEndMs: number,+ out: string[],+ depth: number,+): void {+ if (depth < 0) return;+ let entries: import("node:fs").Dirent[];+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ return;+ }+ for (const e of entries) {+ const full = join(dir, e.name);+ if (e.isDirectory()) {+ pushJsonInRange(full, dayStartMs, dayEndMs, out, depth - 1);+ continue;+ }+ if (!e.isFile() || !e.name.endsWith(".json")) continue;+ try {+ const st = statSync(full);+ if (st.mtimeMs >= dayStartMs && st.mtimeMs < dayEndMs) out.push(full);+ } catch {+ // unreadable β ignore+ }+ }+}diff --git a/src/core/discipline/transcripts/cursor.ts b/src/core/discipline/transcripts/cursor.tsnew file mode 100644index 00000000..53e2b039--- /dev/null+++ b/src/core/discipline/transcripts/cursor.ts@@ -0,0 +1,50 @@+/**+ * Cursor session-transcript paths for the discipline report.+ *+ * Cursor stores per-workspace chat history in `state.vscdb` SQLite+ * files. We probe both the Linux layout+ * (`~/.config/Cursor/User/workspaceStorage/<hash>/state.vscdb`) and+ * the macOS layout (under `~/Library/Application Support/Cursor/`).+ * v0.10.11 only checks file mtime; deeper SQLite parsing is deferred.+ */++import { existsSync, readdirSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++import type { TranscriptRuntime } from "./types.ts";++export const cursorTranscript: TranscriptRuntime = {+ runtime: "cursor",+ agentHint: "cursor-vps-agent",+ collect(dayStartMs, dayEndMs, home = homedir()): string[] {+ const roots = [+ join(home, ".config", "Cursor", "User", "workspaceStorage"),+ join(home, "Library", "Application Support", "Cursor", "User", "workspaceStorage"),+ // macOS XDG-style fallback used by some Cursor builds+ join(home, ".cursor", "workspaceStorage"),+ ];+ const out: string[] = [];+ for (const root of roots) {+ if (!existsSync(root)) continue;+ let dirs: import("node:fs").Dirent[];+ try {+ dirs = readdirSync(root, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const d of dirs) {+ if (!d.isDirectory()) continue;+ const db = join(root, d.name, "state.vscdb");+ if (!existsSync(db)) continue;+ try {+ const st = statSync(db);+ if (st.mtimeMs >= dayStartMs && st.mtimeMs < dayEndMs) out.push(db);+ } catch {+ // unreadable β ignore+ }+ }+ }+ return out;+ },+};diff --git a/src/core/discipline/transcripts/index.ts b/src/core/discipline/transcripts/index.tsnew file mode 100644index 00000000..a6d4f551--- /dev/null+++ b/src/core/discipline/transcripts/index.ts@@ -0,0 +1,50 @@+/**+ * Aggregator for per-runtime transcript activity used by the+ * discipline report (v0.10.11).+ *+ * Each runtime resolver returns a list of files touched in the day+ * window. The aggregator sums them and surfaces a+ * `transcriptConfirmed` flag the renderer can show next to an+ * `alert` row β confirming that the proxy activity signal is not+ * a false positive from disk-time drift alone.+ */++import { claudeCodeTranscript } from "./claude-code.ts";+import { codexTranscript } from "./codex.ts";+import { cursorTranscript } from "./cursor.ts";+import type { TranscriptActivity, TranscriptRuntime } from "./types.ts";++export { claudeCodeTranscript, codexTranscript, cursorTranscript };+export type { TranscriptActivity, TranscriptRuntime };++export const DEFAULT_TRANSCRIPT_RUNTIMES: ReadonlyArray<TranscriptRuntime> = [+ claudeCodeTranscript,+ codexTranscript,+ cursorTranscript,+];++export interface CollectTranscriptOpts {+ readonly dayStartMs: number;+ readonly dayEndMs: number;+ readonly home?: string;+ readonly runtimes?: ReadonlyArray<TranscriptRuntime>;+}++export function collectTranscriptActivity(+ opts: CollectTranscriptOpts,+): TranscriptActivity {+ const runtimes = opts.runtimes ?? DEFAULT_TRANSCRIPT_RUNTIMES;+ const byRuntime = [];+ let total = 0;+ for (const r of runtimes) {+ const files = r.collect(opts.dayStartMs, opts.dayEndMs, opts.home);+ byRuntime.push({+ runtime: r.runtime,+ fileCount: files.length,+ agentHint: r.agentHint,+ });+ total += files.length;+ }+ return { byRuntime, totalFiles: total };+}+diff --git a/src/core/discipline/transcripts/types.ts b/src/core/discipline/transcripts/types.tsnew file mode 100644index 00000000..5815ac61--- /dev/null+++ b/src/core/discipline/transcripts/types.ts@@ -0,0 +1,35 @@+/**+ * Per-runtime session-transcript resolver contract.+ *+ * Each runtime exports a `TranscriptRuntime` object that lists files+ * touched on the report's local day. The discipline-report layer+ * aggregates these into a `TranscriptActivity` summary which feeds+ * into the alert decision.+ */++export interface TranscriptRuntime {+ readonly runtime: "claudecode" | "codex" | "cursor";+ /**+ * Default agent attribution when the transcript itself does not+ * carry an explicit identity. The aggregator surfaces this as the+ * `agentHint` in `TranscriptActivity.byRuntime[runtime]`.+ */+ readonly agentHint: string | null;+ /**+ * Return absolute paths of transcript files that show activity+ * inside the half-open day window `[dayStartMs, dayEndMs)`.+ * `home` is injectable for tests.+ */+ collect(dayStartMs: number, dayEndMs: number, home?: string): string[];+}++export interface TranscriptRuntimeActivity {+ readonly runtime: string;+ readonly fileCount: number;+ readonly agentHint: string | null;+}++export interface TranscriptActivity {+ readonly byRuntime: ReadonlyArray<TranscriptRuntimeActivity>;+ readonly totalFiles: number;+}diff --git a/src/core/install/adapters/_json-mcp.ts b/src/core/install/adapters/_json-mcp.tsnew file mode 100644index 00000000..8fabc761--- /dev/null+++ b/src/core/install/adapters/_json-mcp.ts@@ -0,0 +1,397 @@+/**+ * Shared adapter body for runtimes that consume MCP servers via a JSON+ * config file with a top-level object (default `mcpServers`). Cursor,+ * opencode, kiro, Gemini CLI β all four follow this pattern.+ *+ * Per-target specifics (config path, top-level key, post-install notes,+ * optional MCP probe) are injected via `JsonMcpAdapterSpec`. The body+ * itself owns idempotency, drift detection, manifest I/O, and the+ * user-modified-block safety net.+ */++import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";+import { dirname } from "node:path";++import { atomicWriteFileSync } from "../../fs-atomic.ts";+import {+ mergeMcpServers,+ removeMcpServers,+ OSB_KEY_FULL,+ OSB_KEY_WRITER,+} from "../json-merge.ts";+import { recordEntry, readManifest, removeEntry } from "../manifest.ts";+import { expectedPayloadFromEnv, payloadKeyEquals } from "../payload-equals.ts";+import {+ InstallError,+ type ApplyOpts,+ type ApplyResult,+ type DetectResult,+ type InstallAdapter,+ type InstallEnv,+ type InstallPlan,+ type ManifestEntry,+ type McpPayload,+ type UninstallResult,+ type VerifyResult,+} from "../types.ts";++export interface JsonMcpAdapterSpec {+ readonly target: string;+ readonly label: string;+ /** Top-level key under which MCP servers live. Default `mcpServers`. */+ readonly topLevelKey?: string;+ /** Resolves the absolute path to the runtime's config file. */+ resolveConfigPath(env: InstallEnv): string;+ /** Extra notes attached to `detect.notes` / plan output. */+ readonly notes?: ReadonlyArray<string>;+ /** Plan-level post-install reminders (e.g. "restart Cursor app"). */+ readonly postNotes?: ReadonlyArray<string>;+ /**+ * Optional MCP-ping probe. Return `true` if the runtime answers an+ * MCP handshake; `false` on definite failure. `null` means "we+ * cannot probe" (skip β do not penalise).+ */+ probeMcp?(env: InstallEnv): boolean | null;+ /** Fix-hint text for `verify` when drift detected. */+ readonly fixHintForDrift?: string;+}++function readFileOrEmpty(path: string): string {+ try {+ return readFileSync(path, "utf8");+ } catch {+ return "";+ }+}++function parseJsonObject(raw: string): Record<string, unknown> | null {+ const text = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;+ if (text.trim().length === 0) return {};+ try {+ const parsed = JSON.parse(text);+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;+ return parsed as Record<string, unknown>;+ } catch {+ return null;+ }+}++function readMcpBlock(+ root: Record<string, unknown>,+ topKey: string,+): Record<string, unknown> | null {+ const block = root[topKey] ?? {};+ if (block === null || typeof block !== "object" || Array.isArray(block)) return null;+ return block as Record<string, unknown>;+}++function fileMtimeMs(path: string): number | null {+ try {+ return statSync(path).mtimeMs;+ } catch {+ return null;+ }+}++interface OnDiskState {+ readonly exists: boolean;+ readonly canonical: boolean;+ readonly full: Record<string, unknown> | undefined;+ readonly writer: Record<string, unknown> | undefined;+ readonly raw: string;+ readonly mtimeMs: number | null;+}++function readOnDisk(spec: JsonMcpAdapterSpec, env: InstallEnv, payload: McpPayload): OnDiskState {+ const path = spec.resolveConfigPath(env);+ if (!existsSync(path)) {+ return { exists: false, canonical: false, full: undefined, writer: undefined, raw: "", mtimeMs: null };+ }+ const raw = readFileOrEmpty(path);+ const topKey = spec.topLevelKey ?? "mcpServers";+ const parsed = parseJsonObject(raw);+ if (parsed === null) {+ return { exists: true, canonical: false, full: undefined, writer: undefined, raw, mtimeMs: fileMtimeMs(path) };+ }+ const block = readMcpBlock(parsed, topKey);+ if (block === null) {+ return { exists: true, canonical: false, full: undefined, writer: undefined, raw, mtimeMs: fileMtimeMs(path) };+ }+ const full = block[OSB_KEY_FULL] as Record<string, unknown> | undefined;+ const writer = block[OSB_KEY_WRITER] as Record<string, unknown> | undefined;+ const canonical =+ payloadKeyEquals(full, payload.full) && payloadKeyEquals(writer, payload.writer);+ return { exists: true, canonical, full, writer, raw, mtimeMs: fileMtimeMs(path) };+}++export function createJsonMcpAdapter(spec: JsonMcpAdapterSpec): InstallAdapter {+ const topKey = spec.topLevelKey ?? "mcpServers";++ return {+ target: spec.target,+ label: spec.label,++ detect(env: InstallEnv): DetectResult {+ const path = spec.resolveConfigPath(env);+ const baseNotes = [...(spec.notes ?? [])];+ if (!existsSync(path)) {+ return {+ target: spec.target,+ status: "not-installed",+ configPath: path,+ notes: [...baseNotes, "config file missing"],+ };+ }+ const raw = readFileOrEmpty(path);+ const parsed = parseJsonObject(raw);+ if (parsed === null) {+ return {+ target: spec.target,+ status: "drift",+ configPath: path,+ notes: [...baseNotes, "config file is not valid JSON"],+ };+ }+ const block = readMcpBlock(parsed, topKey);+ if (block === null) {+ return {+ target: spec.target,+ status: "drift",+ configPath: path,+ notes: [...baseNotes, `${topKey} is not a JSON object`],+ };+ }+ const hasFull = OSB_KEY_FULL in block;+ const hasWriter = OSB_KEY_WRITER in block;+ if (!hasFull && !hasWriter) {+ return {+ target: spec.target,+ status: "not-installed",+ configPath: path,+ notes: baseNotes,+ };+ }+ if (hasFull && hasWriter) {+ return {+ target: spec.target,+ status: "installed",+ configPath: path,+ notes: [...baseNotes, `both OSB keys present under ${topKey}`],+ };+ }+ return {+ target: spec.target,+ status: "drift",+ configPath: path,+ notes: [+ ...baseNotes,+ `partial OSB install: ${hasFull ? "writer key missing" : "full-server key missing"}`,+ ],+ };+ },++ plan(payload: McpPayload, env: InstallEnv): InstallPlan {+ const path = spec.resolveConfigPath(env);+ const preview = `json-merge two keys into ${topKey} at ${path}: ` ++ `${OSB_KEY_FULL} β ${payload.full.command} ${payload.full.args.join(" ")}; ` ++ `${OSB_KEY_WRITER} β ${payload.writer.command} ${payload.writer.args.join(" ")}`;+ return {+ target: spec.target,+ steps: [{ kind: "json-merge", path, preview }],+ postNotes: [...(spec.postNotes ?? [])],+ };+ },++ apply(+ _plan: InstallPlan,+ payload: McpPayload,+ env: InstallEnv,+ opts: ApplyOpts,+ ): ApplyResult {+ const path = spec.resolveConfigPath(env);+ const onDisk = readOnDisk(spec, env, payload);+ const manifestEntry = readManifest(env.vault).installs[spec.target];++ // Safety net: if the on-disk content differs from canonical AND+ // mtime is newer than manifest.applied_at AND user didn't pass+ // --force, refuse. This catches hand-edits.+ if (+ manifestEntry &&+ onDisk.exists &&+ !onDisk.canonical &&+ // Mixed: file exists but OSB keys are not exactly canonical.+ // If at least one OSB key is present, treat as potentially+ // hand-edited.+ (onDisk.full !== undefined || onDisk.writer !== undefined) &&+ !opts.force+ ) {+ const appliedAt = Date.parse(manifestEntry.applied_at);+ const mtime = onDisk.mtimeMs ?? 0;+ if (Number.isFinite(appliedAt) && mtime > appliedAt + 1000) {+ throw new InstallError(+ `${spec.target}: ${path} appears hand-edited after the last install ` ++ `(mtime newer than manifest applied_at). Refusing to overwrite.`,+ spec.target,+ "user-modified-block",+ "re-run with --force to overwrite, or run `o2b uninstall --target " ++ spec.target ++ " --apply` first",+ );+ }+ }++ const merged = mergeMcpServers(onDisk.raw, payload, { topLevelKey: topKey });+ const contentChanged = merged !== onDisk.raw;+ if (!opts.dryRun && contentChanged) {+ ensureParent(path);+ atomicWriteFileSync(path, merged);+ }++ // Re-apply with byte-identical content: keep the previous+ // `applied_at` so the user-modified-block detector continues to+ // compare disk mtime against the actual install moment, not the+ // current wall clock.+ const existing = readManifest(env.vault).installs[spec.target];+ const appliedAt = !contentChanged && existing+ ? existing.applied_at+ : env.now.toISOString();+ const manifest: ManifestEntry = {+ target: spec.target,+ applied_at: appliedAt,+ operation: "json-merge",+ config_path: path,+ owned_keys: [`${topKey}.${OSB_KEY_FULL}`, `${topKey}.${OSB_KEY_WRITER}`],+ };+ if (!opts.dryRun && (contentChanged || !existing)) {+ recordEntry(env.vault, manifest);+ }++ return {+ target: spec.target,+ manifest,+ steps_executed: opts.dryRun || !contentChanged ? 0 : 1,+ };+ },++ uninstall(+ env: InstallEnv,+ opts: ApplyOpts & { fromSnippet?: boolean },+ ): UninstallResult {+ const path = spec.resolveConfigPath(env);+ const stored = readManifest(env.vault).installs[spec.target];+ const skipped: Array<readonly [string, string]> = [];+ const removed_keys: string[] = [];+ const removed_paths: string[] = [];++ if (!stored && !opts.fromSnippet) {+ throw new InstallError(+ `${spec.target}: no install manifest entry found. ` ++ `Pass --force-from-snippet to remove based on the canonical payload.`,+ spec.target,+ "manifest-missing",+ "o2b uninstall --target " + spec.target + " --apply --force-from-snippet",+ );+ }++ if (!existsSync(path)) {+ skipped.push([path, "config file no longer present"]);+ if (!opts.dryRun) removeEntry(env.vault, spec.target);+ return { target: spec.target, removed_keys, removed_paths, skipped };+ }++ const raw = readFileOrEmpty(path);+ const next = removeMcpServers(raw, { topLevelKey: topKey });+ if (!opts.dryRun && next !== raw) {+ atomicWriteFileSync(path, next);+ }+ removed_keys.push(`${topKey}.${OSB_KEY_FULL}`, `${topKey}.${OSB_KEY_WRITER}`);+ if (!opts.dryRun) removeEntry(env.vault, spec.target);+ return { target: spec.target, removed_keys, removed_paths, skipped };+ },++ verify(env: InstallEnv): VerifyResult {+ const path = spec.resolveConfigPath(env);+ const stored = readManifest(env.vault).installs[spec.target];+ if (!stored) {+ return {+ target: spec.target,+ status: "not-installed",+ details: ["no install manifest entry"],+ fix_hint: null,+ };+ }+ if (!existsSync(path)) {+ return {+ target: spec.target,+ status: "drift",+ details: [`config file missing: ${path}`],+ fix_hint: spec.fixHintForDrift ?? `o2b install --target ${spec.target} --apply`,+ };+ }+ const raw = readFileOrEmpty(path);+ const parsed = parseJsonObject(raw);+ if (parsed === null) {+ return {+ target: spec.target,+ status: "drift",+ details: [`config file is not valid JSON: ${path}`],+ fix_hint: spec.fixHintForDrift ?? `o2b install --target ${spec.target} --apply`,+ };+ }+ const block = readMcpBlock(parsed, topKey);+ if (block === null) {+ return {+ target: spec.target,+ status: "drift",+ details: [`${topKey} is not a JSON object: ${path}`],+ fix_hint: spec.fixHintForDrift ?? `o2b install --target ${spec.target} --apply`,+ };+ }+ const hasFull = OSB_KEY_FULL in block;+ const hasWriter = OSB_KEY_WRITER in block;+ if (!hasFull || !hasWriter) {+ return {+ target: spec.target,+ status: "drift",+ details: [+ `${hasFull ? "" : OSB_KEY_FULL + " key missing; "}${hasWriter ? "" : OSB_KEY_WRITER + " key missing"}`.trim(),+ ],+ fix_hint: spec.fixHintForDrift ?? `o2b install --target ${spec.target} --apply`,+ };+ }+ const expected = expectedPayloadFromEnv(env);+ if (+ !payloadKeyEquals(block[OSB_KEY_FULL] as Record<string, unknown> | undefined, expected.full) ||+ !payloadKeyEquals(block[OSB_KEY_WRITER] as Record<string, unknown> | undefined, expected.writer)+ ) {+ return {+ target: spec.target,+ status: "drift",+ details: [`${path}: OSB keys differ from canonical payload`],+ fix_hint: spec.fixHintForDrift ?? `o2b install --target ${spec.target} --apply`,+ };+ }+ // Optional MCP probe β does not penalise when it returns null.+ const probe = spec.probeMcp?.(env);+ if (probe === false) {+ return {+ target: spec.target,+ status: "mcp-unreachable",+ details: ["MCP probe failed"],+ fix_hint: "verify the runtime is running and o2b is on PATH",+ };+ }+ return {+ target: spec.target,+ status: "ok",+ details: [`${path}: both OSB keys present`],+ fix_hint: null,+ };+ },+ };+}++function ensureParent(path: string): void {+ const dir = dirname(path);+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });+}diff --git a/src/core/install/adapters/aider.ts b/src/core/install/adapters/aider.tsnew file mode 100644index 00000000..677d83a3--- /dev/null+++ b/src/core/install/adapters/aider.ts@@ -0,0 +1,334 @@+/**+ * Aider adapter β managed-block in `~/.aider.conf.yml` + sidecar+ * context file in the vault.+ *+ * Aider has no native MCP client at the time this adapter was written+ * (see `docs/plans/2026-05-20-multi-runtime-install-design.md` Β§3.2,+ * Β§13). The install path is therefore:+ *+ * 1. Generate `<vault>/.open-second-brain/aider-context.md` from+ * `templates/install/aider-context.md.tmpl` β placeholders are+ * `{{VAULT}}` and `{{AGENT_NAME}}`.+ * 2. Write a marker-fenced managed block to `~/.aider.conf.yml`+ * that injects the sidecar into Aider's `read:` list. If the+ * user already has their own `read:` elsewhere in the same+ * file, Aider's YAML loader treats it as a duplicate key β+ * we surface this caveat in the plan's `postNotes` so the+ * operator can merge by hand.+ *+ * If a future Aider release ships native MCP, switch this adapter to+ * the JSON-merge body. The interface stays the same.+ */++import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import { atomicWriteFileSync } from "../../fs-atomic.ts";+import {+ insertManagedBlock,+ removeManagedBlock,+ hasManagedBlock,+ extractManagedBlock,+} from "../managed-block.ts";+import { recordEntry, readManifest, removeEntry } from "../manifest.ts";+import {+ InstallError,+ type ApplyOpts,+ type ApplyResult,+ type DetectResult,+ type InstallAdapter,+ type InstallEnv,+ type InstallPlan,+ type ManifestEntry,+ type McpPayload,+ type UninstallResult,+ type VerifyResult,+} from "../types.ts";+import { defaultRegistry } from "../registry.ts";++const TARGET = "aider";+const LABEL = "Aider";++function repoRoot(): string {+ return resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..");+}++function templatePath(): string {+ return join(repoRoot(), "templates", "install", "aider-context.md.tmpl");+}++function resolveConfPath(env: InstallEnv): string {+ if (env.env["AIDER_CONFIG"]) return env.env["AIDER_CONFIG"];+ const local = join(env.cwd, ".aider.conf.yml");+ if (existsSync(local)) return local;+ return join(env.home, ".aider.conf.yml");+}++function resolveSidecarPath(env: InstallEnv, opts: { aiderContextPath?: string }): string {+ if (opts.aiderContextPath) return opts.aiderContextPath;+ return join(env.vault, ".open-second-brain", "aider-context.md");+}++function readSafe(path: string): string {+ try {+ return readFileSync(path, "utf8");+ } catch {+ return "";+ }+}++function fileMtimeMs(path: string): number | null {+ try {+ return statSync(path).mtimeMs;+ } catch {+ return null;+ }+}++function resolveAgentName(env: InstallEnv, payload: McpPayload): string {+ return (+ payload.full.env?.["VAULT_AGENT_NAME"] ??+ env.env["VAULT_AGENT_NAME"] ??+ "agent"+ );+}++function renderTemplate(env: InstallEnv, payload: McpPayload): string {+ const tpl = readFileSync(templatePath(), "utf8");+ return tpl+ .replace(/\{\{VAULT\}\}/g, env.vault)+ .replace(/\{\{AGENT_NAME\}\}/g, resolveAgentName(env, payload));+}++function renderManagedBody(sidecarPath: string): string {+ return [+ "# Open Second Brain β agent context.",+ "# Aider auto-includes this file as read-only context.",+ "# Regenerated by `o2b install --target aider --apply` β do not hand-edit.",+ "read:",+ ` - ${sidecarPath}`,+ "",+ ].join("\n");+}++function ensureParent(path: string): void {+ const parent = dirname(path);+ if (!existsSync(parent)) mkdirSync(parent, { recursive: true });+}++export const aiderAdapter: InstallAdapter = {+ target: TARGET,+ label: LABEL,++ detect(env: InstallEnv): DetectResult {+ const path = resolveConfPath(env);+ if (!existsSync(path)) {+ return {+ target: TARGET,+ status: "not-installed",+ configPath: path,+ notes: ["config file missing"],+ };+ }+ const raw = readSafe(path);+ if (hasManagedBlock(raw)) {+ return {+ target: TARGET,+ status: "installed",+ configPath: path,+ notes: [],+ };+ }+ return {+ target: TARGET,+ status: "not-installed",+ configPath: path,+ notes: [],+ };+ },++ plan(_payload: McpPayload, env: InstallEnv): InstallPlan {+ const conf = resolveConfPath(env);+ const sidecar = resolveSidecarPath(env, {});+ return {+ target: TARGET,+ steps: [+ {+ kind: "file-copy",+ path: sidecar,+ preview: `render templates/install/aider-context.md.tmpl β ${sidecar}`,+ },+ {+ kind: "managed-block",+ path: conf,+ preview: `add OSB managed block to ${conf} (read: β ${sidecar})`,+ },+ ],+ postNotes: [+ "If your existing ~/.aider.conf.yml already sets `read:`, YAML treats",+ "duplicate top-level keys as ambiguous. Merge the two `read:` lists",+ "by hand if you keep your own.",+ ],+ };+ },++ apply(+ _plan: InstallPlan,+ payload: McpPayload,+ env: InstallEnv,+ opts: ApplyOpts,+ ): ApplyResult {+ const conf = resolveConfPath(env);+ const sidecar = resolveSidecarPath(env, opts);+ const stored = readManifest(env.vault).installs[TARGET];++ // user-modified-block safety net+ if (stored && existsSync(conf) && !opts.force) {+ const raw = readSafe(conf);+ const current = extractManagedBlock(raw);+ const expected = renderManagedBody(sidecar);+ if (current !== null && current.trim() !== expected.trim()) {+ const appliedAt = Date.parse(stored.applied_at);+ const mtime = fileMtimeMs(conf) ?? 0;+ if (Number.isFinite(appliedAt) && mtime > appliedAt + 1000) {+ throw new InstallError(+ `aider: ${conf} appears hand-edited after the last install ` ++ `(managed block diverges from canonical content).`,+ TARGET,+ "user-modified-block",+ "re-run with --force to overwrite, or run `o2b uninstall --target aider --apply` first",+ );+ }+ }+ }++ // Render sidecar+ const sidecarContent = renderTemplate(env, payload);+ if (!opts.dryRun) {+ ensureParent(sidecar);+ atomicWriteFileSync(sidecar, sidecarContent);+ }++ // Insert managed block+ const confRaw = existsSync(conf) ? readFileSync(conf, "utf8") : "";+ const nextConf = insertManagedBlock(confRaw, renderManagedBody(sidecar));+ if (!opts.dryRun) {+ ensureParent(conf);+ atomicWriteFileSync(conf, nextConf);+ }++ const manifest: ManifestEntry = {+ target: TARGET,+ applied_at: env.now.toISOString(),+ operation: "managed-block",+ config_path: conf,+ owned_paths: [sidecar],+ owned_block_marker: "# >>> open-second-brain managed >>>",+ };+ if (!opts.dryRun) recordEntry(env.vault, manifest);++ return { target: TARGET, manifest, steps_executed: opts.dryRun ? 0 : 2 };+ },++ uninstall(env: InstallEnv, opts: ApplyOpts & { fromSnippet?: boolean }): UninstallResult {+ const conf = resolveConfPath(env);+ const stored = readManifest(env.vault).installs[TARGET];+ const skipped: Array<readonly [string, string]> = [];+ const removed_paths: string[] = [];++ if (!stored && !opts.fromSnippet) {+ throw new InstallError(+ "aider: no install manifest entry found",+ TARGET,+ "manifest-missing",+ "o2b uninstall --target aider --apply --force-from-snippet",+ );+ }++ // Remove managed block from conf file+ if (existsSync(conf)) {+ const raw = readFileSync(conf, "utf8");+ if (hasManagedBlock(raw)) {+ const next = removeManagedBlock(raw);+ if (!opts.dryRun) atomicWriteFileSync(conf, next);+ } else {+ skipped.push([conf, "no managed block present"]);+ }+ } else {+ skipped.push([conf, "config file no longer present"]);+ }++ // Remove sidecar file+ const sidecarTargets = stored?.owned_paths ?? [resolveSidecarPath(env, {})];+ for (const t of sidecarTargets) {+ if (existsSync(t)) {+ if (!opts.dryRun) rmSync(t, { force: true });+ removed_paths.push(t);+ } else {+ skipped.push([t, "sidecar file no longer present"]);+ }+ }++ if (!opts.dryRun) removeEntry(env.vault, TARGET);+ return { target: TARGET, removed_keys: [], removed_paths, skipped };+ },++ verify(env: InstallEnv): VerifyResult {+ const stored = readManifest(env.vault).installs[TARGET];+ if (!stored) {+ return {+ target: TARGET,+ status: "not-installed",+ details: ["no install manifest entry"],+ fix_hint: null,+ };+ }+ const conf = resolveConfPath(env);+ if (!existsSync(conf)) {+ return {+ target: TARGET,+ status: "drift",+ details: [`config file missing: ${conf}`],+ fix_hint: "o2b install --target aider --apply",+ };+ }+ const raw = readSafe(conf);+ if (!hasManagedBlock(raw)) {+ return {+ target: TARGET,+ status: "drift",+ details: [`managed block absent from ${conf}`],+ fix_hint: "o2b install --target aider --apply",+ };+ }+ const sidecarPaths = stored.owned_paths ?? [];+ for (const p of sidecarPaths) {+ if (!existsSync(p)) {+ return {+ target: TARGET,+ status: "drift",+ details: [`sidecar context file missing: ${p}`],+ fix_hint: "o2b install --target aider --apply",+ };+ }+ // Refuse to report ok if the sidecar is suspiciously empty.+ if (readSafe(p).trim().length === 0) {+ return {+ target: TARGET,+ status: "drift",+ details: [`sidecar context file is empty: ${p}`],+ fix_hint: "o2b install --target aider --apply",+ };+ }+ }+ return {+ target: TARGET,+ status: "ok",+ details: [`${conf}: managed block present; sidecar ok`],+ fix_hint: null,+ };+ },+};++defaultRegistry.register(aiderAdapter);diff --git a/src/core/install/adapters/copilot-cli.ts b/src/core/install/adapters/copilot-cli.tsnew file mode 100644index 00000000..819a621f--- /dev/null+++ b/src/core/install/adapters/copilot-cli.ts@@ -0,0 +1,428 @@+/**+ * GitHub Copilot CLI adapter β subprocess-driven, with JSON-file+ * fallback when `copilot` CLI is missing or its `mcp add` errors out.+ *+ * Primary path:+ * - `copilot mcp remove <name>` (best-effort; non-zero is ok if the+ * server wasn't registered)+ * - `copilot mcp add <name> --command <cmd> --arg <arg> ... [--env K=V ...]`+ *+ * Fallback path:+ * - JSON-merge into `${XDG_CONFIG_HOME:-$HOME/.config}/github-copilot/mcp.json`.+ * The exact fallback path is the one Copilot CLI consults at startup+ * when its CLI is not used to register the server.+ *+ * The subprocess seam is injectable via `setCopilotRunner` so tests+ * can drive both branches deterministically.+ */++import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { dirname, join } from "node:path";++import { atomicWriteFileSync } from "../../fs-atomic.ts";+import {+ mergeMcpServers,+ removeMcpServers,+ OSB_KEY_FULL,+ OSB_KEY_WRITER,+} from "../json-merge.ts";+import { expectedPayloadFromEnv, payloadKeyEquals } from "../payload-equals.ts";+import { recordEntry, readManifest, removeEntry } from "../manifest.ts";+import { defaultRegistry } from "../registry.ts";+import {+ InstallError,+ type ApplyOpts,+ type ApplyResult,+ type DetectResult,+ type InstallAdapter,+ type InstallEnv,+ type InstallPlan,+ type ManifestEntry,+ type McpPayload,+ type McpServerEntry,+ type UninstallResult,+ type VerifyResult,+} from "../types.ts";++const TARGET = "copilot-cli";+const LABEL = "GitHub Copilot CLI";++// ---------- Injectable subprocess runner ----------++export interface CopilotRunResult {+ readonly exitCode: number;+ readonly stdout: string;+ readonly stderr: string;+}++export interface CopilotListResult {+ readonly ok: boolean;+ readonly names: ReadonlyArray<string>;+}++export interface CopilotRunner {+ available(): boolean;+ run(args: ReadonlyArray<string>): CopilotRunResult;+ list(): CopilotListResult;+}++const defaultRunner: CopilotRunner = {+ available(): boolean {+ try {+ const r = Bun.spawnSync({ cmd: ["copilot", "--version"], stdout: "pipe", stderr: "pipe" });+ return r.exitCode === 0;+ } catch {+ return false;+ }+ },+ run(args) {+ const r = Bun.spawnSync({ cmd: ["copilot", ...args], stdout: "pipe", stderr: "pipe" });+ return {+ exitCode: r.exitCode ?? 1,+ stdout: r.stdout?.toString() ?? "",+ stderr: r.stderr?.toString() ?? "",+ };+ },+ list(): CopilotListResult {+ const r = Bun.spawnSync({ cmd: ["copilot", "mcp", "list"], stdout: "pipe", stderr: "pipe" });+ if (r.exitCode !== 0) return { ok: false, names: [] };+ const stdout = r.stdout?.toString() ?? "";+ const names = stdout+ .split("\n")+ .map((line) => line.trim())+ .filter((l) => l.length > 0)+ .map((line) => line.split(/\s+/)[0]!)+ .filter((n) => n === OSB_KEY_FULL || n === OSB_KEY_WRITER);+ return { ok: true, names };+ },+};++let activeRunner: CopilotRunner = defaultRunner;++export function setCopilotRunner(r: CopilotRunner): void {+ activeRunner = r;+}++export function resetCopilotRunner(): void {+ activeRunner = defaultRunner;+}++// ---------- helpers ----------++function fallbackPath(env: InstallEnv): string {+ const xdg = env.env["XDG_CONFIG_HOME"];+ const base = xdg && xdg.length > 0 ? xdg : join(env.home, ".config");+ return join(base, "github-copilot", "mcp.json");+}++function ensureParent(path: string): void {+ const dir = dirname(path);+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });+}++function addArgs(name: string, entry: McpServerEntry): string[] {+ const args = ["mcp", "add", name, "--command", entry.command];+ for (const a of entry.args) args.push("--arg", a);+ if (entry.env) {+ for (const [k, v] of Object.entries(entry.env)) args.push("--env", `${k}=${v}`);+ }+ return args;+}++interface ApplyOutcome {+ readonly viaCli: boolean;+ readonly fallbackFile: string | null;+}++function applyViaCli(+ payload: McpPayload,+ stderr: NodeJS.WriteStream | NodeJS.WritableStream,+): { ok: boolean; reason?: string } {+ // best-effort remove+ for (const name of [OSB_KEY_FULL, OSB_KEY_WRITER]) {+ activeRunner.run(["mcp", "remove", name]);+ }+ for (const [name, entry] of [+ [OSB_KEY_FULL, payload.full],+ [OSB_KEY_WRITER, payload.writer],+ ] as const) {+ const r = activeRunner.run(addArgs(name, entry));+ if (r.exitCode !== 0) {+ stderr.write(+ `copilot mcp add failed for ${name} (exit ${r.exitCode}): ${r.stderr.trim()}\n`,+ );+ return { ok: false, reason: r.stderr.trim() || `exit ${r.exitCode}` };+ }+ }+ return { ok: true };+}++function applyViaFile(+ env: InstallEnv,+ payload: McpPayload,+ stderr: NodeJS.WriteStream | NodeJS.WritableStream,+ dryRun: boolean,+): string {+ const path = fallbackPath(env);+ const current = existsSync(path) ? readFileSync(path, "utf8") : "";+ const merged = mergeMcpServers(current, payload);+ if (!dryRun) {+ ensureParent(path);+ atomicWriteFileSync(path, merged);+ }+ stderr.write(`copilot-cli: wrote MCP config to ${path} (file-fallback mode)\n`);+ return path;+}++function uninstallViaCli(): { removed: string[] } {+ const removed: string[] = [];+ for (const name of [OSB_KEY_FULL, OSB_KEY_WRITER]) {+ const r = activeRunner.run(["mcp", "remove", name]);+ if (r.exitCode === 0) removed.push(name);+ }+ return { removed };+}++function uninstallViaFile(env: InstallEnv, dryRun: boolean): { path: string; touched: boolean } {+ const path = fallbackPath(env);+ if (!existsSync(path)) return { path, touched: false };+ const current = readFileSync(path, "utf8");+ const next = removeMcpServers(current);+ if (!dryRun && next !== current) atomicWriteFileSync(path, next);+ return { path, touched: next !== current };+}++// ---------- adapter ----------++export const copilotCliAdapter: InstallAdapter = {+ target: TARGET,+ label: LABEL,++ detect(env: InstallEnv): DetectResult {+ const cliAvailable = activeRunner.available();+ if (cliAvailable) {+ const lst = activeRunner.list();+ if (lst.ok) {+ const has = (n: string) => lst.names.includes(n);+ if (has(OSB_KEY_FULL) && has(OSB_KEY_WRITER)) {+ return {+ target: TARGET,+ status: "installed",+ configPath: null,+ notes: ["copilot CLI present; both OSB MCP servers registered"],+ };+ }+ if (has(OSB_KEY_FULL) || has(OSB_KEY_WRITER)) {+ return {+ target: TARGET,+ status: "drift",+ configPath: null,+ notes: ["copilot CLI present; only one of the two OSB MCP servers registered"],+ };+ }+ return { target: TARGET, status: "not-installed", configPath: null, notes: [] };+ }+ }+ const fb = fallbackPath(env);+ if (existsSync(fb)) {+ try {+ const parsed = JSON.parse(readFileSync(fb, "utf8")) as Record<string, unknown>;+ const block = (parsed["mcpServers"] ?? {}) as Record<string, unknown>;+ const has = (n: string) => n in block;+ if (has(OSB_KEY_FULL) && has(OSB_KEY_WRITER)) {+ return {+ target: TARGET,+ status: "installed",+ configPath: fb,+ notes: ["file-fallback: both OSB keys present"],+ };+ }+ } catch {+ // parse error β drift+ return { target: TARGET, status: "drift", configPath: fb, notes: ["fallback file not valid JSON"] };+ }+ }+ return {+ target: TARGET,+ status: "not-installed",+ configPath: cliAvailable ? null : fb,+ notes: cliAvailable ? [] : ["copilot CLI not available; will use file fallback"],+ };+ },++ plan(payload: McpPayload, env: InstallEnv): InstallPlan {+ void payload;+ const cliAvailable = activeRunner.available();+ if (cliAvailable) {+ return {+ target: TARGET,+ steps: [+ {+ kind: "subprocess",+ path: null,+ preview: `copilot mcp remove ${OSB_KEY_FULL}; copilot mcp remove ${OSB_KEY_WRITER}; copilot mcp add ${OSB_KEY_FULL} ...; copilot mcp add ${OSB_KEY_WRITER} ...`,+ },+ ],+ postNotes: ["copilot CLI present"],+ };+ }+ return {+ target: TARGET,+ steps: [+ {+ kind: "json-merge",+ path: fallbackPath(env),+ preview: `copilot CLI not on PATH; write to fallback file ${fallbackPath(env)}`,+ },+ ],+ postNotes: [+ "copilot CLI was not detected; using file-fallback path",+ "install the copilot CLI for the recommended subprocess-driven flow",+ ],+ };+ },++ apply(+ _plan: InstallPlan,+ payload: McpPayload,+ env: InstallEnv,+ opts: ApplyOpts,+ ): ApplyResult {+ let outcome: ApplyOutcome;+ if (activeRunner.available()) {+ const r = opts.dryRun ? { ok: true } : applyViaCli(payload, opts.stderr);+ if (r.ok) {+ outcome = { viaCli: true, fallbackFile: null };+ } else {+ const file = opts.dryRun ? fallbackPath(env) : applyViaFile(env, payload, opts.stderr, false);+ outcome = { viaCli: false, fallbackFile: file };+ }+ } else {+ const file = applyViaFile(env, payload, opts.stderr, opts.dryRun);+ outcome = { viaCli: false, fallbackFile: file };+ }++ const manifest: ManifestEntry = {+ target: TARGET,+ applied_at: env.now.toISOString(),+ operation: outcome.viaCli ? "subprocess" : "json-merge",+ config_path: outcome.fallbackFile,+ fallback_file: outcome.fallbackFile,+ ...(outcome.viaCli+ ? {}+ : { owned_keys: [`mcpServers.${OSB_KEY_FULL}`, `mcpServers.${OSB_KEY_WRITER}`] }),+ };+ if (!opts.dryRun) recordEntry(env.vault, manifest);+ return { target: TARGET, manifest, steps_executed: opts.dryRun ? 0 : 1 };+ },++ uninstall(env: InstallEnv, opts: ApplyOpts & { fromSnippet?: boolean }): UninstallResult {+ const stored = readManifest(env.vault).installs[TARGET];+ const removed_keys: string[] = [];+ const removed_paths: string[] = [];+ const skipped: Array<readonly [string, string]> = [];++ if (!stored && !opts.fromSnippet) {+ throw new InstallError(+ "copilot-cli: no install manifest entry found",+ TARGET,+ "manifest-missing",+ "o2b uninstall --target copilot-cli --apply --force-from-snippet",+ );+ }++ const viaCli = stored?.operation === "subprocess";+ if (viaCli) {+ const { removed } = uninstallViaCli();+ for (const r of removed) removed_keys.push(r);+ } else {+ const { path, touched } = uninstallViaFile(env, opts.dryRun);+ if (touched) {+ removed_keys.push(`mcpServers.${OSB_KEY_FULL}`, `mcpServers.${OSB_KEY_WRITER}`);+ } else {+ skipped.push([path, "fallback file unchanged"]);+ }+ }+ if (!opts.dryRun) removeEntry(env.vault, TARGET);+ return { target: TARGET, removed_keys, removed_paths, skipped };+ },++ verify(env: InstallEnv): VerifyResult {+ const stored = readManifest(env.vault).installs[TARGET];+ if (!stored) {+ return {+ target: TARGET,+ status: "not-installed",+ details: ["no install manifest entry"],+ fix_hint: null,+ };+ }+ if (stored.operation === "subprocess") {+ const lst = activeRunner.list();+ if (!lst.ok) {+ return {+ target: TARGET,+ status: "mcp-unreachable",+ details: ["`copilot mcp list` failed"],+ fix_hint: "ensure copilot CLI is on PATH and authenticated",+ };+ }+ const has = (n: string) => lst.names.includes(n);+ if (has(OSB_KEY_FULL) && has(OSB_KEY_WRITER)) {+ return { target: TARGET, status: "ok", details: ["both OSB names registered with copilot CLI"], fix_hint: null };+ }+ return {+ target: TARGET,+ status: "drift",+ details: [+ `missing: ${[OSB_KEY_FULL, OSB_KEY_WRITER].filter((n) => !has(n)).join(", ")}`,+ ],+ fix_hint: "o2b install --target copilot-cli --apply",+ };+ }+ // file-fallback path+ const path = stored.fallback_file ?? fallbackPath(env);+ if (!existsSync(path)) {+ return {+ target: TARGET,+ status: "drift",+ details: [`fallback file missing: ${path}`],+ fix_hint: "o2b install --target copilot-cli --apply",+ };+ }+ try {+ const parsed = JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;+ const block = (parsed["mcpServers"] ?? {}) as Record<string, unknown>;+ const expected = expectedPayloadFromEnv(env);+ if (+ payloadKeyEquals(block[OSB_KEY_FULL] as Record<string, unknown> | undefined, expected.full) &&+ payloadKeyEquals(block[OSB_KEY_WRITER] as Record<string, unknown> | undefined, expected.writer)+ ) {+ return { target: TARGET, status: "ok", details: [`${path}: both keys present`], fix_hint: null };+ }+ if (block[OSB_KEY_FULL] && block[OSB_KEY_WRITER]) {+ return {+ target: TARGET,+ status: "drift",+ details: [`${path}: OSB keys differ from canonical payload`],+ fix_hint: "o2b install --target copilot-cli --apply",+ };+ }+ return {+ target: TARGET,+ status: "drift",+ details: [`${path}: missing OSB keys`],+ fix_hint: "o2b install --target copilot-cli --apply",+ };+ } catch {+ return {+ target: TARGET,+ status: "drift",+ details: [`${path}: not valid JSON`],+ fix_hint: "o2b install --target copilot-cli --apply",+ };+ }+ },+};++defaultRegistry.register(copilotCliAdapter);diff --git a/src/core/install/adapters/cursor.ts b/src/core/install/adapters/cursor.tsnew file mode 100644index 00000000..80fd4117--- /dev/null+++ b/src/core/install/adapters/cursor.ts@@ -0,0 +1,32 @@+/**+ * Cursor adapter β JSON-merge into `~/.cursor/mcp.json`.+ *+ * Default scope: user-global. Project-scope (`<cwd>/.cursor/mcp.json`)+ * is deferred per the v0.10.11 design doc Β§12.+ *+ * Cursor needs an app-restart to pick up MCP server changes. The+ * `verify` step reports the disk state cleanly; restart is a+ * note rather than a failure.+ */++import { join } from "node:path";++import { createJsonMcpAdapter } from "./_json-mcp.ts";+import { defaultRegistry } from "../registry.ts";+import type { InstallEnv } from "../types.ts";++function configPath(env: InstallEnv): string {+ return join(env.home, ".cursor", "mcp.json");+}++export const cursorAdapter = createJsonMcpAdapter({+ target: "cursor",+ label: "Cursor",+ resolveConfigPath: configPath,+ postNotes: [+ "Restart the Cursor app to load the new MCP servers.",+ ],+ notes: ["scope: user-global (~/.cursor/mcp.json)"],+});++defaultRegistry.register(cursorAdapter);diff --git a/src/core/install/adapters/gemini-cli.ts b/src/core/install/adapters/gemini-cli.tsnew file mode 100644index 00000000..3223618e--- /dev/null+++ b/src/core/install/adapters/gemini-cli.ts@@ -0,0 +1,25 @@+/**+ * Gemini CLI adapter β JSON-merge into `~/.gemini/settings.json` under+ * the `mcpServers` key, per `google-gemini/gemini-cli` MCP docs.+ */++import { join } from "node:path";++import { createJsonMcpAdapter } from "./_json-mcp.ts";+import { defaultRegistry } from "../registry.ts";+import type { InstallEnv } from "../types.ts";++function configPath(env: InstallEnv): string {+ return join(env.home, ".gemini", "settings.json");+}++export const geminiCliAdapter = createJsonMcpAdapter({+ target: "gemini-cli",+ label: "Google Gemini CLI",+ resolveConfigPath: configPath,+ postNotes: [+ "Start `gemini` to load the registered MCP servers.",+ ],+});++defaultRegistry.register(geminiCliAdapter);diff --git a/src/core/install/adapters/generic.ts b/src/core/install/adapters/generic.tsnew file mode 100644index 00000000..5f611446--- /dev/null+++ b/src/core/install/adapters/generic.ts@@ -0,0 +1,180 @@+/**+ * Generic adapter β long-tail fallback.+ *+ * Prints the canonical MCP server payload to stdout or a named file.+ * Never edits any runtime's own config files. The operator is in+ * charge of copying the printed snippet into wherever their runtime+ * expects it.+ *+ * - `detect` always returns `not-installed` (no canonical config to+ * probe for this target).+ * - `apply` writes payload as JSON (default) or YAML.+ * - `uninstall` reports the path the operator wrote to but does not+ * delete it β the consuming runtime may rely on it.+ */++import { writeFileSync } from "node:fs";++import { recordEntry, removeEntry, readManifest } from "../manifest.ts";+import { OSB_KEY_FULL, OSB_KEY_WRITER } from "../json-merge.ts";+import type {+ ApplyOpts,+ ApplyResult,+ DetectResult,+ InstallAdapter,+ InstallEnv,+ InstallPlan,+ ManifestEntry,+ McpPayload,+ McpServerEntry,+ UninstallResult,+ VerifyResult,+} from "../types.ts";+import { defaultRegistry } from "../registry.ts";++const TARGET = "generic";+const LABEL = "Generic (printout)";++function renderJson(payload: McpPayload): string {+ const out = {+ mcpServers: {+ [OSB_KEY_FULL]: serializeEntry(payload.full),+ [OSB_KEY_WRITER]: serializeEntry(payload.writer),+ },+ };+ return JSON.stringify(out, null, 2) + "\n";+}++function renderYaml(payload: McpPayload): string {+ const lines: string[] = ["mcpServers:"];+ for (const [name, entry] of [+ [OSB_KEY_FULL, payload.full],+ [OSB_KEY_WRITER, payload.writer],+ ] as const) {+ lines.push(` ${name}:`);+ lines.push(` command: ${yamlScalar(entry.command)}`);+ lines.push(` args:`);+ for (const a of entry.args) lines.push(` - ${yamlScalar(a)}`);+ if (entry.env && Object.keys(entry.env).length > 0) {+ lines.push(` env:`);+ for (const [k, v] of Object.entries(entry.env)) {+ lines.push(` ${k}: ${yamlScalar(v)}`);+ }+ }+ }+ return lines.join("\n") + "\n";+}++function yamlScalar(s: string): string {+ // Quote when needed (contains special chars or starts/ends with whitespace).+ if (/[:#\[\]\{\}\,&\*!\|>\'"%@`]/.test(s) || /^\s|\s$/.test(s) || /^[\-?!]/.test(s)) {+ return JSON.stringify(s);+ }+ return s;+}++function serializeEntry(e: McpServerEntry): Record<string, unknown> {+ const out: Record<string, unknown> = { command: e.command, args: [...e.args] };+ if (e.env && Object.keys(e.env).length > 0) out["env"] = { ...e.env };+ return out;+}++export const genericAdapter: InstallAdapter = {+ target: TARGET,+ label: LABEL,++ detect(_env: InstallEnv): DetectResult {+ return {+ target: TARGET,+ status: "not-installed",+ configPath: null,+ notes: ["generic: print-only; never edits external config"],+ };+ },++ plan(_payload: McpPayload, _env: InstallEnv): InstallPlan {+ return {+ target: TARGET,+ steps: [+ {+ kind: "print",+ path: null,+ preview: "render OSB MCP payload to stdout or --out <path>",+ },+ ],+ postNotes: [+ "Copy the printed snippet into your runtime's MCP config manually.",+ ],+ };+ },++ apply(+ _plan: InstallPlan,+ payload: McpPayload,+ env: InstallEnv,+ opts: ApplyOpts,+ ): ApplyResult {+ const format = opts.format ?? "json";+ const text = format === "yaml" ? renderYaml(payload) : renderJson(payload);+ const explicitStdout = opts.outPath === "-";+ const outPath = !explicitStdout && opts.outPath ? opts.outPath : null;++ if (opts.dryRun) {+ // Dry-run: don't write file, don't touch stdout β let the CLI layer+ // surface the planned action.+ } else if (outPath !== null) {+ writeFileSync(outPath, text);+ } else {+ opts.stdout.write(text);+ }++ const manifest: ManifestEntry = {+ target: TARGET,+ applied_at: env.now.toISOString(),+ operation: "print",+ config_path: outPath,+ ...(outPath ? { owned_paths: [outPath] } : {}),+ };+ if (!opts.dryRun) recordEntry(env.vault, manifest);++ return { target: TARGET, manifest, steps_executed: opts.dryRun ? 0 : 1 };+ },++ uninstall(env: InstallEnv, _opts: ApplyOpts & { fromSnippet?: boolean }): UninstallResult {+ const m = readManifest(env.vault).installs[TARGET];+ const skipped: Array<readonly [string, string]> = [];+ if (m?.owned_paths?.length) {+ for (const p of m.owned_paths) {+ skipped.push([p, "generic: file left in place; remove manually if no longer needed"]);+ }+ } else {+ skipped.push([+ "(no recorded path)",+ "generic: never wrote to disk; nothing to do",+ ]);+ }+ removeEntry(env.vault, TARGET);+ return { target: TARGET, removed_keys: [], removed_paths: [], skipped };+ },++ verify(env: InstallEnv): VerifyResult {+ const m = readManifest(env.vault).installs[TARGET];+ if (!m || !m.owned_paths?.length) {+ return {+ target: TARGET,+ status: "not-installed",+ details: ["generic: no recorded output path"],+ fix_hint: null,+ };+ }+ // We don't probe the file's runtime β that's outside our scope.+ return {+ target: TARGET,+ status: "ok",+ details: [`generic: payload written to ${m.owned_paths[0]} (runtime wiring is operator-managed)`],+ fix_hint: null,+ };+ },+};++defaultRegistry.register(genericAdapter);diff --git a/src/core/install/adapters/kiro.ts b/src/core/install/adapters/kiro.tsnew file mode 100644index 00000000..230b9aee--- /dev/null+++ b/src/core/install/adapters/kiro.ts@@ -0,0 +1,29 @@+/**+ * kiro adapter β JSON-merge into `~/.kiro/settings.json` under the+ * `mcpServers` key.+ *+ * The exact config-file location is pinned to upstream `kiro.dev` docs+ * at impl time; the resolver below can be widened (per-OS / project-+ * scope) without changing callers.+ */++import { join } from "node:path";++import { createJsonMcpAdapter } from "./_json-mcp.ts";+import { defaultRegistry } from "../registry.ts";+import type { InstallEnv } from "../types.ts";++function configPath(env: InstallEnv): string {+ return join(env.home, ".kiro", "settings.json");+}++export const kiroAdapter = createJsonMcpAdapter({+ target: "kiro",+ label: "kiro",+ resolveConfigPath: configPath,+ postNotes: [+ "Restart kiro to load the new MCP servers.",+ ],+});++defaultRegistry.register(kiroAdapter);diff --git a/src/core/install/adapters/opencode.ts b/src/core/install/adapters/opencode.tsnew file mode 100644index 00000000..89a38caa--- /dev/null+++ b/src/core/install/adapters/opencode.ts@@ -0,0 +1,30 @@+/**+ * opencode adapter β JSON-merge into `~/.config/opencode/mcp.json`.+ *+ * Per upstream `sst/opencode` MCP docs the file lives under+ * `${XDG_CONFIG_HOME:-$HOME/.config}/opencode/mcp.json` and uses the+ * standard `mcpServers` key.+ */++import { join } from "node:path";++import { createJsonMcpAdapter } from "./_json-mcp.ts";+import { defaultRegistry } from "../registry.ts";+import type { InstallEnv } from "../types.ts";++function configPath(env: InstallEnv): string {+ const xdg = env.env["XDG_CONFIG_HOME"];+ const base = xdg && xdg.length > 0 ? xdg : join(env.home, ".config");+ return join(base, "opencode", "mcp.json");+}++export const opencodeAdapter = createJsonMcpAdapter({+ target: "opencode",+ label: "opencode",+ resolveConfigPath: configPath,+ postNotes: [+ "Restart opencode to load the new MCP servers.",+ ],+});++defaultRegistry.register(opencodeAdapter);diff --git a/src/core/install/adapters/pi.ts b/src/core/install/adapters/pi.tsnew file mode 100644index 00000000..bbcc3da0--- /dev/null+++ b/src/core/install/adapters/pi.ts@@ -0,0 +1,262 @@+/**+ * Pi adapter β skill symlink, no MCP.+ *+ * Pi (pi.dev / pi-mono) intentionally chose "CLI-tool + README + skill"+ * over MCP. For OSB this means: drop the `brain-memory` skill into+ * Pi's `~/.pi/skills/` directory as a symlink and let the agent+ * invoke `o2b brain *` CLI commands from there.+ *+ * Plugin-source resolution order:+ * 1. `opts.piSkillSource` (tests)+ * 2. `OSB_PLUGIN_ROOT` env var + `/skills/brain-memory`+ * 3. `import.meta.url` based β walks up to repo root+ *+ * Target-side resolution order:+ * 1. `opts.piSkillDir` β `<piSkillDir>/brain-memory`+ * 2. `PI_HOME` env var β `<PI_HOME>/skills/brain-memory`+ * 3. `~/.pi/skills/brain-memory`+ */++import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import {+ existsSync,+ lstatSync,+ mkdirSync,+ readlinkSync,+ rmSync,+ symlinkSync,+ type Stats,+} from "node:fs";++import {+ InstallError,+ type ApplyOpts,+ type ApplyResult,+ type DetectResult,+ type InstallAdapter,+ type InstallEnv,+ type InstallPlan,+ type ManifestEntry,+ type McpPayload,+ type UninstallResult,+ type VerifyResult,+} from "../types.ts";+import { recordEntry, readManifest, removeEntry } from "../manifest.ts";+import { defaultRegistry } from "../registry.ts";++const TARGET = "pi";+const LABEL = "Pi (pi.dev)";++function repoRoot(): string {+ return resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..");+}++function resolveSourcePath(opts: ApplyOpts): string {+ if (opts.piSkillSource) return opts.piSkillSource;+ const envRoot = process.env["OSB_PLUGIN_ROOT"];+ if (envRoot) return join(envRoot, "skills", "brain-memory");+ return join(repoRoot(), "skills", "brain-memory");+}++function resolveTargetPath(env: InstallEnv, opts: ApplyOpts | { piSkillDir?: string }): string {+ if ("piSkillDir" in opts && opts.piSkillDir) {+ return join(opts.piSkillDir, "brain-memory");+ }+ const piHome = env.env["PI_HOME"];+ const base = piHome && piHome.length > 0 ? piHome : join(env.home, ".pi");+ return join(base, "skills", "brain-memory");+}++function targetPathFromEnvOnly(env: InstallEnv): string {+ const piHome = env.env["PI_HOME"];+ const base = piHome && piHome.length > 0 ? piHome : join(env.home, ".pi");+ return join(base, "skills", "brain-memory");+}++function lstatOrNull(p: string): Stats | null {+ try {+ return lstatSync(p) as Stats;+ } catch {+ return null;+ }+}++function ensureParent(target: string): void {+ const parent = dirname(target);+ if (!existsSync(parent)) mkdirSync(parent, { recursive: true });+}++export const piAdapter: InstallAdapter = {+ target: TARGET,+ label: LABEL,++ detect(env: InstallEnv): DetectResult {+ const path = targetPathFromEnvOnly(env);+ const stat = lstatOrNull(path);+ if (stat === null) {+ return { target: TARGET, status: "not-installed", configPath: path, notes: [] };+ }+ if (!stat.isSymbolicLink()) {+ return {+ target: TARGET,+ status: "drift",+ configPath: path,+ notes: ["path exists but is not a symlink"],+ };+ }+ return { target: TARGET, status: "installed", configPath: path, notes: [] };+ },++ plan(_payload: McpPayload, env: InstallEnv): InstallPlan {+ const target = targetPathFromEnvOnly(env);+ return {+ target: TARGET,+ steps: [+ {+ kind: "symlink",+ path: target,+ preview: `symlink ${target} β <plugin>/skills/brain-memory`,+ },+ ],+ postNotes: [+ "Pi reads skills from its own skills directory; no MCP registration needed.",+ ],+ };+ },++ apply(+ _plan: InstallPlan,+ _payload: McpPayload,+ env: InstallEnv,+ opts: ApplyOpts,+ ): ApplyResult {+ const target = resolveTargetPath(env, opts);+ const source = resolveSourcePath(opts);++ if (!existsSync(source)) {+ throw new InstallError(+ `pi: skill source not found at ${source}; cannot create symlink`,+ TARGET,+ "config-missing",+ "verify the plugin checkout is intact",+ );+ }++ const stat = lstatOrNull(target);+ if (stat) {+ if (stat.isSymbolicLink()) {+ const current = readlinkSync(target);+ if (current === source) {+ // Already the canonical link.+ const manifest = buildManifest(env, target);+ if (!opts.dryRun) recordEntry(env.vault, manifest);+ return { target: TARGET, manifest, steps_executed: 0 };+ }+ // Different link target β replace.+ if (!opts.dryRun) rmSync(target, { force: true });+ } else {+ if (!opts.force) {+ throw new InstallError(+ `pi: target ${target} exists and is not a symlink; refusing to clobber`,+ TARGET,+ "user-modified-block",+ "re-run with --force to overwrite, or move the existing directory aside",+ );+ }+ if (!opts.dryRun) rmSync(target, { recursive: true, force: true });+ }+ }++ if (!opts.dryRun) {+ ensureParent(target);+ symlinkSync(source, target);+ }++ const manifest = buildManifest(env, target);+ if (!opts.dryRun) recordEntry(env.vault, manifest);+ return { target: TARGET, manifest, steps_executed: opts.dryRun ? 0 : 1 };+ },++ uninstall(env: InstallEnv, opts: ApplyOpts & { fromSnippet?: boolean }): UninstallResult {+ const stored = readManifest(env.vault).installs[TARGET];+ const skipped: Array<readonly [string, string]> = [];+ const removed_paths: string[] = [];++ const targets = stored?.owned_paths ?? [];+ if (targets.length === 0 && !opts.fromSnippet) {+ throw new InstallError(+ "pi: no install manifest entry found",+ TARGET,+ "manifest-missing",+ "o2b uninstall --target pi --apply --force-from-snippet",+ );+ }+ const list = targets.length > 0 ? targets : [targetPathFromEnvOnly(env)];++ for (const t of list) {+ const stat = lstatOrNull(t);+ if (!stat) {+ skipped.push([t, "not present"]);+ continue;+ }+ if (!stat.isSymbolicLink()) {+ skipped.push([t, "not a symlink β refusing to remove"]);+ continue;+ }+ if (!opts.dryRun) rmSync(t, { force: true });+ removed_paths.push(t);+ }+ if (!opts.dryRun) removeEntry(env.vault, TARGET);+ return { target: TARGET, removed_keys: [], removed_paths, skipped };+ },++ verify(env: InstallEnv): VerifyResult {+ const stored = readManifest(env.vault).installs[TARGET];+ if (!stored) {+ return {+ target: TARGET,+ status: "not-installed",+ details: ["no install manifest entry"],+ fix_hint: null,+ };+ }+ const path = stored.owned_paths?.[0] ?? targetPathFromEnvOnly(env);+ const stat = lstatOrNull(path);+ if (!stat || !stat.isSymbolicLink()) {+ return {+ target: TARGET,+ status: "drift",+ details: [stat ? `${path} is not a symlink` : `${path} not present`],+ fix_hint: "o2b install --target pi --apply",+ };+ }+ const target = readlinkSync(path);+ if (!existsSync(target)) {+ return {+ target: TARGET,+ status: "drift",+ details: [`${path} β ${target} (target missing)`],+ fix_hint: "o2b install --target pi --apply",+ };+ }+ return {+ target: TARGET,+ status: "ok",+ details: [`${path} β ${target}`],+ fix_hint: null,+ };+ },+};++function buildManifest(env: InstallEnv, target: string): ManifestEntry {+ return {+ target: TARGET,+ applied_at: env.now.toISOString(),+ operation: "symlink",+ config_path: null,+ owned_paths: [target],+ };+}++defaultRegistry.register(piAdapter);diff --git a/src/core/install/json-merge.ts b/src/core/install/json-merge.tsnew file mode 100644index 00000000..97775b04--- /dev/null+++ b/src/core/install/json-merge.ts@@ -0,0 +1,118 @@+/**+ * Safe merge of OSB's two `mcpServers` keys into an existing JSON+ * config file (Cursor, opencode, kiro, Gemini CLI, Copilot CLI fallback).+ *+ * Invariants:+ * - User-authored keys (other than the two OSB names) are preserved+ * byte-for-byte at the JSON-value level. Stringification uses the+ * same indentation detected from the original.+ * - OSB keys land in insertion order at the end of the chosen+ * top-level object (`mcpServers` by default).+ * - Empty / whitespace-only input yields a minimal valid document.+ * - Malformed JSON throws `JsonMergeError` with the original parse+ * error attached.+ */++import type { McpPayload, McpServerEntry } from "./types.ts";++export class JsonMergeError extends Error {+ constructor(+ message: string,+ public override readonly cause?: unknown,+ ) {+ super(message);+ this.name = "JsonMergeError";+ }+}++export const OSB_KEY_FULL = "open-second-brain";+export const OSB_KEY_WRITER = "open-second-brain-writer";+const DEFAULT_TOP_KEY = "mcpServers";++export interface MergeOpts {+ /** Top-level object key under which MCP servers live. Default `mcpServers`. */+ readonly topLevelKey?: string;+}++export function mergeMcpServers(+ current: string,+ payload: McpPayload,+ opts: MergeOpts = {},+): string {+ const topKey = opts.topLevelKey ?? DEFAULT_TOP_KEY;+ const trimmed = current.trim();+ const root: Record<string, unknown> = trimmed.length === 0 ? {} : parseJson(current);++ const existing = root[topKey];+ const block: Record<string, unknown> =+ existing && typeof existing === "object" && !Array.isArray(existing)+ ? { ...(existing as Record<string, unknown>) }+ : {};++ // Preserve insertion order: user keys first (without our two), then ours.+ delete block[OSB_KEY_FULL];+ delete block[OSB_KEY_WRITER];+ block[OSB_KEY_FULL] = serializeEntry(payload.full);+ block[OSB_KEY_WRITER] = serializeEntry(payload.writer);++ root[topKey] = block;++ const indent = detectIndent(current) ?? 2;+ return JSON.stringify(root, null, indent) + "\n";+}++export function removeMcpServers(current: string, opts: MergeOpts = {}): string {+ const topKey = opts.topLevelKey ?? DEFAULT_TOP_KEY;+ if (current.trim().length === 0) return current;+ const root = parseJson(current);+ const existing = root[topKey];+ if (existing && typeof existing === "object" && !Array.isArray(existing)) {+ const block = { ...(existing as Record<string, unknown>) };+ delete block[OSB_KEY_FULL];+ delete block[OSB_KEY_WRITER];+ root[topKey] = block;+ }+ const indent = detectIndent(current) ?? 2;+ return JSON.stringify(root, null, indent) + "\n";+}++function parseJson(text: string): Record<string, unknown> {+ // Strip a leading UTF-8 BOM if the editor saved one. `JSON.parse` does+ // not accept BOM at the head of input β silently dropping it lets the+ // adapter survive files saved by Windows-side editors.+ const stripped = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;+ try {+ const parsed = JSON.parse(stripped);+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {+ throw new JsonMergeError("expected JSON object at root, got " + typeof parsed);+ }+ return parsed as Record<string, unknown>;+ } catch (e) {+ if (e instanceof JsonMergeError) throw e;+ throw new JsonMergeError("failed to parse JSON: " + (e as Error).message, e);+ }+}++function serializeEntry(e: McpServerEntry): Record<string, unknown> {+ const out: Record<string, unknown> = {+ command: e.command,+ args: [...e.args],+ };+ if (e.env && Object.keys(e.env).length > 0) {+ out["env"] = { ...e.env };+ }+ return out;+}++/**+ * Best-effort indent detection. Looks at the first indented JSON line.+ * Returns the indent width in spaces, or `null` if not detectable.+ */+function detectIndent(text: string): number | null {+ const lines = text.split("\n");+ for (const line of lines) {+ const m = /^( +)\S/.exec(line);+ if (m) return m[1]!.length;+ }+ return null;+}diff --git a/src/core/install/managed-block.ts b/src/core/install/managed-block.tsnew file mode 100644index 00000000..a3ff1598--- /dev/null+++ b/src/core/install/managed-block.ts@@ -0,0 +1,200 @@+/**+ * Marker-fenced managed block editor for text-format configs.+ *+ * Used by Aider (managed block inside YAML) and any text-fallback+ * adapter. Mirrors the convention already in `o2b brain protect`:+ * a block fenced by `# >>> open-second-brain managed >>>` /+ * `# <<< open-second-brain managed <<<` is the unit of overwrite;+ * everything outside is preserved byte-for-byte.+ *+ * Markers are parametrised so different adapters can use different+ * comment styles if needed (e.g. `// >>>` for JS-style configs).+ */++export class ManagedBlockError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "ManagedBlockError";+ }+}++export const DEFAULT_BEGIN_MARKER = "# >>> open-second-brain managed >>>";+export const DEFAULT_END_MARKER = "# <<< open-second-brain managed <<<";++export interface BlockOpts {+ readonly beginMarker?: string;+ readonly endMarker?: string;+}++interface ResolvedOpts {+ readonly begin: string;+ readonly end: string;+}++function resolve(opts: BlockOpts): ResolvedOpts {+ return {+ begin: opts.beginMarker ?? DEFAULT_BEGIN_MARKER,+ end: opts.endMarker ?? DEFAULT_END_MARKER,+ };+}++interface LineMatches {+ readonly beginIdxs: number[];+ readonly endIdxs: number[];+}++function findMarkers(lines: ReadonlyArray<string>, opts: ResolvedOpts): LineMatches {+ const beginIdxs: number[] = [];+ const endIdxs: number[] = [];+ for (let i = 0; i < lines.length; i++) {+ if (lines[i] === opts.begin) beginIdxs.push(i);+ if (lines[i] === opts.end) endIdxs.push(i);+ }+ return { beginIdxs, endIdxs };+}++function validateMarkers(matches: LineMatches): void {+ const { beginIdxs, endIdxs } = matches;+ if (beginIdxs.length > 1) {+ throw new ManagedBlockError("multiple begin markers found; refusing to overwrite");+ }+ if (endIdxs.length > 1) {+ throw new ManagedBlockError("multiple end markers found; refusing to overwrite");+ }+ if (beginIdxs.length === 1 && endIdxs.length === 0) {+ throw new ManagedBlockError("begin marker without matching end; refusing to overwrite");+ }+ if (beginIdxs.length === 0 && endIdxs.length === 1) {+ throw new ManagedBlockError("end marker without matching begin; refusing to overwrite");+ }+ if (beginIdxs.length === 1 && endIdxs.length === 1 && endIdxs[0]! < beginIdxs[0]!) {+ throw new ManagedBlockError("end marker appears before begin marker; refusing to overwrite");+ }+}++interface LineEnding {+ readonly newline: string;+ readonly trailing: boolean;+}++function detectLineEnding(text: string): LineEnding {+ const trailing = text.length > 0 && (text.endsWith("\n") || text.endsWith("\r\n"));+ if (text.includes("\r\n")) return { newline: "\r\n", trailing };+ return { newline: "\n", trailing };+}++function splitLines(text: string): string[] {+ if (text.length === 0) return [];+ // Normalise CRLF to LF for processing; we'll restore on join.+ const normalised = text.replace(/\r\n/g, "\n");+ const lines = normalised.split("\n");+ // If the source had a trailing newline, the final split entry is an empty+ // string. Drop it; we restore the trailing newline on output.+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();+ return lines;+}++function join(lines: ReadonlyArray<string>, ending: LineEnding): string {+ return lines.join(ending.newline) + (ending.trailing ? ending.newline : "");+}++/**+ * Insert or replace the managed block. Idempotent: re-applying with+ * the same body yields byte-equal output.+ */+export function insertManagedBlock(+ current: string,+ body: string,+ opts: BlockOpts = {},+): string {+ const resolved = resolve(opts);+ const ending = detectLineEnding(current);+ const lines = splitLines(current);+ const matches = findMarkers(lines, resolved);+ validateMarkers(matches);++ // Normalise the body lines so the output is deterministic.+ const bodyLines = splitLines(body);++ let nextLines: string[];+ if (matches.beginIdxs.length === 1 && matches.endIdxs.length === 1) {+ nextLines = [+ ...lines.slice(0, matches.beginIdxs[0]!),+ resolved.begin,+ ...bodyLines,+ resolved.end,+ ...lines.slice(matches.endIdxs[0]! + 1),+ ];+ } else {+ // Append; ensure one blank line separating user content from our block+ // when the prior content didn't already end empty.+ const sep = lines.length > 0 && lines[lines.length - 1] !== "" ? [""] : [];+ nextLines = [+ ...lines,+ ...sep,+ resolved.begin,+ ...bodyLines,+ resolved.end,+ ];+ }++ return join(nextLines, { newline: ending.newline, trailing: true });+}++/**+ * Remove the managed block (and its markers). Collapses surrounding+ * blank lines so the file doesn't grow vertical whitespace on repeat+ * install/uninstall cycles.+ */+export function removeManagedBlock(current: string, opts: BlockOpts = {}): string {+ const resolved = resolve(opts);+ const ending = detectLineEnding(current);+ const lines = splitLines(current);+ const matches = findMarkers(lines, resolved);+ if (matches.beginIdxs.length === 0 && matches.endIdxs.length === 0) {+ return current;+ }+ validateMarkers(matches);++ const begin = matches.beginIdxs[0]!;+ const end = matches.endIdxs[0]!;+ const before = lines.slice(0, begin);+ const after = lines.slice(end + 1);++ // Collapse blank-line padding: trailing blanks on `before` + leading+ // blanks on `after` collapse to one separator (or nothing if either+ // side is empty).+ while (before.length > 0 && before[before.length - 1] === "") before.pop();+ while (after.length > 0 && after[0] === "") after.shift();++ let nextLines: string[];+ if (before.length === 0 && after.length === 0) {+ nextLines = [];+ } else if (before.length === 0) {+ nextLines = after;+ } else if (after.length === 0) {+ nextLines = before;+ } else {+ nextLines = [...before, "", ...after];+ }++ return join(nextLines, { newline: ending.newline, trailing: ending.trailing });+}++export function hasManagedBlock(current: string, opts: BlockOpts = {}): boolean {+ const resolved = resolve(opts);+ const lines = splitLines(current);+ const { beginIdxs, endIdxs } = findMarkers(lines, resolved);+ return beginIdxs.length === 1 && endIdxs.length === 1 && endIdxs[0]! > beginIdxs[0]!;+}++export function extractManagedBlock(current: string, opts: BlockOpts = {}): string | null {+ const resolved = resolve(opts);+ const lines = splitLines(current);+ const { beginIdxs, endIdxs } = findMarkers(lines, resolved);+ if (beginIdxs.length !== 1 || endIdxs.length !== 1) return null;+ const begin = beginIdxs[0]!;+ const end = endIdxs[0]!;+ if (end <= begin) return null;+ return lines.slice(begin + 1, end).join("\n");+}diff --git a/src/core/install/manifest.ts b/src/core/install/manifest.tsnew file mode 100644index 00000000..607ffc42--- /dev/null+++ b/src/core/install/manifest.ts@@ -0,0 +1,99 @@+/**+ * Sidecar manifest I/O for install adapters.+ *+ * Records exactly what each install wrote to disk, so `uninstall`+ * removes only OSB-owned content and never user-authored config.+ * One file per vault at `<vault>/.open-second-brain/install.lock.json`.+ *+ * Schema (`schema_version: 1`):+ *+ * ```+ * {+ * "schema_version": 1,+ * "installs": {+ * "<target>": { ...ManifestEntry }+ * }+ * }+ * ```+ *+ * Unknown top-level keys are tolerated (forward-compat). Unknown+ * `schema_version` is a hard error β refuse to read.+ */++import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { dirname, join } from "node:path";++import { atomicWriteFileSync } from "../fs-atomic.ts";+import type { ManifestEntry } from "./types.ts";++const SUPPORTED_SCHEMA_VERSIONS = new Set<number>([1]);++export interface Manifest {+ readonly schema_version: 1;+ readonly installs: Record<string, ManifestEntry>;+}++export function manifestPath(vault: string): string {+ return join(vault, ".open-second-brain", "install.lock.json");+}++export function readManifest(vault: string): Manifest {+ const path = manifestPath(vault);+ if (!existsSync(path)) {+ return { schema_version: 1, installs: {} };+ }+ const raw = readFileSync(path, "utf8");+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (e) {+ throw new Error(+ `install manifest is corrupted JSON: ${path}\n` ++ `Original error: ${(e as Error).message}`,+ );+ }+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {+ throw new Error(`install manifest is not an object: ${path}`);+ }+ const obj = parsed as Record<string, unknown>;+ const sv = obj["schema_version"];+ if (typeof sv !== "number" || !SUPPORTED_SCHEMA_VERSIONS.has(sv)) {+ throw new Error(+ `install manifest schema_version ${sv} not supported (expected one of ${Array.from(SUPPORTED_SCHEMA_VERSIONS).join(", ")}): ${path}`,+ );+ }+ const installs = (obj["installs"] ?? {}) as Record<string, ManifestEntry>;+ return { schema_version: 1, installs };+}++export function recordEntry(vault: string, entry: ManifestEntry): void {+ const current = readManifest(vault);+ const next: Manifest = {+ schema_version: 1,+ installs: { ...current.installs, [entry.target]: entry },+ };+ writeManifest(vault, next);+}++export function removeEntry(vault: string, target: string): void {+ const current = readManifest(vault);+ if (!(target in current.installs)) return;+ const installs = { ...current.installs };+ delete installs[target];+ writeManifest(vault, { schema_version: 1, installs });+}++function writeManifest(vault: string, m: Manifest): void {+ const path = manifestPath(vault);+ // ensureDir is handled by atomicWriteFileSync via mkdirSync β but the+ // helper does not create the parent. Call mkdir explicitly.+ const dir = dirname(path);+ ensureDir(dir);+ const json = JSON.stringify(m, null, 2) + "\n";+ atomicWriteFileSync(path, json);+}++function ensureDir(dir: string): void {+ if (existsSync(dir)) return;+ mkdirSync(dir, { recursive: true });+}diff --git a/src/core/install/payload-equals.ts b/src/core/install/payload-equals.tsnew file mode 100644index 00000000..b99d6cb4--- /dev/null+++ b/src/core/install/payload-equals.ts@@ -0,0 +1,37 @@+import { buildPayload } from "./payload.ts";+import type { InstallEnv, McpPayload, McpServerEntry } from "./types.ts";++export function expectedPayloadFromEnv(env: InstallEnv): McpPayload {+ return buildPayload({+ vault: env.vault,+ agent_name: env.env["VAULT_AGENT_NAME"] ?? null,+ timezone: env.env["VAULT_TIMEZONE"] ?? null,+ });+}++export function payloadKeyEquals(+ current: Record<string, unknown> | undefined,+ expected: McpServerEntry,+): boolean {+ if (!current) return false;+ if (current["command"] !== expected.command) return false;+ const args = current["args"];+ if (!Array.isArray(args) || args.length !== expected.args.length) return false;+ for (let i = 0; i < args.length; i++) {+ if (args[i] !== expected.args[i]) return false;+ }+ const env = current["env"];+ if (expected.env) {+ if (!env || typeof env !== "object") return false;+ const e = env as Record<string, unknown>;+ const expectedKeys = Object.keys(expected.env).sort();+ const actualKeys = Object.keys(e).sort();+ if (expectedKeys.length !== actualKeys.length) return false;+ for (const k of expectedKeys) {+ if (e[k] !== expected.env[k]) return false;+ }+ } else if (env !== undefined) {+ return false;+ }+ return true;+}diff --git a/src/core/install/payload.ts b/src/core/install/payload.tsnew file mode 100644index 00000000..321a254f--- /dev/null+++ b/src/core/install/payload.ts@@ -0,0 +1,51 @@+/**+ * Canonical MCP server payload builder.+ *+ * Pure function: given the plugin config (vault + identity), return the+ * two `McpServerEntry` objects that every adapter writes verbatim.+ * Same input β byte-identical output; this is what lets `--apply`+ * be idempotent and `verify` detect drift via re-construction rather+ * than a stored hash.+ */++import type { McpPayload, McpServerEntry } from "./types.ts";++export class PayloadError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "PayloadError";+ }+}++export interface PayloadConfig {+ readonly vault: string;+ readonly agent_name: string | null;+ readonly timezone: string | null;+}++const COMMAND = "o2b";++export function buildPayload(cfg: PayloadConfig): McpPayload {+ if (!cfg.vault || typeof cfg.vault !== "string") {+ throw new PayloadError("buildPayload: vault is required");+ }+ const env = buildEnv(cfg);+ const full: McpServerEntry = {+ command: COMMAND,+ args: ["mcp", "--vault", cfg.vault],+ ...(env ? { env } : {}),+ };+ const writer: McpServerEntry = {+ command: COMMAND,+ args: ["mcp", "--writer-only", "--vault", cfg.vault],+ ...(env ? { env } : {}),+ };+ return { full, writer };+}++function buildEnv(cfg: PayloadConfig): Record<string, string> | undefined {+ const env: Record<string, string> = {};+ if (cfg.agent_name) env["VAULT_AGENT_NAME"] = cfg.agent_name;+ if (cfg.timezone) env["VAULT_TIMEZONE"] = cfg.timezone;+ return Object.keys(env).length > 0 ? env : undefined;+}diff --git a/src/core/install/registry.ts b/src/core/install/registry.tsnew file mode 100644index 00000000..d1fe7c16--- /dev/null+++ b/src/core/install/registry.ts@@ -0,0 +1,50 @@+/**+ * Adapter registry for the install orchestrator.+ *+ * The default registry is populated by each adapter file at import time+ * (`defaultRegistry.register(cursorAdapter)`). Tests get isolated+ * registries via `createRegistry()` so adapter registration doesn't+ * leak across cases.+ */++import type {+ DetectResult,+ InstallAdapter,+ InstallEnv,+} from "./types.ts";++export interface Registry {+ register(adapter: InstallAdapter): void;+ get(target: string): InstallAdapter | undefined;+ list(): ReadonlyArray<InstallAdapter>;+ targets(): ReadonlyArray<string>;+ detectAll(env: InstallEnv): ReadonlyArray<DetectResult>;+}++export function createRegistry(): Registry {+ const order: string[] = [];+ const byTarget = new Map<string, InstallAdapter>();+ return {+ register(adapter) {+ if (byTarget.has(adapter.target)) {+ throw new Error(`duplicate adapter registration for target "${adapter.target}"`);+ }+ byTarget.set(adapter.target, adapter);+ order.push(adapter.target);+ },+ get(target) {+ return byTarget.get(target);+ },+ list() {+ return order.map((t) => byTarget.get(t)!) as ReadonlyArray<InstallAdapter>;+ },+ targets() {+ return [...order];+ },+ detectAll(env) {+ return order.map((t) => byTarget.get(t)!.detect(env));+ },+ };+}++export const defaultRegistry = createRegistry();diff --git a/src/core/install/types.ts b/src/core/install/types.tsnew file mode 100644index 00000000..58f28f5a--- /dev/null+++ b/src/core/install/types.ts@@ -0,0 +1,167 @@+/**+ * Shared types for the multi-runtime install orchestrator (v0.10.11).+ *+ * One `InstallAdapter` interface drives `o2b install`, `o2b uninstall`,+ * `o2b install --check`, and `o2b init --interactive`. Per-runtime+ * adapters live in `./adapters/<name>.ts` and each register+ * themselves into the default registry on import.+ *+ * See `docs/plans/2026-05-20-multi-runtime-install-design.md` Β§2.2 for+ * field semantics.+ */++// ---------- Constant sets (runtime checkable) ----------++export const ADAPTER_STATUSES = new Set([+ "not-installed",+ "installed",+ "drift",+ "unsupported-on-this-platform",+] as const);+export type AdapterStatus = typeof ADAPTER_STATUSES extends Set<infer U> ? U : never;++export const INSTALL_STEP_KINDS = new Set([+ "json-merge",+ "managed-block",+ "subprocess",+ "file-copy",+ "symlink",+ "print",+] as const);+export type InstallStepKind = typeof INSTALL_STEP_KINDS extends Set<infer U> ? U : never;++export const VERIFY_STATUSES = new Set([+ "ok",+ "drift",+ "not-installed",+ "mcp-unreachable",+] as const);+export type VerifyStatus = typeof VERIFY_STATUSES extends Set<infer U> ? U : never;++// ---------- MCP payload (canonical entries that adapters write) ----------++export interface McpServerEntry {+ readonly command: string;+ readonly args: ReadonlyArray<string>;+ readonly env?: Readonly<Record<string, string>>;+}++export interface McpPayload {+ readonly full: McpServerEntry;+ readonly writer: McpServerEntry;+}++// ---------- Adapter call surface ----------++export interface InstallEnv {+ readonly vault: string;+ readonly home: string;+ readonly cwd: string;+ readonly env: Readonly<Record<string, string>>;+ readonly now: Date;+}++export interface DetectResult {+ readonly target: string;+ readonly status: AdapterStatus;+ readonly configPath: string | null;+ readonly notes: ReadonlyArray<string>;+}++export interface InstallStep {+ readonly kind: InstallStepKind;+ readonly path: string | null;+ readonly preview: string;+}++export interface InstallPlan {+ readonly target: string;+ readonly steps: ReadonlyArray<InstallStep>;+ readonly postNotes: ReadonlyArray<string>;+}++export interface ApplyOpts {+ readonly dryRun: boolean;+ readonly force: boolean;+ readonly stdout: NodeJS.WriteStream | NodeJS.WritableStream;+ readonly stderr: NodeJS.WriteStream | NodeJS.WritableStream;+ /** Generic adapter: output file path. "-" or undefined β stdout. */+ readonly outPath?: string;+ /** Generic adapter: render format. Default "json". */+ readonly format?: "json" | "yaml";+ /** Pi adapter: override `~/.pi/skills/` location. */+ readonly piSkillDir?: string;+ /** Pi adapter: override the source skill directory used as symlink target. */+ readonly piSkillSource?: string;+ /** Aider adapter: override the generated context file path. */+ readonly aiderContextPath?: string;+}++export interface ManifestEntry {+ readonly target: string;+ readonly applied_at: string;+ readonly operation: InstallStepKind;+ readonly config_path: string | null;+ readonly owned_keys?: ReadonlyArray<string>;+ readonly owned_paths?: ReadonlyArray<string>;+ readonly owned_block_marker?: string;+ readonly fallback_file?: string | null;+}++export interface ApplyResult {+ readonly target: string;+ readonly manifest: ManifestEntry;+ readonly steps_executed: number;+}++export interface UninstallResult {+ readonly target: string;+ readonly removed_keys: ReadonlyArray<string>;+ readonly removed_paths: ReadonlyArray<string>;+ readonly skipped: ReadonlyArray<readonly [string, string]>;+}++export interface VerifyResult {+ readonly target: string;+ readonly status: VerifyStatus;+ readonly details: ReadonlyArray<string>;+ readonly fix_hint: string | null;+}++export interface SessionPathsResult {+ readonly target: string;+ readonly paths: ReadonlyArray<string>;+ readonly format: "claude-jsonl" | "codex-json" | "cursor-sqlite" | "unknown";+}++export interface InstallAdapter {+ readonly target: string;+ readonly label: string;+ detect(env: InstallEnv): DetectResult;+ plan(payload: McpPayload, env: InstallEnv): InstallPlan;+ apply(plan: InstallPlan, payload: McpPayload, env: InstallEnv, opts: ApplyOpts): ApplyResult;+ uninstall(env: InstallEnv, opts: ApplyOpts & { fromSnippet?: boolean }): UninstallResult;+ verify(env: InstallEnv): VerifyResult;+ sessionPaths?(env: InstallEnv): SessionPathsResult | null;+}++// ---------- Errors ----------++export class InstallError extends Error {+ constructor(+ message: string,+ public readonly target: string,+ public readonly kind:+ | "manifest-missing"+ | "user-modified-block"+ | "config-parse"+ | "subprocess-failed"+ | "config-missing"+ | "platform-unsupported"+ | "other",+ public readonly hint?: string,+ ) {+ super(message);+ this.name = "InstallError";+ }+}diff --git a/templates/install/aider-context.md.tmpl b/templates/install/aider-context.md.tmplnew file mode 100644index 00000000..5bb3857e--- /dev/null+++ b/templates/install/aider-context.md.tmpl@@ -0,0 +1,38 @@+# Open Second Brain β agent context for Aider++You have access to an Open Second Brain vault rooted at `{{VAULT}}`. The+vault holds an observing-memory layer at `{{VAULT}}/Brain/` with your+active preferences, log, and recent retire events.++You run as identity `@{{AGENT_NAME}}`.++## When to write to Brain++You cannot call Brain MCP tools from Aider β Aider has no MCP client at+the time this context was generated. Use the `o2b` CLI on PATH:++- `o2b brain feedback --topic <slug> --signal positive|negative \+ --principle "..." [--scope writing|coding|...]` when the user+ expresses a rule that should outlast the current task.+- `o2b brain apply-evidence --preference <pref-id> --artifact "[[path]]" \+ --result applied|violated|outdated` after producing a durable+ artifact that touches an active preference.+- `o2b brain note --text "..."` for durable narrative milestones that+ fit neither category (release shipped, PR merged, fact discovered).++## Read access++- `o2b brain query --preference <id>` β fetch one preference by id.+- `o2b brain query --topic <slug>` β fetch preferences by topic.+- `o2b brain digest` β read the latest activity digest.+- The file `{{VAULT}}/Brain/active.md` is the authoritative list of+ active preferences and the Most-applied window.++## Sanity checks++- `o2b brain doctor` β runs schema + invariant lints over `Brain/`.+- `o2b install --check --target aider` β verifies that this Aider+ install is recognised by OSB.++This file is regenerated on every `o2b install --target aider --apply`.+Do not hand-edit; changes will be overwritten.diff --git a/tests/cli/init-interactive.test.ts b/tests/cli/init-interactive.test.tsnew file mode 100644index 00000000..86318035--- /dev/null+++ b/tests/cli/init-interactive.test.ts@@ -0,0 +1,173 @@+/**+ * `o2b init --interactive` β wizard tests.+ *+ * The wizard composes existing commands via an injected runner; we+ * verify the command sequence under scripted user input.+ */++import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Writable } from "node:stream";++import {+ runWizard,+ type WizardOpts,+ type WizardReader,+ type WizardRunner,+} from "../../src/cli/install/init-interactive.ts";++let home: string;++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), "osb-wizard-h-"));+});+afterEach(() => {+ try { rmSync(home, { recursive: true, force: true }); } catch {}+});++function scriptedReader(answers: string[]): WizardReader {+ let i = 0;+ return {+ async read() {+ if (i >= answers.length) return null;+ const a = answers[i]!;+ i += 1;+ return a;+ },+ };+}++function silentStreams() {+ const stdoutBuf: string[] = [];+ const stderrBuf: string[] = [];+ const stdout = new Writable({+ write(chunk, _e, cb) { stdoutBuf.push(chunk.toString()); cb(); },+ });+ const stderr = new Writable({+ write(chunk, _e, cb) { stderrBuf.push(chunk.toString()); cb(); },+ });+ return {+ stdout: stdout as unknown as NodeJS.WriteStream,+ stderr: stderr as unknown as NodeJS.WriteStream,+ stdoutBuf,+ stderrBuf,+ };+}++function recordingRunner(): { runner: WizardRunner; calls: string[][] } {+ const calls: string[][] = [];+ const runner: WizardRunner = async (cmd) => {+ calls.push([...cmd]);+ return { exitCode: 0, stdout: "", stderr: "" };+ };+ return { runner, calls };+}++describe("init wizard", () => {+ test("happy path: confirm yes runs init + brain init + per-target installs", async () => {+ const vaultPath = join(home, "vault");+ // ensure no candidate vault directory exists, so prompt 1 needs explicit path+ const answers = [+ vaultPath, // vault path+ "claude-vps", // agent name+ "UTC", // timezone+ "en", // language+ "1,2", // pick targets 1 and 2 (whichever they are)+ "y", // brain init+ "n", // starter+ "yes", // confirm+ ];+ const { runner, calls } = recordingRunner();+ const { stdout, stderr } = silentStreams();+ const opts: WizardOpts = {+ reader: scriptedReader(answers), stdout, stderr, runner,+ };+ const r = await runWizard(opts);+ expect(r.exitCode).toBe(0);+ const argv0s = calls.map((c) => c[0]);+ expect(argv0s).toContain("init");+ expect(argv0s).toContain("brain");+ expect(argv0s).toContain("install");+ // First call must be `o2b init --vault ... --agent-name ... --timezone ...`+ const initCall = calls.find((c) => c[0] === "init")!;+ expect(initCall).toContain("--vault");+ expect(initCall).toContain("--agent-name");+ expect(initCall).toContain("--timezone");+ expect(initCall).toContain("claude-vps");+ expect(initCall).toContain("UTC");+ // Final call must be `o2b install --check`+ expect(calls[calls.length - 1]).toEqual(["install", "--check"]);+ });++ test("'no' at confirmation runs nothing", async () => {+ const vaultPath = join(home, "vault");+ const answers = [+ vaultPath, "claude-vps", "UTC", "en",+ "none", // no targets+ "n", // no brain init+ "no", // do not confirm+ ];+ const { runner, calls } = recordingRunner();+ const { stdout, stderr } = silentStreams();+ const opts: WizardOpts = {+ reader: scriptedReader(answers), stdout, stderr, runner,+ };+ const r = await runWizard(opts);+ expect(r.exitCode).toBe(0);+ expect(calls.length).toBe(0);+ });++ test("invalid tz prompts for retry until valid", async () => {+ const vaultPath = join(home, "vault");+ const answers = [+ vaultPath,+ "claude-vps",+ "Mars/Cydonia", // invalid IANA+ "Europe/Belgrade", // valid retry+ "en",+ "none",+ "n",+ "no",+ ];+ const { runner, calls } = recordingRunner();+ const { stdout, stderr, stdoutBuf } = silentStreams();+ const opts: WizardOpts = {+ reader: scriptedReader(answers), stdout, stderr, runner,+ };+ const r = await runWizard(opts);+ expect(r.exitCode).toBe(0);+ expect(stdoutBuf.join("")).toContain("invalid IANA");+ expect(calls.length).toBe(0);+ });++ test("brain init with starter adds --starter flag", async () => {+ const vaultPath = join(home, "vault");+ const answers = [+ vaultPath, "claude-vps", "UTC", "en",+ "none", "y", "y", "yes",+ ];+ const { runner, calls } = recordingRunner();+ const { stdout, stderr } = silentStreams();+ const opts: WizardOpts = {+ reader: scriptedReader(answers), stdout, stderr, runner,+ };+ const r = await runWizard(opts);+ expect(r.exitCode).toBe(0);+ const brainCall = calls.find((c) => c[0] === "brain" && c[1] === "init")!;+ expect(brainCall).toContain("--starter");+ });++ test("runner failure surfaces non-zero exit code", async () => {+ const vaultPath = join(home, "vault");+ const answers = [vaultPath, "claude-vps", "UTC", "en", "none", "n", "yes"];+ const runner: WizardRunner = async () => ({ exitCode: 1, stdout: "", stderr: "init failed" });+ const { stdout, stderr } = silentStreams();+ const opts: WizardOpts = {+ reader: scriptedReader(answers), stdout, stderr, runner,+ };+ const r = await runWizard(opts);+ expect(r.exitCode).toBe(1);+ });+});diff --git a/tests/cli/install-verb.test.ts b/tests/cli/install-verb.test.tsnew file mode 100644index 00000000..bebae3c2--- /dev/null+++ b/tests/cli/install-verb.test.ts@@ -0,0 +1,203 @@+/**+ * `o2b install` CLI verb β subprocess-level tests.+ *+ * The adapter modules each have direct unit tests; here we verify+ * the verb wiring: detect-only printout, plan-only mode, --apply,+ * --check, --json, exit codes.+ */++import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync, utimesSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let vault: string;+let home: string;+let configPath: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-install-verb-v-"));+ home = mkdtempSync(join(tmpdir(), "osb-install-verb-h-"));+ configPath = join(home, "config.yaml");+ writeFileSync(+ configPath,+ `vault: "${vault}"\nagent_name: "claude-vps"\ntimezone: "UTC"\n`,+ );+});+afterEach(() => {+ for (const p of [vault, home]) {+ try { rmSync(p, { recursive: true, force: true }); } catch {}+ }+});++function envBase(extra: Record<string, string> = {}) {+ return {+ HOME: home,+ OPEN_SECOND_BRAIN_CONFIG: configPath,+ VAULT_DIR: vault,+ VAULT_AGENT_NAME: "claude-vps",+ VAULT_TIMEZONE: "UTC",+ ...extra,+ };+}++describe("o2b install β detect mode", () => {+ test("no args prints the table with no file writes", async () => {+ const r = await runCli(["install"], { env: envBase() });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("detected runtimes");+ // No file should have been written+ expect(existsSync(join(home, ".cursor", "mcp.json"))).toBe(false);+ });++ test("--json emits machine-readable payload", async () => {+ const r = await runCli(["install", "--json"], { env: envBase() });+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.schema_version).toBe(1);+ expect(Array.isArray(parsed.targets)).toBe(true);+ expect(parsed.targets.length).toBeGreaterThan(0);+ });+});++describe("o2b install --target X (plan-only)", () => {+ test("prints plan without touching the file system", async () => {+ const r = await runCli(["install", "--target", "cursor"], { env: envBase() });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("plan");+ expect(r.stdout).toContain("json-merge");+ expect(existsSync(join(home, ".cursor", "mcp.json"))).toBe(false);+ });++ test("--target unknown exits 2", async () => {+ const r = await runCli(["install", "--target", "nope"], { env: envBase() });+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("unknown --target");+ });+});++describe("o2b install --target X --apply", () => {+ test("writes the cursor config file", async () => {+ const r = await runCli(+ ["install", "--target", "cursor", "--apply"],+ { env: envBase() },+ );+ expect(r.returncode).toBe(0);+ const cfgPath = join(home, ".cursor", "mcp.json");+ expect(existsSync(cfgPath)).toBe(true);+ const parsed = JSON.parse(readFileSync(cfgPath, "utf8"));+ expect(parsed.mcpServers["open-second-brain"]).toBeDefined();+ expect(parsed.mcpServers["open-second-brain-writer"]).toBeDefined();+ });++ test("user hand-edit + re-apply without --force exits 4", async () => {+ await runCli(["install", "--target", "cursor", "--apply"], { env: envBase() });+ const cfgPath = join(home, ".cursor", "mcp.json");+ const before = JSON.parse(readFileSync(cfgPath, "utf8"));+ before.mcpServers["open-second-brain"] = { command: "TAMPERED", args: [] };+ writeFileSync(cfgPath, JSON.stringify(before, null, 2) + "\n");+ // bump mtime well into the future+ const future = new Date(Date.now() + 3600 * 1000);+ utimesSync(cfgPath, future, future);++ const r = await runCli(["install", "--target", "cursor", "--apply"], { env: envBase() });+ expect(r.returncode).toBe(4);+ expect(r.stderr).toContain("hand-edited");+ });+});++describe("o2b install --target generic", () => {+ test("--out <path> writes the JSON payload to that path", async () => {+ const outPath = join(home, "snippet.json");+ const r = await runCli(+ ["install", "--target", "generic", "--apply", "--out", outPath],+ { env: envBase() },+ );+ expect(r.returncode).toBe(0);+ expect(existsSync(outPath)).toBe(true);+ const parsed = JSON.parse(readFileSync(outPath, "utf8"));+ expect(parsed.mcpServers["open-second-brain"]).toBeDefined();+ });++ test("--format yaml emits YAML to stdout", async () => {+ const r = await runCli(+ ["install", "--target", "generic", "--apply", "--out", "-", "--format", "yaml"],+ { env: envBase() },+ );+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("mcpServers:");+ });+});++describe("o2b install --check", () => {+ test("with no installs, exits 0 with 'not-installed' rows", async () => {+ const r = await runCli(["install", "--check"], { env: envBase() });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("not-installed");+ });++ test("after install --apply, reports ok and exits 0", async () => {+ await runCli(["install", "--target", "cursor", "--apply"], { env: envBase() });+ const r = await runCli(["install", "--check", "--target", "cursor"], { env: envBase() });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("ok");+ });++ test("--check without configured vault exits 2 with vault-not-configured", async () => {+ // Pass an empty/unwritable config + no VAULT_DIR β every adapter would+ // otherwise silently report not-installed against a bogus path.+ const r = await runCli(["install", "--check"], { env: { VAULT_DIR: "" } });+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("vault not configured");+ });++ test("after partial-key drift, exits 3", async () => {+ await runCli(["install", "--target", "cursor", "--apply"], { env: envBase() });+ const cfgPath = join(home, ".cursor", "mcp.json");+ const parsed = JSON.parse(readFileSync(cfgPath, "utf8"));+ delete parsed.mcpServers["open-second-brain-writer"];+ writeFileSync(cfgPath, JSON.stringify(parsed, null, 2) + "\n");+ const r = await runCli(["install", "--check", "--target", "cursor"], { env: envBase() });+ expect(r.returncode).toBe(3);+ expect(r.stdout).toContain("drift");+ });++ test("after canonical payload drift, exits 3", async () => {+ await runCli(["install", "--target", "cursor", "--apply"], { env: envBase() });+ const cfgPath = join(home, ".cursor", "mcp.json");+ const parsed = JSON.parse(readFileSync(cfgPath, "utf8"));+ parsed.mcpServers["open-second-brain"].command = "TAMPERED";+ writeFileSync(cfgPath, JSON.stringify(parsed, null, 2) + "\n");+ const r = await runCli(["install", "--check", "--target", "cursor"], { env: envBase() });+ expect(r.returncode).toBe(3);+ expect(r.stdout).toContain("canonical payload");+ });+});++describe("o2b uninstall --target X", () => {+ test("dry-run prints what would be removed but does nothing", async () => {+ await runCli(["install", "--target", "cursor", "--apply"], { env: envBase() });+ const r = await runCli(["uninstall", "--target", "cursor"], { env: envBase() });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("dry-run");+ // file still has OSB keys+ const parsed = JSON.parse(readFileSync(join(home, ".cursor", "mcp.json"), "utf8"));+ expect(parsed.mcpServers["open-second-brain"]).toBeDefined();+ });++ test("--apply removes OSB keys", async () => {+ await runCli(["install", "--target", "cursor", "--apply"], { env: envBase() });+ const r = await runCli(["uninstall", "--target", "cursor", "--apply"], { env: envBase() });+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(readFileSync(join(home, ".cursor", "mcp.json"), "utf8"));+ expect(parsed.mcpServers["open-second-brain"]).toBeUndefined();+ expect(parsed.mcpServers["open-second-brain-writer"]).toBeUndefined();+ });++ test("--target unknown exits 2", async () => {+ const r = await runCli(["uninstall", "--target", "nope", "--apply"], { env: envBase() });+ expect(r.returncode).toBe(2);+ });+});diff --git a/tests/cli/mcp-writer-probe.test.ts b/tests/cli/mcp-writer-probe.test.tsnew file mode 100644index 00000000..d89ed969--- /dev/null+++ b/tests/cli/mcp-writer-probe.test.ts@@ -0,0 +1,96 @@+import { describe, expect, test, beforeAll, afterAll } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { runCli } from "../helpers/run-cli.ts";++describe("o2b mcp --writer-only alias", () => {+ test("--writer-only without --scope sets scope=writer", async () => {+ let tmp: string | null = null;+ try {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-wo-"));+ const init = JSON.stringify({+ jsonrpc: "2.0", id: 1, method: "initialize",+ params: { protocolVersion: "2025-06-18", capabilities: {} },+ });+ const list = JSON.stringify({+ jsonrpc: "2.0", id: 2, method: "tools/list", params: {},+ });+ const res = await runCli(+ ["mcp", "--writer-only"],+ { stdin: `${init}\n${list}\n`, env: { VAULT_DIR: tmp } },+ );+ expect(res.returncode).toBe(0);+ const lines = res.stdout.trim().split("\n").map((l) => JSON.parse(l));+ const names = (lines[1].result.tools as Array<{ name: string }>)+ .map((t) => t.name).sort();+ expect(names).toEqual([+ "brain_apply_evidence",+ "brain_context",+ "brain_feedback",+ "brain_note",+ ]);+ } finally {+ if (tmp) rmSync(tmp, { recursive: true, force: true });+ }+ });++ test("--writer-only with --scope full is rejected (exit 2)", async () => {+ const res = await runCli(+ ["mcp", "--writer-only", "--scope", "full"],+ { stdin: "" },+ );+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("--writer-only");+ });++ test("--writer-only with --scope writer is accepted", async () => {+ let tmp: string | null = null;+ try {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-wo2-"));+ const init = JSON.stringify({+ jsonrpc: "2.0", id: 1, method: "initialize",+ params: { protocolVersion: "2025-06-18", capabilities: {} },+ });+ const res = await runCli(+ ["mcp", "--writer-only", "--scope", "writer"],+ { stdin: `${init}\n`, env: { VAULT_DIR: tmp } },+ );+ expect(res.returncode).toBe(0);+ } finally {+ if (tmp) rmSync(tmp, { recursive: true, force: true });+ }+ });+});++describe("o2b mcp --probe", () => {+ let tmp: string;+ beforeAll(() => { tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-probe-")); });+ afterAll(() => { rmSync(tmp, { recursive: true, force: true }); });++ test("--probe with valid vault exits 0 with tool count", async () => {+ const res = await runCli(+ ["mcp", "--probe"],+ { stdin: "", env: { VAULT_DIR: tmp } },+ );+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain("mcp probe ok");+ expect(res.stdout).toMatch(/\d+ tools/);+ });++ test("--probe --writer-only reports the writer-scope tool count", async () => {+ const res = await runCli(+ ["mcp", "--probe", "--writer-only"],+ { stdin: "", env: { VAULT_DIR: tmp } },+ );+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain("open-second-brain-writer");+ expect(res.stdout).toMatch(/[1-9]\d* tools/);+ });++ test("--probe without vault exits non-zero with FAIL message", async () => {+ const res = await runCli(["mcp", "--probe"], { stdin: "" });+ expect(res.returncode).toBeGreaterThan(0);+ expect(res.stdout).toContain("mcp probe FAIL");+ });+});diff --git a/tests/core/brain/digest-most-applied.test.ts b/tests/core/brain/digest-most-applied.test.tsnew file mode 100644index 00000000..74936819--- /dev/null+++ b/tests/core/brain/digest-most-applied.test.ts@@ -0,0 +1,169 @@+/**+ * `brain_digest` v0.10.11 β `most_applied` block in Markdown + JSON.+ *+ * Mirrors `Brain/active.md`'s `Most-applied (Nd)` section behind the+ * same `_brain.yaml:active.most_applied_*` knobs.+ */++import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { renderDigest } from "../../../src/core/brain/digest.ts";+import { appendLogEvent } from "../../../src/core/brain/log.ts";+import {+ BRAIN_APPLY_RESULT,+ BRAIN_LOG_EVENT_KIND,+} from "../../../src/core/brain/types.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-digest-ma-"));+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ // confirmed preference referenced by apply-evidence events+ writeFileSync(+ join(vault, "Brain", "preferences", "pref-a.md"),+ `---+kind: brain-preference+id: pref-a+created_at: 2026-04-01T00:00:00Z+confirmed_at: 2026-04-05T00:00:00Z+unconfirmed_until: 2026-04-08T00:00:00Z+tags: []+topic: a+status: confirmed+principle: principle a+evidenced_by: []+applied_count: 0+violated_count: 0+last_evidence_at: null+confidence: medium+confidence_value: 0.5+pinned: false+---+body+`,+ );+});++afterEach(() => {+ try { rmSync(vault, { recursive: true, force: true }); } catch {}+});++function writeBrainYaml(content: string): void {+ writeFileSync(join(vault, "Brain", "_brain.yaml"), content);+}++function seedApplied(stamp: string, prefRef: string): void {+ appendLogEvent(vault, {+ timestamp: stamp,+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,+ body: { preference: prefRef, result: BRAIN_APPLY_RESULT.applied, artifact: "[[x.md]]" },+ });+}++describe("digest most_applied block β defaults", () => {+ test("JSON contains the block at defaults (30d / 10) even when empty", () => {+ const result = renderDigest(vault, {+ format: "json",+ now: new Date("2026-05-20T12:00:00Z"),+ since: new Date("2026-05-19T12:00:00Z"),+ until: new Date("2026-05-20T12:00:00Z"),+ });+ const parsed = JSON.parse(result.content);+ expect(parsed.most_applied).toBeDefined();+ expect(parsed.most_applied.window_days).toBe(30);+ expect(parsed.most_applied.limit).toBe(10);+ expect(parsed.most_applied.entries).toEqual([]);+ });++ test("Markdown omits the section when window has no applied events", () => {+ const result = renderDigest(vault, {+ format: "markdown",+ now: new Date("2026-05-20T12:00:00Z"),+ since: new Date("2026-05-19T12:00:00Z"),+ until: new Date("2026-05-20T12:00:00Z"),+ });+ expect(result.content).not.toContain("## Most-applied");+ });++ test("JSON entries populated when applied events exist in window", () => {+ seedApplied("2026-05-15T10:00:00Z", "[[pref-a]]");+ seedApplied("2026-05-15T11:00:00Z", "[[pref-a]]");+ const result = renderDigest(vault, {+ format: "json",+ now: new Date("2026-05-20T12:00:00Z"),+ since: new Date("2026-05-19T12:00:00Z"),+ until: new Date("2026-05-20T12:00:00Z"),+ });+ const parsed = JSON.parse(result.content);+ expect(parsed.most_applied.entries.length).toBe(1);+ expect(parsed.most_applied.entries[0].id).toBe("pref-a");+ expect(parsed.most_applied.entries[0].applied_in_window).toBe(2);+ });++ test("Markdown renders the section with the default window in the header", () => {+ seedApplied("2026-05-15T10:00:00Z", "[[pref-a]]");+ const result = renderDigest(vault, {+ format: "markdown",+ now: new Date("2026-05-20T12:00:00Z"),+ since: new Date("2026-05-19T12:00:00Z"),+ until: new Date("2026-05-20T12:00:00Z"),+ });+ expect(result.content).toContain("## Most-applied (30d)");+ });+});++describe("digest most_applied block β custom config", () => {+ test("honours window_days / limit from _brain.yaml", () => {+ writeBrainYaml(+ "schema_version: 1\n" ++ "active:\n" ++ " most_applied_window_days: 7\n" ++ " most_applied_limit: 3\n",+ );+ seedApplied("2026-05-19T10:00:00Z", "[[pref-a]]"); // within 7d+ const result = renderDigest(vault, {+ format: "json",+ now: new Date("2026-05-20T12:00:00Z"),+ since: new Date("2026-05-19T12:00:00Z"),+ until: new Date("2026-05-20T12:00:00Z"),+ });+ const parsed = JSON.parse(result.content);+ expect(parsed.most_applied.window_days).toBe(7);+ expect(parsed.most_applied.limit).toBe(3);+ });++ test("Markdown header reflects custom window", () => {+ writeBrainYaml(+ "schema_version: 1\n" ++ "active:\n" ++ " most_applied_window_days: 14\n" ++ " most_applied_limit: 5\n",+ );+ seedApplied("2026-05-19T10:00:00Z", "[[pref-a]]");+ const result = renderDigest(vault, {+ format: "markdown",+ now: new Date("2026-05-20T12:00:00Z"),+ since: new Date("2026-05-19T12:00:00Z"),+ until: new Date("2026-05-20T12:00:00Z"),+ });+ expect(result.content).toContain("## Most-applied (14d)");+ });++ test("malformed _brain.yaml does not break the digest (falls back to defaults)", () => {+ writeBrainYaml("this is not yaml\nschema_version: nope\n");+ const result = renderDigest(vault, {+ format: "json",+ now: new Date("2026-05-20T12:00:00Z"),+ since: new Date("2026-05-19T12:00:00Z"),+ until: new Date("2026-05-20T12:00:00Z"),+ });+ const parsed = JSON.parse(result.content);+ expect(parsed.most_applied.window_days).toBe(30);+ });+});diff --git a/tests/core/brain/most-applied.test.ts b/tests/core/brain/most-applied.test.tsindex 96d2cbaf..01de561e 100644--- a/tests/core/brain/most-applied.test.ts+++ b/tests/core/brain/most-applied.test.ts@@ -212,4 +212,45 @@ describe("computeMostApplied", () => {const result = computeMostApplied(vault, [buildPref("pref-a")], { now });expect(result.length).toBe(1);});++ describe("custom windowDays / limit (v0.10.11)", () => {+ test("windowDays: 7 excludes events older than 7 days", () => {+ const now = new Date("2026-05-20T00:00:00Z");+ seedApplied(vault, "2026-05-19T00:00:00Z", "[[pref-a]]"); // 1d ago+ seedApplied(vault, "2026-05-10T00:00:00Z", "[[pref-a]]"); // 10d ago+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now, windowDays: 7 });+ expect(result.length).toBe(1);+ expect(result[0]!.applied_30d).toBe(1);+ });++ test("windowDays: 365 includes events from one year ago", () => {+ const now = new Date("2026-05-20T00:00:00Z");+ seedApplied(vault, "2025-06-01T00:00:00Z", "[[pref-a]]"); // ~354 days ago+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now, windowDays: 365 });+ expect(result.length).toBe(1);+ });++ test("limit: 2 truncates a 3-pref result", () => {+ const now = new Date("2026-05-20T00:00:00Z");+ seedApplied(vault, "2026-05-19T00:00:00Z", "[[pref-a]]");+ seedApplied(vault, "2026-05-19T00:00:00Z", "[[pref-a]]");+ seedApplied(vault, "2026-05-19T00:00:00Z", "[[pref-b]]");+ seedApplied(vault, "2026-05-19T00:00:00Z", "[[pref-c]]");+ const result = computeMostApplied(+ vault,+ [buildPref("pref-a"), buildPref("pref-b"), buildPref("pref-c")],+ { now, limit: 2 },+ );+ expect(result.length).toBe(2);+ expect(result.map((r) => r.preference.id)).toEqual(["pref-a", "pref-b"]);+ });++ test("default windowDays still 30 when option omitted", () => {+ const now = new Date("2026-05-20T00:00:00Z");+ seedApplied(vault, "2026-05-15T00:00:00Z", "[[pref-a]]"); // 5d ago+ seedApplied(vault, "2026-04-10T00:00:00Z", "[[pref-a]]"); // 40d ago β excluded+ const result = computeMostApplied(vault, [buildPref("pref-a")], { now });+ expect(result[0]!.applied_30d).toBe(1);+ });+ });});diff --git a/tests/core/brain/policy-active.test.ts b/tests/core/brain/policy-active.test.tsnew file mode 100644index 00000000..d8663eaa--- /dev/null+++ b/tests/core/brain/policy-active.test.ts@@ -0,0 +1,116 @@+/**+ * `active.{most_applied_window_days, most_applied_limit}` block (v0.10.11).+ */++import { describe, expect, test } from "bun:test";+import {+ BrainConfigError,+ parseBrainYaml,+ validateBrainConfigDetailed,+} from "../../../src/core/brain/policy.ts";++function validate(yaml: string) {+ return validateBrainConfigDetailed(parseBrainYaml(yaml), "<test>");+}++const HEAD = `schema_version: 1\n`;++describe("active.most_applied_* config block", () => {+ test("absent block β cfg.active is undefined; consumers use defaults", () => {+ const { config } = validate(HEAD);+ expect(config.active).toBeUndefined();+ });++ test("present with values β loaded into BrainMostAppliedConfig", () => {+ const { config } = validate(+ HEAD ++ `active:\n` ++ ` most_applied_window_days: 7\n` ++ ` most_applied_limit: 3\n`,+ );+ expect(config.active?.most_applied?.window_days).toBe(7);+ expect(config.active?.most_applied?.limit).toBe(3);+ });++ test("empty active block (no most_applied keys) is permitted", () => {+ const { config } = validate(HEAD + `active:\n __reserved: 1\n`);+ // unknown sub-key warns, but the block is otherwise valid+ expect(config.active).toEqual({});+ });++ test("window_days: 0 rejected", () => {+ expect(() =>+ validate(+ HEAD + `active:\n most_applied_window_days: 0\n most_applied_limit: 5\n`,+ ),+ ).toThrow(BrainConfigError);+ });++ test("window_days: 366 rejected", () => {+ expect(() =>+ validate(+ HEAD + `active:\n most_applied_window_days: 366\n most_applied_limit: 5\n`,+ ),+ ).toThrow(BrainConfigError);+ });++ test("limit: 0 rejected", () => {+ expect(() =>+ validate(+ HEAD + `active:\n most_applied_window_days: 30\n most_applied_limit: 0\n`,+ ),+ ).toThrow(BrainConfigError);+ });++ test("limit: 51 rejected", () => {+ expect(() =>+ validate(+ HEAD + `active:\n most_applied_window_days: 30\n most_applied_limit: 51\n`,+ ),+ ).toThrow(BrainConfigError);+ });++ test("non-integer window_days rejected", () => {+ expect(() =>+ validate(+ HEAD + `active:\n most_applied_window_days: 30.5\n most_applied_limit: 10\n`,+ ),+ ).toThrow(BrainConfigError);+ });++ test("string window_days rejected", () => {+ expect(() =>+ validate(+ HEAD + `active:\n most_applied_window_days: "thirty"\n`,+ ),+ ).toThrow(BrainConfigError);+ });++ test("only window_days set β limit defaults to 10", () => {+ const { config } = validate(+ HEAD + `active:\n most_applied_window_days: 14\n`,+ );+ expect(config.active?.most_applied?.window_days).toBe(14);+ expect(config.active?.most_applied?.limit).toBe(10);+ });++ test("only limit set β window_days defaults to 30", () => {+ const { config } = validate(+ HEAD + `active:\n most_applied_limit: 3\n`,+ );+ expect(config.active?.most_applied?.window_days).toBe(30);+ expect(config.active?.most_applied?.limit).toBe(3);+ });++ test("unknown sub-key under active: emits warning, doesn't throw", () => {+ const { warnings } = validate(+ HEAD + `active:\n most_applied_window_days: 30\n future_thing: 1\n`,+ );+ const found = warnings.find((w) => w.message.includes("future_thing"));+ expect(found).toBeDefined();+ });++ test("non-object active value is a hard error", () => {+ expect(() => validate(HEAD + `active: not-a-map\n`)).toThrow(BrainConfigError);+ });+});diff --git a/tests/core/discipline/transcripts.test.ts b/tests/core/discipline/transcripts.test.tsnew file mode 100644index 00000000..9589cdc8--- /dev/null+++ b/tests/core/discipline/transcripts.test.ts@@ -0,0 +1,134 @@+/**+ * Per-runtime session-transcript resolvers (v0.10.11).+ */++import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, utimesSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { claudeCodeTranscript } from "../../../src/core/discipline/transcripts/claude-code.ts";+import { codexTranscript } from "../../../src/core/discipline/transcripts/codex.ts";+import { cursorTranscript } from "../../../src/core/discipline/transcripts/cursor.ts";+import { collectTranscriptActivity } from "../../../src/core/discipline/transcripts/index.ts";++let home: string;++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), "osb-transcripts-h-"));+});+afterEach(() => {+ try { rmSync(home, { recursive: true, force: true }); } catch {}+});++const DAY_START = new Date("2026-05-19T00:00:00Z").getTime();+const DAY_END = new Date("2026-05-20T00:00:00Z").getTime();+const IN_DAY = new Date("2026-05-19T12:00:00Z");+const OUT_OF_DAY = new Date("2026-05-17T12:00:00Z");++function writeWithMtime(path: string, contents: string, when: Date): void {+ writeFileSync(path, contents);+ utimesSync(path, when, when);+}++describe("claude-code transcript resolver", () => {+ test("returns nothing when ~/.claude/projects is missing", () => {+ expect(claudeCodeTranscript.collect(DAY_START, DAY_END, home)).toEqual([]);+ });++ test("returns sessions modified within the window", () => {+ const projDir = join(home, ".claude", "projects", "my-proj");+ mkdirSync(projDir, { recursive: true });+ writeWithMtime(join(projDir, "sess-a.jsonl"), "{}", IN_DAY);+ writeWithMtime(join(projDir, "sess-b.jsonl"), "{}", OUT_OF_DAY);+ const out = claudeCodeTranscript.collect(DAY_START, DAY_END, home);+ expect(out).toHaveLength(1);+ expect(out[0]).toContain("sess-a.jsonl");+ });++ test("non-jsonl files are ignored", () => {+ const projDir = join(home, ".claude", "projects", "p");+ mkdirSync(projDir, { recursive: true });+ writeWithMtime(join(projDir, "readme.md"), "ok", IN_DAY);+ expect(claudeCodeTranscript.collect(DAY_START, DAY_END, home)).toEqual([]);+ });+});++describe("codex transcript resolver", () => {+ test("returns nothing when ~/.codex is missing", () => {+ expect(codexTranscript.collect(DAY_START, DAY_END, home)).toEqual([]);+ });++ test("walks sessions/ subdir for .json files", () => {+ const dir = join(home, ".codex", "sessions");+ mkdirSync(dir, { recursive: true });+ writeWithMtime(join(dir, "a.json"), "{}", IN_DAY);+ writeWithMtime(join(dir, "b.json"), "{}", OUT_OF_DAY);+ const out = codexTranscript.collect(DAY_START, DAY_END, home);+ expect(out).toHaveLength(1);+ });++ test("walks nested subdirs", () => {+ const dir = join(home, ".codex", ".tmp", "marketplaces", "x");+ mkdirSync(dir, { recursive: true });+ writeWithMtime(join(dir, "trace.json"), "{}", IN_DAY);+ const out = codexTranscript.collect(DAY_START, DAY_END, home);+ expect(out).toHaveLength(1);+ });+});++describe("cursor transcript resolver", () => {+ test("returns nothing when no Cursor workspace storage exists", () => {+ expect(cursorTranscript.collect(DAY_START, DAY_END, home)).toEqual([]);+ });++ test("returns state.vscdb files modified within the window", () => {+ const dir = join(home, ".config", "Cursor", "User", "workspaceStorage", "abc123");+ mkdirSync(dir, { recursive: true });+ writeWithMtime(join(dir, "state.vscdb"), "binary", IN_DAY);+ const out = cursorTranscript.collect(DAY_START, DAY_END, home);+ expect(out).toHaveLength(1);+ });++ test("excludes state.vscdb modified outside the window", () => {+ const dir = join(home, ".config", "Cursor", "User", "workspaceStorage", "abc");+ mkdirSync(dir, { recursive: true });+ writeWithMtime(join(dir, "state.vscdb"), "binary", OUT_OF_DAY);+ expect(cursorTranscript.collect(DAY_START, DAY_END, home)).toEqual([]);+ });+});++describe("collectTranscriptActivity aggregator", () => {+ test("sums file counts across all registered runtimes", () => {+ // Claude+ const cdir = join(home, ".claude", "projects", "p");+ mkdirSync(cdir, { recursive: true });+ writeWithMtime(join(cdir, "s.jsonl"), "{}", IN_DAY);+ // Codex+ const xdir = join(home, ".codex", "sessions");+ mkdirSync(xdir, { recursive: true });+ writeWithMtime(join(xdir, "a.json"), "{}", IN_DAY);+ writeWithMtime(join(xdir, "b.json"), "{}", IN_DAY);+ // Cursor+ const wdir = join(home, ".config", "Cursor", "User", "workspaceStorage", "ws");+ mkdirSync(wdir, { recursive: true });+ writeWithMtime(join(wdir, "state.vscdb"), "x", IN_DAY);++ const out = collectTranscriptActivity({+ dayStartMs: DAY_START, dayEndMs: DAY_END, home,+ });+ expect(out.totalFiles).toBe(4);+ expect(out.byRuntime.map((b) => `${b.runtime}=${b.fileCount}`).sort()).toEqual([+ "claudecode=1",+ "codex=2",+ "cursor=1",+ ]);+ });++ test("totalFiles is zero when no runtime found anything", () => {+ const out = collectTranscriptActivity({+ dayStartMs: DAY_START, dayEndMs: DAY_END, home,+ });+ expect(out.totalFiles).toBe(0);+ });+});diff --git a/tests/core/install/adapters/aider.test.ts b/tests/core/install/adapters/aider.test.tsnew file mode 100644index 00000000..6b78f8b7--- /dev/null+++ b/tests/core/install/adapters/aider.test.ts@@ -0,0 +1,165 @@+import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import {+ mkdtempSync,+ rmSync,+ writeFileSync,+ readFileSync,+ existsSync,+ mkdirSync,+ utimesSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Writable } from "node:stream";++import { aiderAdapter } from "../../../../src/core/install/adapters/aider.ts";+import { buildPayload } from "../../../../src/core/install/payload.ts";+import { readManifest } from "../../../../src/core/install/manifest.ts";+import { InstallError } from "../../../../src/core/install/types.ts";+import {+ hasManagedBlock,+ extractManagedBlock,+} from "../../../../src/core/install/managed-block.ts";++let vault: string;+let home: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-aider-v-"));+ home = mkdtempSync(join(tmpdir(), "osb-aider-h-"));+});+afterEach(() => {+ for (const p of [vault, home]) {+ try { rmSync(p, { recursive: true, force: true }); } catch {}+ }+});++function env(now = new Date("2026-05-20T12:00:00.000Z"), envVars: Record<string, string> = {}) {+ return { vault, home, cwd: home, env: envVars, now };+}++function applyOpts(overrides: Record<string, unknown> = {}) {+ const sink = new Writable({ write(_c, _e, cb) { cb(); } });+ return {+ dryRun: false, force: false,+ stdout: sink as unknown as NodeJS.WriteStream,+ stderr: sink as unknown as NodeJS.WriteStream,+ ...overrides,+ };+}++function aiderConfPath() {+ return join(home, ".aider.conf.yml");+}++const payload = buildPayload({ vault: "/v", agent_name: "claude-vps", timezone: "UTC" });++describe("aider adapter", () => {+ test("detect on clean home returns not-installed at default path", () => {+ const r = aiderAdapter.detect(env());+ expect(r.status).toBe("not-installed");+ expect(r.configPath).toBe(aiderConfPath());+ });++ test("apply creates ~/.aider.conf.yml with managed block + sidecar context file", () => {+ aiderAdapter.apply(aiderAdapter.plan(payload, env()), payload, env(), applyOpts());+ expect(existsSync(aiderConfPath())).toBe(true);+ const conf = readFileSync(aiderConfPath(), "utf8");+ expect(hasManagedBlock(conf)).toBe(true);+ const body = extractManagedBlock(conf);+ expect(body).toContain("read:");+ const sidecarPath = join(vault, ".open-second-brain", "aider-context.md");+ expect(existsSync(sidecarPath)).toBe(true);+ const sidecar = readFileSync(sidecarPath, "utf8");+ expect(sidecar).toContain("@claude-vps");+ expect(sidecar).toContain(vault);+ expect(readManifest(vault).installs.aider).toBeDefined();+ });++ test("re-apply is idempotent (managed-block + sidecar bytes unchanged)", () => {+ aiderAdapter.apply(aiderAdapter.plan(payload, env()), payload, env(), applyOpts());+ const conf1 = readFileSync(aiderConfPath(), "utf8");+ const sidecarPath = join(vault, ".open-second-brain", "aider-context.md");+ const side1 = readFileSync(sidecarPath, "utf8");+ aiderAdapter.apply(aiderAdapter.plan(payload, env()), payload, env(), applyOpts());+ expect(readFileSync(aiderConfPath(), "utf8")).toBe(conf1);+ expect(readFileSync(sidecarPath, "utf8")).toBe(side1);+ });++ test("preserves user-authored config above and below the managed block", () => {+ const userConf =+ "# user config\nmodel: gpt-4o-mini\nedit-format: diff\n";+ writeFileSync(aiderConfPath(), userConf);+ aiderAdapter.apply(aiderAdapter.plan(payload, env()), payload, env(), applyOpts());+ const conf = readFileSync(aiderConfPath(), "utf8");+ expect(conf.startsWith("# user config\nmodel: gpt-4o-mini\nedit-format: diff\n")).toBe(true);+ expect(hasManagedBlock(conf)).toBe(true);+ });++ test("uninstall removes managed block + sidecar file, drops manifest entry", () => {+ const userConf = "model: gpt-4o-mini\n";+ writeFileSync(aiderConfPath(), userConf);+ aiderAdapter.apply(aiderAdapter.plan(payload, env()), payload, env(), applyOpts());+ aiderAdapter.uninstall(env(), applyOpts());++ const conf = readFileSync(aiderConfPath(), "utf8");+ expect(hasManagedBlock(conf)).toBe(false);+ expect(conf).toContain("model: gpt-4o-mini");+ expect(existsSync(join(vault, ".open-second-brain", "aider-context.md"))).toBe(false);+ expect(readManifest(vault).installs.aider).toBeUndefined();+ });++ test("uninstall without manifest entry throws manifest-missing", () => {+ writeFileSync(aiderConfPath(), "# top\n");+ try {+ aiderAdapter.uninstall(env(), applyOpts());+ expect.unreachable("expected throw");+ } catch (err) {+ expect(err).toBeInstanceOf(InstallError);+ expect((err as InstallError).kind).toBe("manifest-missing");+ }+ });++ test("verify reports ok after install", () => {+ aiderAdapter.apply(aiderAdapter.plan(payload, env()), payload, env(), applyOpts());+ expect(aiderAdapter.verify(env()).status).toBe("ok");+ });++ test("verify reports drift when sidecar context file removed", () => {+ aiderAdapter.apply(aiderAdapter.plan(payload, env()), payload, env(), applyOpts());+ rmSync(join(vault, ".open-second-brain", "aider-context.md"), { force: true });+ expect(aiderAdapter.verify(env()).status).toBe("drift");+ });++ test("hand-edited block + mtime newer β apply refuses without --force", () => {+ aiderAdapter.apply(aiderAdapter.plan(payload, env()), payload, env(), applyOpts());+ // Tamper with managed block+ const conf = readFileSync(aiderConfPath(), "utf8");+ const tampered = conf.replace(/aider-context\.md/g, "TAMPERED");+ writeFileSync(aiderConfPath(), tampered);+ const future = new Date("2026-05-20T13:00:00.000Z");+ utimesSync(aiderConfPath(), future, future);++ try {+ aiderAdapter.apply(+ aiderAdapter.plan(payload, env(new Date("2026-05-20T13:05:00.000Z"))),+ payload,+ env(new Date("2026-05-20T13:05:00.000Z")),+ applyOpts(),+ );+ expect.unreachable("should have thrown");+ } catch (err) {+ expect(err).toBeInstanceOf(InstallError);+ expect((err as InstallError).kind).toBe("user-modified-block");+ }+ });++ test("AIDER_CONFIG env var overrides config path", () => {+ const custom = mkdtempSync(join(tmpdir(), "osb-aider-custom-"));+ const customConf = join(custom, "my-aider.yml");+ const e = env(new Date(), { AIDER_CONFIG: customConf });+ aiderAdapter.apply(aiderAdapter.plan(payload, e), payload, e, applyOpts());+ expect(existsSync(customConf)).toBe(true);+ try { rmSync(custom, { recursive: true, force: true }); } catch {}+ });+});diff --git a/tests/core/install/adapters/copilot-cli.test.ts b/tests/core/install/adapters/copilot-cli.test.tsnew file mode 100644index 00000000..ed94d8d4--- /dev/null+++ b/tests/core/install/adapters/copilot-cli.test.ts@@ -0,0 +1,217 @@+import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import {+ mkdtempSync, rmSync, existsSync, readFileSync, mkdirSync, writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Writable } from "node:stream";++import {+ copilotCliAdapter,+ setCopilotRunner,+ resetCopilotRunner,+ type CopilotRunner,+} from "../../../../src/core/install/adapters/copilot-cli.ts";+import { buildPayload } from "../../../../src/core/install/payload.ts";+import { readManifest } from "../../../../src/core/install/manifest.ts";++let vault: string;+let home: string;+let stderrBuf: string[];++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-copilot-v-"));+ home = mkdtempSync(join(tmpdir(), "osb-copilot-h-"));+ stderrBuf = [];+});+afterEach(() => {+ resetCopilotRunner();+ for (const p of [vault, home]) {+ try { rmSync(p, { recursive: true, force: true }); } catch {}+ }+});++function env() {+ return {+ vault,+ home,+ cwd: home,+ env: { VAULT_AGENT_NAME: "claude-vps", VAULT_TIMEZONE: "UTC" },+ now: new Date("2026-05-20T12:00:00.000Z"),+ };+}++function applyOpts() {+ const stdout = new Writable({ write(_c, _e, cb) { cb(); } });+ const stderr = new Writable({+ write(chunk, _e, cb) { stderrBuf.push(chunk.toString()); cb(); },+ });+ return {+ dryRun: false, force: false,+ stdout: stdout as unknown as NodeJS.WriteStream,+ stderr: stderr as unknown as NodeJS.WriteStream,+ };+}++function payload() {+ return buildPayload({ vault, agent_name: "claude-vps", timezone: "UTC" });+}++function fallbackFile() {+ return join(home, ".config", "github-copilot", "mcp.json");+}++describe("copilot-cli adapter β happy path via CLI subprocess", () => {+ test("apply calls `copilot mcp remove` + `copilot mcp add` for both names", () => {+ const calls: string[][] = [];+ const runner: CopilotRunner = {+ available: () => true,+ run: (args) => {+ calls.push([...args]);+ return { exitCode: 0, stdout: "", stderr: "" };+ },+ list: () => ({ ok: true, names: ["open-second-brain", "open-second-brain-writer"] }),+ };+ setCopilotRunner(runner);+ const p = payload();+ copilotCliAdapter.apply(copilotCliAdapter.plan(p, env()), p, env(), applyOpts());+ const ops = calls.map((c) => `${c[0]} ${c[1]}`);+ expect(ops).toContain("mcp remove");+ expect(ops).toContain("mcp add");+ const manifest = readManifest(vault).installs["copilot-cli"];+ expect(manifest).toBeDefined();+ expect(manifest!.operation).toBe("subprocess");+ expect(manifest!.fallback_file).toBeNull();+ });+});++describe("copilot-cli adapter β fallback to JSON file", () => {+ test("uses file fallback when CLI absent", () => {+ const runner: CopilotRunner = {+ available: () => false,+ run: () => { throw new Error("should not run"); },+ list: () => ({ ok: false, names: [] }),+ };+ setCopilotRunner(runner);+ const p = payload();+ copilotCliAdapter.apply(copilotCliAdapter.plan(p, env()), p, env(), applyOpts());+ expect(existsSync(fallbackFile())).toBe(true);+ const parsed = JSON.parse(readFileSync(fallbackFile(), "utf8"));+ expect(parsed.mcpServers["open-second-brain"]).toBeDefined();+ expect(parsed.mcpServers["open-second-brain-writer"]).toBeDefined();+ expect(stderrBuf.join("").length).toBeGreaterThan(0);+ const manifest = readManifest(vault).installs["copilot-cli"];+ expect(manifest!.fallback_file).toBe(fallbackFile());+ });++ test("falls back when CLI add returns non-zero", () => {+ let n = 0;+ const runner: CopilotRunner = {+ available: () => true,+ run: (args) => {+ n += 1;+ if (args.includes("add")) return { exitCode: 1, stdout: "", stderr: "boom" };+ return { exitCode: 0, stdout: "", stderr: "" };+ },+ list: () => ({ ok: true, names: [] }),+ };+ setCopilotRunner(runner);+ const p = payload();+ copilotCliAdapter.apply(copilotCliAdapter.plan(p, env()), p, env(), applyOpts());+ expect(n).toBeGreaterThan(0);+ expect(existsSync(fallbackFile())).toBe(true);+ expect(stderrBuf.join("")).toContain("copilot mcp add failed");+ });+});++describe("copilot-cli adapter β verify", () => {+ test("verify ok when CLI lists both names", () => {+ const runner: CopilotRunner = {+ available: () => true,+ run: () => ({ exitCode: 0, stdout: "", stderr: "" }),+ list: () => ({ ok: true, names: ["open-second-brain", "open-second-brain-writer"] }),+ };+ setCopilotRunner(runner);+ const p = payload();+ copilotCliAdapter.apply(copilotCliAdapter.plan(p, env()), p, env(), applyOpts());+ expect(copilotCliAdapter.verify(env()).status).toBe("ok");+ });++ test("verify ok when fallback file has both keys", () => {+ const runner: CopilotRunner = {+ available: () => false,+ run: () => { throw new Error("nope"); },+ list: () => ({ ok: false, names: [] }),+ };+ setCopilotRunner(runner);+ const p = payload();+ copilotCliAdapter.apply(copilotCliAdapter.plan(p, env()), p, env(), applyOpts());+ expect(copilotCliAdapter.verify(env()).status).toBe("ok");+ });++ test("verify drift when fallback file payload was changed", () => {+ const runner: CopilotRunner = {+ available: () => false,+ run: () => { throw new Error("nope"); },+ list: () => ({ ok: false, names: [] }),+ };+ setCopilotRunner(runner);+ const p = payload();+ copilotCliAdapter.apply(copilotCliAdapter.plan(p, env()), p, env(), applyOpts());+ const parsed = JSON.parse(readFileSync(fallbackFile(), "utf8"));+ parsed.mcpServers["open-second-brain"].command = "TAMPERED";+ writeFileSync(fallbackFile(), JSON.stringify(parsed, null, 2) + "\n");+ const v = copilotCliAdapter.verify(env());+ expect(v.status).toBe("drift");+ expect(v.details.join("\n")).toContain("canonical payload");+ });++ test("verify drift when CLI lists only one name", () => {+ const runner: CopilotRunner = {+ available: () => true,+ run: () => ({ exitCode: 0, stdout: "", stderr: "" }),+ list: () => ({ ok: true, names: ["open-second-brain"] }),+ };+ setCopilotRunner(runner);+ const p = payload();+ copilotCliAdapter.apply(copilotCliAdapter.plan(p, env()), p, env(), applyOpts());+ expect(copilotCliAdapter.verify(env()).status).toBe("drift");+ });+});++describe("copilot-cli adapter β uninstall", () => {+ test("uninstall via CLI removes both names", () => {+ const calls: string[][] = [];+ const runner: CopilotRunner = {+ available: () => true,+ run: (args) => {+ calls.push([...args]);+ return { exitCode: 0, stdout: "", stderr: "" };+ },+ list: () => ({ ok: true, names: ["open-second-brain", "open-second-brain-writer"] }),+ };+ setCopilotRunner(runner);+ const p = payload();+ copilotCliAdapter.apply(copilotCliAdapter.plan(p, env()), p, env(), applyOpts());+ calls.length = 0;+ copilotCliAdapter.uninstall(env(), applyOpts());+ const removeCalls = calls.filter((c) => c[0] === "mcp" && c[1] === "remove");+ expect(removeCalls.length).toBe(2);+ expect(readManifest(vault).installs["copilot-cli"]).toBeUndefined();+ });++ test("uninstall via fallback file removes both keys", () => {+ const runner: CopilotRunner = {+ available: () => false,+ run: () => { throw new Error("nope"); },+ list: () => ({ ok: false, names: [] }),+ };+ setCopilotRunner(runner);+ const p = payload();+ copilotCliAdapter.apply(copilotCliAdapter.plan(p, env()), p, env(), applyOpts());+ copilotCliAdapter.uninstall(env(), applyOpts());+ const parsed = JSON.parse(readFileSync(fallbackFile(), "utf8"));+ expect(parsed.mcpServers["open-second-brain"]).toBeUndefined();+ expect(parsed.mcpServers["open-second-brain-writer"]).toBeUndefined();+ });+});diff --git a/tests/core/install/adapters/cursor.test.ts b/tests/core/install/adapters/cursor.test.tsnew file mode 100644index 00000000..71f83d43--- /dev/null+++ b/tests/core/install/adapters/cursor.test.ts@@ -0,0 +1,247 @@+import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import {+ mkdtempSync,+ rmSync,+ readFileSync,+ writeFileSync,+ mkdirSync,+ utimesSync,+ existsSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Writable } from "node:stream";++import { cursorAdapter } from "../../../../src/core/install/adapters/cursor.ts";+import { buildPayload } from "../../../../src/core/install/payload.ts";+import { readManifest } from "../../../../src/core/install/manifest.ts";+import { InstallError } from "../../../../src/core/install/types.ts";++let vault: string;+let home: string;+let stdoutBuf: string[];+let stderrBuf: string[];++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-cursor-v-"));+ home = mkdtempSync(join(tmpdir(), "osb-cursor-h-"));+ stdoutBuf = [];+ stderrBuf = [];+});++afterEach(() => {+ try { rmSync(vault, { recursive: true, force: true }); } catch {}+ try { rmSync(home, { recursive: true, force: true }); } catch {}+});++function makeEnv(now = new Date("2026-05-20T12:00:00.000Z")) {+ return {+ vault,+ home,+ cwd: home,+ env: { VAULT_AGENT_NAME: "claude-vps", VAULT_TIMEZONE: "UTC" },+ now,+ };+}++function makeStreams() {+ const stdout = new Writable({+ write(chunk, _enc, cb) { stdoutBuf.push(chunk.toString()); cb(); },+ });+ const stderr = new Writable({+ write(chunk, _enc, cb) { stderrBuf.push(chunk.toString()); cb(); },+ });+ return { stdout, stderr };+}++function payload() {+ return buildPayload({+ vault, agent_name: "claude-vps", timezone: "UTC",+ });+}++function applyOpts(overrides: Record<string, unknown> = {}) {+ const { stdout, stderr } = makeStreams();+ return {+ dryRun: false, force: false,+ stdout: stdout as unknown as NodeJS.WriteStream,+ stderr: stderr as unknown as NodeJS.WriteStream,+ ...overrides,+ };+}++function cursorConfigPath() {+ return join(home, ".cursor", "mcp.json");+}++describe("cursor adapter", () => {+ test("detect on clean home returns not-installed", () => {+ const r = cursorAdapter.detect(makeEnv());+ expect(r.status).toBe("not-installed");+ expect(r.configPath).toBe(cursorConfigPath());+ });++ test("apply on clean home creates config with both OSB keys", () => {+ const p = payload();+ const plan = cursorAdapter.plan(p, makeEnv());+ const result = cursorAdapter.apply(plan, p, makeEnv(), applyOpts());+ expect(existsSync(cursorConfigPath())).toBe(true);+ const parsed = JSON.parse(readFileSync(cursorConfigPath(), "utf8"));+ expect(Object.keys(parsed.mcpServers)).toEqual([+ "open-second-brain",+ "open-second-brain-writer",+ ]);+ expect(result.manifest.owned_keys).toEqual([+ "mcpServers.open-second-brain",+ "mcpServers.open-second-brain-writer",+ ]);+ expect(readManifest(vault).installs.cursor).toBeDefined();+ });++ test("re-apply is idempotent (file bytes unchanged)", () => {+ const p = payload();+ const plan = cursorAdapter.plan(p, makeEnv());+ cursorAdapter.apply(plan, p, makeEnv(), applyOpts());+ const after1 = readFileSync(cursorConfigPath(), "utf8");+ cursorAdapter.apply(plan, p, makeEnv(), applyOpts());+ const after2 = readFileSync(cursorConfigPath(), "utf8");+ expect(after2).toBe(after1);+ });++ test("apply preserves unrelated mcpServers keys", () => {+ mkdirSync(join(home, ".cursor"), { recursive: true });+ writeFileSync(cursorConfigPath(),+ JSON.stringify({ mcpServers: { other: { command: "x", args: [] } } }, null, 2) + "\n");+ const p = payload();+ const plan = cursorAdapter.plan(p, makeEnv());+ cursorAdapter.apply(plan, p, makeEnv(), applyOpts());+ const parsed = JSON.parse(readFileSync(cursorConfigPath(), "utf8"));+ expect(parsed.mcpServers.other).toEqual({ command: "x", args: [] });+ expect(Object.keys(parsed.mcpServers)).toEqual([+ "other",+ "open-second-brain",+ "open-second-brain-writer",+ ]);+ });++ test("verify on installed config reports ok", () => {+ const p = payload();+ const plan = cursorAdapter.plan(p, makeEnv());+ cursorAdapter.apply(plan, p, makeEnv(), applyOpts());+ const v = cursorAdapter.verify(makeEnv());+ expect(v.status).toBe("ok");+ });++ test("verify reports drift when writer key was manually removed", () => {+ const p = payload();+ const plan = cursorAdapter.plan(p, makeEnv());+ cursorAdapter.apply(plan, p, makeEnv(), applyOpts());+ const parsed = JSON.parse(readFileSync(cursorConfigPath(), "utf8"));+ delete parsed.mcpServers["open-second-brain-writer"];+ writeFileSync(cursorConfigPath(), JSON.stringify(parsed, null, 2) + "\n");+ const v = cursorAdapter.verify(makeEnv());+ expect(v.status).toBe("drift");+ expect(v.fix_hint).toContain("o2b install --target cursor --apply");+ });++ test("verify reports drift when OSB key payload was manually changed", () => {+ const p = payload();+ const plan = cursorAdapter.plan(p, makeEnv());+ cursorAdapter.apply(plan, p, makeEnv(), applyOpts());+ const parsed = JSON.parse(readFileSync(cursorConfigPath(), "utf8"));+ parsed.mcpServers["open-second-brain"].command = "TAMPERED";+ writeFileSync(cursorConfigPath(), JSON.stringify(parsed, null, 2) + "\n");+ const v = cursorAdapter.verify(makeEnv());+ expect(v.status).toBe("drift");+ expect(v.details.join("\n")).toContain("canonical payload");+ });++ test("detect reports drift instead of throwing when config root is not an object", () => {+ mkdirSync(join(home, ".cursor"), { recursive: true });+ writeFileSync(cursorConfigPath(), "null\n");+ const r = cursorAdapter.detect(makeEnv());+ expect(r.status).toBe("drift");+ });++ test("uninstall removes both OSB keys, preserves user key, drops manifest entry", () => {+ mkdirSync(join(home, ".cursor"), { recursive: true });+ writeFileSync(cursorConfigPath(),+ JSON.stringify({ mcpServers: { other: { command: "x", args: [] } } }, null, 2) + "\n");+ const p = payload();+ cursorAdapter.apply(cursorAdapter.plan(p, makeEnv()), p, makeEnv(), applyOpts());+ cursorAdapter.uninstall(makeEnv(), applyOpts());+ const parsed = JSON.parse(readFileSync(cursorConfigPath(), "utf8"));+ expect(parsed.mcpServers["open-second-brain"]).toBeUndefined();+ expect(parsed.mcpServers["open-second-brain-writer"]).toBeUndefined();+ expect(parsed.mcpServers.other).toEqual({ command: "x", args: [] });+ expect(readManifest(vault).installs.cursor).toBeUndefined();+ });++ test("uninstall without manifest entry throws manifest-missing", () => {+ mkdirSync(join(home, ".cursor"), { recursive: true });+ writeFileSync(cursorConfigPath(),+ JSON.stringify({ mcpServers: { "open-second-brain": { command: "o2b", args: ["mcp"] } } }, null, 2) + "\n");+ try {+ cursorAdapter.uninstall(makeEnv(), applyOpts());+ expect.unreachable("should have thrown");+ } catch (err) {+ expect(err).toBeInstanceOf(InstallError);+ expect((err as InstallError).kind).toBe("manifest-missing");+ }+ });++ test("uninstall --force-from-snippet works without manifest", () => {+ mkdirSync(join(home, ".cursor"), { recursive: true });+ writeFileSync(cursorConfigPath(),+ JSON.stringify({ mcpServers: { "open-second-brain": { command: "o2b", args: ["mcp"] } } }, null, 2) + "\n");+ expect(() => cursorAdapter.uninstall(makeEnv(), applyOpts({ fromSnippet: true })))+ .not.toThrow();+ const parsed = JSON.parse(readFileSync(cursorConfigPath(), "utf8"));+ expect(parsed.mcpServers["open-second-brain"]).toBeUndefined();+ });++ test("user hand-edits the block, re-apply without --force throws user-modified-block", () => {+ const env1 = makeEnv(new Date("2026-05-20T12:00:00.000Z"));+ const p = payload();+ cursorAdapter.apply(cursorAdapter.plan(p, env1), p, env1, applyOpts());+ // Tamper with the file and bump mtime past the manifest applied_at.+ const parsed = JSON.parse(readFileSync(cursorConfigPath(), "utf8"));+ parsed.mcpServers["open-second-brain"] = { command: "TAMPERED", args: [] };+ writeFileSync(cursorConfigPath(), JSON.stringify(parsed, null, 2) + "\n");+ const future = new Date("2026-05-20T13:00:00.000Z");+ utimesSync(cursorConfigPath(), future, future);++ const env2 = makeEnv(new Date("2026-05-20T13:05:00.000Z"));+ try {+ cursorAdapter.apply(cursorAdapter.plan(p, env2), p, env2, applyOpts());+ expect.unreachable("should have thrown");+ } catch (err) {+ expect(err).toBeInstanceOf(InstallError);+ expect((err as InstallError).kind).toBe("user-modified-block");+ }+ });++ test("user hand-edits + --force overwrites", () => {+ const env1 = makeEnv(new Date("2026-05-20T12:00:00.000Z"));+ const p = payload();+ cursorAdapter.apply(cursorAdapter.plan(p, env1), p, env1, applyOpts());+ const parsed = JSON.parse(readFileSync(cursorConfigPath(), "utf8"));+ parsed.mcpServers["open-second-brain"] = { command: "TAMPERED", args: [] };+ writeFileSync(cursorConfigPath(), JSON.stringify(parsed, null, 2) + "\n");+ const future = new Date("2026-05-20T13:00:00.000Z");+ utimesSync(cursorConfigPath(), future, future);++ const env2 = makeEnv(new Date("2026-05-20T13:05:00.000Z"));+ cursorAdapter.apply(cursorAdapter.plan(p, env2), p, env2, applyOpts({ force: true }));+ const after = JSON.parse(readFileSync(cursorConfigPath(), "utf8"));+ expect(after.mcpServers["open-second-brain"].command).toBe("o2b");+ });++ test("dryRun does not write the config file or manifest", () => {+ const p = payload();+ const plan = cursorAdapter.plan(p, makeEnv());+ cursorAdapter.apply(plan, p, makeEnv(), applyOpts({ dryRun: true }));+ expect(existsSync(cursorConfigPath())).toBe(false);+ expect(readManifest(vault).installs.cursor).toBeUndefined();+ });+});diff --git a/tests/core/install/adapters/generic.test.ts b/tests/core/install/adapters/generic.test.tsnew file mode 100644index 00000000..a3534b36--- /dev/null+++ b/tests/core/install/adapters/generic.test.ts@@ -0,0 +1,128 @@+import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import { mkdtempSync, rmSync, readFileSync, existsSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Writable } from "node:stream";++import { genericAdapter } from "../../../../src/core/install/adapters/generic.ts";+import type { InstallEnv } from "../../../../src/core/install/types.ts";+import { buildPayload } from "../../../../src/core/install/payload.ts";++let vault: string;+let home: string;+let stdoutBuf: string[];+let stderrBuf: string[];+let stdout: Writable;+let stderr: Writable;+let env: InstallEnv;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-generic-v-"));+ home = mkdtempSync(join(tmpdir(), "osb-generic-h-"));+ stdoutBuf = [];+ stderrBuf = [];+ stdout = new Writable({+ write(chunk, _enc, cb) { stdoutBuf.push(chunk.toString()); cb(); },+ });+ stderr = new Writable({+ write(chunk, _enc, cb) { stderrBuf.push(chunk.toString()); cb(); },+ });+ env = {+ vault, home, cwd: home,+ env: {}, now: new Date("2026-05-20T12:00:00.000Z"),+ };+});++afterEach(() => {+ try { rmSync(vault, { recursive: true, force: true }); } catch {}+ try { rmSync(home, { recursive: true, force: true }); } catch {}+});++const payload = buildPayload({+ vault: "/home/u/vault", agent_name: "a", timezone: "UTC",+});++function applyOpts(extra: Partial<Parameters<typeof genericAdapter.apply>[3]> = {}) {+ return {+ dryRun: false, force: false,+ stdout: stdout as unknown as NodeJS.WriteStream,+ stderr: stderr as unknown as NodeJS.WriteStream,+ ...extra,+ };+}++describe("generic adapter", () => {+ test("detect always returns not-installed", () => {+ const r = genericAdapter.detect(env);+ expect(r.target).toBe("generic");+ expect(r.status).toBe("not-installed");+ expect(r.configPath).toBeNull();+ });++ test("plan returns a single print step", () => {+ const p = genericAdapter.plan(payload, env);+ expect(p.target).toBe("generic");+ expect(p.steps.length).toBe(1);+ expect(p.steps[0]!.kind).toBe("print");+ });++ test("apply (default) prints JSON to stdout", () => {+ const plan = genericAdapter.plan(payload, env);+ const result = genericAdapter.apply(plan, payload, env, applyOpts());+ const out = stdoutBuf.join("");+ const parsed = JSON.parse(out);+ expect(parsed.mcpServers["open-second-brain"]).toBeDefined();+ expect(parsed.mcpServers["open-second-brain-writer"]).toBeDefined();+ expect(result.manifest.operation).toBe("print");+ expect(result.manifest.config_path).toBeNull();+ });++ test("apply with --out <path> writes file", () => {+ const outPath = join(home, "out.json");+ const plan = genericAdapter.plan(payload, env);+ const result = genericAdapter.apply(plan, payload, env, applyOpts({ outPath }));+ expect(existsSync(outPath)).toBe(true);+ const raw = readFileSync(outPath, "utf8");+ expect(JSON.parse(raw).mcpServers["open-second-brain"]).toBeDefined();+ expect(result.manifest.config_path).toBe(outPath);+ // stdout should remain empty when file path provided+ expect(stdoutBuf.join("").length).toBe(0);+ });++ test("apply with --out - writes to stdout", () => {+ const plan = genericAdapter.plan(payload, env);+ genericAdapter.apply(plan, payload, env, applyOpts({ outPath: "-" }));+ expect(stdoutBuf.join("").length).toBeGreaterThan(0);+ });++ test("apply with format=yaml writes YAML", () => {+ const plan = genericAdapter.plan(payload, env);+ genericAdapter.apply(plan, payload, env, applyOpts({ format: "yaml" }));+ const out = stdoutBuf.join("");+ expect(out).toContain("mcpServers:");+ expect(out).toContain("open-second-brain:");+ expect(() => JSON.parse(out)).toThrow(); // not JSON+ });++ test("apply dryRun does not write the output file", () => {+ const outPath = join(home, "out.json");+ const plan = genericAdapter.plan(payload, env);+ genericAdapter.apply(plan, payload, env, applyOpts({ outPath, dryRun: true }));+ expect(existsSync(outPath)).toBe(false);+ });++ test("verify returns not-installed when no out_path recorded", () => {+ const r = genericAdapter.verify(env);+ expect(r.status).toBe("not-installed");+ });++ test("uninstall reports the path the operator must remove themselves", () => {+ const outPath = join(home, "out.json");+ const plan = genericAdapter.plan(payload, env);+ genericAdapter.apply(plan, payload, env, applyOpts({ outPath }));+ const result = genericAdapter.uninstall(env, applyOpts());+ expect(result.skipped.length).toBeGreaterThan(0);+ // generic must not delete the operator's file+ expect(existsSync(outPath)).toBe(true);+ });+});diff --git a/tests/core/install/adapters/json-mcp-smoke.test.ts b/tests/core/install/adapters/json-mcp-smoke.test.tsnew file mode 100644index 00000000..ad8ad8b2--- /dev/null+++ b/tests/core/install/adapters/json-mcp-smoke.test.ts@@ -0,0 +1,106 @@+/**+ * Smoke tests for opencode / kiro / gemini-cli adapters.+ *+ * They share the same JSON-merge body as cursor (deeply tested in+ * `cursor.test.ts`). Here we only assert that each adapter+ * resolves the expected per-target config path and that a+ * clean install+uninstall cycle works end-to-end.+ */++import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import { mkdtempSync, rmSync, existsSync, readFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Writable } from "node:stream";++import { opencodeAdapter } from "../../../../src/core/install/adapters/opencode.ts";+import { kiroAdapter } from "../../../../src/core/install/adapters/kiro.ts";+import { geminiCliAdapter } from "../../../../src/core/install/adapters/gemini-cli.ts";+import { buildPayload } from "../../../../src/core/install/payload.ts";+import { readManifest } from "../../../../src/core/install/manifest.ts";++let vault: string;+let home: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-jsonmcp-v-"));+ home = mkdtempSync(join(tmpdir(), "osb-jsonmcp-h-"));+});+afterEach(() => {+ try { rmSync(vault, { recursive: true, force: true }); } catch {}+ try { rmSync(home, { recursive: true, force: true }); } catch {}+});++function env(extraEnv: Record<string, string> = {}) {+ return {+ vault, home, cwd: home,+ // verify() rebuilds the canonical payload from these env vars; they+ // must match the values passed to buildPayload() below or every+ // smoke check would report drift.+ env: { VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC", ...extraEnv },+ now: new Date("2026-05-20T12:00:00.000Z"),+ };+}++function applyOpts() {+ const sink = new Writable({ write(_c, _e, cb) { cb(); } });+ return {+ dryRun: false, force: false,+ stdout: sink as unknown as NodeJS.WriteStream,+ stderr: sink as unknown as NodeJS.WriteStream,+ };+}++function payload() {+ return buildPayload({ vault, agent_name: "a", timezone: "UTC" });+}++describe("opencode adapter β config path resolution", () => {+ test("default path is ~/.config/opencode/mcp.json", () => {+ const r = opencodeAdapter.detect(env());+ expect(r.configPath).toBe(join(home, ".config", "opencode", "mcp.json"));+ });++ test("XDG_CONFIG_HOME override is honoured", () => {+ const xdg = mkdtempSync(join(tmpdir(), "osb-xdg-"));+ const r = opencodeAdapter.detect(env({ XDG_CONFIG_HOME: xdg }));+ expect(r.configPath).toBe(join(xdg, "opencode", "mcp.json"));+ try { rmSync(xdg, { recursive: true, force: true }); } catch {}+ });++ test("install + uninstall round-trip", () => {+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());+ const path = opencodeAdapter.detect(env()).configPath!;+ expect(existsSync(path)).toBe(true);+ expect(readManifest(vault).installs.opencode).toBeDefined();++ opencodeAdapter.uninstall(env(), applyOpts());+ expect(readManifest(vault).installs.opencode).toBeUndefined();+ const parsed = JSON.parse(readFileSync(path, "utf8"));+ expect(parsed.mcpServers["open-second-brain"]).toBeUndefined();+ });+});++describe("kiro adapter β config path resolution", () => {+ test("default path is ~/.kiro/settings.json", () => {+ const r = kiroAdapter.detect(env());+ expect(r.configPath).toBe(join(home, ".kiro", "settings.json"));+ });++ test("install + verify ok", () => {+ kiroAdapter.apply(kiroAdapter.plan(payload(), env()), payload(), env(), applyOpts());+ expect(kiroAdapter.verify(env()).status).toBe("ok");+ });+});++describe("gemini-cli adapter β config path resolution", () => {+ test("default path is ~/.gemini/settings.json", () => {+ const r = geminiCliAdapter.detect(env());+ expect(r.configPath).toBe(join(home, ".gemini", "settings.json"));+ });++ test("install + verify ok", () => {+ geminiCliAdapter.apply(geminiCliAdapter.plan(payload(), env()), payload(), env(), applyOpts());+ expect(geminiCliAdapter.verify(env()).status).toBe("ok");+ });+});diff --git a/tests/core/install/adapters/pi.test.ts b/tests/core/install/adapters/pi.test.tsnew file mode 100644index 00000000..1404df2f--- /dev/null+++ b/tests/core/install/adapters/pi.test.ts@@ -0,0 +1,139 @@+import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import {+ mkdtempSync,+ rmSync,+ mkdirSync,+ writeFileSync,+ symlinkSync,+ existsSync,+ lstatSync,+ readlinkSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Writable } from "node:stream";++import { piAdapter } from "../../../../src/core/install/adapters/pi.ts";+import { buildPayload } from "../../../../src/core/install/payload.ts";+import { readManifest } from "../../../../src/core/install/manifest.ts";+import { InstallError } from "../../../../src/core/install/types.ts";++let vault: string;+let home: string;+let pluginRoot: string;+let skillSource: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-pi-v-"));+ home = mkdtempSync(join(tmpdir(), "osb-pi-h-"));+ pluginRoot = mkdtempSync(join(tmpdir(), "osb-pi-r-"));+ skillSource = join(pluginRoot, "skills", "brain-memory");+ mkdirSync(skillSource, { recursive: true });+ writeFileSync(join(skillSource, "SKILL.md"), "# brain-memory skill\n");+});++afterEach(() => {+ for (const p of [vault, home, pluginRoot]) {+ try { rmSync(p, { recursive: true, force: true }); } catch {}+ }+});++function env() {+ return { vault, home, cwd: home, env: {}, now: new Date("2026-05-20T12:00:00.000Z") };+}++function applyOpts(overrides: Record<string, unknown> = {}) {+ const sink = new Writable({ write(_c, _e, cb) { cb(); } });+ return {+ dryRun: false, force: false,+ stdout: sink as unknown as NodeJS.WriteStream,+ stderr: sink as unknown as NodeJS.WriteStream,+ piSkillSource: skillSource,+ ...overrides,+ };+}++const payload = buildPayload({ vault: "/v", agent_name: "a", timezone: "UTC" });++describe("pi adapter", () => {+ const linkPath = () => join(home, ".pi", "skills", "brain-memory");++ test("detect on clean home returns not-installed at the default path", () => {+ const r = piAdapter.detect(env());+ expect(r.status).toBe("not-installed");+ expect(r.configPath).toBe(linkPath());+ });++ test("apply creates symlink ~/.pi/skills/brain-memory pointing at source", () => {+ piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts());+ expect(lstatSync(linkPath()).isSymbolicLink()).toBe(true);+ expect(readlinkSync(linkPath())).toBe(skillSource);+ expect(readManifest(vault).installs.pi).toBeDefined();+ });++ test("re-apply on valid symlink is a no-op (idempotent)", () => {+ piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts());+ const before = readlinkSync(linkPath());+ piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts());+ const after = readlinkSync(linkPath());+ expect(after).toBe(before);+ });++ test("re-apply replaces broken symlink (target removed)", () => {+ piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts());+ // Remove the source β symlink is now dangling+ rmSync(skillSource, { recursive: true, force: true });+ mkdirSync(skillSource, { recursive: true });+ writeFileSync(join(skillSource, "SKILL.md"), "# new\n");+ piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts());+ expect(existsSync(linkPath())).toBe(true);+ expect(readlinkSync(linkPath())).toBe(skillSource);+ });++ test("refuses to clobber a non-symlink directory at the target without --force", () => {+ mkdirSync(linkPath(), { recursive: true });+ writeFileSync(join(linkPath(), "user-file.md"), "stay clear\n");+ try {+ piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts());+ expect.unreachable("expected throw");+ } catch (err) {+ expect(err).toBeInstanceOf(InstallError);+ }+ expect(lstatSync(linkPath()).isDirectory()).toBe(true);+ expect(existsSync(join(linkPath(), "user-file.md"))).toBe(true);+ });++ test("--force overrides the non-symlink-at-target refusal", () => {+ mkdirSync(linkPath(), { recursive: true });+ writeFileSync(join(linkPath(), "user-file.md"), "will go\n");+ piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts({ force: true }));+ expect(lstatSync(linkPath()).isSymbolicLink()).toBe(true);+ });++ test("piSkillDir override changes target location", () => {+ const altDir = mkdtempSync(join(tmpdir(), "osb-pi-alt-"));+ piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts({ piSkillDir: altDir }));+ expect(lstatSync(join(altDir, "brain-memory")).isSymbolicLink()).toBe(true);+ try { rmSync(altDir, { recursive: true, force: true }); } catch {}+ });++ test("uninstall removes the symlink only, leaves source alone", () => {+ piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts());+ piAdapter.uninstall(env(), applyOpts());+ expect(existsSync(linkPath())).toBe(false);+ // Source must still be there+ expect(existsSync(join(skillSource, "SKILL.md"))).toBe(true);+ expect(readManifest(vault).installs.pi).toBeUndefined();+ });++ test("verify returns ok when symlink is valid", () => {+ piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts());+ expect(piAdapter.verify(env()).status).toBe("ok");+ });++ test("verify reports drift when symlink is broken (target gone)", () => {+ piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts());+ rmSync(skillSource, { recursive: true, force: true });+ expect(piAdapter.verify(env()).status).toBe("drift");+ });+});diff --git a/tests/core/install/json-merge.test.ts b/tests/core/install/json-merge.test.tsnew file mode 100644index 00000000..813ae536--- /dev/null+++ b/tests/core/install/json-merge.test.ts@@ -0,0 +1,156 @@+import { describe, expect, test } from "bun:test";+import {+ mergeMcpServers,+ removeMcpServers,+ JsonMergeError,+} from "../../../src/core/install/json-merge.ts";+import type { McpPayload } from "../../../src/core/install/types.ts";++const OSB_PAYLOAD: McpPayload = {+ full: {+ command: "o2b",+ args: ["mcp", "--vault", "/home/u/vault"],+ env: { VAULT_AGENT_NAME: "claude-vps-agent", VAULT_TIMEZONE: "Europe/Belgrade" },+ },+ writer: {+ command: "o2b",+ args: ["mcp", "--writer-only", "--vault", "/home/u/vault"],+ env: { VAULT_AGENT_NAME: "claude-vps-agent", VAULT_TIMEZONE: "Europe/Belgrade" },+ },+};++describe("mergeMcpServers", () => {+ test("creates file from scratch when input is empty", () => {+ const out = mergeMcpServers("", OSB_PAYLOAD);+ const parsed = JSON.parse(out);+ expect(Object.keys(parsed.mcpServers)).toEqual([+ "open-second-brain",+ "open-second-brain-writer",+ ]);+ expect(out.endsWith("\n")).toBe(true);+ });++ test("creates file from null/undefined-ish empty whitespace", () => {+ const out = mergeMcpServers(" \n ", OSB_PAYLOAD);+ const parsed = JSON.parse(out);+ expect(parsed.mcpServers["open-second-brain"]).toBeDefined();+ });++ test("preserves unrelated mcpServers keys, OSB keys appended", () => {+ const before = `{+ "mcpServers": {+ "other": { "command": "x", "args": [] }+ }+}+`;+ const out = mergeMcpServers(before, OSB_PAYLOAD);+ const parsed = JSON.parse(out);+ expect(Object.keys(parsed.mcpServers)).toEqual([+ "other",+ "open-second-brain",+ "open-second-brain-writer",+ ]);+ expect(parsed.mcpServers.other).toEqual({ command: "x", args: [] });+ });++ test("preserves unrelated top-level keys", () => {+ const before = `{+ "theme": "dark",+ "mcpServers": {}+}+`;+ const out = mergeMcpServers(before, OSB_PAYLOAD);+ const parsed = JSON.parse(out);+ expect(parsed.theme).toBe("dark");+ });++ test("overwrites old OSB keys with current canonical payload", () => {+ const before = `{+ "mcpServers": {+ "open-second-brain": { "command": "o2b", "args": ["mcp", "--vault", "/OLD"] }+ }+}+`;+ const out = mergeMcpServers(before, OSB_PAYLOAD);+ const parsed = JSON.parse(out);+ expect(parsed.mcpServers["open-second-brain"].args).toEqual([+ "mcp", "--vault", "/home/u/vault",+ ]);+ });++ test("uses different top-level key when overridden (kiro/gemini-style)", () => {+ const before = `{+ "mcp_servers": {+ "other": { "command": "x" }+ }+}+`;+ const out = mergeMcpServers(before, OSB_PAYLOAD, { topLevelKey: "mcp_servers" });+ const parsed = JSON.parse(out);+ expect(parsed.mcp_servers["open-second-brain"]).toBeDefined();+ expect(parsed.mcp_servers.other.command).toBe("x");+ });++ test("preserves 4-space indent", () => {+ const before = `{+ "mcpServers": {+ "other": { "command": "x" }+ }+}+`;+ const out = mergeMcpServers(before, OSB_PAYLOAD);+ // 4-space indent detection: at least one line starts with exactly 4 spaces followed by a quote+ expect(out.split("\n").some((l) => /^ {4}"/.test(l))).toBe(true);+ });++ test("rejects malformed JSON with file context", () => {+ expect(() => mergeMcpServers('{ "mcpServers":', OSB_PAYLOAD)).toThrow(JsonMergeError);+ });+});++describe("removeMcpServers", () => {+ test("removes both OSB keys, preserves others", () => {+ const before = mergeMcpServers(+ `{+ "mcpServers": {+ "other": { "command": "x" }+ }+}+`,+ OSB_PAYLOAD,+ );+ const after = removeMcpServers(before);+ const parsed = JSON.parse(after);+ expect(parsed.mcpServers["open-second-brain"]).toBeUndefined();+ expect(parsed.mcpServers["open-second-brain-writer"]).toBeUndefined();+ expect(parsed.mcpServers.other).toEqual({ command: "x" });+ });++ test("noop when OSB keys not present", () => {+ const before = `{+ "mcpServers": { "other": { "command": "x" } }+}+`;+ const after = removeMcpServers(before);+ const parsed = JSON.parse(after);+ expect(parsed.mcpServers.other).toEqual({ command: "x" });+ });++ test("noop on empty input", () => {+ expect(removeMcpServers("")).toBe("");+ });++ test("custom topLevelKey works for remove too", () => {+ const before = `{+ "mcp_servers": {+ "open-second-brain": { "command": "o2b" },+ "other": { "command": "x" }+ }+}+`;+ const after = removeMcpServers(before, { topLevelKey: "mcp_servers" });+ const parsed = JSON.parse(after);+ expect(parsed.mcp_servers["open-second-brain"]).toBeUndefined();+ expect(parsed.mcp_servers.other.command).toBe("x");+ });+});diff --git a/tests/core/install/managed-block.test.ts b/tests/core/install/managed-block.test.tsnew file mode 100644index 00000000..ac386175--- /dev/null+++ b/tests/core/install/managed-block.test.ts@@ -0,0 +1,95 @@+import { describe, expect, test } from "bun:test";+import {+ insertManagedBlock,+ removeManagedBlock,+ hasManagedBlock,+ extractManagedBlock,+ ManagedBlockError,+ DEFAULT_BEGIN_MARKER,+ DEFAULT_END_MARKER,+} from "../../../src/core/install/managed-block.ts";++describe("managed-block insertManagedBlock", () => {+ test("appends block when no marker present, preserves preceding content", () => {+ const before = `# user config\nkey: value\n`;+ const out = insertManagedBlock(before, " - path/to/file\n");+ expect(out).toContain(DEFAULT_BEGIN_MARKER);+ expect(out).toContain(DEFAULT_END_MARKER);+ expect(out).toContain(" - path/to/file");+ expect(out.startsWith("# user config\nkey: value\n")).toBe(true);+ });++ test("replaces existing block, leaves surrounding content untouched", () => {+ const before = `# top\n${DEFAULT_BEGIN_MARKER}\nOLD\n${DEFAULT_END_MARKER}\n# bottom\n`;+ const out = insertManagedBlock(before, "NEW\n");+ expect(out).toContain("NEW");+ expect(out).not.toContain("OLD");+ expect(out.startsWith("# top\n")).toBe(true);+ expect(out.trimEnd().endsWith("# bottom")).toBe(true);+ });++ test("re-apply is idempotent", () => {+ const before = `# top\n`;+ const once = insertManagedBlock(before, "BODY\n");+ const twice = insertManagedBlock(once, "BODY\n");+ expect(once).toBe(twice);+ });++ test("CRLF input preserves CRLF line endings on write", () => {+ const before = `# top\r\nkey: value\r\n`;+ const out = insertManagedBlock(before, "BODY\n");+ expect(out.includes("\r\n")).toBe(true);+ });++ test("rejects nested begin markers", () => {+ const malformed = `${DEFAULT_BEGIN_MARKER}\n${DEFAULT_BEGIN_MARKER}\n${DEFAULT_END_MARKER}\n`;+ expect(() => insertManagedBlock(malformed, "x")).toThrow(ManagedBlockError);+ });++ test("rejects unterminated block (begin without end)", () => {+ const malformed = `${DEFAULT_BEGIN_MARKER}\nstuff\n`;+ expect(() => insertManagedBlock(malformed, "x")).toThrow(ManagedBlockError);+ });++ test("custom markers parametrised through opts", () => {+ const before = "# top\n";+ const out = insertManagedBlock(before, "X\n", {+ beginMarker: "# >>>>> open-second-brain custom >>>>>",+ endMarker: "# <<<<< open-second-brain custom <<<<<",+ });+ expect(out).toContain("# >>>>> open-second-brain custom >>>>>");+ });+});++describe("managed-block removeManagedBlock", () => {+ test("removes block and markers, normalises blank lines", () => {+ const before = `# top\n\n${DEFAULT_BEGIN_MARKER}\nBODY\n${DEFAULT_END_MARKER}\n\n# bottom\n`;+ const out = removeManagedBlock(before);+ expect(out).not.toContain(DEFAULT_BEGIN_MARKER);+ expect(out).not.toContain("BODY");+ expect(out).toContain("# top");+ expect(out).toContain("# bottom");+ expect(out.includes("\n\n\n")).toBe(false);+ });++ test("noop when no block present", () => {+ const before = `# nothing here\n`;+ expect(removeManagedBlock(before)).toBe(before);+ });+});++describe("managed-block detection helpers", () => {+ test("hasManagedBlock recognises a present block", () => {+ const text = `${DEFAULT_BEGIN_MARKER}\nbody\n${DEFAULT_END_MARKER}\n`;+ expect(hasManagedBlock(text)).toBe(true);+ });++ test("hasManagedBlock false when missing", () => {+ expect(hasManagedBlock("# nothing\n")).toBe(false);+ });++ test("extractManagedBlock returns the body without markers", () => {+ const text = `# x\n${DEFAULT_BEGIN_MARKER}\nLINE1\nLINE2\n${DEFAULT_END_MARKER}\n# y\n`;+ expect(extractManagedBlock(text)).toBe("LINE1\nLINE2");+ });+});diff --git a/tests/core/install/manifest.test.ts b/tests/core/install/manifest.test.tsnew file mode 100644index 00000000..268dc203--- /dev/null+++ b/tests/core/install/manifest.test.ts@@ -0,0 +1,117 @@+import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import { mkdtempSync, rmSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import {+ readManifest,+ recordEntry,+ removeEntry,+ manifestPath,+} from "../../../src/core/install/manifest.ts";+import type { ManifestEntry } from "../../../src/core/install/types.ts";++let vault: string;+beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-manifest-"));+});+afterEach(() => {+ try { rmSync(vault, { recursive: true, force: true }); } catch {}+});++describe("install manifest sidecar", () => {+ test("manifestPath lives under <vault>/.open-second-brain/install.lock.json", () => {+ expect(manifestPath(vault)).toBe(join(vault, ".open-second-brain", "install.lock.json"));+ });++ test("readManifest returns empty shell when file is missing", () => {+ const m = readManifest(vault);+ expect(m.schema_version).toBe(1);+ expect(m.installs).toEqual({});+ });++ test("recordEntry creates sidecar dir + file with trailing newline", () => {+ const entry: ManifestEntry = {+ target: "cursor",+ applied_at: "2026-05-20T12:00:00.000Z",+ operation: "json-merge",+ config_path: "/home/u/.cursor/mcp.json",+ owned_keys: ["mcpServers.open-second-brain"],+ };+ recordEntry(vault, entry);+ const m = readManifest(vault);+ expect(m.installs.cursor).toEqual(entry);+ const raw = readFileSync(manifestPath(vault), "utf8");+ expect(raw.endsWith("\n")).toBe(true);+ });++ test("recordEntry overwrites existing entry for the same target", () => {+ recordEntry(vault, {+ target: "cursor",+ applied_at: "2026-05-20T12:00:00.000Z",+ operation: "json-merge",+ config_path: "/a",+ owned_keys: ["mcpServers.open-second-brain"],+ });+ recordEntry(vault, {+ target: "cursor",+ applied_at: "2026-05-20T12:05:00.000Z",+ operation: "json-merge",+ config_path: "/b",+ owned_keys: ["mcpServers.open-second-brain"],+ });+ const m = readManifest(vault);+ expect(m.installs.cursor!.applied_at).toBe("2026-05-20T12:05:00.000Z");+ expect(m.installs.cursor!.config_path).toBe("/b");+ });++ test("removeEntry deletes the named target only", () => {+ recordEntry(vault, {+ target: "cursor",+ applied_at: "2026-05-20T12:00:00.000Z",+ operation: "json-merge",+ config_path: "/a",+ owned_keys: ["mcpServers.open-second-brain"],+ });+ recordEntry(vault, {+ target: "pi",+ applied_at: "2026-05-20T12:00:00.000Z",+ operation: "symlink",+ config_path: null,+ owned_paths: ["/p"],+ });+ removeEntry(vault, "cursor");+ const m = readManifest(vault);+ expect(m.installs.cursor).toBeUndefined();+ expect(m.installs.pi).toBeDefined();+ });++ test("removeEntry on missing target is a no-op", () => {+ expect(() => removeEntry(vault, "cursor")).not.toThrow();+ expect(readManifest(vault).installs).toEqual({});+ });++ test("readManifest tolerates forward-compat unknown top-level keys", () => {+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ writeFileSync(+ manifestPath(vault),+ JSON.stringify({ schema_version: 1, installs: {}, future_thing: 42 }),+ );+ const m = readManifest(vault);+ expect(m.schema_version).toBe(1);+ });++ test("readManifest rejects unknown schema_version", () => {+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ writeFileSync(+ manifestPath(vault),+ JSON.stringify({ schema_version: 999, installs: {} }),+ );+ expect(() => readManifest(vault)).toThrow(/schema_version/);+ });++ test("readManifest rejects malformed JSON", () => {+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ writeFileSync(manifestPath(vault), "{ not json");+ expect(() => readManifest(vault)).toThrow();+ });+});diff --git a/tests/core/install/payload.test.ts b/tests/core/install/payload.test.tsnew file mode 100644index 00000000..be638279--- /dev/null+++ b/tests/core/install/payload.test.ts@@ -0,0 +1,51 @@+import { describe, expect, test } from "bun:test";+import { buildPayload, PayloadError } from "../../../src/core/install/payload.ts";++describe("buildPayload", () => {+ test("returns full + writer entries with vault arg", () => {+ const { full, writer } = buildPayload({+ vault: "/home/u/vault",+ agent_name: "claude-vps",+ timezone: "Europe/Belgrade",+ });+ expect(full.command).toBe("o2b");+ expect(full.args).toEqual(["mcp", "--vault", "/home/u/vault"]);+ expect(writer.command).toBe("o2b");+ expect(writer.args).toEqual(["mcp", "--writer-only", "--vault", "/home/u/vault"]);+ });++ test("includes env when agent_name + timezone present", () => {+ const { full, writer } = buildPayload({+ vault: "/v", agent_name: "a", timezone: "UTC",+ });+ expect(full.env).toEqual({ VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" });+ expect(writer.env).toEqual({ VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" });+ });++ test("omits env entirely when both agent_name and timezone are null", () => {+ const { full } = buildPayload({ vault: "/v", agent_name: null, timezone: null });+ expect(full.env).toBeUndefined();+ });++ test("partial env: only agent_name", () => {+ const { full } = buildPayload({ vault: "/v", agent_name: "a", timezone: null });+ expect(full.env).toEqual({ VAULT_AGENT_NAME: "a" });+ });++ test("partial env: only timezone", () => {+ const { full } = buildPayload({ vault: "/v", agent_name: null, timezone: "UTC" });+ expect(full.env).toEqual({ VAULT_TIMEZONE: "UTC" });+ });++ test("throws PayloadError on missing vault", () => {+ expect(() => buildPayload({ vault: "", agent_name: null, timezone: null }))+ .toThrow(PayloadError);+ expect(() => buildPayload({ vault: null as unknown as string, agent_name: null, timezone: null }))+ .toThrow(PayloadError);+ });++ test("writer args carry --writer-only before --vault", () => {+ const { writer } = buildPayload({ vault: "/v", agent_name: null, timezone: null });+ expect(writer.args.indexOf("--writer-only")).toBeLessThan(writer.args.indexOf("--vault"));+ });+});diff --git a/tests/core/install/registry.test.ts b/tests/core/install/registry.test.tsnew file mode 100644index 00000000..c954659b--- /dev/null+++ b/tests/core/install/registry.test.ts@@ -0,0 +1,98 @@+import { describe, expect, test } from "bun:test";+import { createRegistry } from "../../../src/core/install/registry.ts";+import type {+ InstallAdapter,+ InstallEnv,+ DetectResult,+ InstallPlan,+ ApplyResult,+ UninstallResult,+ VerifyResult,+} from "../../../src/core/install/types.ts";++function makeFakeAdapter(target: string): InstallAdapter {+ return {+ target,+ label: target,+ detect(env: InstallEnv): DetectResult {+ void env;+ return { target, status: "not-installed", configPath: null, notes: [] };+ },+ plan(): InstallPlan {+ return { target, steps: [], postNotes: [] };+ },+ apply(): ApplyResult {+ return {+ target,+ steps_executed: 0,+ manifest: {+ target,+ applied_at: "2026-05-20T00:00:00.000Z",+ operation: "print",+ config_path: null,+ },+ };+ },+ uninstall(): UninstallResult {+ return { target, removed_keys: [], removed_paths: [], skipped: [] };+ },+ verify(): VerifyResult {+ return { target, status: "not-installed", details: [], fix_hint: null };+ },+ };+}++function makeEnv(): InstallEnv {+ return {+ vault: "/tmp/v",+ home: "/tmp/h",+ cwd: "/tmp/c",+ env: {},+ now: new Date("2026-05-20T00:00:00.000Z"),+ };+}++describe("install registry", () => {+ test("starts empty", () => {+ const reg = createRegistry();+ expect(reg.list()).toEqual([]);+ expect(reg.get("cursor")).toBeUndefined();+ });++ test("register + get round-trip", () => {+ const reg = createRegistry();+ const a = makeFakeAdapter("test");+ reg.register(a);+ expect(reg.get("test")).toBe(a);+ expect(reg.list().map((x) => x.target)).toEqual(["test"]);+ });++ test("register rejects duplicate target", () => {+ const reg = createRegistry();+ reg.register(makeFakeAdapter("cursor"));+ expect(() => reg.register(makeFakeAdapter("cursor"))).toThrow(/duplicate/i);+ });++ test("detectAll returns one entry per registered adapter", () => {+ const reg = createRegistry();+ reg.register(makeFakeAdapter("a"));+ reg.register(makeFakeAdapter("b"));+ const out = reg.detectAll(makeEnv());+ expect(out.map((d) => d.target).sort()).toEqual(["a", "b"]);+ });++ test("list returns adapters in registration order", () => {+ const reg = createRegistry();+ reg.register(makeFakeAdapter("b"));+ reg.register(makeFakeAdapter("a"));+ reg.register(makeFakeAdapter("c"));+ expect(reg.list().map((x) => x.target)).toEqual(["b", "a", "c"]);+ });++ test("targets() returns target names only", () => {+ const reg = createRegistry();+ reg.register(makeFakeAdapter("a"));+ reg.register(makeFakeAdapter("b"));+ expect(reg.targets()).toEqual(["a", "b"]);+ });+});diff --git a/tests/core/install/types.test.ts b/tests/core/install/types.test.tsnew file mode 100644index 00000000..ca02122f--- /dev/null+++ b/tests/core/install/types.test.ts@@ -0,0 +1,47 @@+import { describe, expect, test } from "bun:test";+import {+ ADAPTER_STATUSES,+ INSTALL_STEP_KINDS,+ VERIFY_STATUSES,+ InstallError,+} from "../../../src/core/install/types.ts";++describe("install types", () => {+ test("ADAPTER_STATUSES covers the four documented states", () => {+ expect(new Set(ADAPTER_STATUSES)).toEqual(+ new Set([+ "not-installed",+ "installed",+ "drift",+ "unsupported-on-this-platform",+ ]),+ );+ });++ test("INSTALL_STEP_KINDS covers the six operation kinds", () => {+ expect(new Set(INSTALL_STEP_KINDS)).toEqual(+ new Set([+ "json-merge",+ "managed-block",+ "subprocess",+ "file-copy",+ "symlink",+ "print",+ ]),+ );+ });++ test("VERIFY_STATUSES covers the four documented states", () => {+ expect(new Set(VERIFY_STATUSES)).toEqual(+ new Set(["ok", "drift", "not-installed", "mcp-unreachable"]),+ );+ });++ test("InstallError carries target + kind + hint", () => {+ const err = new InstallError("nope", "cursor", "user-modified-block", "run with --force");+ expect(err.target).toBe("cursor");+ expect(err.kind).toBe("user-modified-block");+ expect(err.hint).toBe("run with --force");+ expect(err.message).toBe("nope");+ });+});diff --git a/tests/discipline/render.test.ts b/tests/discipline/render.test.tsindex 6adf2938..f5d9a4ba 100644--- a/tests/discipline/render.test.ts+++ b/tests/discipline/render.test.ts@@ -47,5 +47,52 @@ describe("renderReport", () => {});expect(text).toContain("Status: alert");expect(text).toContain("zero brain events");+ expect(text).not.toContain("transcript\\-confirmed");+ });++ test("status: alert + transcripts present adds transcript-confirmed sub-reason", () => {+ const text = renderReport({+ localDate: "2026-05-17",+ timezone: "UTC",+ status: "alert",+ events: { byAgent: { "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 } }, unknownAgents: [], total: 0 },+ activity: {+ repo: [{ path: "/x", git: { commits: 3, filesChanged: 5, insertions: 10, deletions: 2 } }],+ nonRepo: [],+ vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },+ transcripts: {+ byRuntime: [+ { runtime: "claudecode", fileCount: 2, agentHint: "claude-vps-agent" },+ { runtime: "codex", fileCount: 0, agentHint: "codex-vps-agent" },+ ],+ totalFiles: 2,+ },+ },+ });+ expect(text).toContain("Status: alert");+ expect(text).toContain("transcripts β claudecode: 2");+ expect(text).toContain("transcript\\-confirmed");+ });++ test("transcripts with zero files omit the line and skip the sub-reason", () => {+ const text = renderReport({+ localDate: "2026-05-17",+ timezone: "UTC",+ status: "alert",+ events: { byAgent: { "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 } }, unknownAgents: [], total: 0 },+ activity: {+ repo: [{ path: "/x", git: { commits: 1, filesChanged: 1, insertions: 1, deletions: 0 } }],+ nonRepo: [],+ vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },+ transcripts: {+ byRuntime: [+ { runtime: "claudecode", fileCount: 0, agentHint: "claude-vps-agent" },+ ],+ totalFiles: 0,+ },+ },+ });+ expect(text).not.toContain("transcripts β");+ expect(text).not.toContain("transcript\\-confirmed");});});diff --git a/tests/discipline/report.test.ts b/tests/discipline/report.test.tsindex c5f967ec..a8116fc5 100644--- a/tests/discipline/report.test.ts+++ b/tests/discipline/report.test.ts@@ -52,4 +52,20 @@ describe("runDisciplineReport", () => {expect(res.text).toBe("");rmSync(vault, { recursive: true });});++ test("missing Brain config disables report for legacy bare vaults", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-disc-missing-"));+ const res = runDisciplineReport({ vault, now: new Date() });+ expect(res.status).toBe("disabled");+ expect(res.text).toBe("");+ rmSync(vault, { recursive: true });+ });++ test("malformed Brain config is not silently disabled", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-disc-bad-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "not: valid: yaml\n", "utf8");+ expect(() => runDisciplineReport({ vault, now: new Date() })).toThrow();+ rmSync(vault, { recursive: true });+ });});