Local-first 🧠memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
fix(opencode): support both plugin APIs (v1.74.1) (#190)
Jason Kölker542d214b5e6b
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 5b228014..180697ed 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.74.0",+ "version": "1.74.1","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 2bcd535a..91670c83 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.74.0",+ "version": "1.74.1","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f968c0fd..10e8c8af 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,14 @@ 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.74.1] - 2026-10-07++The bundled opencode plugin loads and works on OpenCode V2 hosts from the same installed file that already served V1. Contributed by @jkoelker in #190, with the maintainer-side completion of the V2 event names against the released 2.0.24 build.++### Fixed++- **The opencode plugin supports the V1 and V2 plugin APIs from one file.** The module now default-exports `{ id, server, setup }`: OpenCode V1 keeps calling `server()` exactly as before, and OpenCode V2 loads the same installed copy through `setup()`, which feature-detects every capability it needs (`location.directory`, `session.hook` / `get` / `context`, `tool.hook`, `event.subscribe`) and does nothing when one is missing, so hosts without a hook stay unaffected. Under V2, active-context injection rides the session `context` hook, the post-write reminder rides `tool.hook("execute.after")`, and session capture subscribes to the event stream and merges each snapshot with the earlier turns so history survives compactions; a committed revert removes the saved boundary and the turns after it, rebuilding from active context when the boundary was never captured. Verified live against opencode 2.0.24: plugin load, context hook, capture spool and post-write reminder.+- **V2 capture listens on the turn-end events a released opencode emits.** opencode 2.0.24 never fires `session.idle`; a finished turn emits `session.execution.succeeded` (failed and interrupted runs likewise). The capture set now covers those names alongside the v2-tree names, plus `session.compaction.failed`, so a turn that ends or fails on a released V2 host still lands its spool snapshot.## [1.74.0] - 2026-10-07Open Second Brain now defends against near-duplicate memory at the points a fact enters or leaves the vault: one reach-aware near-duplicate kernel scores the note-write receipt hint, the feedback advisory and a new retire-sibling list, so a context-driven retire names the active paraphrases that would otherwise survive it; the receipt hint can look beyond the written page's directory through the keyword index; every receipt lint finding answers at the caller's reach; extract-signals grounds time bounds in each turn's timestamp and refuses a payload that repeats a topic; and route metrics time each write stage without carrying any content.@@ -8269,6 +8277,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[1.74.1]: https://github.com/itechmeat/open-second-brain/compare/v1.74.0...v1.74.1[1.74.0]: https://github.com/itechmeat/open-second-brain/compare/v1.73.1...v1.74.0[1.73.1]: https://github.com/itechmeat/open-second-brain/compare/v1.73.0...v1.73.1[1.73.0]: https://github.com/itechmeat/open-second-brain/compare/v1.72.0...v1.73.0diff --git a/install/opencode.md b/install/opencode.mdindex aba54021..29acaff3 100644--- a/install/opencode.md+++ b/install/opencode.md@@ -25,6 +25,12 @@ o2b install --target opencode --applyRestart `opencode` to load the MCP servers and the plugin.+The bundled plugin supports OpenCode V1 1.18.29+ and V2 from the same+installed file: V1 calls `server()` and V2 calls `setup()`. Older V1+releases do not support the shared object entrypoint. `--check` verifies+the installed files and MCP configuration, not whether the running host+loaded the plugin; on V2, check its state with `opencode api get /api/plugin`.+opencode's Brain writes attribute to an **opencode-specific identity** derivedfrom your configured `agent_name`: the host segment is kept and the vendortoken is swapped to `opencode` (`claude-vps-agent` -> `opencode-vps-agent`; a@@ -43,7 +49,11 @@ manual step is needed.the Claude Code and Codex hook layers; if the shim or the vault ismissing the inject silently skips.- **Session capture** - on `session.idle` / `session.compacted` /- `session.deleted` the plugin snapshots the session as a JSONL spool+ `session.deleted` (V1), or turn end / compaction / committed revert+ (V2: `session.execution.*`, `session.compaction.*`,+ `session.revert.committed`, `session.deleted`; opencode v2.0.24 emits+ the `execution` names, the v2 tree also still emits `session.idle`), the+ plugin snapshots the session as a JSONL spoolunder `${XDG_DATA_HOME:-$HOME/.local/share}/open-second-brain/opencode/`.Import captured sessions with:@@ -52,6 +62,14 @@ manual step is needed.--vault /path/to/vault```+ V2 exposes only the active context to plugins, so snapshots merge+ across compactions. Its event subscription is live-only: a session+ already compacted before the plugin loads cannot recover older turns.+ Capture reconnects after a stream disconnect, but events missed during+ the gap cannot be replayed. Committed reverts remove the saved boundary+ and later messages; if the boundary was never captured, the spool is+ rebuilt from active context and older saved history is lost with a warning.+- **Post-write reminder** - after file-mutating tools (`write`,`edit`, `multiedit`, `patch`, `apply_patch`) the standard loggingnudge is appended to the tool output so the agent considers@@ -100,10 +118,10 @@ installed plugin file. User-authored config is untouched.- **No stop-log guardrail.** opencode exposes no blocking stop hook,so the guardrail that vetoes an unlogged artifact turn cannot bereproduced; 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.+- **V1 context inject rides an experimental hook**+ (`experimental.chat.system.transform`). V2 instead uses the session+ `context` hook. If a future V1 release changes the experimental hook,+ the inject degrades to no-op while capture and the MCP servers keep working.## Notesdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex a87e3eeb..7f92e91d 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "1.74.0",+ "version": "1.74.1","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 89d92f17..b1236a0b 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.74.0",+ "version": "1.74.1","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 853282de..54ea4bf2 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.74.0"+version: "1.74.1"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 9a0f1ffd..60a65b31 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.74.0",+ "version": "1.74.1","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 853282de..54ea4bf2 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.74.0"+version: "1.74.1"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/opencode/open-second-brain.ts b/plugins/opencode/open-second-brain.tsindex cd77adad..8ed60ae9 100644--- a/plugins/opencode/open-second-brain.ts+++ b/plugins/opencode/open-second-brain.ts@@ -7,18 +7,21 @@* Bun globals opencode already provides) so the copy works standalone* inside opencode's plugin sandbox.*- * Three behaviors, mirroring the Claude Code / Codex hook layer:+ * Supports OpenCode V1 (server) and V2 (setup). Three behaviors mirror+ * the Claude Code / Codex hook layer:*- * 1. Active-context inject: `experimental.chat.system.transform`+ * 1. Active-context inject: V1 `experimental.chat.system.transform` /+ * V2 `session.hook("context")`* 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+ * 2. Session capture: V1 snapshots the full message list on idle,+ * compaction, or deletion; V2 snapshots active context on idle and+ * before/after compaction, merging with earlier snapshots to retain+ * history. The deterministic JSONL spool lives under* `${XDG_DATA_HOME:-~/.local/share}/open-second-brain/opencode/`* (`%LOCALAPPDATA%\\open-second-brain\\opencode\\` on native Windows)* (override: `OSB_OPENCODE_SPOOL_DIR`). The spool format is owned@@ -27,21 +30,37 @@* adapter. Snapshot-rewrite, not append: idempotent and* self-healing after crashes.*- * 3. Post-write reminder: `tool.execute.after` appends the standard+ * 3. Post-write reminder: V1 `tool.execute.after` /+ * V2 `tool.hook("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.+ * session API error must never break the operator's opencode session.*/-import { mkdirSync, renameSync, writeFileSync } from "node:fs";+import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";+import { setTimeout as sleep } from "node:timers/promises";const SPOOL_FORMAT = 1;const SPOOL_ORIGINATOR = "open-second-brain-opencode-plugin";const CAPTURE_EVENTS = new Set(["session.idle", "session.compacted", "session.deleted"]);+const V2_CAPTURE_EVENTS = new Set([+ // v2 tree naming: the turn ends with an idle event.+ "session.idle",+ // v2 >= 2.0.24 naming: the turn ends with an execution event, and a+ // failed or interrupted run still leaves messages worth capturing.+ "session.execution.succeeded",+ "session.execution.failed",+ "session.execution.interrupted",+ "session.compaction.started",+ "session.compaction.ended",+ "session.compaction.failed",+ "session.revert.committed",+ "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. */@@ -107,16 +126,17 @@ function extractSessionId(properties: unknown): string | null {}/**- * Normalizes one SDK message (`{info, parts}`) into a spool turn.+ * Normalizes a V1 SDK message (`{info, parts}`) or a V2 session message+ * (`{id, type, text|content}`) 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"]);+ const info = asRecord(m["info"]) ?? m;if (!info || typeof info["id"] !== "string") return null;- const role = info["role"];+ const role = info["role"] ?? info["type"];if (role !== "user" && role !== "assistant" && role !== "system") return null;const time = asRecord(info["time"]);@@ -125,18 +145,29 @@ function normalizeMessage(message: unknown): SpoolTurn | null {const texts: string[] = [];const toolCalls: Array<{ name: string; id?: string; input: Record<string, unknown> }> = [];- const parts = Array.isArray(m["parts"]) ? m["parts"] : [];+ if (typeof m["text"] === "string" && m["text"].length > 0) texts.push(m["text"]);+ const parts = Array.isArray(m["parts"])+ ? m["parts"]+ : Array.isArray(m["content"])+ ? m["content"]+ : [];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") {+ } else if (part["type"] === "tool") {+ const tool = typeof part["tool"] === "string" ? part["tool"] : part["name"];+ if (typeof tool !== "string") continue;const state = asRecord(part["state"]);const input = state ? (asRecord(state["input"]) ?? {}) : {};toolCalls.push({- name: part["tool"],- ...(typeof part["callID"] === "string" ? { id: part["callID"] } : {}),+ name: tool,+ ...(typeof part["callID"] === "string"+ ? { id: part["callID"] }+ : typeof part["id"] === "string"+ ? { id: part["id"] }+ : {}),input,});}@@ -157,7 +188,13 @@ function normalizeMessage(message: unknown): SpoolTurn | null {* 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 {+function writeSpool(+ sessionId: string,+ directory: string,+ messages: unknown[],+ preserveExisting = false,+ revertTo?: string,+): void {const name = sanitizeSessionId(sessionId);if (name === null) return;const meta = {@@ -167,14 +204,60 @@ function writeSpool(sessionId: string, directory: string, messages: unknown[]):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`);+ const turns = new Map<string, SpoolTurn | null>();+ if (preserveExisting) {+ try {+ const lines = readFileSync(target, "utf8").trimEnd().split("\n");+ const previous = asRecord(JSON.parse(lines[0]!));+ if (previous?.["session_id"] === sessionId && previous["format"] === SPOOL_FORMAT) {+ // Include control-message IDs so a revert can target a non-transcript boundary.+ if (Array.isArray(previous["message_ids"])) {+ for (const id of previous["message_ids"]) {+ if (typeof id === "string") turns.set(id, null);+ }+ }+ for (const line of lines.slice(1)) {+ const turn = asRecord(JSON.parse(line));+ if (turn?.["type"] === "turn" && typeof turn["turnId"] === "string") {+ turns.set(turn["turnId"], turn as unknown as SpoolTurn);+ }+ }+ }+ } catch {+ // A missing or incomplete previous snapshot must not block a fresh one.+ }+ }+ if (revertTo !== undefined) {+ const ids = Array.from(turns.keys());+ const boundary = ids.indexOf(revertTo);+ if (boundary === -1) {+ // An older or missed snapshot cannot locate the boundary safely.+ // Rebuild from authoritative context rather than reintroducing removed turns.+ console.warn(+ "Open Second Brain: revert boundary was not captured; rebuilding from active context",+ );+ turns.clear();+ } else {+ for (const id of ids.slice(boundary)) turns.delete(id);+ }+ }+ for (const message of messages) {+ const record = asRecord(message);+ const info = asRecord(record?.["info"]) ?? record;+ if (typeof info?.["id"] === "string") turns.set(info["id"], normalizeMessage(message));+ }+ const lines = [+ JSON.stringify({+ ...meta,+ ...(preserveExisting ? { message_ids: Array.from(turns.keys()) } : {}),+ }),+ ...Array.from(turns.values())+ .filter((turn) => turn !== null)+ .map((turn) => JSON.stringify(turn)),+ ];spoolWriteSeq += 1;const tmp = join(dir, `.${name}.jsonl.tmp-${process.pid}-${spoolWriteSeq}`);writeFileSync(tmp, lines.join("\n") + "\n", "utf8");@@ -221,6 +304,19 @@ function renderActiveContext(cwd: string): string | null {}}+/** Each loaded plugin instance has its own short-lived active-context cache. */+function activeContextFor(cwd: string): () => string | null {+ let cache: { value: string | null; at: number } | null = null;+ return () => {+ const now = Date.now();+ const ttl = cache?.value === null ? ACTIVE_CONTEXT_NEGATIVE_TTL_MS : ACTIVE_CONTEXT_TTL_MS;+ if (cache === null || now - cache.at > ttl) {+ cache = { value: renderActiveContext(cwd), at: now };+ }+ return cache.value;+ };+}+/*** How to start the `o2b-hook` shim `bin` (a bare name or a path), or null* when it cannot be found.@@ -264,10 +360,9 @@ function hookCommand(bin: string): {}/**- * Plugin entry point. opencode calls this once at startup with the SDK- * client and project info, and wires the returned hooks.+ * V1 entry point, called through the default export's server() method.*/-export const OpenSecondBrain = async (pluginInput: {+const openSecondBrainV1 = async (pluginInput: {client: unknown;project?: unknown;directory?: string;@@ -278,7 +373,7 @@ export const OpenSecondBrain = async (pluginInput: {// 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;+ const getActiveContext = activeContextFor(injectCwd);async function captureSession(sessionId: string): Promise<void> {const session = client ? asRecord(client["session"]) : null;@@ -308,16 +403,9 @@ export const OpenSecondBrain = async (pluginInput: {"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);+ const context = getActiveContext();+ if (context !== null && Array.isArray(output?.system)) {+ output.system.push(context);}} catch {// Inject is a nicety; the session works without it.@@ -337,3 +425,125 @@ export const OpenSecondBrain = async (pluginInput: {},};};++interface V2Context {+ location: { directory: string };+ session: {+ hook(+ name: "context",+ callback: (event: { system: Array<{ type: "text"; text: string }> }) => void,+ ): Promise<unknown>;+ get(input: { sessionID: string }): Promise<unknown>;+ context(input: { sessionID: string }): Promise<unknown>;+ };+ tool: {+ hook(+ name: "execute.after",+ callback: (event: {+ tool: string;+ status: string;+ result?: { content: unknown[]; [key: string]: unknown };+ }) => void,+ ): Promise<unknown>;+ };+ event: {+ subscribe(input: { signal: AbortSignal }): AsyncIterable<{+ type?: string;+ data?: unknown;+ properties?: unknown;+ location?: { directory?: string };+ }>;+ };+}++/** V2 reads this default definition; V1 calls server() on the same object. */+export default {+ id: "open-second-brain",+ server: openSecondBrainV1,+ async setup(ctx: V2Context) {+ // V1's experimental V2 loader also calls setup(), but without these+ // capabilities; its separate V1 loader still runs server().+ if (+ typeof ctx?.location?.directory !== "string" ||+ typeof ctx.session?.hook !== "function" ||+ typeof ctx.session?.get !== "function" ||+ typeof ctx.session?.context !== "function" ||+ typeof ctx.tool?.hook !== "function" ||+ typeof ctx.event?.subscribe !== "function"+ )+ return;++ const directory = ctx.location.directory;+ const getActiveContext = activeContextFor(directory);++ await ctx.session.hook("context", (event) => {+ try {+ const context = getActiveContext();+ if (context !== null) event.system.push({ type: "text", text: context });+ } catch {+ // Context injection is best-effort.+ }+ });++ await ctx.tool.hook("execute.after", (event) => {+ try {+ if (event.status !== "completed" || !MUTATING_TOOLS.has(event.tool.toLowerCase())) return;+ if (!event.result || !Array.isArray(event.result.content)) return;+ event.result = {+ ...event.result,+ content: [...event.result.content, { type: "text", text: POST_WRITE_NUDGE }],+ };+ } catch {+ // Reminder is best-effort; tool results remain untouched on failure.+ }+ });++ const controller = new AbortController();+ void (async () => {+ let retryDelay = 1_000;+ while (!controller.signal.aborted) {+ try {+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {+ retryDelay = 1_000;+ try {+ if (!event || !V2_CAPTURE_EVENTS.has(event.type ?? "")) continue;+ const sessionID = extractSessionId(event.data ?? event.properties);+ if (sessionID === null) continue;+ // The event stream is server-wide, not scoped to this plugin's location.+ const eventDirectory = event.location?.directory;+ if (eventDirectory && eventDirectory !== directory) continue;+ if (!eventDirectory) {+ const session = asRecord(await ctx.session.get({ sessionID }));+ const location = asRecord(session?.["location"]);+ if (location?.["directory"] !== directory) continue;+ }+ const revertTo =+ event.type === "session.revert.committed"+ ? asRecord(event.data ?? event.properties)?.["to"]+ : undefined;+ if (event.type === "session.revert.committed" && typeof revertTo !== "string")+ continue;+ const messages = messageList(await ctx.session.context({ sessionID }));+ if (messages !== null)+ writeSpool(sessionID, directory, messages, true, revertTo as string | undefined);+ } catch {+ // A failed snapshot must not stop later session captures.+ }+ }+ } catch {+ // Subscriptions are live-only and do not reconnect automatically.+ }+ if (controller.signal.aborted) break;+ console.warn(`Open Second Brain: capture stream ended; retrying in ${retryDelay}ms`);+ try {+ await sleep(retryDelay, undefined, { signal: controller.signal, ref: false });+ } catch {+ break; // Cleanup aborts a pending retry immediately.+ }+ retryDelay = Math.min(retryDelay * 2, 30_000);+ }+ })();++ return () => controller.abort();+ },+};diff --git a/pyproject.toml b/pyproject.tomlindex 0ce15915..92ebf2b1 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "1.74.0"+version = "1.74.1"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/tests/core/install/adapters/opencode.test.ts b/tests/core/install/adapters/opencode.test.tsindex 6540248e..49aa52bb 100644--- a/tests/core/install/adapters/opencode.test.ts+++ b/tests/core/install/adapters/opencode.test.ts@@ -17,6 +17,7 @@ import { join, dirname } from "node:path";import { Writable } from "node:stream";import { opencodeAdapter } from "../../../../src/core/install/adapters/opencode.ts";+import { installedPluginContent } from "../../../../src/core/install/opencode-plugin-asset.ts";import {WINDOWS_LAUNCHER_ENV,buildPayload,@@ -247,7 +248,7 @@ describe("opencode adapter - bundled plugin installation", () => {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");+ expect(content).toContain("export default {");});test("manifest records the plugin file as an owned path", () => {@@ -275,7 +276,7 @@ describe("opencode adapter - bundled plugin installation", () => {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");+ expect(readFileSync(pluginPath(), "utf8")).toBe(installedPluginContent());});test("dry-run apply does not write the plugin file", () => {@@ -297,7 +298,7 @@ describe("opencode adapter - bundled plugin installation", () => {mkdirSync(pluginPath(), { recursive: true });opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());const content = readFileSync(pluginPath(), "utf8");- expect(content).toContain("export const OpenSecondBrain");+ expect(content).toContain("export default {");});test("uninstall removes the plugin file", () => {diff --git a/tests/plugins/opencode-plugin.test.ts b/tests/plugins/opencode-plugin.test.tsindex a47009ed..fa4a7aeb 100644--- a/tests/plugins/opencode-plugin.test.ts+++ b/tests/plugins/opencode-plugin.test.ts@@ -2,8 +2,8 @@* 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+ * exercised directly through V1 server() and V2 setup() with 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.@@ -13,8 +13,9 @@ 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 { setTimeout as sleep } from "node:timers/promises";-import { OpenSecondBrain } from "../../plugins/opencode/open-second-brain.ts";+import OpenSecondBrain from "../../plugins/opencode/open-second-brain.ts";let spoolDir: string;let binDir: string;@@ -122,7 +123,158 @@ const MESSAGES: FakeMessage[] = [];async function makeHooks(client: unknown) {- return await OpenSecondBrain(pluginInput(client) as never);+ return await OpenSecondBrain.server(pluginInput(client) as never);+}++interface V2ToolEvent {+ tool: string;+ status: string;+ result?: { content: unknown[]; [key: string]: unknown };+}++async function makeV2Plugin(+ messages: unknown[] | ((call: number) => unknown[]),+ events: Array<{+ type: string;+ data?: unknown;+ properties?: unknown;+ location?: { directory: string };+ }> = [],+ sessionDirectories: Record<string, string> = {},+ disconnectedStreams: Array<"error" | "end"> = [],+) {+ let contextHook: ((event: { system: Array<{ type: "text"; text: string }> }) => void) | undefined;+ let toolHook: ((event: V2ToolEvent) => void) | undefined;+ let signal: AbortSignal | undefined;+ let drained!: () => void;+ const processed = new Promise<void>((resolve) => {+ drained = resolve;+ });+ const contextCalls: string[] = [];+ const subscriptions: number[] = [];+ const ctx = {+ location: { directory: "/work/dir" },+ session: {+ async hook(_name: string, callback: typeof contextHook) {+ contextHook = callback;+ },+ async get({ sessionID }: { sessionID: string }) {+ return { location: { directory: sessionDirectories[sessionID] ?? "/work/dir" } };+ },+ async context({ sessionID }: { sessionID: string }) {+ contextCalls.push(sessionID);+ return typeof messages === "function" ? messages(contextCalls.length - 1) : messages;+ },+ },+ tool: {+ async hook(_name: string, callback: typeof toolHook) {+ toolHook = callback;+ },+ },+ event: {+ async *subscribe(input: { signal: AbortSignal }) {+ signal = input.signal;+ subscriptions.push(Date.now());+ const disconnected = disconnectedStreams.shift();+ if (disconnected === "error") throw new Error("Event stream disconnected");+ if (disconnected === "end") return;+ for (const event of events) yield event;+ drained();+ await new Promise<void>((resolve) => {+ if (input.signal.aborted) resolve();+ else input.signal.addEventListener("abort", () => resolve(), { once: true });+ });+ },+ },+ };+ const cleanup = await OpenSecondBrain.setup(ctx as never);+ if (!cleanup) throw new Error("V2 setup did not register its event subscription");+ const timeout = new AbortController();+ try {+ await Promise.race([+ processed,+ sleep(3_500, undefined, { signal: timeout.signal }).then(() => {+ throw new Error("V2 capture did not resume after stream disconnect");+ }),+ ]);+ } catch (error) {+ cleanup();+ throw error;+ } finally {+ timeout.abort();+ }+ return {+ contextHook: contextHook!,+ toolHook: toolHook!,+ contextCalls,+ subscriptions,+ signal: signal!,+ cleanup,+ };+}++test("exports V1 server and V2 setup on one default definition", () => {+ expect(OpenSecondBrain.id).toBe("open-second-brain");+ expect(typeof OpenSecondBrain.server).toBe("function");+ expect(typeof OpenSecondBrain.setup).toBe("function");+});++test("V1's experimental V2 loader can omit the released V2 capabilities", async () => {+ const v1Context = {+ options: {},+ agent: {},+ aisdk: {},+ catalog: {},+ command: {},+ integration: {},+ plugin: {},+ reference: {},+ skill: {},+ };+ expect(await OpenSecondBrain.setup(v1Context as never)).toBeUndefined();+});++for (const missing of [+ "location.directory",+ "session.hook",+ "session.get",+ "session.context",+ "tool.hook",+ "event.subscribe",+]) {+ test(`V2 setup registers nothing without ${missing}`, async () => {+ const registered: string[] = [];+ const context = {+ location: { directory: "/work/dir" },+ session: {+ async hook() {+ registered.push("context");+ },+ async get() {+ return { location: { directory: "/work/dir" } };+ },+ async context() {+ return [];+ },+ },+ tool: {+ async hook() {+ registered.push("tool");+ },+ },+ event: {+ async *subscribe() {+ registered.push("event");+ yield { type: "irrelevant" };+ },+ },+ };+ const [domain, member] = missing.split(".");+ delete (context as unknown as Record<string, Record<string, unknown>>)[domain!]![member!];++ expect(await OpenSecondBrain.setup(context as never)).toBeUndefined();+ expect(registered).toEqual([]);+ });}describe("opencode plugin - session capture spool", () => {@@ -216,12 +368,12 @@ describe("opencode plugin - spool location without the override", () => {const PLUGIN = join(import.meta.dir, "..", "..", "plugins", "opencode", "open-second-brain.ts");const DRIVER = `-import { OpenSecondBrain } from ${JSON.stringify(PLUGIN)};+import OpenSecondBrain from ${JSON.stringify(PLUGIN)};const client = { session: { async messages() { return { data: [{ info: { id: "m1", role: "user", time: { created: 1765900000000 } },parts: [{ type: "text", text: "hi" }] },] }; } } };-const hooks = await OpenSecondBrain({ client, project: { id: "p" }, directory: "/w", worktree: "/w" });+const hooks = await OpenSecondBrain.server({ client, project: { id: "p" }, directory: "/w", worktree: "/w" });await hooks.event({ event: { type: "session.idle", properties: { sessionID: "sess-loc" } } });`;@@ -371,3 +523,358 @@ describe("opencode plugin - post-write reminder", () => {expect(output.output).toEqual({ structured: true });});});++describe("opencode plugin - V2", () => {+ for (const executionType of [+ "session.execution.succeeded",+ "session.execution.failed",+ "session.execution.interrupted",+ ]) {+ test(`opencode 2.0.24 turn-end event ${executionType} writes a spool snapshot`, async () => {+ const plugin = await makeV2Plugin(+ [+ {+ id: "msg-exec",+ type: "user",+ time: { created: 1765900000000 },+ text: "captured on execution end",+ },+ ],+ [+ {+ type: executionType,+ data: { sessionID: "sess-execution" },+ location: { directory: "/work/dir" },+ },+ ],+ );+ try {+ const turns = readFileSync(join(spoolDir, "sess-execution.jsonl"), "utf8")+ .trim()+ .split("\n")+ .slice(1)+ .map((line) => JSON.parse(line));+ expect(turns.map((turn) => turn.turnId)).toEqual(["msg-exec"]);+ } finally {+ plugin.cleanup();+ }+ });+ }++ test("a revert with an uncaptured boundary rebuilds from current context", async () => {+ const plugin = await makeV2Plugin(+ (call) => [+ {+ id: call === 0 ? "msg-old" : "msg-current",+ type: "user",+ time: { created: 1765900000000 },+ text: call === 0 ? "old" : "current",+ },+ ],+ [+ {+ type: "session.idle",+ data: { sessionID: "sess-missed-boundary" },+ location: { directory: "/work/dir" },+ },+ {+ type: "session.revert.committed",+ data: { sessionID: "sess-missed-boundary", to: "msg-uncaptured" },+ location: { directory: "/work/dir" },+ },+ ],+ );+ try {+ const turns = readFileSync(join(spoolDir, "sess-missed-boundary.jsonl"), "utf8")+ .trim()+ .split("\n")+ .slice(1)+ .map((line) => JSON.parse(line));+ expect(turns.map((turn) => turn.turnId)).toEqual(["msg-current"]);+ } finally {+ plugin.cleanup();+ }+ });++ for (const boundaryType of ["user", "compaction"]) {+ test(`a committed revert removes the ${boundaryType} boundary and following turns`, async () => {+ const before = {+ id: "msg-retained",+ type: "user",+ time: { created: 1765900000000 },+ text: "keep",+ };+ const boundary = {+ id: "msg-boundary",+ type: boundaryType,+ time: { created: 1765900060000 },+ ...(boundaryType === "user" ? { text: "undo this" } : {}),+ };+ const removed = {+ id: "msg-removed",+ type: "user",+ time: { created: 1765900120000 },+ text: "removed suffix",+ };+ const after = {+ id: "msg-new",+ type: "user",+ time: { created: 1765900180000 },+ text: "new branch",+ };+ const plugin = await makeV2Plugin(+ (call) => (call === 0 ? [before, boundary, removed] : call === 1 ? [removed] : [after]),+ [+ {+ type: "session.compaction.started",+ data: { sessionID: "sess-revert" },+ location: { directory: "/work/dir" },+ },+ {+ type: "session.compaction.ended",+ data: { sessionID: "sess-revert" },+ location: { directory: "/work/dir" },+ },+ {+ type: "session.revert.committed",+ data: { sessionID: "sess-revert", to: "msg-boundary" },+ location: { directory: "/work/dir" },+ },+ {+ type: "session.idle",+ data: { sessionID: "sess-revert" },+ location: { directory: "/work/dir" },+ },+ ],+ );+ try {+ const turns = readFileSync(join(spoolDir, "sess-revert.jsonl"), "utf8")+ .trim()+ .split("\n")+ .slice(1)+ .map((line) => JSON.parse(line));+ expect(turns.map((turn) => turn.turnId)).toEqual(["msg-retained", "msg-new"]);+ expect(turns.map((turn) => turn.text)).toEqual(["keep", "new branch"]);+ } finally {+ plugin.cleanup();+ }+ });+ }++ for (const disconnect of ["error", "end"] as const) {+ test(`capture resumes after a stream ${disconnect}`, async () => {+ const plugin = await makeV2Plugin(+ [+ {+ id: "msg-recovered",+ type: "user",+ time: { created: 1765900000000 },+ text: "after reconnect",+ },+ ],+ [+ {+ type: "session.idle",+ data: { sessionID: "sess-recovered" },+ location: { directory: "/work/dir" },+ },+ ],+ {},+ [disconnect],+ );+ try {+ const lines = readFileSync(join(spoolDir, "sess-recovered.jsonl"), "utf8")+ .trim()+ .split("\n");+ expect(JSON.parse(lines[1]!)).toMatchObject({+ turnId: "msg-recovered",+ text: "after reconnect",+ });+ expect(plugin.subscriptions).toHaveLength(2);+ expect(plugin.subscriptions[1]! - plugin.subscriptions[0]!).toBeGreaterThanOrEqual(900);+ } finally {+ plugin.cleanup();+ }+ await sleep(1_100);+ expect(plugin.subscriptions).toHaveLength(2);+ });+ }++ test("cleanup during retry prevents another event subscription", async () => {+ let attempts = 0;+ let disconnected!: () => void;+ const ended = new Promise<void>((resolve) => {+ disconnected = resolve;+ });+ const ctx = {+ location: { directory: "/work/dir" },+ session: {+ async hook() {},+ async get() {+ return {};+ },+ async context() {+ return [];+ },+ },+ tool: { async hook() {} },+ event: {+ async *subscribe() {+ attempts++;+ yield { type: "server.connected" };+ disconnected();+ throw new Error("Disconnected");+ },+ },+ };+ const cleanup = await OpenSecondBrain.setup(ctx as never);+ if (!cleanup) throw new Error("V2 capture did not start");+ try {+ await ended;+ await sleep(10);+ cleanup();+ await sleep(1_100);+ expect(attempts).toBe(1);+ } finally {+ cleanup();+ }+ });++ test("captures V2 session messages with text and tool calls, then stops on cleanup", async () => {+ const messages = [+ { id: "msg-user", type: "user", time: { created: 1765900000000 }, text: "fix this" },+ {+ id: "msg-assistant",+ type: "assistant",+ time: { created: 1765900060000 },+ content: [+ { type: "text", text: "done" },+ {+ type: "tool",+ id: "call-8",+ name: "patch",+ state: { status: "completed", input: { path: "/a.ts" } },+ },+ ],+ },+ { id: "msg-idle", type: "idle", time: { created: 1765900080000 } },+ ];+ const plugin = await makeV2Plugin(+ messages,+ [+ { type: "file.edited", data: { sessionID: "sess-v2" } },+ { type: "session.idle", data: { sessionID: "sess-other" } },+ {+ type: "session.idle",+ data: { sessionID: "sess-v2" },+ location: { directory: "/work/dir" },+ },+ ],+ { "sess-other": "/other/project" },+ );+ expect(plugin.contextCalls).toEqual(["sess-v2"]);+ expect(existsSync(join(spoolDir, "sess-other.jsonl"))).toBe(false);+ const lines = readFileSync(join(spoolDir, "sess-v2.jsonl"), "utf8").trim().split("\n");+ expect(JSON.parse(lines[0]!)).toMatchObject({ type: "session_meta", directory: "/work/dir" });+ expect(lines.slice(1).map((line) => JSON.parse(line))).toEqual([+ {+ type: "turn",+ turnId: "msg-user",+ timestamp: new Date(1765900000000).toISOString(),+ role: "user",+ text: "fix this",+ },+ {+ type: "turn",+ turnId: "msg-assistant",+ timestamp: new Date(1765900060000).toISOString(),+ role: "assistant",+ text: "done",+ toolCalls: [{ name: "patch", id: "call-8", input: { path: "/a.ts" } }],+ },+ ]);+ plugin.cleanup();+ expect(plugin.signal.aborted).toBe(true);+ });++ test("keeps pre-compaction turns when V2 context only returns recent messages", async () => {+ const before = [+ { id: "msg_before", type: "user", time: { created: 1765900000000 }, text: "before" },+ ];+ const after = [+ {+ id: "msg_after",+ type: "assistant",+ time: { created: 1765900060000 },+ content: [{ type: "text", text: "after" }],+ },+ ];+ const plugin = await makeV2Plugin(+ (call) => (call === 0 ? before : after),+ [+ {+ type: "session.compaction.started",+ data: { sessionID: "sess-compact" },+ location: { directory: "/work/dir" },+ },+ {+ type: "session.compaction.ended",+ data: { sessionID: "sess-compact" },+ location: { directory: "/work/dir" },+ },+ {+ type: "session.idle",+ data: { sessionID: "sess-compact" },+ location: { directory: "/work/dir" },+ },+ ],+ );+ const lines = readFileSync(join(spoolDir, "sess-compact.jsonl"), "utf8").trim().split("\n");+ expect(lines.slice(1).map((line) => JSON.parse(line))).toEqual([+ {+ type: "turn",+ turnId: "msg_before",+ timestamp: new Date(1765900000000).toISOString(),+ role: "user",+ text: "before",+ },+ {+ type: "turn",+ turnId: "msg_after",+ timestamp: new Date(1765900060000).toISOString(),+ role: "assistant",+ text: "after",+ },+ ]);+ plugin.cleanup();+ });++ test("injects context and appends a text part after successful write tools", async () => {+ process.env["OSB_HOOK_BIN"] = stubHookBin("ACTIVE PREFS BLOCK");+ const plugin = await makeV2Plugin([]);+ const request = { system: [{ type: "text" as const, text: "base" }] };+ plugin.contextHook(request);+ expect(request.system).toEqual([+ { type: "text", text: "base" },+ { type: "text", text: "ACTIVE PREFS BLOCK" },+ ]);+ const result: V2ToolEvent = {+ tool: "patch",+ status: "completed",+ result: { content: [{ type: "text", text: "wrote /a.ts" }] },+ };+ plugin.toolHook(result);+ expect(result.result?.content).toEqual([+ { type: "text", text: "wrote /a.ts" },+ { type: "text", text: expect.stringContaining("Open Second Brain: artifact written.") },+ ]);+ const unchanged: V2ToolEvent = {+ tool: "read",+ status: "completed",+ result: { content: [{ type: "text", text: "file contents" }] },+ };+ plugin.toolHook(unchanged);+ expect(unchanged.result?.content).toEqual([{ type: "text", text: "file contents" }]);+ plugin.cleanup();+ });+});diff --git a/uv.lock b/uv.lockindex a0a02f99..0358a18b 100644--- a/uv.lock+++ b/uv.lock@@ -4,5 +4,5 @@ requires-python = ">=3.11"[[package]]name = "open-second-brain"-version = "1.74.0"+version = "1.74.1"source = { editable = "." }