Skip to content

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

TypeScript

feat: native opencode integration - config-correct install, bundled plugin, session capture (#88)

Sol Aitken96f1ff4bf0ae
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 35747d43..9b209b47 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,54 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.4.0] - 2026-06-10
+
+Native opencode integration: the install adapter now writes the config
+opencode actually reads, and a bundled plugin brings the runtime to
+near-parity with the Claude Code and Codex integrations - live active
+context injection, lifecycle-driven session capture, and the post-write
+logging reminder.
+
+### Added
+
+- **Bundled opencode plugin** (`plugins/opencode/open-second-brain.ts`):
+ a single zero-dependency file installed into
+ `~/.config/opencode/plugins/` by `o2b install --target opencode
+ --apply`. On each chat request it appends the rendered
+ `Brain/active.md` digest to the system prompt (via the same
+ `o2b-hook active-inject` shim the Claude Code and Codex hook layers
+ use, cached with a 5 minute TTL); on `session.idle` /
+ `session.compacted` / `session.deleted` it snapshots the session as
+ a deterministic JSONL spool under
+ `${XDG_DATA_HOME:-~/.local/share}/open-second-brain/opencode/`; after
+ file-mutating tools it appends the standard logging nudge to the
+ tool output. Every hook is fail-soft - a missing vault, missing
+ binary, or SDK error never breaks the opencode session.
+- **opencode session adapter** (`src/core/brain/sessions/opencode.ts`):
+ fourth adapter in the session registry. Imports the plugin-owned
+ spool format (`format: 1`, originator
+ `open-second-brain-opencode-plugin`) through the same
+ `o2b brain import-session` flow as Claude, Codex, and Hermes
+ transcripts; a spool written by a newer plugin fails with a
+ versioned error instead of silently dropping fields.
+- **Pluggable MCP entry shape** in the shared JSON-merge install layer:
+ `createJsonMcpAdapter` accepts `serializeEntry` / `entryEquals`, so
+ runtimes whose MCP config schema differs from the default
+ `{command, args, env}` entry reuse the same
+ detect/plan/apply/verify/uninstall body with drift detection intact.
+ Existing targets (Cursor, kiro, Gemini CLI) are byte-identical.
+
+### Fixed
+
+- **opencode install adapter targeted a file opencode does not read.**
+ The adapter now merges the two Open Second Brain servers into
+ `~/.config/opencode/opencode.json` under the `mcp` key using
+ opencode's entry schema (`{type: "local", command: [bin, ...args],
+ environment, enabled: true}`), honouring `XDG_CONFIG_HOME`. Apply
+ also migrates the stale `~/.config/opencode/mcp.json` written by
+ earlier releases: the two Open Second Brain keys are removed, and the
+ file is deleted when nothing else remains.
+
## [1.3.0] - 2026-06-10
Continuity, Hygiene & Freshness Suite: one conversation stays one
@@ -5122,7 +5170,8 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
-[Unreleased]: https://github.com/itechmeat/open-second-brain/compare/v1.2.0...HEAD
+[1.4.0]: https://github.com/itechmeat/open-second-brain/compare/v1.3.0...v1.4.0
+[1.3.0]: https://github.com/itechmeat/open-second-brain/compare/v1.2.0...v1.3.0
[1.2.0]: https://github.com/itechmeat/open-second-brain/compare/v1.1.0...v1.2.0
[1.1.0]: https://github.com/itechmeat/open-second-brain/compare/v1.0.1...v1.1.0
[1.0.1]: https://github.com/itechmeat/open-second-brain/compare/v1.0.0...v1.0.1
diff --git a/README.md b/README.md
index 2e52fb12..790ccc62 100644
--- a/README.md
+++ b/README.md
@@ -69,7 +69,8 @@ Enable Open Second Brain as the memory provider in `~/.hermes/config.yaml` (`mem
| Claude Code | Marketplace plugin (bundled `.mcp.json` + hooks) - [`install/claudecode.md`](install/claudecode.md) |
| OpenAI Codex | `codex plugin marketplace add ...` - [`install/codex.md`](install/codex.md) |
| OpenClaw | Native JS plugin, no MCP needed - [`install/openclaw.md`](install/openclaw.md) |
-| Cursor · Aider · opencode · kiro · Copilot CLI · Gemini CLI · Pi | `o2b install --target <name> --apply` - see [`install/`](install/) |
+| opencode | `o2b install --target opencode --apply` (MCP servers + native plugin) - [`install/opencode.md`](install/opencode.md) |
+| Cursor · Aider · kiro · Copilot CLI · Gemini CLI · Pi | `o2b install --target <name> --apply` - see [`install/`](install/) |
| Any other MCP host | `o2b install --target generic --apply` - [`install/generic.md`](install/generic.md) |
Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-brain/install.lock.json` so `o2b uninstall --target <name> --apply` removes exactly what it added.
diff --git a/docs/brainstorm/opencode-native-integration/cli-output/claude.md b/docs/brainstorm/opencode-native-integration/cli-output/claude.md
new file mode 100644
index 00000000..62e267a7
--- /dev/null
+++ b/docs/brainstorm/opencode-native-integration/cli-output/claude.md
@@ -0,0 +1,40 @@
+### Variant 1: Config-surface only (no plugin)
+
+- **Approach**: Rewrite `src/core/install/adapters/opencode.ts` to write the real `~/.config/opencode/opencode.json` (extending `createJsonMcpAdapter` with a pluggable entry-shape transform to emit `{type: "local", command: [...], environment, enabled}`), migrate and delete the stale `mcp.json`, and wire rules via the native `instructions` key pointing at the vault's active-context file. Session parity comes from a new session adapter in `SESSION_ADAPTERS` that parses opencode's on-disk storage under `~/.local/share/opencode/storage/`. No plugin is shipped.
+- **Trade-offs**:
+ - Pro: smallest surface; everything fits the existing install-adapter and session-adapter patterns with zero new runtime pieces.
+ - Pro: nothing runs inside opencode, so fail-soft is trivial.
+ - Con: the storage format is undocumented and unstable; the importer will silently break on opencode upgrades and fixtures will drift from reality.
+ - Con: no live behavior at all - no session-start context inject timing, no idle/compact capture triggers, no post-write reminders; clearly below Claude Code/Codex parity.
+ - Con: `instructions` injects statically per config load, not per session, so freshness of active context is weaker.
+- **Complexity**: small
+- **Risk**: high
+
+### Variant 2: Bundled self-contained plugin plus spool-file session adapter
+
+- **Approach**: The install adapter does three things: writes the correct `mcp` entry into `opencode.json` (via the extended `_json-mcp.ts` entry-shape hook), migrates the stale `mcp.json`, and copies a single zero-dependency bundled plugin file into `~/.config/opencode/plugins/`. The plugin uses public hooks only: on `session.created` it injects active context (spawning `o2b` or reading `Brain/active.md`, wrapped in try/catch for fail-soft), and on `session.idle` / `session.compacted` / `session.deleted` it pulls messages through the SDK `client` and appends a normalized JSONL spool file; a fourth session adapter (`opencode`) with `detect(firstLine)` plus `iterate(path)` imports that spool through the existing registry, exactly like claude/codex/hermes. Rules ride on native AGENTS.md support.
+- **Trade-offs**:
+ - Pro: the JSONL format is owned by Open Second Brain, so the session adapter and its fixtures are stable and fully testable offline; the only untested-on-CI piece is the thin plugin, which is a pure function testable with a fake `client`.
+ - Pro: reuses every existing pattern (install lifecycle, manifest, drift detection, session registry) and keeps the MCP server runtime-agnostic.
+ - Pro: fail-soft is localized in one small plugin file; opencode keeps working if vault or binary is absent.
+ - Con: capture is event-driven only; sessions where opencode crashes before `session.idle` may lose the tail.
+ - Con: a copied plugin file can drift from the installed o2b version; needs a version marker plus drift check in the manifest.
+ - Con: some hooks used for niceties (`experimental.chat.system.transform`) are experimental; must degrade gracefully.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: npm-distributed plugin with live streaming capture
+
+- **Approach**: Publish `@open-second-brain/opencode-plugin` to npm and register it under the `plugin` key in `opencode.json`; the install adapter only edits config. The plugin streams continuously: `message.updated` and `tool.execute.after` events are translated into the existing hook payload protocol and piped to the bundled `o2b-hook` binary on stdin (extending `hooks/lib/detect.ts` with an opencode payload shape), so capture, reminders, and guardrails all flow through the same hook layer Claude Code and Codex use, with no import adapter and no spool files.
+- **Trade-offs**:
+ - Pro: deepest parity - the opencode runtime becomes a first-class peer in the existing hook layer rather than a parallel path; capture is real-time with no tail loss.
+ - Pro: opencode-native distribution with version pinning and auto-install; no copied-file drift.
+ - Con: requires a publish pipeline and network at user install time; dev and CI machines without network cannot exercise the real install path.
+ - Con: lockstep versioning between the npm plugin and the local o2b binary becomes an ongoing release burden.
+ - Con: per-message spawning of the hook binary is chatty and harder to fixture-test end to end; failure modes multiply.
+- **Complexity**: large
+- **Risk**: medium
+
+### Recommended: Variant 2
+
+**Rationale**: Variant 2 reaches genuine parity (live context inject, event-driven capture, registry-based session import) while keeping every risky dependency under the project's control: the spool JSONL is an owned format, the plugin is one self-contained file shipped by the existing install framework, and everything is testable from fixtures with opencode absent, which Variants 1 and 3 cannot claim. Variant 1 stakes session capture on an undocumented storage format, and Variant 3 buys marginal extra parity at the cost of a publish pipeline, network-dependent installs, and lockstep versioning that contradict the zero-dep and offline-test constraints.
diff --git a/docs/brainstorm/opencode-native-integration/cli-output/prompt.md b/docs/brainstorm/opencode-native-integration/cli-output/prompt.md
new file mode 100644
index 00000000..505b2af9
--- /dev/null
+++ b/docs/brainstorm/opencode-native-integration/cli-output/prompt.md
@@ -0,0 +1,74 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+Add a native opencode (https://opencode.ai) integration to Open Second Brain, mirroring the depth of the existing Claude Code and Codex integrations - as native as the opencode extensibility surface allows.
+
+Known facts, validated against opencode docs 2026-06-10:
+
+- opencode MCP config lives in `opencode.json` (global: `~/.config/opencode/opencode.json`) under the `mcp` key with entries shaped `{ "type": "local", "command": ["o2b", "mcp", ...], "environment": {...}, "enabled": true }`. The repo's current `src/core/install/adapters/opencode.ts` writes `~/.config/opencode/mcp.json` with a `mcpServers` key - a file opencode does not read. The integration must start writing the real config and migrate/clean up the stale one.
+- opencode's native extensibility surface is a plugin system: JS/TS files in `~/.config/opencode/plugins/` (global) or `.opencode/plugins/` (project), auto-loaded at startup. A plugin exports `async ({ project, client, $, directory, worktree }) => Hooks` where `client` is an SDK client to the running opencode server. Hooks include: `event` (bus: session.created / session.idle / session.compacted / session.deleted / message.updated / file.edited / ...), `chat.message`, `chat.params`, `tool.execute.before` / `tool.execute.after`, `command.execute.before`, `experimental.session.compacting`, `experimental.chat.system.transform`, custom `tool` definitions, `dispose`. Plugins can also be distributed as npm packages listed under the `plugin` key in opencode.json.
+- Rules: opencode reads AGENTS.md natively and supports an `instructions` config key (file paths/globs).
+- The plugin SDK `client` can read session messages via public API - a candidate for session capture without reverse-engineering opencode's on-disk storage (`~/.local/share/opencode/storage/`), whose format is undocumented and unstable.
+- opencode is NOT installed on the dev server; tests must run from fixtures.
+
+What the existing integrations provide (parity targets):
+
+1. Claude Code: hooks (SessionStart active-context inject, session-capture on UserPromptSubmit/Stop/SessionEnd/PostCompact, post-write reminders, stop-log guardrail) via hooks/hooks.json calling a bundled `o2b-hook` binary reading a JSON payload on stdin; MCP server auto-registered via bundled .mcp.json; session import adapter parsing Claude JSONL transcripts (src/core/brain/sessions/claude.ts) registered in a 3-adapter registry (claude/codex/hermes) with first-line format autodetection.
+2. Codex: same hook layer (runtime detected from payload shape, hooks/lib/detect.ts), explicit `codex mcp add` registration, session import adapter for rollout-event JSONL.
+3. Install adapters framework: src/core/install/ with a registry, `createJsonMcpAdapter` factory (_json-mcp.ts, supports custom topLevelKey but currently hardcodes the `{command, args, env}` entry shape), canonical payload builder (payload.ts builds two servers: full + writer-only), manifest in install.lock.json, detect/plan/apply/verify/uninstall lifecycle per adapter, drift detection, atomic writes.
+
+# Project context
+
+Open Second Brain - TypeScript, Bun runtime, SQLite. An agent-owned second brain in an Obsidian-compatible Markdown vault, exposed to coding agents via MCP (stdio) plus per-runtime hook layers.
+
+Recent commits:
+0340560 feat: Continuity, Hygiene & Freshness Suite - session lineage, memory hygiene, anticipatory cache (v1.3.0) (#87)
+8972f13 refactor: SOLID/DRY decomposition - domain modules, unified helpers, surface guards (v1.2.0) (#86)
+6651228 refactor: language-agnostic fact extraction + README slim (v1.1.0) (#85)
+9886d9a refactor: make search and classification language-agnostic (#84)
+618870e refactor!: remove the pay.sh integration and the Pay Memory layer (#83)
+957a403 feat!: Stability & Trust - 1.0.0 API freeze, deprecation sweep, safeguard, staged dream, timezone, report deltas (#79)
+6d09d3c feat: Link & Recall Intelligence Suite - alias resolution, bridge discovery, communities, recall benchmark, self-tuning (#77)
+
+Related files:
+- src/core/install/adapters/opencode.ts (stale config-path adapter to replace)
+- src/core/install/adapters/_json-mcp.ts (shared JSON-merge adapter body)
+- src/core/install/payload.ts (canonical two-server MCP payload)
+- src/core/install/types.ts, src/core/install/json-merge.ts, src/core/install/manifest.ts
+- src/core/brain/sessions/{types,registry,claude,codex,hermes,import}.ts (session adapter contract + registry)
+- hooks/hooks.json, hooks/lib/stdin.ts (HookPayloadBase), hooks/lib/detect.ts (runtime detection)
+- src/mcp/server.ts, src/mcp/stdio.ts (MCP stdio server)
+- install/opencode.md, install.md, README.md (docs)
+- tests/core/install/adapters/*, tests/core/brain.sessions.*.test.ts, tests/fixtures/sessions/*, tests/fixtures/install/*
+
+Conventions:
+- Strict TDD: failing test first, then code; zero lint/typecheck warnings gate
+- Conventional commits; one PR = one CHANGELOG version
+- Session adapters: detect(firstLine) + iterate(path) -> AsyncIterable<SessionTurn>, registered in SESSION_ADAPTERS, fixtures as tests/fixtures/sessions/<id>-minimal.jsonl
+- Install adapters: detect/plan/apply/verify/uninstall, idempotent apply, drift via payload re-construction, atomic writes, manifest record
+- English-only repo content; full product name "Open Second Brain" in public artifacts; no exclamation marks in docs; no em-dashes
+
+Constraints:
+- Do not break the existing install targets (cursor, kiro, gemini-cli share _json-mcp.ts)
+- No new heavyweight external dependencies; the opencode plugin itself should be self-contained (opencode auto-installs plugin deps via Bun, but prefer zero-dep)
+- opencode absent on dev/CI machines: everything testable from fixtures; no network in tests
+- The plugin must fail soft: if the vault or o2b binary is missing, opencode must keep working
+- Keep the MCP server runtime-agnostic; runtime-specific logic belongs in install adapters, hooks layer, or the shipped plugin
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### Variant N: <short name>
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/opencode-native-integration/design.md b/docs/brainstorm/opencode-native-integration/design.md
new file mode 100644
index 00000000..ccf8af82
--- /dev/null
+++ b/docs/brainstorm/opencode-native-integration/design.md
@@ -0,0 +1,72 @@
+# opencode native integration - bundled plugin, spool capture, config-correct install
+
+**Status:** draft
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+**Kanban:** t_d505b2b9
+
+## Problem statement
+
+Open Second Brain integrates deeply with Claude Code and Codex (hooks, session import, MCP registration) but its opencode support is a single install adapter that writes `~/.config/opencode/mcp.json` with an `mcpServers` key - a file current opencode does not read at all. opencode's real extensibility surface (a documented plugin system with lifecycle hooks plus an SDK client, and `opencode.json` with an `mcp` key) is unused. Operators running opencode get no MCP registration that works, no active-context injection, no session capture, and no session import.
+
+## Scope
+
+- Fix the install adapter to write the config opencode actually reads: `~/.config/opencode/opencode.json`, `mcp` key, entries shaped `{type: "local", command: [...], environment, enabled: true}`. Migrate away the stale `mcp.json` written by previous Open Second Brain versions.
+- Extend the shared JSON-merge layer (`json-merge.ts`, `_json-mcp.ts`, drift detection) with a pluggable entry shape so the opencode adapter, and any future runtime with a non-`mcpServers` schema, reuses the same lifecycle.
+- Ship a single-file, zero-dependency opencode plugin (TypeScript, public hook API only) installed by the adapter into `~/.config/opencode/plugins/`. The plugin: injects active Brain context per session, snapshots session turns into a spool JSONL on lifecycle events, and emits a post-write logging reminder after file-mutating tools. Fail-soft everywhere.
+- Add a fourth session adapter `opencode` to `SESSION_ADAPTERS` that detects and imports the spool JSONL (a format this repo owns), wired through the existing `importSessionPath` flow.
+- Docs: rewrite `install/opencode.md`, update `install.md` quick table and `README.md` runtime list, CHANGELOG entry.
+
+## Out of scope
+
+- Stop-log guardrail parity. opencode has no blocking stop hook; `session.idle` cannot veto a turn. Documented as a known gap.
+- Parsing opencode's on-disk storage (`~/.local/share/opencode/storage/`). Undocumented, unstable; the spool file is the contract instead.
+- npm distribution of the plugin (`plugin` key). Revisit if the bundled-file copy proves brittle in the field.
+- Wiring the `instructions` config key. AGENTS.md support is native in opencode and per-session inject covers freshness.
+- Hermes/Claude hook-layer changes (`hooks/hooks.json`, `hooks/lib/detect.ts` runtime detection). The plugin does not route through `o2b-hook`.
+
+## Chosen approach
+
+Variant 2 from `variants.md` (consultant-recommended, accepted without override).
+
+The install adapter becomes the single entry point: `o2b install --target opencode --apply` (a) merges the two canonical MCP servers into `opencode.json` under `mcp` using opencode's entry schema, (b) copies the bundled plugin file into the global plugins directory with a version-stamped header, (c) removes Open Second Brain keys from the legacy `mcp.json` if present, and records everything in the install manifest so `verify` reports drift and `uninstall` reverses all three.
+
+The plugin is one self-contained TypeScript file exporting the standard opencode plugin function. It receives the SDK `client` and uses three hooks:
+
+- `experimental.chat.system.transform` - appends the rendered active-context block to the system prompt array. The block comes from spawning the bundled `o2b-hook active-inject` PATH shim (the same binary the Claude Code and Codex hook layers call) with a synthetic `{"hook_event_name":"SessionStart"}` payload on stdin and parsing `hookSpecificOutput.additionalContext` from stdout - vault resolution, budgeting, and quiet-failure semantics are inherited rather than reimplemented. Cached per session with a short TTL. Experimental API: the entire body is wrapped so a signature change degrades to no-op.
+- `event` - on `session.idle`, `session.compacted`, `session.deleted`: fetch the full message list through `client.session.messages()` and atomically rewrite `${XDG_DATA_HOME:-~/.local/share}/open-second-brain/opencode/<sessionID>.jsonl` as a snapshot (meta line + one normalized turn line per message). Snapshot-rewrite, not append: idempotent, self-healing after crashes, and dedup downstream is by content hash already.
+- `tool.execute.after` - for file-mutating tools (`write`, `edit`, `patch`, `bash` heuristics mirroring `NATIVE_ARTIFACT_NAMES` semantics): appends the standard logging reminder to the tool output so the model sees it, matching the Claude Code post-write-reminder contract.
+
+The spool format is owned by this repo: first line `{"type":"session_meta","originator":"open-second-brain-opencode-plugin","format":1,...}`, subsequent lines `{"type":"turn","turnId","timestamp","role","text","toolCalls"}` - deliberately close to `SessionTurn` so the session adapter is a thin validator. The `opencode` session adapter detects on the meta line's `originator` and yields turns; `importSessionPath` pointed at the spool directory does the rest (dedup, markers, lineage).
+
+## Design decisions
+
+- **Pluggable entry shape, not a forked adapter body.** `json-merge.ts` gains `serializeEntry`/`entryEquals` injection points (defaults preserve current behavior byte-for-byte). Cursor, kiro, Gemini CLI continue on defaults; the smoke tests pin that.
+- **Spool snapshot over event append.** `session.idle` can fire many times per session; append-only would duplicate turns and require dedup in the adapter. A full-snapshot rewrite on each lifecycle event is idempotent and keeps the adapter dumb.
+- **Plugin discovers nothing about the vault.** The spool lands in an XDG data path independent of vault location; the active-context inject shells to `o2b-hook` on PATH (or `OSB_HOOK_BIN` override) which resolves the vault from the persisted Open Second Brain config, and silently skips when absent. No vault path is baked into the plugin file, so one plugin file serves any number of vaults and the file content is deterministic for drift detection.
+- **Version-stamped plugin copy.** The installed plugin carries `// open-second-brain plugin v<version>` in its header; the manifest records the content hash. `verify` flags drift when the bundled source and the installed copy diverge (operator edited it, or an upgrade has not been re-applied).
+- **Legacy `mcp.json` migration is removal-only.** We delete our two keys (and the file if it becomes empty and we created it per the manifest); we never translate user-authored entries - not ours to interpret.
+- **Reminder via tool-output suffix, not TUI toast.** The reminder's audience is the model (same as Claude Code's `systemMessage`), not the human; a toast would nag the operator and be invisible to the agent.
+
+## File changes
+
+New:
+- `plugins/opencode/open-second-brain.ts` - the bundled plugin source.
+- `src/core/install/opencode-plugin-asset.ts` - resolves the bundled plugin source path + version stamp for the adapter and drift checks.
+- `src/core/brain/sessions/opencode.ts` - spool session adapter.
+- `tests/core/install/adapters/opencode.test.ts`, `tests/core/brain.sessions.opencode.test.ts`, `tests/plugins/opencode-plugin.test.ts` - per-unit tests.
+- `tests/fixtures/sessions/opencode-minimal.jsonl`, install fixtures under `tests/fixtures/install/opencode/`.
+- `install/opencode.md` rewrite (file exists; content replaced).
+
+Modified:
+- `src/core/install/json-merge.ts`, `src/core/install/adapters/_json-mcp.ts`, `src/core/install/payload-equals.ts` - entry-shape injection.
+- `src/core/install/adapters/opencode.ts` - full rewrite onto the new spec.
+- `src/core/brain/sessions/types.ts`, `src/core/brain/sessions/registry.ts` - fourth adapter id + registration.
+- `install.md`, `README.md`, `CHANGELOG.md`.
+- `tests/core/install/adapters/json-mcp-smoke.test.ts` - pins default-shape invariance for existing targets.
+
+## Risks and open questions
+
+- `experimental.chat.system.transform` may change signature in a future opencode release; mitigated by full-body try/catch no-op and by keeping capture (the higher-value half) on the stable `event` bus.
+- `client.session.messages()` response shape is typed by the SDK but unverified against a live opencode here (none installed); the plugin tests run against a fake client built from the published SDK types, and the spool meta line carries `format: 1` so a field mismatch surfaces as a versioned import error, not silent corruption.
+- The exact tool names opencode uses for file mutation (`write`/`edit`/`patch`) need verification against the docs during implementation; the matcher is a conservative allowlist and misses only the reminder nicety, never capture.
diff --git a/docs/brainstorm/opencode-native-integration/plan.md b/docs/brainstorm/opencode-native-integration/plan.md
new file mode 100644
index 00000000..67f4247b
--- /dev/null
+++ b/docs/brainstorm/opencode-native-integration/plan.md
@@ -0,0 +1,35 @@
+# opencode native integration - implementation plan
+
+Design: `design.md`. Each task is one atomic conventional commit on `feat/opencode-native-integration`, test-first.
+
+## Tasks
+
+### Task 1: Pluggable MCP entry shape in the shared JSON-merge layer
+- **Files**: `src/core/install/json-merge.ts`, `src/core/install/adapters/_json-mcp.ts`, `src/core/install/payload-equals.ts`, `tests/core/install/adapters/json-mcp-smoke.test.ts` (+ a focused unit test for the new injection points)
+- **Acceptance**: `mergeMcpServers` / `removeMcpServers` / drift comparison accept optional `serializeEntry` and `entryEquals`; with them omitted, output for cursor/kiro/gemini-cli fixtures is byte-identical to today (smoke test pins it); a custom shape round-trips through merge → detect → verify.
+- **Depends on**: none
+
+### Task 2: opencode install adapter rewrite (opencode.json `mcp` block + legacy migration)
+- **Files**: `src/core/install/adapters/opencode.ts`, `tests/core/install/adapters/opencode.test.ts`, `tests/fixtures/install/opencode/*`
+- **Acceptance**: apply on a clean home writes `~/.config/opencode/opencode.json` with `mcp.open-second-brain` and `mcp.open-second-brain-writer` shaped `{type:"local", command:[array], environment, enabled:true}` preserving user keys; apply with a legacy `~/.config/opencode/mcp.json` containing our keys removes them (file deleted only when empty and manifest-owned); detect/plan/verify/uninstall lifecycle green including drift detection on the new shape; XDG_CONFIG_HOME honored.
+- **Depends on**: Task 1
+
+### Task 3: Bundled opencode plugin (single file, zero-dep)
+- **Files**: `plugins/opencode/open-second-brain.ts`, `src/core/install/opencode-plugin-asset.ts`, `tests/plugins/opencode-plugin.test.ts`
+- **Acceptance**: plugin module exports the opencode plugin function; with a fake `client` and temp XDG dirs: (a) `event` session.idle/compacted/deleted produces a spool snapshot `<sessionID>.jsonl` with meta line `format:1` + normalized turn lines, atomic rewrite, idempotent across repeated idles; (b) `experimental.chat.system.transform` appends rendered context when the `o2b-hook active-inject` spawn succeeds (fake via `OSB_HOOK_BIN` pointing at a stub script) and no-ops (no throw) when the binary is missing; (c) `tool.execute.after` appends the reminder only for file-mutating tool ids; (d) every hook body swallows internal errors (fail-soft assertion with a throwing fake client).
+- **Depends on**: none
+
+### Task 4: Plugin installation through the adapter (copy + manifest + drift)
+- **Files**: `src/core/install/adapters/opencode.ts`, `src/core/install/opencode-plugin-asset.ts`, `tests/core/install/adapters/opencode.test.ts`
+- **Acceptance**: apply copies the bundled plugin into `~/.config/opencode/plugins/open-second-brain.ts` with version-stamped header; manifest records the content hash; verify reports drift when the installed copy is edited; uninstall removes the plugin file; re-apply after upgrade refreshes the copy.
+- **Depends on**: Task 2, Task 3
+
+### Task 5: opencode session adapter + registry wiring
+- **Files**: `src/core/brain/sessions/opencode.ts`, `src/core/brain/sessions/types.ts`, `src/core/brain/sessions/registry.ts`, `tests/core/brain.sessions.opencode.test.ts`, `tests/fixtures/sessions/opencode-minimal.jsonl`, cross-table cases in `tests/core/brain.sessions.registry.test.ts`
+- **Acceptance**: `detect` matches only the spool meta line (originator `open-second-brain-opencode-plugin`), rejects claude/codex/hermes first lines and vice versa (cross-table test extended to 4x4); `iterate` yields normalized turns incl. tool calls; `importSession` on the fixture produces the same counter semantics as other adapters; unknown `format` > 1 fails with a versioned error.
+- **Depends on**: Task 3 (spool format frozen)
+
+### Task 6: Docs and changelog
+- **Files**: `install/opencode.md`, `install.md`, `README.md`, `CHANGELOG.md`
+- **Acceptance**: install/opencode.md documents the full flow (install, what gets written where, plugin behavior, spool import command, known gaps: no stop guardrail, experimental inject); install.md table row updated; README runtime list updated; CHANGELOG entry under the next version header; `bun run lint` and docs checks green.
+- **Depends on**: Tasks 1-5
diff --git a/docs/brainstorm/opencode-native-integration/variants.md b/docs/brainstorm/opencode-native-integration/variants.md
new file mode 100644
index 00000000..91315398
--- /dev/null
+++ b/docs/brainstorm/opencode-native-integration/variants.md
@@ -0,0 +1,56 @@
+# opencode native integration - brainstorm audit trail
+
+Consultant: Claude Code (`claude -p`), 2026-06-10. Prompt: `cli-output/prompt.md`. Raw output: `cli-output/claude.md`.
+
+## Variants produced
+
+### Variant 1: Config-surface only (no plugin)
+
+- **Approach**: Rewrite `src/core/install/adapters/opencode.ts` to write the real `~/.config/opencode/opencode.json` (extending `createJsonMcpAdapter` with a pluggable entry-shape transform to emit `{type: "local", command: [...], environment, enabled}`), migrate and delete the stale `mcp.json`, and wire rules via the native `instructions` key pointing at the vault's active-context file. Session parity comes from a new session adapter in `SESSION_ADAPTERS` that parses opencode's on-disk storage under `~/.local/share/opencode/storage/`. No plugin is shipped.
+- **Trade-offs**:
+ - Pro: smallest surface; everything fits the existing install-adapter and session-adapter patterns with zero new runtime pieces.
+ - Pro: nothing runs inside opencode, so fail-soft is trivial.
+ - Con: the storage format is undocumented and unstable; the importer will silently break on opencode upgrades and fixtures will drift from reality.
+ - Con: no live behavior at all - no session-start context inject timing, no idle/compact capture triggers, no post-write reminders; clearly below Claude Code/Codex parity.
+ - Con: `instructions` injects statically per config load, not per session, so freshness of active context is weaker.
+- **Complexity**: small
+- **Risk**: high
+
+### Variant 2: Bundled self-contained plugin plus spool-file session adapter
+
+- **Approach**: The install adapter does three things: writes the correct `mcp` entry into `opencode.json` (via the extended `_json-mcp.ts` entry-shape hook), migrates the stale `mcp.json`, and copies a single zero-dependency bundled plugin file into `~/.config/opencode/plugins/`. The plugin uses public hooks only: on `session.created` it injects active context (spawning `o2b` or reading `Brain/active.md`, wrapped in try/catch for fail-soft), and on `session.idle` / `session.compacted` / `session.deleted` it pulls messages through the SDK `client` and appends a normalized JSONL spool file; a fourth session adapter (`opencode`) with `detect(firstLine)` plus `iterate(path)` imports that spool through the existing registry, exactly like claude/codex/hermes. Rules ride on native AGENTS.md support.
+- **Trade-offs**:
+ - Pro: the JSONL format is owned by Open Second Brain, so the session adapter and its fixtures are stable and fully testable offline; the only untested-on-CI piece is the thin plugin, which is a pure function testable with a fake `client`.
+ - Pro: reuses every existing pattern (install lifecycle, manifest, drift detection, session registry) and keeps the MCP server runtime-agnostic.
+ - Pro: fail-soft is localized in one small plugin file; opencode keeps working if vault or binary is absent.
+ - Con: capture is event-driven only; sessions where opencode crashes before `session.idle` may lose the tail.
+ - Con: a copied plugin file can drift from the installed o2b version; needs a version marker plus drift check in the manifest.
+ - Con: some hooks used for niceties (`experimental.chat.system.transform`) are experimental; must degrade gracefully.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: npm-distributed plugin with live streaming capture
+
+- **Approach**: Publish `@open-second-brain/opencode-plugin` to npm and register it under the `plugin` key in `opencode.json`; the install adapter only edits config. The plugin streams continuously: `message.updated` and `tool.execute.after` events are translated into the existing hook payload protocol and piped to the bundled `o2b-hook` binary on stdin (extending `hooks/lib/detect.ts` with an opencode payload shape), so capture, reminders, and guardrails all flow through the same hook layer Claude Code and Codex use, with no import adapter and no spool files.
+- **Trade-offs**:
+ - Pro: deepest parity - the opencode runtime becomes a first-class peer in the existing hook layer rather than a parallel path; capture is real-time with no tail loss.
+ - Pro: opencode-native distribution with version pinning and auto-install; no copied-file drift.
+ - Con: requires a publish pipeline and network at user install time; dev and CI machines without network cannot exercise the real install path.
+ - Con: lockstep versioning between the npm plugin and the local o2b binary becomes an ongoing release burden.
+ - Con: per-message spawning of the hook binary is chatty and harder to fixture-test end to end; failure modes multiply.
+
+- **Complexity**: large
+- **Risk**: medium
+
+### Consultant recommendation: Variant 2
+
+Variant 2 reaches genuine parity (live context inject, event-driven capture, registry-based session import) while keeping every risky dependency under the project's control: the spool JSONL is an owned format, the plugin is one self-contained file shipped by the existing install framework, and everything is testable from fixtures with opencode absent, which Variants 1 and 3 cannot claim. Variant 1 stakes session capture on an undocumented storage format, and Variant 3 buys marginal extra parity at the cost of a publish pipeline, network-dependent installs, and lockstep versioning that contradict the zero-dep and offline-test constraints.
+
+## Orchestrator decision
+
+Variant 2, accepted as recommended. Project context confirms the consultant's reasoning on every axis that matters here: the repo's test discipline requires offline fixtures (opencode is absent on the dev server and CI), the install framework already carries manifest plus drift detection that a copied plugin file slots into, and the project has been burned before by reverse-engineered third-party formats (the session adapters deliberately parse only documented or self-owned shapes). No override needed.
+
+Two scope refinements on top of the consultant's sketch, both subtractive:
+
+1. The Claude Code `stop-log-guardrail` has no opencode analog - opencode exposes no blocking stop hook. Explicitly out of scope rather than approximated through `session.idle`, which cannot block and would only add noise.
+2. The `instructions` config key is not wired by the install adapter. opencode reads AGENTS.md natively, and the active-context freshness problem is solved by the plugin's per-session inject; a third, statically-loaded context channel would duplicate content.
diff --git a/install.md b/install.md
index c4de6099..4d832b3d 100644
--- a/install.md
+++ b/install.md
@@ -26,7 +26,7 @@ in one command:
|----------------------|----------------------------------------------------|-----------------------------------------------------------------------|
| 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 |
+| opencode | `o2b install --target opencode --apply` | `install/opencode.md` — MCP servers + native plugin |
| 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` |
diff --git a/install/opencode.md b/install/opencode.md
index 0f8a41ad..9208c530 100644
--- a/install/opencode.md
+++ b/install/opencode.md
@@ -1,8 +1,21 @@
# 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.
+`o2b install --target opencode --apply` performs a native integration
+in one pass:
+
+1. **MCP servers** - merges the two Open Second Brain servers
+ (`open-second-brain`, `open-second-brain-writer`) into
+ `${XDG_CONFIG_HOME:-$HOME/.config}/opencode/opencode.json` under the
+ `mcp` key, using opencode's entry schema
+ (`{"type": "local", "command": [...], "environment": {...},
+ "enabled": true}`). User-authored entries are preserved.
+2. **Plugin** - copies the bundled Open Second Brain plugin into
+ `${XDG_CONFIG_HOME:-$HOME/.config}/opencode/plugins/open-second-brain.ts`.
+ opencode auto-loads it at startup.
+3. **Legacy cleanup** - releases before v1.4.0 wrote
+ `~/.config/opencode/mcp.json`, a file opencode never reads. Apply
+ removes the two Open Second Brain keys from it (and deletes the file
+ when nothing else remains).
## Install
@@ -10,7 +23,34 @@ via JSON-merge. User-authored entries in `mcpServers` are preserved.
o2b install --target opencode --apply
```
-Restart `opencode` to load the new servers.
+Restart `opencode` to load the MCP servers and the plugin.
+
+## What the plugin does
+
+- **Active context inject** - appends the rendered `Brain/active.md`
+ digest to the system prompt of each chat request (cached, 5 minute
+ TTL), so the agent sees live preferences without calling
+ `brain_query` first. Uses the same `o2b-hook active-inject` shim as
+ the Claude Code and Codex hook layers; if the shim or the vault is
+ missing the inject silently skips.
+- **Session capture** - on `session.idle` / `session.compacted` /
+ `session.deleted` the plugin snapshots the session as a JSONL spool
+ under `${XDG_DATA_HOME:-$HOME/.local/share}/open-second-brain/opencode/`.
+ Import captured sessions with:
+
+ ```bash
+ o2b brain import-session ~/.local/share/open-second-brain/opencode/ \
+ --vault /path/to/vault
+ ```
+
+- **Post-write reminder** - after file-mutating tools (`write`,
+ `edit`, `multiedit`, `patch`, `apply_patch`) the standard logging
+ nudge is appended to the tool output so the agent considers
+ `brain_feedback` / `brain_apply_evidence` / `brain_note` before its
+ final reply.
+
+Every plugin hook is fail-soft: a missing vault, missing `o2b-hook`
+binary, or SDK error never breaks the opencode session.
## Verify
@@ -18,20 +58,34 @@ Restart `opencode` to load the new servers.
o2b install --check --target opencode
```
+Reports drift when the MCP entries differ from canonical or the
+installed plugin copy differs from the bundled version (for example
+after an Open Second Brain upgrade - re-run apply to refresh it).
+
## Uninstall
```bash
o2b uninstall --target opencode --apply
```
+Removes the two `mcp` keys from `opencode.json` and deletes the
+installed plugin file. User-authored config is untouched.
+
+## Known gaps relative to Claude Code / Codex
+
+- **No stop-log guardrail.** opencode exposes no blocking stop hook,
+ so the guardrail that vetoes an unlogged artifact turn cannot be
+ reproduced; the post-write reminder still fires.
+- **Context inject rides an experimental hook**
+ (`experimental.chat.system.transform`). If a future opencode release
+ changes it, the inject degrades to no-op while capture and the MCP
+ servers keep working.
+
## Notes
- Upstream is `anomalyco/opencode` (formerly hosted under
- `sst/opencode`). Confirm the MCP config path against the current
- upstream docs before adopting on a new release — the project has
- moved its config layout between releases. The adapter defaults to
- `~/.config/opencode/mcp.json` and reads `XDG_CONFIG_HOME` when
- set; if upstream renames the file (e.g. to `opencode.json`),
- the JSON-merge adapter pattern keeps working — only the
- resolver function in `src/core/install/adapters/opencode.ts`
- needs an update.
+ `sst/opencode`); config schema verified against
+ https://opencode.ai/docs 2026-06-10.
+- Rules: opencode reads `AGENTS.md` natively, so vault-level rules can
+ also travel as project instructions without any Open Second Brain
+ involvement.
diff --git a/plugins/opencode/open-second-brain.ts b/plugins/opencode/open-second-brain.ts
new file mode 100644
index 00000000..8aa66711
--- /dev/null
+++ b/plugins/opencode/open-second-brain.ts
@@ -0,0 +1,284 @@
+/**
+ * Open Second Brain plugin for opencode (https://opencode.ai).
+ *
+ * Installed by `o2b install --target opencode --apply` into
+ * `~/.config/opencode/plugins/open-second-brain.ts`. The file is
+ * deliberately self-contained (no imports beyond node builtins and the
+ * Bun globals opencode already provides) so the copy works standalone
+ * inside opencode's plugin sandbox.
+ *
+ * Three behaviors, mirroring the Claude Code / Codex hook layer:
+ *
+ * 1. Active-context inject: `experimental.chat.system.transform`
+ * spawns the bundled `o2b-hook active-inject` PATH shim (override:
+ * `OSB_HOOK_BIN`) with a synthetic SessionStart payload and appends
+ * `hookSpecificOutput.additionalContext` to the system prompt.
+ * Vault resolution, budgeting, and quiet-failure semantics are
+ * inherited from the shim rather than reimplemented here.
+ *
+ * 2. Session capture: on `session.idle` / `session.compacted` /
+ * `session.deleted` the full message list is fetched through the
+ * SDK client and snapshotted as a deterministic JSONL spool under
+ * `${XDG_DATA_HOME:-~/.local/share}/open-second-brain/opencode/`
+ * (override: `OSB_OPENCODE_SPOOL_DIR`). The spool format is owned
+ * by Open Second Brain (`format: 1`); `o2b brain import-session`
+ * pointed at the spool dir ingests it via the `opencode` session
+ * adapter. Snapshot-rewrite, not append: idempotent and
+ * self-healing after crashes.
+ *
+ * 3. Post-write reminder: `tool.execute.after` appends the standard
+ * logging nudge to the output of file-mutating tools so the model
+ * sees it, matching the Claude Code post-write-reminder contract.
+ *
+ * Every hook body is fail-soft: a missing vault, missing binary, or
+ * SDK error must never break the operator's opencode session.
+ */
+
+import { mkdirSync, renameSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+const SPOOL_FORMAT = 1;
+const SPOOL_ORIGINATOR = "open-second-brain-opencode-plugin";
+const CAPTURE_EVENTS = new Set(["session.idle", "session.compacted", "session.deleted"]);
+const MUTATING_TOOLS = new Set(["write", "edit", "multiedit", "patch", "apply_patch"]);
+const ACTIVE_CONTEXT_TTL_MS = 5 * 60 * 1000;
+/** A failed render retries sooner than a successful one expires. */
+const ACTIVE_CONTEXT_NEGATIVE_TTL_MS = 30 * 1000;
+const HOOK_TIMEOUT_MS = 10_000;
+
+/** Disambiguates concurrent spool writes within one process. */
+let spoolWriteSeq = 0;
+
+const POST_WRITE_NUDGE =
+ "Open Second Brain: artifact written. If a taste signal or scoped " +
+ "preference applies, call brain_feedback / brain_apply_evidence / " +
+ "brain_note (full contract earlier in this session).";
+
+interface SpoolTurn {
+ readonly type: "turn";
+ readonly turnId: string;
+ readonly timestamp: string;
+ readonly role: "user" | "assistant" | "system";
+ readonly text?: string;
+ readonly toolCalls?: ReadonlyArray<{
+ readonly name: string;
+ readonly id?: string;
+ readonly input: Record<string, unknown>;
+ }>;
+}
+
+function spoolDir(): string {
+ const override = process.env["OSB_OPENCODE_SPOOL_DIR"];
+ if (override && override.length > 0) return override;
+ const xdg = process.env["XDG_DATA_HOME"];
+ const base = xdg && xdg.length > 0 ? xdg : join(homedir(), ".local", "share");
+ return join(base, "open-second-brain", "opencode");
+}
+
+function sanitizeSessionId(id: string): string | null {
+ const name = id.replace(/[^A-Za-z0-9._-]/g, "_");
+ if (name.length === 0 || /^\.{1,2}$/.test(name)) return null;
+ return name;
+}
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
+ return value as Record<string, unknown>;
+}
+
+function extractSessionId(properties: unknown): string | null {
+ const props = asRecord(properties);
+ if (!props) return null;
+ if (typeof props["sessionID"] === "string") return props["sessionID"];
+ const info = asRecord(props["info"]);
+ if (info && typeof info["id"] === "string") return info["id"];
+ const session = asRecord(props["session"]);
+ if (session && typeof session["id"] === "string") return session["id"];
+ return null;
+}
+
+/**
+ * Normalizes one SDK message (`{info, parts}`) into a spool turn.
+ * Unknown roles and empty messages return null and are skipped: the
+ * spool only carries what the session adapter understands.
+ */
+function normalizeMessage(message: unknown): SpoolTurn | null {
+ const m = asRecord(message);
+ if (!m) return null;
+ const info = asRecord(m["info"]);
+ if (!info || typeof info["id"] !== "string") return null;
+ const role = info["role"];
+ if (role !== "user" && role !== "assistant" && role !== "system") return null;
+
+ const time = asRecord(info["time"]);
+ const created = time && typeof time["created"] === "number" ? time["created"] : null;
+ const timestamp = created !== null ? new Date(created).toISOString() : new Date(0).toISOString();
+
+ const texts: string[] = [];
+ const toolCalls: Array<{ name: string; id?: string; input: Record<string, unknown> }> = [];
+ const parts = Array.isArray(m["parts"]) ? m["parts"] : [];
+ for (const rawPart of parts) {
+ const part = asRecord(rawPart);
+ if (!part) continue;
+ if (part["type"] === "text" && typeof part["text"] === "string" && part["text"].length > 0) {
+ texts.push(part["text"]);
+ } else if (part["type"] === "tool" && typeof part["tool"] === "string") {
+ const state = asRecord(part["state"]);
+ const input = state ? (asRecord(state["input"]) ?? {}) : {};
+ toolCalls.push({
+ name: part["tool"],
+ ...(typeof part["callID"] === "string" ? { id: part["callID"] } : {}),
+ input,
+ });
+ }
+ }
+ if (texts.length === 0 && toolCalls.length === 0) return null;
+ return {
+ type: "turn",
+ turnId: info["id"],
+ timestamp,
+ role,
+ ...(texts.length > 0 ? { text: texts.join("\n") } : {}),
+ ...(toolCalls.length > 0 ? { toolCalls } : {}),
+ };
+}
+
+/**
+ * Deterministic snapshot write: same messages produce a byte-identical
+ * file (no wall-clock fields), so repeated `session.idle` events are
+ * no-ops for downstream content-hash dedup. Atomic via tmp + rename.
+ */
+function writeSpool(sessionId: string, directory: string, messages: unknown[]): void {
+ const name = sanitizeSessionId(sessionId);
+ if (name === null) return;
+ const meta = {
+ type: "session_meta",
+ originator: SPOOL_ORIGINATOR,
+ format: SPOOL_FORMAT,
+ session_id: sessionId,
+ directory,
+ };
+ const lines = [JSON.stringify(meta)];
+ for (const message of messages) {
+ const turn = normalizeMessage(message);
+ if (turn) lines.push(JSON.stringify(turn));
+ }
+ const dir = spoolDir();
+ mkdirSync(dir, { recursive: true });
+ const target = join(dir, `${name}.jsonl`);
+ spoolWriteSeq += 1;
+ const tmp = join(dir, `.${name}.jsonl.tmp-${process.pid}-${spoolWriteSeq}`);
+ writeFileSync(tmp, lines.join("\n") + "\n", "utf8");
+ renameSync(tmp, target);
+}
+
+/** Pulls the message list out of the SDK response defensively. */
+function messageList(response: unknown): unknown[] | null {
+ if (Array.isArray(response)) return response;
+ const r = asRecord(response);
+ if (r && Array.isArray(r["data"])) return r["data"];
+ return null;
+}
+
+/**
+ * Renders the active-context block by spawning the same
+ * `o2b-hook active-inject` shim the Claude Code and Codex hook layers
+ * use. Returns null on every failure mode (binary missing, timeout,
+ * empty or malformed output) — the caller treats null as "no inject".
+ */
+function renderActiveContext(cwd: string): string | null {
+ try {
+ const bin = process.env["OSB_HOOK_BIN"] ?? "o2b-hook";
+ const proc = Bun.spawnSync([bin, "active-inject"], {
+ stdin: Buffer.from(JSON.stringify({ hook_event_name: "SessionStart", cwd })),
+ stdout: "pipe",
+ stderr: "ignore",
+ timeout: HOOK_TIMEOUT_MS,
+ });
+ if (!proc.success) return null;
+ const raw = proc.stdout.toString("utf8").trim();
+ if (raw.length === 0) return null;
+ const parsed = asRecord(JSON.parse(raw));
+ const hookOutput = parsed ? asRecord(parsed["hookSpecificOutput"]) : null;
+ const context = hookOutput ? hookOutput["additionalContext"] : null;
+ return typeof context === "string" && context.length > 0 ? context : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Plugin entry point. opencode calls this once at startup with the SDK
+ * client and project info, and wires the returned hooks.
+ */
+export const OpenSecondBrain = async (pluginInput: {
+ client: unknown;
+ project?: unknown;
+ directory?: string;
+ worktree?: string;
+}) => {
+ const directory = typeof pluginInput.directory === "string" ? pluginInput.directory : "";
+ const worktree = typeof pluginInput.worktree === "string" ? pluginInput.worktree : "";
+ // Anchor active-inject to the real project scope, not an arbitrary dir.
+ const injectCwd = worktree || directory || process.cwd();
+ const client = asRecord(pluginInput.client);
+ let activeContextCache: { value: string | null; at: number } | null = null;
+
+ async function captureSession(sessionId: string): Promise<void> {
+ const session = client ? asRecord(client["session"]) : null;
+ const messages = session ? session["messages"] : null;
+ if (typeof messages !== "function") return;
+ // Invoke as a method bound to `session`: the opencode SDK client
+ // dereferences `this._client` internally, so a detached call
+ // (`messages(...)`) throws "undefined is not an object". Reflect.apply
+ // carries the receiver without re-narrowing the SDK's untyped shape.
+ const response: unknown = await Reflect.apply(messages, session, [{ path: { id: sessionId } }]);
+ const list = messageList(response);
+ if (list === null) return;
+ writeSpool(sessionId, directory, list);
+ }
+
+ return {
+ event: async ({ event }: { event: { type?: string; properties?: unknown } }) => {
+ try {
+ if (typeof event?.type !== "string" || !CAPTURE_EVENTS.has(event.type)) return;
+ const sessionId = extractSessionId(event.properties);
+ if (sessionId === null) return;
+ await captureSession(sessionId);
+ } catch {
+ // Capture is best-effort; never break the operator's session.
+ }
+ },
+
+ "experimental.chat.system.transform": async (_input: unknown, output: { system: string[] }) => {
+ try {
+ const now = Date.now();
+ const ttl =
+ activeContextCache?.value === null
+ ? ACTIVE_CONTEXT_NEGATIVE_TTL_MS
+ : ACTIVE_CONTEXT_TTL_MS;
+ if (activeContextCache === null || now - activeContextCache.at > ttl) {
+ activeContextCache = { value: renderActiveContext(injectCwd), at: now };
+ }
+ if (activeContextCache.value !== null && Array.isArray(output?.system)) {
+ output.system.push(activeContextCache.value);
+ }
+ } catch {
+ // Inject is a nicety; the session works without it.
+ }
+ },
+
+ "tool.execute.after": async (input: { tool?: string }, output: { output?: unknown }) => {
+ try {
+ const tool = typeof input?.tool === "string" ? input.tool.toLowerCase() : "";
+ if (!MUTATING_TOOLS.has(tool)) return;
+ if (output && typeof output.output === "string") {
+ output.output = `${output.output}\n\n${POST_WRITE_NUDGE}`;
+ }
+ } catch {
+ // Reminder is a nicety; tool output stays untouched on failure.
+ }
+ },
+ };
+};
diff --git a/src/core/brain/sessions/opencode.ts b/src/core/brain/sessions/opencode.ts
new file mode 100644
index 00000000..64418347
--- /dev/null
+++ b/src/core/brain/sessions/opencode.ts
@@ -0,0 +1,128 @@
+/**
+ * opencode spool adapter.
+ *
+ * Unlike the claude/codex/hermes adapters, which parse a third-party
+ * transcript schema, this one reads a format Open Second Brain owns:
+ * the JSONL spool written by the bundled opencode plugin
+ * (`plugins/opencode/open-second-brain.ts`) under
+ * `${XDG_DATA_HOME:-~/.local/share}/open-second-brain/opencode/`.
+ *
+ * - Line 1: `{type: "session_meta", originator:
+ * "open-second-brain-opencode-plugin", format: 1, session_id, ...}`
+ * - Lines 2+: `{type: "turn", turnId, timestamp, role, text?,
+ * toolCalls?}` — deliberately shaped like `SessionTurn`, so this
+ * adapter is a validator, not a translator.
+ *
+ * `format` is a hard gate: a spool written by a newer plugin fails
+ * with a PARSE error naming the version instead of silently dropping
+ * fields it does not understand.
+ */
+
+import { readFileSync } from "node:fs";
+
+import { SessionImportError } from "./types.ts";
+import type { SessionAdapter, SessionToolCall, SessionTurn } from "./types.ts";
+
+const ORIGINATOR = "open-second-brain-opencode-plugin";
+const SUPPORTED_FORMAT = 1;
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
+ return value as Record<string, unknown>;
+}
+
+function parseMetaLine(line: string): Record<string, unknown> | null {
+ let obj: unknown;
+ try {
+ obj = JSON.parse(line);
+ } catch {
+ return null;
+ }
+ const o = asRecord(obj);
+ if (!o) return null;
+ if (o["type"] !== "session_meta" || o["originator"] !== ORIGINATOR) return null;
+ return o;
+}
+
+function buildTurn(obj: Record<string, unknown>): SessionTurn | null {
+ if (obj["type"] !== "turn") return null;
+ const turnId = obj["turnId"];
+ if (typeof turnId !== "string" || turnId.length === 0) return null;
+ const role = obj["role"];
+ if (role !== "user" && role !== "assistant" && role !== "system") return null;
+ const timestamp =
+ typeof obj["timestamp"] === "string" ? obj["timestamp"] : new Date(0).toISOString();
+
+ const toolCalls: SessionToolCall[] = [];
+ if (Array.isArray(obj["toolCalls"])) {
+ for (const raw of obj["toolCalls"]) {
+ const tc = asRecord(raw);
+ if (!tc || typeof tc["name"] !== "string" || tc["name"].length === 0) continue;
+ const input = asRecord(tc["input"]) ?? {};
+ toolCalls.push({
+ name: tc["name"],
+ input,
+ ...(typeof tc["id"] === "string" ? { id: tc["id"] } : {}),
+ });
+ }
+ }
+
+ return {
+ turnId,
+ timestamp,
+ role,
+ ...(typeof obj["text"] === "string" && obj["text"].length > 0 ? { text: obj["text"] } : {}),
+ ...(toolCalls.length > 0 ? { toolCalls } : {}),
+ };
+}
+
+export const opencodeAdapter: SessionAdapter = {
+ id: "opencode",
+ defaultAgent: "opencode",
+ detect(firstLine: string): boolean {
+ return parseMetaLine(firstLine) !== null;
+ },
+ async *iterate(path: string): AsyncIterable<SessionTurn> {
+ const text = readFileSync(path, "utf8");
+ const lines = text.split("\n");
+ // Hard gate even under explicit `--format opencode`: a file whose
+ // first line is not our meta line must not partially import.
+ const meta = lines.length > 0 ? parseMetaLine(lines[0]!.trim()) : null;
+ if (meta === null) {
+ throw new SessionImportError(
+ "PARSE",
+ `opencode spool meta line missing or invalid; expected first line ` +
+ `with originator ${ORIGINATOR}`,
+ );
+ }
+ const format = meta["format"];
+ if (typeof format !== "number") {
+ throw new SessionImportError(
+ "PARSE",
+ `opencode spool meta line carries no numeric format field; ` +
+ `expected format ${SUPPORTED_FORMAT}`,
+ );
+ }
+ if (format > SUPPORTED_FORMAT) {
+ throw new SessionImportError(
+ "PARSE",
+ `opencode spool format ${format} is newer than supported ` +
+ `format ${SUPPORTED_FORMAT}; upgrade Open Second Brain to import it`,
+ );
+ }
+ for (const line of lines.slice(1)) {
+ const trimmed = line.trim();
+ if (trimmed === "") continue;
+ let obj: unknown;
+ try {
+ obj = JSON.parse(trimmed);
+ } catch {
+ continue;
+ }
+ const o = asRecord(obj);
+ if (!o) continue;
+ const turn = buildTurn(o);
+ if (turn) yield turn;
+ }
+ },
+};
diff --git a/src/core/brain/sessions/registry.ts b/src/core/brain/sessions/registry.ts
index 49f38409..8feffd53 100644
--- a/src/core/brain/sessions/registry.ts
+++ b/src/core/brain/sessions/registry.ts
@@ -12,12 +12,14 @@
import { claudeAdapter } from "./claude.ts";
import { codexAdapter } from "./codex.ts";
import { hermesAdapter } from "./hermes.ts";
+import { opencodeAdapter } from "./opencode.ts";
import type { SessionAdapter, SessionAdapterId } from "./types.ts";
export const SESSION_ADAPTERS: ReadonlyArray<SessionAdapter> = Object.freeze([
claudeAdapter,
codexAdapter,
hermesAdapter,
+ opencodeAdapter,
]);
export function isSessionAdapterId(value: string): value is SessionAdapterId {
diff --git a/src/core/brain/sessions/types.ts b/src/core/brain/sessions/types.ts
index cdbc4c56..92ebe155 100644
--- a/src/core/brain/sessions/types.ts
+++ b/src/core/brain/sessions/types.ts
@@ -1,8 +1,9 @@
/**
* Public contract for `o2b brain import-session` adapters (§16).
*
- * Each runtime (Claude Code, Codex CLI, Hermes) stores chat
- * transcripts in its own JSONL schema. An adapter normalises one
+ * Each runtime (Claude Code, Codex CLI, Hermes, opencode) stores
+ * chat transcripts in its own JSONL schema (opencode via the spool
+ * the bundled plugin writes). An adapter normalises one
* such schema into the `SessionTurn` shape so the orchestrator
* (`sessions/import.ts`) can extract `@osb` markers from text and
* replay `brain_feedback` tool-use calls without caring which
@@ -13,7 +14,7 @@
* entry — no other code path needs to change.
*/
-export type SessionAdapterId = "claude" | "codex" | "hermes";
+export type SessionAdapterId = "claude" | "codex" | "hermes" | "opencode";
export interface SessionToolCall {
/** Tool name as emitted by the runtime, e.g. `brain_feedback`. */
diff --git a/src/core/install/adapters/_json-mcp.ts b/src/core/install/adapters/_json-mcp.ts
index d05307f1..62143bf8 100644
--- a/src/core/install/adapters/_json-mcp.ts
+++ b/src/core/install/adapters/_json-mcp.ts
@@ -1,7 +1,8 @@
/**
* 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.
+ * kiro, Gemini CLI follow the default shape; opencode reuses the same
+ * body with a custom top-level key and entry shape.
*
* Per-target specifics (config path, top-level key, post-install notes,
* optional MCP probe) are injected via `JsonMcpAdapterSpec`. The body
@@ -15,7 +16,7 @@ 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 { deepJsonEquals, expectedPayloadFromEnv, payloadKeyEquals } from "../payload-equals.ts";
import {
InstallError,
type ApplyOpts,
@@ -26,6 +27,7 @@ import {
type InstallPlan,
type ManifestEntry,
type McpPayload,
+ type McpServerEntry,
type UninstallResult,
type VerifyResult,
} from "../types.ts";
@@ -35,6 +37,23 @@ export interface JsonMcpAdapterSpec {
readonly label: string;
/** Top-level key under which MCP servers live. Default `mcpServers`. */
readonly topLevelKey?: string;
+ /**
+ * Maps the canonical `McpServerEntry` to the runtime's on-disk entry
+ * shape. Default emits `{command, args, env?}`. Adapters whose runtime
+ * uses a different schema (opencode: `{type, command: [bin, ...args],
+ * environment?, enabled}`) inject the mapping here.
+ */
+ readonly serializeEntry?: (entry: McpServerEntry) => Record<string, unknown>;
+ /**
+ * Compares an on-disk entry against the canonical payload for
+ * idempotency and drift detection. Defaults to `payloadKeyEquals`
+ * when `serializeEntry` is absent, and to strict structural equality
+ * against `serializeEntry(expected)` when it is present.
+ */
+ readonly entryEquals?: (
+ current: Record<string, unknown> | undefined,
+ expected: McpServerEntry,
+ ) => boolean;
/** Resolves the absolute path to the runtime's config file. */
resolveConfigPath(env: InstallEnv): string;
/** Extra notes attached to `detect.notes` / plan output. */
@@ -135,11 +154,30 @@ function readOnDisk(spec: JsonMcpAdapterSpec, env: InstallEnv, payload: McpPaylo
}
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);
+ const equals = resolveEntryEquals(spec);
+ const canonical = equals(full, payload.full) && equals(writer, payload.writer);
return { exists: true, canonical, full, writer, raw, mtimeMs: fileMtimeMs(path) };
}
+/**
+ * Resolution order for the entry comparator: explicit `entryEquals`
+ * wins; a spec with only `serializeEntry` gets strict structural
+ * equality against the re-serialized canonical entry; the default
+ * shape keeps the historical `payloadKeyEquals` semantics (extra
+ * top-level entry keys tolerated).
+ */
+function resolveEntryEquals(
+ spec: JsonMcpAdapterSpec,
+): (current: Record<string, unknown> | undefined, expected: McpServerEntry) => boolean {
+ if (spec.entryEquals) return spec.entryEquals;
+ const serialize = spec.serializeEntry;
+ if (serialize) {
+ return (current, expected) =>
+ current !== undefined && deepJsonEquals(current, serialize(expected));
+ }
+ return payloadKeyEquals;
+}
+
export function createJsonMcpAdapter(spec: JsonMcpAdapterSpec): InstallAdapter {
const topKey = spec.topLevelKey ?? "mcpServers";
@@ -252,7 +290,10 @@ export function createJsonMcpAdapter(spec: JsonMcpAdapterSpec): InstallAdapter {
}
}
- const merged = mergeMcpServers(onDisk.raw, payload, { topLevelKey: topKey });
+ const merged = mergeMcpServers(onDisk.raw, payload, {
+ topLevelKey: topKey,
+ ...(spec.serializeEntry ? { serializeEntry: spec.serializeEntry } : {}),
+ });
const contentChanged = merged !== onDisk.raw;
if (!opts.dryRun && contentChanged) {
ensureParent(path);
@@ -367,15 +408,10 @@ export function createJsonMcpAdapter(spec: JsonMcpAdapterSpec): InstallAdapter {
};
}
const expected = expectedPayloadFromEnv(env);
+ const equals = resolveEntryEquals(spec);
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,
- )
+ !equals(block[OSB_KEY_FULL] as Record<string, unknown> | undefined, expected.full) ||
+ !equals(block[OSB_KEY_WRITER] as Record<string, unknown> | undefined, expected.writer)
) {
return {
target: spec.target,
diff --git a/src/core/install/adapters/opencode.ts b/src/core/install/adapters/opencode.ts
index 5ab89aa6..864bbb08 100644
--- a/src/core/install/adapters/opencode.ts
+++ b/src/core/install/adapters/opencode.ts
@@ -1,30 +1,224 @@
/**
- * opencode adapter — JSON-merge into `~/.config/opencode/mcp.json`.
+ * opencode adapter — JSON-merge into `~/.config/opencode/opencode.json`.
*
* Upstream is `anomalyco/opencode` (formerly hosted under
- * `sst/opencode`). The MCP config file lives under
- * `${XDG_CONFIG_HOME:-$HOME/.config}/opencode/mcp.json` and uses the
- * standard `mcpServers` key. Re-verify against upstream docs if a
- * new opencode release ships before the next OSB release.
+ * `sst/opencode`). Verified against https://opencode.ai/docs 2026-06-10:
+ * MCP servers live in `opencode.json` (global copy under
+ * `${XDG_CONFIG_HOME:-$HOME/.config}/opencode/`) beneath the `mcp` key,
+ * each entry shaped `{type: "local", command: [bin, ...args],
+ * environment?, enabled}`.
+ *
+ * Releases up to v1.3.0 wrote `~/.config/opencode/mcp.json` with an
+ * `mcpServers` key — a file opencode never reads. `apply` migrates our
+ * two keys out of that file (and deletes it when nothing else is left)
+ * so stale registrations do not shadow the real one in operator
+ * debugging sessions.
*/
-import { join } from "node:path";
+import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { atomicWriteFileSync } from "../../fs-atomic.ts";
import { createJsonMcpAdapter } from "./_json-mcp.ts";
+import { OSB_KEY_FULL, OSB_KEY_WRITER } from "../json-merge.ts";
+import { recordEntry, readManifest } from "../manifest.ts";
+import { OPENCODE_PLUGIN_FILENAME, installedPluginContent } from "../opencode-plugin-asset.ts";
import { defaultRegistry } from "../registry.ts";
-import type { InstallEnv } from "../types.ts";
+import type {
+ ApplyOpts,
+ ApplyResult,
+ InstallEnv,
+ InstallPlan,
+ McpPayload,
+ McpServerEntry,
+ UninstallResult,
+ VerifyResult,
+} from "../types.ts";
-function configPath(env: InstallEnv): string {
+function opencodeDir(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");
+ return join(base, "opencode");
+}
+
+function configPath(env: InstallEnv): string {
+ return join(opencodeDir(env), "opencode.json");
+}
+
+function legacyConfigPath(env: InstallEnv): string {
+ return join(opencodeDir(env), "mcp.json");
}
-export const opencodeAdapter = createJsonMcpAdapter({
+/**
+ * Canonical `McpServerEntry` → opencode `mcp` entry. opencode takes the
+ * full argv as one `command` array and calls the env map `environment`;
+ * `enabled: true` is explicit so an operator toggling the server off
+ * shows up as drift instead of silently staying off after re-apply.
+ */
+export function serializeOpencodeEntry(entry: McpServerEntry): Record<string, unknown> {
+ return {
+ type: "local",
+ command: [entry.command, ...entry.args],
+ ...(entry.env && Object.keys(entry.env).length > 0 ? { environment: { ...entry.env } } : {}),
+ enabled: true,
+ };
+}
+
+/**
+ * Best-effort removal of our keys from the legacy `mcp.json`. Never
+ * throws: a malformed or absent file is left as-is — migration is an
+ * opportunistic cleanup, not a gate on the real install.
+ */
+function migrateLegacyMcpJson(env: InstallEnv, opts: ApplyOpts): void {
+ const path = legacyConfigPath(env);
+ if (opts.dryRun || !existsSync(path)) return;
+ try {
+ const raw = readFileSync(path, "utf8");
+ const parsed: unknown = JSON.parse(raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw);
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return;
+ const root = parsed as Record<string, unknown>;
+ const servers = root["mcpServers"];
+ if (servers === null || typeof servers !== "object" || Array.isArray(servers)) return;
+ const block = servers as Record<string, unknown>;
+ if (!(OSB_KEY_FULL in block) && !(OSB_KEY_WRITER in block)) return;
+ delete block[OSB_KEY_FULL];
+ delete block[OSB_KEY_WRITER];
+ const fileIsEmpty = Object.keys(block).length === 0 && Object.keys(root).length === 1;
+ if (fileIsEmpty) {
+ rmSync(path);
+ return;
+ }
+ atomicWriteFileSync(path, JSON.stringify(root, null, 2) + "\n");
+ } catch {
+ // Unreadable or unparseable legacy file: not ours to interpret.
+ }
+}
+
+function pluginPath(env: InstallEnv): string {
+ return join(opencodeDir(env), "plugins", OPENCODE_PLUGIN_FILENAME);
+}
+
+/**
+ * Reads the installed plugin copy, or null when the path is absent,
+ * not a regular file, or unreadable. Callers treat null as "needs
+ * (re)install" / drift instead of letting a stray directory or a
+ * permissions problem abort the whole install flow.
+ */
+function readPluginCopy(path: string): string | null {
+ try {
+ if (!lstatSync(path).isFile()) return null;
+ return readFileSync(path, "utf8");
+ } catch {
+ return null;
+ }
+}
+
+const base = createJsonMcpAdapter({
target: "opencode",
label: "opencode",
+ topLevelKey: "mcp",
resolveConfigPath: configPath,
- postNotes: ["Restart opencode to load the new MCP servers."],
+ serializeEntry: serializeOpencodeEntry,
+ postNotes: ["Restart opencode to load the new MCP servers and the Open Second Brain plugin."],
});
+export const opencodeAdapter = {
+ ...base,
+
+ plan(payload: McpPayload, env: InstallEnv): InstallPlan {
+ const basePlan = base.plan(payload, env);
+ const steps = [...basePlan.steps];
+ steps.push({
+ kind: "file-copy",
+ path: pluginPath(env),
+ preview: `copy the bundled Open Second Brain plugin to ${pluginPath(env)}`,
+ });
+ const legacy = legacyConfigPath(env);
+ if (existsSync(legacy)) {
+ steps.push({
+ kind: "json-merge",
+ path: legacy,
+ preview: `remove Open Second Brain keys from the legacy ${legacy} (delete when empty)`,
+ });
+ }
+ return { ...basePlan, steps };
+ },
+
+ apply(plan: InstallPlan, payload: McpPayload, env: InstallEnv, opts: ApplyOpts): ApplyResult {
+ const result = base.apply(plan, payload, env, opts);
+ migrateLegacyMcpJson(env, opts);
+
+ const plugin = pluginPath(env);
+ let pluginWritten = 0;
+ if (!opts.dryRun) {
+ const expected = installedPluginContent();
+ const current = readPluginCopy(plugin);
+ if (current !== expected) {
+ // A stray directory or special file at the plugin path must not
+ // abort the install; clear it before the atomic write.
+ if (current === null && existsSync(plugin)) {
+ rmSync(plugin, { recursive: true, force: true });
+ }
+ const dir = dirname(plugin);
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
+ atomicWriteFileSync(plugin, expected);
+ pluginWritten = 1;
+ }
+ // The base body records ownership of the two JSON keys; extend the
+ // entry with the plugin file so verify and uninstall track it too.
+ const stored = readManifest(env.vault).installs[base.target] ?? result.manifest;
+ const manifest = { ...stored, owned_paths: [plugin] };
+ recordEntry(env.vault, manifest);
+ return {
+ ...result,
+ manifest,
+ steps_executed: result.steps_executed + pluginWritten,
+ };
+ }
+ return result;
+ },
+
+ verify(env: InstallEnv): VerifyResult {
+ const baseResult = base.verify(env);
+ if (baseResult.status !== "ok") return baseResult;
+ const plugin = pluginPath(env);
+ const fixHint = "o2b install --target opencode --apply";
+ const current = readPluginCopy(plugin);
+ if (current === null) {
+ return {
+ target: base.target,
+ status: "drift",
+ details: [`plugin file missing, unreadable, or not a regular file: ${plugin}`],
+ fix_hint: fixHint,
+ };
+ }
+ if (current !== installedPluginContent()) {
+ return {
+ target: base.target,
+ status: "drift",
+ details: [`plugin file differs from the bundled version: ${plugin}`],
+ fix_hint: fixHint,
+ };
+ }
+ return baseResult;
+ },
+
+ uninstall(env: InstallEnv, opts: ApplyOpts & { fromSnippet?: boolean }): UninstallResult {
+ const result = base.uninstall(env, opts);
+ const plugin = pluginPath(env);
+ if (existsSync(plugin)) {
+ try {
+ if (!opts.dryRun) rmSync(plugin, { recursive: true, force: true });
+ return { ...result, removed_paths: [...result.removed_paths, plugin] };
+ } catch (e) {
+ return {
+ ...result,
+ skipped: [...result.skipped, [plugin, `could not remove: ${(e as Error).message}`]],
+ };
+ }
+ }
+ return result;
+ },
+};
+
defaultRegistry.register(opencodeAdapter);
diff --git a/src/core/install/json-merge.ts b/src/core/install/json-merge.ts
index 97775b04..408315a9 100644
--- a/src/core/install/json-merge.ts
+++ b/src/core/install/json-merge.ts
@@ -32,6 +32,13 @@ const DEFAULT_TOP_KEY = "mcpServers";
export interface MergeOpts {
/** Top-level object key under which MCP servers live. Default `mcpServers`. */
readonly topLevelKey?: string;
+ /**
+ * Maps the canonical `McpServerEntry` to the runtime's on-disk entry
+ * shape. Default emits `{command, args, env?}` (Cursor, kiro,
+ * Gemini CLI). opencode injects `{type, command: [bin, ...args],
+ * environment?, enabled}` here.
+ */
+ readonly serializeEntry?: (entry: McpServerEntry) => Record<string, unknown>;
}
export function mergeMcpServers(
@@ -50,10 +57,11 @@ export function mergeMcpServers(
: {};
// Preserve insertion order: user keys first (without our two), then ours.
+ const serialize = opts.serializeEntry ?? serializeEntry;
delete block[OSB_KEY_FULL];
delete block[OSB_KEY_WRITER];
- block[OSB_KEY_FULL] = serializeEntry(payload.full);
- block[OSB_KEY_WRITER] = serializeEntry(payload.writer);
+ block[OSB_KEY_FULL] = serialize(payload.full);
+ block[OSB_KEY_WRITER] = serialize(payload.writer);
root[topKey] = block;
diff --git a/src/core/install/opencode-plugin-asset.ts b/src/core/install/opencode-plugin-asset.ts
new file mode 100644
index 00000000..3cea8197
--- /dev/null
+++ b/src/core/install/opencode-plugin-asset.ts
@@ -0,0 +1,43 @@
+/**
+ * Bundled opencode plugin asset.
+ *
+ * The plugin source lives at `plugins/opencode/open-second-brain.ts`
+ * in the repository (and inside every packaged install, which ships
+ * the directory verbatim). The install adapter copies it into
+ * `~/.config/opencode/plugins/` with a version-stamped header so
+ * `verify` can flag a stale or hand-edited copy by content comparison
+ * against this re-constructed expectation — same drift model as the
+ * JSON payload.
+ */
+
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import packageJson from "../../../package.json";
+
+const PLUGIN_SOURCE_PATH = join(
+ import.meta.dir,
+ "..",
+ "..",
+ "..",
+ "plugins",
+ "opencode",
+ "open-second-brain.ts",
+);
+
+export const OPENCODE_PLUGIN_FILENAME = "open-second-brain.ts";
+
+/**
+ * The exact bytes the installed plugin file must contain for the
+ * current Open Second Brain version. Deterministic: same source and
+ * version produce identical content, which is what makes re-apply
+ * idempotent and drift detection a string comparison.
+ */
+export function installedPluginContent(): string {
+ const source = readFileSync(PLUGIN_SOURCE_PATH, "utf8");
+ return (
+ `// open-second-brain plugin v${packageJson.version}` +
+ " (installed copy; re-apply `o2b install --target opencode --apply` after upgrades)\n" +
+ source
+ );
+}
diff --git a/src/core/install/payload-equals.ts b/src/core/install/payload-equals.ts
index bce191d2..8008faab 100644
--- a/src/core/install/payload-equals.ts
+++ b/src/core/install/payload-equals.ts
@@ -9,6 +9,45 @@ export function expectedPayloadFromEnv(env: InstallEnv): McpPayload {
});
}
+/**
+ * Strict structural equality over JSON-shaped values. Used by adapters
+ * with a custom on-disk entry shape (`serializeEntry`) to compare the
+ * current entry against the re-serialized canonical payload: any added,
+ * removed, or changed field counts as drift, matching the
+ * "drift via payload re-construction" model.
+ */
+export function deepJsonEquals(a: unknown, b: unknown): boolean {
+ if (a === b) return true;
+ if (Array.isArray(a) && Array.isArray(b)) {
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) {
+ if (!deepJsonEquals(a[i], b[i])) return false;
+ }
+ return true;
+ }
+ if (
+ a !== null &&
+ b !== null &&
+ typeof a === "object" &&
+ typeof b === "object" &&
+ !Array.isArray(a) &&
+ !Array.isArray(b)
+ ) {
+ const ka = Object.keys(a as Record<string, unknown>).toSorted();
+ const kb = Object.keys(b as Record<string, unknown>).toSorted();
+ if (ka.length !== kb.length) return false;
+ for (let i = 0; i < ka.length; i++) {
+ if (ka[i] !== kb[i]) return false;
+ const k = ka[i]!;
+ if (!deepJsonEquals((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) {
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+}
+
export function payloadKeyEquals(
current: Record<string, unknown> | undefined,
expected: McpServerEntry,
diff --git a/tests/core/brain.sessions.import.test.ts b/tests/core/brain.sessions.import.test.ts
index ffa1cd65..e1162adb 100644
--- a/tests/core/brain.sessions.import.test.ts
+++ b/tests/core/brain.sessions.import.test.ts
@@ -21,6 +21,7 @@ import { describeSessionRecall } from "../../src/core/brain/session-recall.ts";
const CLAUDE = resolve("tests/fixtures/sessions/claude-minimal.jsonl");
const CODEX = resolve("tests/fixtures/sessions/codex-minimal.jsonl");
const HERMES = resolve("tests/fixtures/sessions/hermes-minimal.jsonl");
+const OPENCODE = resolve("tests/fixtures/sessions/opencode-minimal.jsonl");
let tmp: string;
@@ -181,6 +182,12 @@ describe("importSession", () => {
expect(res.signals_created).toBeGreaterThan(0);
});
+ test("handles the opencode spool fixture", async () => {
+ const res = await importSession(tmp, OPENCODE, { agent: "test" });
+ expect(res.format).toBe("opencode");
+ expect(res.signals_created).toBeGreaterThan(0);
+ });
+
test("throws SessionImportError(DETECT_FAIL) on unknown format", async () => {
const junk = join(tmp, "junk.jsonl");
writeFileSync(junk, '{"foo":"bar"}\n');
diff --git a/tests/core/brain.sessions.opencode.test.ts b/tests/core/brain.sessions.opencode.test.ts
new file mode 100644
index 00000000..452d05ad
--- /dev/null
+++ b/tests/core/brain.sessions.opencode.test.ts
@@ -0,0 +1,131 @@
+/**
+ * opencode spool adapter tests.
+ *
+ * The spool is written by the bundled opencode plugin
+ * (`plugins/opencode/open-second-brain.ts`) and is a format this repo
+ * owns: meta line `{type: "session_meta", originator:
+ * "open-second-brain-opencode-plugin", format: 1}` followed by
+ * `{type: "turn", ...}` lines already shaped like `SessionTurn`.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+
+import { opencodeAdapter } from "../../src/core/brain/sessions/opencode.ts";
+
+const FIXTURE = resolve("tests/fixtures/sessions/opencode-minimal.jsonl");
+
+async function collect(path: string) {
+ const turns = [];
+ for await (const t of opencodeAdapter.iterate(path)) turns.push(t);
+ return turns;
+}
+
+function tmpSpool(lines: string[]): string {
+ const dir = mkdtempSync(join(tmpdir(), "osb-oc-adapter-"));
+ const path = join(dir, "spool.jsonl");
+ writeFileSync(path, lines.join("\n") + "\n");
+ return path;
+}
+
+const META = JSON.stringify({
+ type: "session_meta",
+ originator: "open-second-brain-opencode-plugin",
+ format: 1,
+ session_id: "s1",
+});
+
+describe("opencode adapter — detect", () => {
+ test("matches the spool meta line", () => {
+ expect(
+ opencodeAdapter.detect(
+ '{"type":"session_meta","originator":"open-second-brain-opencode-plugin","format":1}',
+ ),
+ ).toBe(true);
+ });
+
+ test("rejects codex session_meta (different originator)", () => {
+ expect(
+ opencodeAdapter.detect(
+ '{"timestamp":"t","type":"session_meta","payload":{"originator":"codex_exec"}}',
+ ),
+ ).toBe(false);
+ });
+
+ test("rejects garbage and unrelated JSON", () => {
+ expect(opencodeAdapter.detect("not json")).toBe(false);
+ expect(opencodeAdapter.detect('{"foo":1}')).toBe(false);
+ });
+});
+
+describe("opencode adapter — iterate", () => {
+ test("yields normalized turns from the fixture", async () => {
+ const turns = await collect(FIXTURE);
+ expect(turns).toHaveLength(3);
+ expect(turns[0]).toEqual({
+ turnId: "msg_user_1",
+ timestamp: "2026-06-10T09:00:00.000Z",
+ role: "user",
+ text:
+ "How should I handle DB mocking?\n" +
+ '@osb feedback negative topic=mocking principle="don\'t mock DB in integration tests" scope=testing',
+ });
+ expect(turns[1]!.role).toBe("assistant");
+ expect(turns[2]!.toolCalls).toEqual([
+ {
+ name: "brain_feedback",
+ id: "call_oc_1",
+ input: {
+ topic: "mocking",
+ signal: "negative",
+ principle: "avoid mocking the database in integration tests",
+ scope: "testing",
+ },
+ },
+ ]);
+ });
+
+ test("skips malformed lines and unknown roles without failing", async () => {
+ const path = tmpSpool([
+ META,
+ "{ not json",
+ '{"type":"turn","turnId":"x1","timestamp":"2026-06-10T09:00:00.000Z","role":"alien","text":"hi"}',
+ '{"type":"turn","turnId":"x2","timestamp":"2026-06-10T09:00:01.000Z","role":"user","text":"ok"}',
+ ]);
+ const turns = await collect(path);
+ expect(turns.map((t) => t.turnId)).toEqual(["x2"]);
+ });
+
+ test("rejects a spool with a newer format version", async () => {
+ const path = tmpSpool([
+ JSON.stringify({
+ type: "session_meta",
+ originator: "open-second-brain-opencode-plugin",
+ format: 2,
+ session_id: "s2",
+ }),
+ '{"type":"turn","turnId":"x1","timestamp":"2026-06-10T09:00:00.000Z","role":"user","text":"hi"}',
+ ]);
+ await expect(collect(path)).rejects.toThrow(/format/);
+ });
+
+ test("rejects a file whose first line is not the spool meta", async () => {
+ const path = tmpSpool([
+ '{"type":"turn","turnId":"x1","timestamp":"2026-06-10T09:00:00.000Z","role":"user","text":"hi"}',
+ '{"type":"turn","turnId":"x2","timestamp":"2026-06-10T09:00:01.000Z","role":"user","text":"ok"}',
+ ]);
+ await expect(collect(path)).rejects.toThrow(/meta line missing or invalid/);
+ });
+
+ test("turns without text but with toolCalls survive", async () => {
+ const path = tmpSpool([
+ META,
+ '{"type":"turn","turnId":"t1","timestamp":"2026-06-10T09:00:00.000Z","role":"assistant","toolCalls":[{"name":"brain_note","input":{"text":"x"}}]}',
+ ]);
+ const turns = await collect(path);
+ expect(turns[0]!.text).toBeUndefined();
+ expect(turns[0]!.toolCalls![0]!.name).toBe("brain_note");
+ });
+});
diff --git a/tests/core/brain.sessions.registry.test.ts b/tests/core/brain.sessions.registry.test.ts
index fbfe759c..f30c2b6c 100644
--- a/tests/core/brain.sessions.registry.test.ts
+++ b/tests/core/brain.sessions.registry.test.ts
@@ -19,6 +19,7 @@ const FIXTURES = {
claude: resolve("tests/fixtures/sessions/claude-minimal.jsonl"),
codex: resolve("tests/fixtures/sessions/codex-minimal.jsonl"),
hermes: resolve("tests/fixtures/sessions/hermes-minimal.jsonl"),
+ opencode: resolve("tests/fixtures/sessions/opencode-minimal.jsonl"),
};
function firstLine(path: string): string {
@@ -26,16 +27,17 @@ function firstLine(path: string): string {
}
describe("registry — single source of adapters", () => {
- test("exposes all three adapters", () => {
+ test("exposes all four adapters", () => {
const ids = SESSION_ADAPTERS.map((a) => a.id).toSorted();
- expect(ids).toEqual(["claude", "codex", "hermes"]);
+ expect(ids).toEqual(["claude", "codex", "hermes", "opencode"]);
});
test("owns runtime validation and help choices", () => {
- expect(sessionAdapterFormatChoices()).toBe("auto|claude|codex|hermes");
+ expect(sessionAdapterFormatChoices()).toBe("auto|claude|codex|hermes|opencode");
expect(isSessionAdapterId("claude")).toBe(true);
expect(isSessionAdapterId("codex")).toBe(true);
expect(isSessionAdapterId("hermes")).toBe(true);
+ expect(isSessionAdapterId("opencode")).toBe(true);
expect(isSessionAdapterId("copilot")).toBe(false);
});
@@ -45,6 +47,7 @@ describe("registry — single source of adapters", () => {
claude: "claude",
codex: "codex",
hermes: "hermes",
+ opencode: "opencode",
});
});
@@ -52,6 +55,7 @@ describe("registry — single source of adapters", () => {
expect(getAdapter("claude").id).toBe("claude");
expect(getAdapter("codex").id).toBe("codex");
expect(getAdapter("hermes").id).toBe("hermes");
+ expect(getAdapter("opencode").id).toBe("opencode");
});
});
@@ -65,6 +69,21 @@ describe("detectAdapter — autodetect across all three formats", () => {
test("picks hermes on the hermes fixture", () => {
expect(detectAdapter(firstLine(FIXTURES.hermes))?.id).toBe("hermes");
});
+ test("picks opencode on the opencode fixture", () => {
+ expect(detectAdapter(firstLine(FIXTURES.opencode))?.id).toBe("opencode");
+ });
+
+ test("no adapter claims a foreign fixture (full cross-table)", () => {
+ for (const [name, path] of Object.entries(FIXTURES)) {
+ const detected = detectAdapter(firstLine(path));
+ expect(detected?.id).toBe(name as never);
+ for (const adapter of SESSION_ADAPTERS) {
+ if (adapter.id !== name) {
+ expect(adapter.detect(firstLine(path))).toBe(false);
+ }
+ }
+ }
+ });
test("returns null on unknown JSON", () => {
expect(detectAdapter(`{"foo":"bar"}`)).toBeNull();
diff --git a/tests/core/install/adapters/json-mcp-custom-shape.test.ts b/tests/core/install/adapters/json-mcp-custom-shape.test.ts
new file mode 100644
index 00000000..0c7ecbe3
--- /dev/null
+++ b/tests/core/install/adapters/json-mcp-custom-shape.test.ts
@@ -0,0 +1,139 @@
+/**
+ * Lifecycle test for the entry-shape injection points on
+ * `createJsonMcpAdapter` (`serializeEntry` + `entryEquals`).
+ *
+ * Uses an inline spec with an opencode-style entry shape
+ * (`{type, command: [bin, ...args], environment?, enabled}`) and walks
+ * detect → plan → apply → verify → drift → uninstall against temp dirs.
+ * The real opencode adapter has its own test file; this one pins the
+ * shared body's behavior for ANY custom shape.
+ */
+
+import { describe, expect, test, beforeEach, afterEach } from "bun:test";
+import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Writable } from "node:stream";
+
+import { createJsonMcpAdapter } from "../../../../src/core/install/adapters/_json-mcp.ts";
+import { buildPayload } from "../../../../src/core/install/payload.ts";
+import { readManifest } from "../../../../src/core/install/manifest.ts";
+import { deepJsonEquals } from "../../../../src/core/install/payload-equals.ts";
+import type { InstallEnv, McpServerEntry } from "../../../../src/core/install/types.ts";
+
+let vault: string;
+let home: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-shape-v-"));
+ home = mkdtempSync(join(tmpdir(), "osb-shape-h-"));
+});
+afterEach(() => {
+ try {
+ rmSync(vault, { recursive: true, force: true });
+ } catch {}
+ try {
+ rmSync(home, { recursive: true, force: true });
+ } catch {}
+});
+
+function customShape(e: McpServerEntry): Record<string, unknown> {
+ return {
+ type: "local",
+ command: [e.command, ...e.args],
+ ...(e.env && Object.keys(e.env).length > 0 ? { environment: { ...e.env } } : {}),
+ enabled: true,
+ };
+}
+
+const adapter = createJsonMcpAdapter({
+ target: "custom-shape-test",
+ label: "custom shape (test only)",
+ topLevelKey: "mcp",
+ resolveConfigPath: (env: InstallEnv) => join(env.home, ".customrt", "config.json"),
+ serializeEntry: customShape,
+ entryEquals: (current, expected) => deepJsonEquals(current, customShape(expected)),
+});
+
+function env() {
+ return {
+ vault,
+ home,
+ cwd: home,
+ env: { VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" },
+ now: new Date("2026-06-10T12: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("createJsonMcpAdapter with custom entry shape", () => {
+ test("apply writes the custom shape under the custom top-level key", () => {
+ adapter.apply(adapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const path = join(home, ".customrt", "config.json");
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
+ const full = parsed.mcp["open-second-brain"];
+ expect(full.type).toBe("local");
+ expect(full.command).toEqual(["o2b", "mcp", "--vault", vault]);
+ expect(full.environment).toEqual({ VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" });
+ expect(full.enabled).toBe(true);
+ expect(full.args).toBeUndefined();
+ });
+
+ test("verify reports ok for a canonical custom-shape install", () => {
+ adapter.apply(adapter.plan(payload(), env()), payload(), env(), applyOpts());
+ expect(adapter.verify(env()).status).toBe("ok");
+ expect(adapter.detect(env()).status).toBe("installed");
+ });
+
+ test("re-apply on a canonical install is a no-op (idempotent)", () => {
+ adapter.apply(adapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const path = join(home, ".customrt", "config.json");
+ const before = readFileSync(path, "utf8");
+ const second = adapter.apply(adapter.plan(payload(), env()), payload(), env(), applyOpts());
+ expect(second.steps_executed).toBe(0);
+ expect(readFileSync(path, "utf8")).toBe(before);
+ });
+
+ test("verify reports drift when the custom-shape entry is edited", () => {
+ adapter.apply(adapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const path = join(home, ".customrt", "config.json");
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
+ parsed.mcp["open-second-brain"].enabled = false;
+ writeFileSync(path, JSON.stringify(parsed, null, 2) + "\n");
+ const v = adapter.verify(env());
+ expect(v.status).toBe("drift");
+ });
+
+ test("uninstall removes only our keys and the manifest entry", () => {
+ const path = join(home, ".customrt", "config.json");
+ adapter.apply(adapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
+ parsed.mcp.other = { type: "remote", url: "https://x" };
+ writeFileSync(path, JSON.stringify(parsed, null, 2) + "\n");
+
+ adapter.uninstall(env(), applyOpts());
+ expect(readManifest(vault).installs["custom-shape-test"]).toBeUndefined();
+ const after = JSON.parse(readFileSync(path, "utf8"));
+ expect(after.mcp["open-second-brain"]).toBeUndefined();
+ expect(after.mcp["open-second-brain-writer"]).toBeUndefined();
+ expect(after.mcp.other).toEqual({ type: "remote", url: "https://x" });
+ expect(existsSync(path)).toBe(true);
+ });
+});
diff --git a/tests/core/install/adapters/json-mcp-smoke.test.ts b/tests/core/install/adapters/json-mcp-smoke.test.ts
index 4541783d..b4071494 100644
--- a/tests/core/install/adapters/json-mcp-smoke.test.ts
+++ b/tests/core/install/adapters/json-mcp-smoke.test.ts
@@ -1,10 +1,12 @@
/**
- * Smoke tests for opencode / kiro / gemini-cli adapters.
+ * Smoke tests for 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.
+ * clean install+uninstall cycle works end-to-end. opencode has its
+ * own file (`opencode.test.ts`) since it uses a custom entry shape
+ * plus legacy-config migration.
*/
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
@@ -13,7 +15,6 @@ 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";
@@ -66,34 +67,6 @@ 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());
diff --git a/tests/core/install/adapters/opencode.test.ts b/tests/core/install/adapters/opencode.test.ts
new file mode 100644
index 00000000..06baddef
--- /dev/null
+++ b/tests/core/install/adapters/opencode.test.ts
@@ -0,0 +1,308 @@
+/**
+ * opencode adapter tests.
+ *
+ * The adapter writes the config opencode actually reads:
+ * `${XDG_CONFIG_HOME:-~/.config}/opencode/opencode.json`, `mcp` key,
+ * entries shaped `{type: "local", command: [bin, ...args],
+ * environment?, enabled: true}` (verified against opencode.ai/docs
+ * 2026-06-10). Earlier Open Second Brain releases wrote
+ * `~/.config/opencode/mcp.json` with an `mcpServers` key - a file
+ * opencode never reads; apply migrates our keys out of it.
+ */
+
+import { describe, expect, test, beforeEach, afterEach } from "bun:test";
+import { mkdtempSync, rmSync, readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+import { Writable } from "node:stream";
+
+import { opencodeAdapter } from "../../../../src/core/install/adapters/opencode.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-opencode-v-"));
+ home = mkdtempSync(join(tmpdir(), "osb-opencode-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,
+ env: { VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC", ...extraEnv },
+ now: new Date("2026-06-10T12: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" });
+}
+
+function configPath() {
+ return join(home, ".config", "opencode", "opencode.json");
+}
+
+function legacyPath() {
+ return join(home, ".config", "opencode", "mcp.json");
+}
+
+function writeJson(path: string, value: unknown) {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, JSON.stringify(value, null, 2) + "\n");
+}
+
+describe("opencode adapter - config path", () => {
+ test("default path is ~/.config/opencode/opencode.json", () => {
+ const r = opencodeAdapter.detect(env());
+ expect(r.configPath).toBe(configPath());
+ });
+
+ 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", "opencode.json"));
+ try {
+ rmSync(xdg, { recursive: true, force: true });
+ } catch {}
+ });
+});
+
+describe("opencode adapter - apply", () => {
+ test("clean home: writes opencode.json with both keys in the opencode entry schema", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
+ const full = parsed.mcp["open-second-brain"];
+ expect(full).toEqual({
+ type: "local",
+ command: ["o2b", "mcp", "--vault", vault],
+ environment: { VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" },
+ enabled: true,
+ });
+ const writer = parsed.mcp["open-second-brain-writer"];
+ expect(writer.command).toEqual(["o2b", "mcp", "--writer-only", "--vault", vault]);
+ expect(writer.type).toBe("local");
+ expect(readManifest(vault).installs["opencode"]).toBeDefined();
+ });
+
+ test("preserves user-authored opencode.json content", () => {
+ writeJson(configPath(), {
+ $schema: "https://opencode.ai/config.json",
+ theme: "dark",
+ mcp: { other: { type: "remote", url: "https://x" } },
+ });
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
+ expect(parsed["$schema"]).toBe("https://opencode.ai/config.json");
+ expect(parsed.theme).toBe("dark");
+ expect(parsed.mcp.other).toEqual({ type: "remote", url: "https://x" });
+ expect(parsed.mcp["open-second-brain"].type).toBe("local");
+ });
+
+ test("idempotent re-apply executes no steps", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const before = readFileSync(configPath(), "utf8");
+ const second = opencodeAdapter.apply(
+ opencodeAdapter.plan(payload(), env()),
+ payload(),
+ env(),
+ applyOpts(),
+ );
+ expect(second.steps_executed).toBe(0);
+ expect(readFileSync(configPath(), "utf8")).toBe(before);
+ });
+});
+
+describe("opencode adapter - lifecycle", () => {
+ test("detect installed and verify ok after apply", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ expect(opencodeAdapter.detect(env()).status).toBe("installed");
+ expect(opencodeAdapter.verify(env()).status).toBe("ok");
+ });
+
+ test("verify reports drift when an entry field is edited", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
+ parsed.mcp["open-second-brain"].enabled = false;
+ writeFileSync(configPath(), JSON.stringify(parsed, null, 2) + "\n");
+ expect(opencodeAdapter.verify(env()).status).toBe("drift");
+ });
+
+ test("uninstall removes our keys, keeps user keys, clears manifest", () => {
+ writeJson(configPath(), { mcp: { other: { type: "remote", url: "https://x" } } });
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ opencodeAdapter.uninstall(env(), applyOpts());
+ const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
+ expect(parsed.mcp["open-second-brain"]).toBeUndefined();
+ expect(parsed.mcp["open-second-brain-writer"]).toBeUndefined();
+ expect(parsed.mcp.other).toEqual({ type: "remote", url: "https://x" });
+ expect(readManifest(vault).installs["opencode"]).toBeUndefined();
+ });
+});
+
+describe("opencode adapter - legacy mcp.json migration", () => {
+ function legacyEntry(writerOnly = false) {
+ return {
+ command: "o2b",
+ args: writerOnly ? ["mcp", "--writer-only", "--vault", vault] : ["mcp", "--vault", vault],
+ env: { VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" },
+ };
+ }
+
+ test("apply removes our keys from a legacy mcp.json, keeps user keys", () => {
+ writeJson(legacyPath(), {
+ mcpServers: {
+ "open-second-brain": legacyEntry(),
+ "open-second-brain-writer": legacyEntry(true),
+ other: { command: "x", args: [] },
+ },
+ });
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const legacy = JSON.parse(readFileSync(legacyPath(), "utf8"));
+ expect(legacy.mcpServers["open-second-brain"]).toBeUndefined();
+ expect(legacy.mcpServers["open-second-brain-writer"]).toBeUndefined();
+ expect(legacy.mcpServers.other).toEqual({ command: "x", args: [] });
+ });
+
+ test("apply deletes a legacy mcp.json that contained only our keys", () => {
+ writeJson(legacyPath(), {
+ mcpServers: {
+ "open-second-brain": legacyEntry(),
+ "open-second-brain-writer": legacyEntry(true),
+ },
+ });
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ expect(existsSync(legacyPath())).toBe(false);
+ });
+
+ test("apply leaves a legacy mcp.json without our keys untouched", () => {
+ writeJson(legacyPath(), { mcpServers: { other: { command: "x" } } });
+ const before = readFileSync(legacyPath(), "utf8");
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ expect(readFileSync(legacyPath(), "utf8")).toBe(before);
+ });
+
+ test("apply ignores a malformed legacy mcp.json", () => {
+ mkdirSync(dirname(legacyPath()), { recursive: true });
+ writeFileSync(legacyPath(), "{ not json");
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ expect(readFileSync(legacyPath(), "utf8")).toBe("{ not json");
+ expect(JSON.parse(readFileSync(configPath(), "utf8")).mcp["open-second-brain"]).toBeDefined();
+ });
+});
+
+describe("opencode adapter - bundled plugin installation", () => {
+ function pluginPath() {
+ return join(home, ".config", "opencode", "plugins", "open-second-brain.ts");
+ }
+
+ test("apply copies the bundled plugin with a version-stamped header", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ expect(existsSync(pluginPath())).toBe(true);
+ const content = readFileSync(pluginPath(), "utf8");
+ expect(content.startsWith("// open-second-brain plugin v")).toBe(true);
+ expect(content).toContain("export const OpenSecondBrain");
+ });
+
+ test("manifest records the plugin file as an owned path", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const entry = readManifest(vault).installs["opencode"];
+ expect(entry?.owned_paths).toContain(pluginPath());
+ });
+
+ test("verify reports drift when the installed plugin is edited", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ expect(opencodeAdapter.verify(env()).status).toBe("ok");
+ writeFileSync(pluginPath(), "// hand-edited\n");
+ const v = opencodeAdapter.verify(env());
+ expect(v.status).toBe("drift");
+ expect(v.details.join(" ")).toContain("plugin");
+ });
+
+ test("verify reports drift when the plugin file is missing", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ rmSync(pluginPath());
+ expect(opencodeAdapter.verify(env()).status).toBe("drift");
+ });
+
+ test("re-apply refreshes an outdated plugin copy", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ writeFileSync(pluginPath(), "// stale copy from an older release\n");
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ expect(readFileSync(pluginPath(), "utf8")).toContain("export const OpenSecondBrain");
+ });
+
+ test("dry-run apply does not write the plugin file", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), {
+ ...applyOpts(),
+ dryRun: true,
+ });
+ expect(existsSync(pluginPath())).toBe(false);
+ });
+
+ test("verify reports drift when the plugin path is a directory", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ rmSync(pluginPath(), { recursive: true, force: true });
+ mkdirSync(pluginPath(), { recursive: true });
+ expect(opencodeAdapter.verify(env()).status).toBe("drift");
+ });
+
+ test("apply replaces a stray directory at the plugin path", () => {
+ mkdirSync(pluginPath(), { recursive: true });
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const content = readFileSync(pluginPath(), "utf8");
+ expect(content).toContain("export const OpenSecondBrain");
+ });
+
+ test("uninstall removes the plugin file", () => {
+ opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
+ const r = opencodeAdapter.uninstall(env(), applyOpts());
+ expect(existsSync(pluginPath())).toBe(false);
+ expect(r.removed_paths).toContain(pluginPath());
+ });
+});
+
+describe("opencode adapter - plan completeness", () => {
+ test("plan lists the plugin copy step", () => {
+ const plan = opencodeAdapter.plan(payload(), env());
+ const kinds = plan.steps.map((s) => s.kind);
+ expect(kinds).toContain("json-merge");
+ expect(kinds).toContain("file-copy");
+ expect(plan.steps.find((s) => s.kind === "file-copy")?.path).toContain(
+ "plugins/open-second-brain.ts",
+ );
+ });
+
+ test("plan lists the legacy migration step only when mcp.json exists", () => {
+ const without = opencodeAdapter.plan(payload(), env());
+ expect(without.steps.some((s) => s.path === legacyPath())).toBe(false);
+ writeJson(legacyPath(), { mcpServers: {} });
+ const withLegacy = opencodeAdapter.plan(payload(), env());
+ expect(withLegacy.steps.some((s) => s.path === legacyPath())).toBe(true);
+ });
+});
diff --git a/tests/core/install/json-merge.test.ts b/tests/core/install/json-merge.test.ts
index 317cb9d5..7b9ba159 100644
--- a/tests/core/install/json-merge.test.ts
+++ b/tests/core/install/json-merge.test.ts
@@ -156,3 +156,69 @@ describe("removeMcpServers", () => {
expect(parsed.mcp_servers.other.command).toBe("x");
});
});
+
+// opencode-style entry shape: `{type, command: [bin, ...args], environment, enabled}`.
+const opencodeShape = (e: {
+ command: string;
+ args: readonly string[];
+ env?: Record<string, string>;
+}) => ({
+ type: "local",
+ command: [e.command, ...e.args],
+ ...(e.env && Object.keys(e.env).length > 0 ? { environment: { ...e.env } } : {}),
+ enabled: true,
+});
+
+describe("mergeMcpServers serializeEntry injection", () => {
+ test("custom serializeEntry controls the on-disk entry shape", () => {
+ const out = mergeMcpServers("", OSB_PAYLOAD, {
+ topLevelKey: "mcp",
+ serializeEntry: opencodeShape,
+ });
+ const parsed = JSON.parse(out);
+ const full = parsed.mcp["open-second-brain"];
+ expect(full.type).toBe("local");
+ expect(full.command).toEqual(["o2b", "mcp", "--vault", "/home/u/vault"]);
+ expect(full.environment).toEqual({
+ VAULT_AGENT_NAME: "claude-vps-agent",
+ VAULT_TIMEZONE: "Europe/Belgrade",
+ });
+ expect(full.enabled).toBe(true);
+ expect(full.args).toBeUndefined();
+ expect(full.env).toBeUndefined();
+ });
+
+ test("custom serializeEntry preserves user-authored sibling entries", () => {
+ const before = `{
+ "mcp": { "other": { "type": "remote", "url": "https://x" } },
+ "theme": "dark"
+}
+`;
+ const out = mergeMcpServers(before, OSB_PAYLOAD, {
+ topLevelKey: "mcp",
+ serializeEntry: opencodeShape,
+ });
+ const parsed = JSON.parse(out);
+ expect(parsed.theme).toBe("dark");
+ expect(parsed.mcp.other).toEqual({ type: "remote", url: "https://x" });
+ expect(parsed.mcp["open-second-brain-writer"].command).toEqual([
+ "o2b",
+ "mcp",
+ "--writer-only",
+ "--vault",
+ "/home/u/vault",
+ ]);
+ });
+
+ test("omitting serializeEntry keeps the default shape byte-identical", () => {
+ const explicit = mergeMcpServers("", OSB_PAYLOAD, { serializeEntry: undefined });
+ const implicit = mergeMcpServers("", OSB_PAYLOAD);
+ expect(explicit).toBe(implicit);
+ const parsed = JSON.parse(implicit);
+ expect(parsed.mcpServers["open-second-brain"]).toEqual({
+ command: "o2b",
+ args: ["mcp", "--vault", "/home/u/vault"],
+ env: { VAULT_AGENT_NAME: "claude-vps-agent", VAULT_TIMEZONE: "Europe/Belgrade" },
+ });
+ });
+});
diff --git a/tests/fixtures/sessions/opencode-minimal.jsonl b/tests/fixtures/sessions/opencode-minimal.jsonl
new file mode 100644
index 00000000..87f3aae0
--- /dev/null
+++ b/tests/fixtures/sessions/opencode-minimal.jsonl
@@ -0,0 +1,4 @@
+{"type":"session_meta","originator":"open-second-brain-opencode-plugin","format":1,"session_id":"ses_oc_0001","directory":"/tmp/project"}
+{"type":"turn","turnId":"msg_user_1","timestamp":"2026-06-10T09:00:00.000Z","role":"user","text":"How should I handle DB mocking?\n@osb feedback negative topic=mocking principle=\"don't mock DB in integration tests\" scope=testing"}
+{"type":"turn","turnId":"msg_asst_1","timestamp":"2026-06-10T09:00:05.000Z","role":"assistant","text":"I'll record that as a preference."}
+{"type":"turn","turnId":"msg_asst_2","timestamp":"2026-06-10T09:00:06.000Z","role":"assistant","toolCalls":[{"name":"brain_feedback","id":"call_oc_1","input":{"topic":"mocking","signal":"negative","principle":"avoid mocking the database in integration tests","scope":"testing"}}]}
diff --git a/tests/plugins/opencode-plugin.test.ts b/tests/plugins/opencode-plugin.test.ts
new file mode 100644
index 00000000..d2831f45
--- /dev/null
+++ b/tests/plugins/opencode-plugin.test.ts
@@ -0,0 +1,255 @@
+/**
+ * Tests for the bundled opencode plugin (`plugins/opencode/open-second-brain.ts`).
+ *
+ * opencode is not installed on dev or CI machines: the plugin is
+ * exercised directly with a fake SDK `client`, a stub `o2b-hook`
+ * executable (via `OSB_HOOK_BIN`), and a temp spool dir (via
+ * `OSB_OPENCODE_SPOOL_DIR`). Every hook must be fail-soft: a broken
+ * client, missing binary, or unwritable spool dir must never throw
+ * into opencode.
+ */
+
+import { describe, expect, test, beforeEach, afterEach } from "bun:test";
+import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync, chmodSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { OpenSecondBrain } from "../../plugins/opencode/open-second-brain.ts";
+
+let spoolDir: string;
+let binDir: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ spoolDir = mkdtempSync(join(tmpdir(), "osb-oc-spool-"));
+ binDir = mkdtempSync(join(tmpdir(), "osb-oc-bin-"));
+ for (const k of ["OSB_HOOK_BIN", "OSB_OPENCODE_SPOOL_DIR"]) {
+ savedEnv[k] = process.env[k];
+ }
+ process.env["OSB_OPENCODE_SPOOL_DIR"] = spoolDir;
+});
+
+afterEach(() => {
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ for (const d of [spoolDir, binDir]) {
+ try {
+ rmSync(d, { recursive: true, force: true });
+ } catch {}
+ }
+});
+
+/** Stub o2b-hook that prints an active-inject response. */
+function stubHookBin(context: string | null): string {
+ const path = join(binDir, "o2b-hook");
+ const body =
+ context === null
+ ? "#!/bin/sh\nexit 0\n"
+ : `#!/bin/sh\ncat > /dev/null\nprintf '%s' '${JSON.stringify({
+ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: context },
+ })}'\n`;
+ writeFileSync(path, body);
+ chmodSync(path, 0o755);
+ return path;
+}
+
+interface FakeMessage {
+ info: { id: string; role: string; time?: { created?: number } };
+ parts: Array<Record<string, unknown>>;
+}
+
+function fakeClient(messages: FakeMessage[] | (() => never)) {
+ // Faithful to the real opencode SDK client: `session.messages` is a
+ // method that reads instance state through `this` (the shipped client
+ // dereferences `this._client`). Modeling it as a `this`-dependent
+ // method shorthand - not an arrow - means a detached call
+ // (`const m = session.messages; await m(...)`) throws here exactly as
+ // it does against the real client, so the capture path must invoke it
+ // as a method.
+ return {
+ session: {
+ messageStore: messages,
+ async messages(this: { messageStore: FakeMessage[] | (() => never) }, _opts: unknown) {
+ const store = this.messageStore;
+ if (typeof store === "function") store();
+ return { data: store };
+ },
+ },
+ };
+}
+
+function pluginInput(client: unknown) {
+ return {
+ client,
+ project: { id: "proj-1" },
+ directory: "/work/dir",
+ worktree: "/work/dir",
+ $: undefined,
+ serverUrl: new URL("http://localhost:1"),
+ };
+}
+
+const MESSAGES: FakeMessage[] = [
+ {
+ info: { id: "msg-1", role: "user", time: { created: 1765900000000 } },
+ parts: [{ type: "text", text: "please fix the bug" }],
+ },
+ {
+ info: { id: "msg-2", role: "assistant", time: { created: 1765900060000 } },
+ parts: [
+ { type: "text", text: "working on it" },
+ { type: "tool", tool: "edit", callID: "call-7", state: { input: { filePath: "/a.ts" } } },
+ ],
+ },
+ {
+ info: { id: "msg-3", role: "ignored-kind" },
+ parts: [{ type: "text", text: "dropped" }],
+ },
+];
+
+async function makeHooks(client: unknown) {
+ return await OpenSecondBrain(pluginInput(client) as never);
+}
+
+describe("opencode plugin - session capture spool", () => {
+ test("session.idle writes a spool snapshot with meta line and normalized turns", async () => {
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ await hooks.event!({
+ event: { type: "session.idle", properties: { sessionID: "sess-abc" } },
+ } as never);
+
+ const file = join(spoolDir, "sess-abc.jsonl");
+ expect(existsSync(file)).toBe(true);
+ const lines = readFileSync(file, "utf8").trim().split("\n");
+ const meta = JSON.parse(lines[0]!);
+ expect(meta.type).toBe("session_meta");
+ expect(meta.originator).toBe("open-second-brain-opencode-plugin");
+ expect(meta.format).toBe(1);
+ expect(meta.session_id).toBe("sess-abc");
+
+ const turns = lines.slice(1).map((l) => JSON.parse(l));
+ expect(turns).toHaveLength(2);
+ expect(turns[0]).toEqual({
+ type: "turn",
+ turnId: "msg-1",
+ timestamp: new Date(1765900000000).toISOString(),
+ role: "user",
+ text: "please fix the bug",
+ });
+ expect(turns[1].role).toBe("assistant");
+ expect(turns[1].text).toBe("working on it");
+ expect(turns[1].toolCalls).toEqual([
+ { name: "edit", id: "call-7", input: { filePath: "/a.ts" } },
+ ]);
+ });
+
+ test("snapshot rewrite is idempotent across repeated idle events", async () => {
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ const ev = { event: { type: "session.idle", properties: { sessionID: "sess-abc" } } };
+ await hooks.event!(ev as never);
+ const first = readFileSync(join(spoolDir, "sess-abc.jsonl"), "utf8");
+ await hooks.event!(ev as never);
+ expect(readFileSync(join(spoolDir, "sess-abc.jsonl"), "utf8")).toBe(first);
+ });
+
+ test("unrelated event types do not touch the spool", async () => {
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ await hooks.event!({
+ event: { type: "file.edited", properties: { sessionID: "sess-abc" } },
+ } as never);
+ expect(existsSync(join(spoolDir, "sess-abc.jsonl"))).toBe(false);
+ });
+
+ test("session id is sanitized for the spool filename", async () => {
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ await hooks.event!({
+ event: { type: "session.idle", properties: { sessionID: "../../evil" } },
+ } as never);
+ expect(existsSync(join(spoolDir, ".._.._evil.jsonl"))).toBe(true);
+ });
+
+ test("a throwing client never propagates out of the event hook", async () => {
+ const hooks = await makeHooks(
+ fakeClient(() => {
+ throw new Error("boom");
+ }),
+ );
+ await hooks.event!({
+ event: { type: "session.idle", properties: { sessionID: "sess-x" } },
+ } as never);
+ expect(existsSync(join(spoolDir, "sess-x.jsonl"))).toBe(false);
+ });
+});
+
+describe("opencode plugin - active context inject", () => {
+ test("appends rendered context to the system array when o2b-hook responds", async () => {
+ process.env["OSB_HOOK_BIN"] = stubHookBin("ACTIVE PREFS BLOCK");
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ const output = { system: ["base"] };
+ await hooks["experimental.chat.system.transform"]!({} as never, output as never);
+ expect(output.system).toEqual(["base", "ACTIVE PREFS BLOCK"]);
+ });
+
+ test("caches the rendered context between calls", async () => {
+ process.env["OSB_HOOK_BIN"] = stubHookBin("CACHED BLOCK");
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ const out1 = { system: [] as string[] };
+ await hooks["experimental.chat.system.transform"]!({} as never, out1 as never);
+ // Re-point the stub at different content: a cached plugin must not pick it up.
+ stubHookBin("CHANGED BLOCK");
+ const out2 = { system: [] as string[] };
+ await hooks["experimental.chat.system.transform"]!({} as never, out2 as never);
+ expect(out2.system).toEqual(["CACHED BLOCK"]);
+ });
+
+ test("missing o2b-hook binary degrades to no-op", async () => {
+ process.env["OSB_HOOK_BIN"] = join(binDir, "does-not-exist");
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ const output = { system: ["base"] };
+ await hooks["experimental.chat.system.transform"]!({} as never, output as never);
+ expect(output.system).toEqual(["base"]);
+ });
+
+ test("silent o2b-hook (no stdout) degrades to no-op", async () => {
+ process.env["OSB_HOOK_BIN"] = stubHookBin(null);
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ const output = { system: [] as string[] };
+ await hooks["experimental.chat.system.transform"]!({} as never, output as never);
+ expect(output.system).toEqual([]);
+ });
+});
+
+describe("opencode plugin - post-write reminder", () => {
+ test("appends the nudge to file-mutating tool output", async () => {
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ const output = { title: "t", output: "wrote /a.ts", metadata: {} };
+ await hooks["tool.execute.after"]!(
+ { tool: "edit", sessionID: "s", callID: "c" } as never,
+ output as never,
+ );
+ expect(output.output).toContain("wrote /a.ts");
+ expect(output.output).toContain("Open Second Brain: artifact written.");
+ });
+
+ test("leaves non-mutating tool output untouched", async () => {
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ const output = { title: "t", output: "file contents", metadata: {} };
+ await hooks["tool.execute.after"]!(
+ { tool: "read", sessionID: "s", callID: "c" } as never,
+ output as never,
+ );
+ expect(output.output).toBe("file contents");
+ });
+
+ test("non-string output is left alone", async () => {
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ const output = { title: "t", output: { structured: true }, metadata: {} };
+ await hooks["tool.execute.after"]!(
+ { tool: "write", sessionID: "s", callID: "c" } as never,
+ output as never,
+ );
+ expect(output.output).toEqual({ structured: true });
+ });
+});
diff --git a/tsconfig.json b/tsconfig.json
index e8d591f8..d19527ca 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -19,5 +19,12 @@
"forceConsistentCasingInFileNames": true,
"types": ["bun"]
},
- "include": ["src/**/*.ts", "src/**/*.d.ts", "tests/**/*.ts", "scripts/**/*.ts", "hooks/**/*.ts"]
+ "include": [
+ "src/**/*.ts",
+ "src/**/*.d.ts",
+ "tests/**/*.ts",
+ "scripts/**/*.ts",
+ "hooks/**/*.ts",
+ "plugins/opencode/**/*.ts"
+ ]
}