Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

fix(cli): emit OpenCode plugin hooks for the V2 setup context

HazielMagallanes98a66b73566c
diff --git a/src/cli/client_adapter.c b/src/cli/client_adapter.c
index cfd2719c7..60cb0cd3d 100644
--- a/src/cli/client_adapter.c
+++ b/src/cli/client_adapter.c
@@ -427,9 +427,15 @@ char *cbm_client_adapter_opencode(const char *binary_path) {
sb_append(&sb, "// OpenCode already reaches every tool over MCP; this module adds the\n"
"// context surfaces other clients get through hook configuration: graph\n"
"// lookup after grep/glob, index-coverage notes after read, session-start\n"
- "// tier routing (carried on the first tool result of each session, since\n"
- "// OpenCode documents no context-output lifecycle hook), and reinjection\n"
- "// after compaction via the documented experimental surface.\n");
+ "// tier routing (carried on the first tool result of each session), and\n"
+ "// reinjection after compaction through the session context channel.\n"
+ "//\n"
+ "// Two runtimes load this module:\n"
+ "// - OpenCode 1.18.x dispatches the hooks returned by server(ctx).\n"
+ "// - OpenCode 2 ignores server and calls setup(ctx), which registers the\n"
+ "// same behaviour on the context's tool and session hook domains. Each\n"
+ "// registration fails open, and the matching server() hook yields once\n"
+ "// its domain has registered.\n");
sb_append(&sb, "import { spawn } from 'node:child_process';\n\n");
sb_append(&sb, "const BIN = '");
sb_append(&sb, bin);
@@ -481,64 +487,193 @@ char *cbm_client_adapter_opencode(const char *binary_path) {
" });\n"
"}\n\n");
+ /* OpenCode 2 tool results are structured (Tool.Result: content is the
+ * string/parts surface the model reads, output is the tool's schema-typed
+ * value). Append to content first, then a string output; if neither text
+ * surface exists, leave the result untouched so the tool's own output is
+ * never hidden. The caller assigns the returned result onto event.result. */
+ sb_append(&sb,
+ "function appendResult(result, extra) {\n"
+ " if (!result || typeof result !== 'object') return result;\n"
+ " if (typeof result.content === 'string') {\n"
+ " return { ...result, content: result.content + '\\n' + extra };\n"
+ " }\n"
+ " if (Array.isArray(result.content)) {\n"
+ " const content = result.content.slice();\n"
+ " for (let i = content.length - 1; i >= 0; i--) {\n"
+ " if (content[i] && content[i].type === 'text') {\n"
+ " content[i] = { ...content[i], text: content[i].text + '\\n' + extra };\n"
+ " return { ...result, content };\n"
+ " }\n"
+ " }\n"
+ " content.push({ type: 'text', text: extra });\n"
+ " return { ...result, content };\n"
+ " }\n"
+ " if (typeof result.output === 'string') {\n"
+ " return { ...result, output: result.output + '\\n' + extra };\n"
+ " }\n"
+ " return result;\n"
+ "}\n\n");
+
+ /* Per-domain registration flags: a host that dispatches both server() and
+ * setup() with domains must not append the note twice. The server() hook
+ * for a domain yields once setup() registered that same domain. */
+ sb_append(&sb, "let toolHooksRegistered = false;\n"
+ "let sessionHooksRegistered = false;\n\n");
+
sb_append(
- &sb, "export default {\n"
- " id: 'codebase-memory-augment',\n"
- " // V2 config loader: requires id + setup|effect; no tool domain yet\n"
- " // at this point, so there is nothing to register here.\n"
- " setup() {},\n"
- " // Server runtime: reads default.server and dispatches the hooks it returns.\n"
- " server: async (ctx) => {\n"
- " const dir = ctx?.directory;\n"
- " const seen = new Set();\n"
- " const lifecycle = () =>\n"
- " augment({ hook_event_name: 'SessionStart', cwd: dir });\n"
- " return {\n"
- " 'tool.execute.after': async (input, output) => {\n"
- " if (typeof output?.output !== 'string') return;\n"
- " const pieces = [];\n"
- " const sid = input?.sessionID;\n"
- " if (typeof sid === 'string' && !seen.has(sid)) {\n"
- " seen.add(sid);\n"
- " pieces.push(await lifecycle());\n"
- " }\n"
- " const args = input?.args ?? {};\n"
- " const search =\n"
- " input?.tool === 'grep' ? 'Grep' : input?.tool === 'glob' ? 'Glob' : null;\n"
- " if (search) {\n"
- " pieces.push(await augment({\n"
- " hook_event_name: 'PreToolUse',\n"
- " tool_name: search,\n"
- " tool_input: args,\n"
- " cwd: dir,\n"
- " }));\n"
- " } else if (input?.tool === 'read') {\n"
- " const filePath = args.filePath ?? args.file_path ?? args.path;\n"
- " if (typeof filePath === 'string' && filePath) {\n"
- " pieces.push(await augment({\n"
- " hook_event_name: 'PostToolUse',\n"
- " tool_name: 'Read',\n"
- " tool_input: { file_path: filePath },\n"
- " cwd: dir,\n"
- " }));\n"
- " }\n"
- " }\n"
- " const extra = pieces.filter(Boolean).join('\\n');\n"
- " if (extra) {\n"
- " output.output += '\\n' + extra;\n"
- " }\n"
- " },\n"
- " // Documented (experimental) compaction surface: output.context is the\n"
- " // mutable array of context strings for the rebuilt session.\n"
- " 'experimental.session.compacting': async (_input, output) => {\n"
- " const note = await lifecycle();\n"
- " if (note && Array.isArray(output?.context)) {\n"
- " output.context.push(note);\n"
- " }\n"
- " },\n"
- " };\n"
- " },\n"
- "};\n");
+ &sb,
+ "export default {\n"
+ " id: 'codebase-memory-augment',\n"
+ " // OpenCode 1.18.x server runtime: reads default.server and dispatches\n"
+ " // the hooks it returns.\n"
+ " server: async (ctx) => {\n"
+ " const dir = ctx?.directory;\n"
+ " const seen = new Set();\n"
+ " const lifecycle = () =>\n"
+ " augment({ hook_event_name: 'SessionStart', cwd: dir });\n"
+ " return {\n"
+ " 'tool.execute.after': async (input, output) => {\n"
+ " if (toolHooksRegistered) return;\n"
+ " if (typeof output?.output !== 'string') return;\n"
+ " const pieces = [];\n"
+ " const sid = input?.sessionID;\n"
+ " if (typeof sid === 'string' && !seen.has(sid)) {\n"
+ " seen.add(sid);\n"
+ " pieces.push(await lifecycle());\n"
+ " }\n"
+ " const args = input?.args ?? {};\n"
+ " const search =\n"
+ " input?.tool === 'grep' ? 'Grep' : input?.tool === 'glob' ? 'Glob' : null;\n"
+ " if (search) {\n"
+ " pieces.push(await augment({\n"
+ " hook_event_name: 'PreToolUse',\n"
+ " tool_name: search,\n"
+ " tool_input: args,\n"
+ " cwd: dir,\n"
+ " }));\n"
+ " } else if (input?.tool === 'read') {\n"
+ " const filePath = args.filePath ?? args.file_path ?? args.path;\n"
+ " if (typeof filePath === 'string' && filePath) {\n"
+ " pieces.push(await augment({\n"
+ " hook_event_name: 'PostToolUse',\n"
+ " tool_name: 'Read',\n"
+ " tool_input: { file_path: filePath },\n"
+ " cwd: dir,\n"
+ " }));\n"
+ " }\n"
+ " }\n"
+ " const extra = pieces.filter(Boolean).join('\\n');\n"
+ " if (extra) {\n"
+ " output.output += '\\n' + extra;\n"
+ " }\n"
+ " },\n"
+ " // Documented (experimental) compaction surface: output.context is the\n"
+ " // mutable array of context strings for the rebuilt session.\n"
+ " 'experimental.session.compacting': async (_input, output) => {\n"
+ " if (sessionHooksRegistered) return;\n"
+ " const note = await lifecycle();\n"
+ " if (note && Array.isArray(output?.context)) {\n"
+ " output.context.push(note);\n"
+ " }\n"
+ " },\n"
+ " };\n"
+ " },\n"
+ " // OpenCode 2 runtime: default.server is ignored and setup(ctx) registers\n"
+ " // the hooks on the context domains. Each registration fails open, so one\n"
+ " // missing domain cannot break the host or the other domain.\n"
+ " async setup(ctx) {\n"
+ " const seen = new Set();\n"
+ " const dirs = new Map();\n"
+ " const dirFor = async (sessionID) => {\n"
+ " if (typeof sessionID !== 'string' || sessionID === '') return undefined;\n"
+ " if (dirs.has(sessionID)) return dirs.get(sessionID);\n"
+ " try {\n"
+ " const session = await ctx.session.get({ sessionID });\n"
+ " const dir = session?.location?.directory;\n"
+ " if (typeof dir === 'string' && dir !== '') {\n"
+ " dirs.set(sessionID, dir);\n"
+ " return dir;\n"
+ " }\n"
+ " } catch {}\n"
+ " return undefined;\n"
+ " };\n"
+ " const lifecycle = (dir) =>\n"
+ " augment({ hook_event_name: 'SessionStart', cwd: dir });\n"
+ " if (ctx?.tool?.hook) {\n"
+ " try {\n"
+ " await ctx.tool.hook('execute.after', async (event) => {\n"
+ " if (event?.status !== 'completed') return;\n"
+ " const dir = await dirFor(event?.sessionID);\n"
+ " if (!dir) return;\n"
+ " const pieces = [];\n"
+ " if (typeof event?.sessionID === 'string' && !seen.has(event.sessionID)) {\n"
+ " seen.add(event.sessionID);\n"
+ " pieces.push(await lifecycle(dir));\n"
+ " }\n"
+ " const args = event?.input ?? {};\n"
+ " const search =\n"
+ " event?.tool === 'grep' ? 'Grep' : event?.tool === 'glob' ? 'Glob' : null;\n"
+ " if (search) {\n"
+ " pieces.push(await augment({\n"
+ " hook_event_name: 'PreToolUse',\n"
+ " tool_name: search,\n"
+ " tool_input: args,\n"
+ " cwd: dir,\n"
+ " }));\n"
+ " } else if (event?.tool === 'read') {\n"
+ " const filePath = args.filePath ?? args.file_path ?? args.path;\n"
+ " if (typeof filePath === 'string' && filePath) {\n"
+ " pieces.push(await augment({\n"
+ " hook_event_name: 'PostToolUse',\n"
+ " tool_name: 'Read',\n"
+ " tool_input: { file_path: filePath },\n"
+ " cwd: dir,\n"
+ " }));\n"
+ " }\n"
+ " }\n"
+ " const extra = pieces.filter(Boolean).join('\\n');\n"
+ " if (extra) {\n"
+ " event.result = appendResult(event.result, extra);\n"
+ " }\n"
+ " });\n"
+ " toolHooksRegistered = true;\n"
+ " } catch {\n"
+ " // Fail open: the server() tool hook stays active.\n"
+ " }\n"
+ " }\n"
+ " // OpenCode 2 compaction: persist the note as a keyed session\n"
+ " // instruction (a <context> entry) instead of editing the system\n"
+ " // prompt; entries survive compaction. Hosts without the channel\n"
+ " // skip reinjection rather than failing the plugin.\n"
+ " if (ctx?.session?.hook) {\n"
+ " try {\n"
+ " await ctx.session.hook('compaction', async (event) => {\n"
+ " const sessionID = event?.sessionID;\n"
+ " if (typeof sessionID !== 'string' || sessionID === '') return;\n"
+ " const entry = ctx?.session?.instructions?.entry;\n"
+ " if (typeof entry?.put !== 'function') return;\n"
+ " const dir = await dirFor(sessionID);\n"
+ " if (!dir) return;\n"
+ " const note = await lifecycle(dir);\n"
+ " if (!note) return;\n"
+ " try {\n"
+ " await entry.put({\n"
+ " sessionID,\n"
+ " key: 'codebase-memory-session-note',\n"
+ " value: note,\n"
+ " });\n"
+ " } catch {\n"
+ " // Fail open: reinjection is best-effort.\n"
+ " }\n"
+ " });\n"
+ " sessionHooksRegistered = true;\n"
+ " } catch {\n"
+ " // Fail open: the server() compaction hook stays active.\n"
+ " }\n"
+ " }\n"
+ " },\n"
+ "};\n");
if (sb.failed) {
free(sb.buf);
diff --git a/src/cli/client_adapter.h b/src/cli/client_adapter.h
index c1bfb652e..bbe197d89 100644
--- a/src/cli/client_adapter.h
+++ b/src/cli/client_adapter.h
@@ -48,11 +48,17 @@ char *cbm_client_adapter_pi(const char *binary_path);
* other clients get through their own native hook configuration. OpenCode has
* no such configuration; a plugin module is its only extension point.
*
- * NOTE for maintainers: this hooks `tool.execute.after`, whose ability to
- * modify a tool's output is NOT part of OpenCode's documented plugin contract
- * (only `tool.execute.before`'s argument mutation is). If OpenCode changes it,
- * augmentation stops silently — no error, no signal. That risk is accepted
- * deliberately and recorded here so it is not rediscovered as a mystery.
+ * NOTE for maintainers: the module serves two loader generations from one
+ * default export. OpenCode 1.18.x dispatches the hooks returned by
+ * `server(ctx)`; its `tool.execute.after` ability to modify a tool's output is
+ * NOT part of the documented plugin contract (only `tool.execute.before`'s
+ * argument mutation is), so if that runtime changes, augmentation stops
+ * silently — no error, no signal. That risk is accepted deliberately for the
+ * server() path and recorded here so it is not rediscovered as a mystery.
+ * OpenCode 2 ignores `server` and calls `setup(ctx)`, which registers
+ * `execute.after` and `compaction` on the context domains. Each registration
+ * fails open, and the post-compaction note is stored as a keyed session
+ * instruction (`<context>` entry) instead of the system prompt.
*
* Returns NULL on allocation failure or when binary_path is NULL/empty. */
char *cbm_client_adapter_opencode(const char *binary_path);
diff --git a/tests/test_agent_clients.c b/tests/test_agent_clients.c
index 0d57723a0..a3afe1494 100644
--- a/tests/test_agent_clients.c
+++ b/tests/test_agent_clients.c
@@ -1342,18 +1342,59 @@ TEST(client_adapter_opencode_covers_lifecycle_read_and_compaction) {
PASS();
}
-/* #2077: OpenCode's V2 loader only reads the default export and needs an
- * id plus a setup()/effect() function; the old named export had neither. */
+/* #2077/#2089/#2204: the two OpenCode runtimes read different entries of the
+ * default export. 1.18.x dispatches the hooks returned by `server(ctx)`; 2.x
+ * ignores `server` and calls `setup(ctx)`, whose context provides the tool and
+ * session hook domains. Registrations fail open per domain, so the matching
+ * server() hook yields once its domain is registered. The post-compaction note
+ * goes through a keyed session instruction (a <context> entry that survives
+ * compaction), never the system prompt. */
TEST(client_adapter_opencode_exports_the_v2_default_definition_issue2077) {
char *js = cbm_client_adapter_opencode("/usr/local/bin/codebase-memory-mcp");
ASSERT_NOT_NULL(js);
ASSERT_NOT_NULL(strstr(js, "export default {"));
ASSERT_NOT_NULL(strstr(js, "id: 'codebase-memory-augment'"));
- /* Hooks live under server(), which the server runtime reads; setup()
- * stays empty since the V2 config loader has no tool domain yet. */
- ASSERT_NOT_NULL(strstr(js, "setup() {}"));
+ /* OpenCode 1.18.x server runtime. */
ASSERT_NOT_NULL(strstr(js, "server: async (ctx) => {"));
- ASSERT_NULL(strstr(js, "async setup(ctx) {"));
+ /* OpenCode 2 registers through the setup context; the domains exist on
+ * 2.x, so setup is no longer the empty placeholder #2089 pinned. */
+ ASSERT_NOT_NULL(strstr(js, "async setup(ctx) {"));
+ ASSERT_NOT_NULL(strstr(js, "ctx.tool.hook('execute.after'"));
+ ASSERT_NOT_NULL(strstr(js, "ctx.session.hook('compaction'"));
+ ASSERT_NULL(strstr(js, "ctx.session.hook('context'"));
+ /* content is the surface the model reads; prefer it over output, and never
+ * synthesize content that would hide the tool's own result. */
+ const char *content_first = strstr(js, "if (typeof result.content === 'string') {");
+ const char *output_fallback = strstr(js, "if (typeof result.output === 'string') {");
+ ASSERT_NOT_NULL(content_first);
+ ASSERT_NOT_NULL(output_fallback);
+ ASSERT_TRUE(content_first < output_fallback);
+ ASSERT_NULL(strstr(js, "if (result.content === undefined)"));
+ /* Compaction uses the durable session context channel, not the system
+ * prompt; older hosts without it skip reinjection. */
+ ASSERT_NOT_NULL(strstr(js, "event?.sessionID"));
+ ASSERT_NOT_NULL(strstr(js, "ctx?.session?.instructions?.entry"));
+ /* The plugin instance's location is not the session's location in a
+ * multi-project server: resolve each session's directory. */
+ ASSERT_NOT_NULL(strstr(js, "const dir = await dirFor("));
+ ASSERT_NOT_NULL(strstr(js, "ctx.session.get({ sessionID })"));
+ ASSERT_NOT_NULL(strstr(js, "dirs.has(sessionID)"));
+ ASSERT_NOT_NULL(strstr(js, "if (!dir) return;"));
+ /* No fallback to the plugin instance's location: that is not the session's
+ * location in a multi-project server. */
+ ASSERT_NULL(strstr(js, "ctx?.location?.directory"));
+ ASSERT_NOT_NULL(strstr(js, "key: 'codebase-memory-session-note'"));
+ ASSERT_NULL(strstr(js, "event.system.push"));
+ ASSERT_NULL(strstr(js, "pendingReinject"));
+ /* Registrations fail open per domain; the server() hooks yield per domain. */
+ ASSERT_NOT_NULL(strstr(js, "toolHooksRegistered = true;"));
+ ASSERT_NOT_NULL(strstr(js, "sessionHooksRegistered = true;"));
+ ASSERT_NOT_NULL(strstr(js, "if (toolHooksRegistered) return;"));
+ ASSERT_NOT_NULL(strstr(js, "if (sessionHooksRegistered) return;"));
+ ASSERT_NOT_NULL(strstr(js, "catch {"));
+ ASSERT_NOT_NULL(strstr(js, "event.result = appendResult(event.result, extra);"));
+ /* The empty setup placeholder and the old named export must both be gone. */
+ ASSERT_NULL(strstr(js, "setup() {}"));
ASSERT_NULL(strstr(js, "export const CodebaseMemory"));
free(js);
PASS();