From d6c4514de2dcbbcb62133a314c2602ecaa709a21 Mon Sep 17 00:00:00 2001 From: lukemaj Date: Wed, 18 Nov 2026 11:41:11 +0100 Subject: [PATCH] feat: OpenCode plugin supports the OpenCode 2.x plugin API (#271) OpenCode 2.x loads only a default object with `id` and `setup`, so the 1.x-shaped plugin was skipped and sessions ran without Project Direction or the Elon gate. The default export is now `{id, server, setup}`: 1.x calls `server` with the existing hooks; 2.x calls `setup`, which appends the loader context through `session.hook("context")` and runs the Elon gate from `tool.hook("execute.before")`. `setup` does nothing in the reduced context 1.x also passes it. Co-Authored-By: Claude Opus 5.5 --- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .grok-plugin/plugin.json | 2 +- .muse-plugin/plugin.json | 2 +- CHANGELOG.md | 6 + README.md | 6 +- VERSION | 2 +- docs/opencode.md | 28 ++++- opencode/agentsmd-project-direction.js | 90 ++++++++++++--- tests/test_elon_gate.py | 75 ++++++------ tests/test_opencode_plugin.py | 153 ++++++++++++++++++------- tools/versionctl/pyproject.toml | 2 +- 12 files changed, 264 insertions(+), 106 deletions(-) diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 23730b3..1d71d0d 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agentsmd", - "version": "17.4.9", + "version": "17.5.0", "description": "Portable agent rules, Project Direction, Delivery System profiles, owned workflow Skills, and deterministic version control.", "author": { "name": "lukaszmaj" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 0e691f2..99f3ba1 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agentsmd", - "version": "17.4.9", + "version": "17.5.0", "description": "Portable agent rules, Project Direction, Delivery System profiles, owned workflow Skills, and deterministic version control.", "author": { "name": "lukaszmaj", diff --git a/.grok-plugin/plugin.json b/.grok-plugin/plugin.json index e30cef7..97b5e6a 100644 --- a/.grok-plugin/plugin.json +++ b/.grok-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agentsmd", - "version": "17.4.9", + "version": "17.5.0", "description": "Portable agent rules, Project Direction, Delivery System profiles, owned workflow Skills, and deterministic version control.", "author": { "name": "lukaszmaj" diff --git a/.muse-plugin/plugin.json b/.muse-plugin/plugin.json index 59c8ce3..2e721ab 100644 --- a/.muse-plugin/plugin.json +++ b/.muse-plugin/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "name": "agentsmd", "displayName": "AgentsMD", - "version": "17.4.9", + "version": "17.5.0", "description": "Portable agent rules, Project Direction, Delivery System profiles, owned workflow Skills, and deterministic version control.", "compat": { "source": "native", diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bf6691..b851efd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,12 @@ All completed repository versions are recorded here. Release entries follow SemVer and identify one user-consumable repository state. +## [17.5.0] - 2026-11-18 + +### Added + +- OpenCode plugin supports the OpenCode 2.x plugin API and keeps 1.x working (#271) + ## [17.4.9] - 2026-11-15 ### Changed diff --git a/README.md b/README.md index 1a8f770..5ade49a 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ Do not link the Skills into `~/.agents/skills` or `~/.claude/skills`; Codex and Grok Build scan those directories too, so a harness that already has the plugin would list every Skill twice as a duplicate. The second command links the AgentsMD OpenCode plugin into the same directory's `plugins` folder. The plugin -targets OpenCode **1.18.32**. [OpenCode details](docs/opencode.md) covers its +works on OpenCode **1.18.32**, **1.19.6** and **2.3.2**. [OpenCode details](docs/opencode.md) covers its status, update and uninstall commands. **Muse Code 1.4.9:** @@ -276,7 +276,7 @@ healthy and carries your private preferences. | Codex | `SessionStart`, `UserPromptSubmit`, `SubagentStart` | The loader emits nothing on `PreToolUse`; it runs only the Elon gate | Plugin hook (`hooks/hooks.json`) | Explicit reading after a subagent's private compaction | | Claude Code | `SessionStart`, `UserPromptSubmit`, `SubagentStart` | The loader emits nothing on `PreToolUse`; it runs only the Elon gate | Plugin hook (`hooks/hooks.json`), plus the `operations` pointer from `hooks/claude.json` at `SessionStart` | Explicit reading when the hook reports a problem; `UserPromptSubmit` and `SubagentStart` delivery was not separately exercised live | | Grok Build | `PreToolUse`, on the first tool call of a session | `SessionStart`, `UserPromptSubmit`, `SubagentStart`: Grok discards their output | Owned global hook file from `bin/agentsmd-grok-hook` | Explicit reading for the first response, before the first tool call | -| OpenCode | Every session, appended to the system prompt | OpenCode has no such lifecycle events | Plugin `experimental.chat.system.transform`, which also appends the `operations` pointer; `tool.execute.before` runs the Elon gate | Explicit reading when the plugin reports a problem | +| OpenCode | Every session, appended to the system prompt | OpenCode has no such lifecycle events | Plugin `experimental.chat.system.transform` (1.x) or `session.hook("context")` (2.x), which also appends the `operations` pointer; `tool.execute.before` (1.x) or `tool.hook("execute.before")` (2.x) runs the Elon gate | Explicit reading when the plugin reports a problem | | Muse | `SessionStart`, `UserPromptSubmit`, `SubagentStart` | `PreToolUse` runs only the Elon gate | Native plugin wrappers, plus the operations pointer at `SessionStart` | PostCompact re-delivery unproven; live tool-call blocking pending Live Verification | `SessionStart` loads at startup, resume, clear, and compact on Codex and Claude @@ -300,7 +300,7 @@ through the hook that already runs there: | --- | --- | | Claude Code, Codex | `UserPromptSubmit` from `hooks/hooks.json` | | Muse | The `UserPromptSubmit` wrapper | -| OpenCode | `experimental.chat.system.transform`, as the last line of the loader context on every request | +| OpenCode | `experimental.chat.system.transform` (1.x) or `session.hook("context")` (2.x), as the last line of the loader context on every request | | Grok Build | Not supported. Grok discards the output of an allowing `UserPromptSubmit` hook, and `PreToolUse` fires on every tool call, which would repeat the reminder many times per turn | No hook checks the reply itself (#201). diff --git a/VERSION b/VERSION index bf2c4a3..6f0844e 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -17.4.9 +17.5.0 diff --git a/docs/opencode.md b/docs/opencode.md index 1c44fee..59eea0a 100644 --- a/docs/opencode.md +++ b/docs/opencode.md @@ -152,11 +152,26 @@ verdicts. Any loader failure leaves the system prompt unchanged and logs one `agentsmd-project-direction:` line to stderr. Start a fresh OpenCode session after install; a running session keeps its loaded plugins. -The plugin uses `experimental.chat.system.transform`, which is experimental in -OpenCode **1.18.32**, the version the bounded run adapter pins. The plugin -context exposes no harness version, so the pin is documented, not enforced at -runtime. Treat a different OpenCode version as unproved until the seam is -rechecked. +One module serves both OpenCode plugin APIs. Its default export is +`{id, server, setup}`: OpenCode 1.x calls `server`, and OpenCode 2.x calls +`setup` and ignores `server`. OpenCode 1.x also calls `setup`, with a context +that has no session or tool hooks; `setup` then registers nothing. + +| Purpose | OpenCode 1.x | OpenCode 2.x | +| --- | --- | --- | +| Load the module | default `{id, server}`, `server(context)` returns hooks | default `{id, setup}`, `setup(context)` registers hooks | +| Working directory | `context.directory`, else `context.worktree` | `context.location.directory` | +| Append to the system prompt | `experimental.chat.system.transform`: push strings onto `output.system` | `context.session.hook("context", …)`: push `{type: "text", text}` onto `input.system` | +| Elon gate before a tool runs | `tool.execute.before`: read `input.tool` and `output.args`; throw to block | `context.tool.hook("execute.before", …)`: read `input.tool` and `input.input`; throw to block | + +In 2.x a throw from `execute.before` fails the call with that message before the +tool runs, as in 1.x. The 2.x shell tool is named `shell`, which the loader +already treats as a shell. The 1.x system transform is experimental. + +The plugin was proved on OpenCode **1.18.32**, which the bounded run adapter +pins, **1.19.6** and **2.3.2**. The plugin context exposes no harness version, so +this list is documented, not enforced at runtime. Treat another OpenCode version +as unproved until the seam is rechecked. The entry reports the Skill links' ownership states: `missing`, `owned-link`, `divergent-link`, `regular-file`, `other-path` and `broken-link`. Install @@ -219,7 +234,8 @@ install, repeat install, preserved user entries, uninstall and rejected shared directories, explicit CLI arguments, stale-head refusal, malformed events, errors and timeout. It uses a fake CLI and spends no model quota. `python3 -m unittest tests.test_opencode_plugin -v` -runs the plugin module under Node against a fixture repository and asserts that +runs the plugin module under Node through both the 1.x `server` and the 2.x +`setup` hooks against a fixture repository and asserts that the appended system entry equals the loader payload byte for byte, that an installed link resolves the canonical loader, and that an unreachable or failing loader leaves the system prompt unchanged. It skips when `node` is absent. The full repository and versionctl suites diff --git a/opencode/agentsmd-project-direction.js b/opencode/agentsmd-project-direction.js index 07656b2..2cb963b 100644 --- a/opencode/agentsmd-project-direction.js +++ b/opencode/agentsmd-project-direction.js @@ -7,6 +7,10 @@ * prompt. Any failure leaves the system prompt unchanged and logs one line. * It also appends the pointer to the operations Skill from * `bin/operations-routing`, because OpenCode does not always load it on its own. + * + * One default export serves both plugin APIs. OpenCode 1.x loads `{id, server}` + * and calls `server`; OpenCode 2.x loads `{id, setup}`, calls `setup` and + * ignores `server`. */ import { spawnSync } from "node:child_process"; @@ -14,12 +18,11 @@ import { realpathSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -// `experimental.chat.system.transform` is experimental in this OpenCode -// version, which the bounded run adapter pins as well. The plugin context -// exposes no harness version, so the pin is documentation, not a runtime gate. -// OpenCode treats every export of a plugin module as a plugin function, so the -// pin stays a module constant and a property of the exported function. -const SUPPORTED_OPENCODE_VERSION = "1.18.32"; +// The OpenCode versions this plugin was proved on. The 1.x hooks are +// experimental and the bounded run adapter pins 1.18.32. The plugin context +// exposes no harness version, so the list is documentation, not a runtime gate. +const SUPPORTED_OPENCODE_VERSIONS = Object.freeze(["1.18.32", "1.19.6", "2.3.2"]); +const PLUGIN_ID = "agentsmd-project-direction"; const LOG_PREFIX = "agentsmd-project-direction:"; const LOADER = ["bin", "project-direction"]; @@ -70,8 +73,7 @@ function loadRouting() { return routing; } -function sessionKey(input, directory) { - const given = input && input.sessionID; +function sessionKey(given, directory) { return typeof given === "string" && given.trim() ? given : `agentsmd-opencode:${directory}`; @@ -153,9 +155,21 @@ function elonGate(directory, sessionID, tool, args) { return null; } -agentsmdProjectDirection.supportedOpenCodeVersion = SUPPORTED_OPENCODE_VERSION; +function systemEntries(directory, sessionID) { + const entries = []; + const loaded = loadContext(directory, sessionID); + if (loaded) { + entries.push(loaded); + } + const table = loadRouting(); + if (table) { + entries.push(table); + } + return entries; +} -export default async function agentsmdProjectDirection(context) { +// OpenCode 1.x: hooks returned from `server`. +async function server(context) { const directory = (context && (context.directory || context.worktree)) || process.cwd(); return { @@ -163,19 +177,14 @@ export default async function agentsmdProjectDirection(context) { if (!output || !Array.isArray(output.system)) { return; } - const loaded = loadContext(directory, sessionKey(input, directory)); - if (loaded) { - output.system.push(loaded); - } - const table = loadRouting(); - if (table) { - output.system.push(table); - } + output.system.push( + ...systemEntries(directory, sessionKey(input && input.sessionID, directory)), + ); }, "tool.execute.before": async (input, output) => { const blocked = elonGate( directory, - sessionKey(input, directory), + sessionKey(input && input.sessionID, directory), input && input.tool, output && output.args, ); @@ -185,3 +194,46 @@ export default async function agentsmdProjectDirection(context) { }, }; } + +// OpenCode 2.x: hooks registered from `setup`. The `context` hook edits each +// primary model request; a throw in `execute.before` fails the tool call +// before it runs. OpenCode 1.x also calls `setup`, with a context that has no +// session or tool hooks; `server` already covers 1.x, so setup does nothing. +async function setup(context) { + const session = context && context.session; + const tool = context && context.tool; + if ( + !session || typeof session.hook !== "function" || + !tool || typeof tool.hook !== "function" + ) { + return; + } + const location = context.location; + const directory = (location && location.directory) || process.cwd(); + await session.hook("context", (input) => { + if (!input || !Array.isArray(input.system)) { + return; + } + for (const text of systemEntries(directory, sessionKey(input.sessionID, directory))) { + input.system.push({ type: "text", text }); + } + }); + await tool.hook("execute.before", (input) => { + const blocked = elonGate( + directory, + sessionKey(input && input.sessionID, directory), + input && input.tool, + input && input.input, + ); + if (blocked) { + throw new Error(blocked); + } + }); +} + +export default { + id: PLUGIN_ID, + server, + setup, + supportedOpenCodeVersions: SUPPORTED_OPENCODE_VERSIONS, +}; diff --git a/tests/test_elon_gate.py b/tests/test_elon_gate.py index 84968d0..050427a 100644 --- a/tests/test_elon_gate.py +++ b/tests/test_elon_gate.py @@ -1221,47 +1221,56 @@ def test_read_only_gh_api_and_status_posts_pass(self) -> None: with self.subTest(command=command): self.assertEqual(self.hook({"command": command}, tool_name="Bash").returncode, 0) + # Calls the plugin's pre-tool hook through OpenCode 1.x `server` or the 2.x + # `setup` registration, printing `allowed` or `blocked:`. + OPENCODE_GATE_DRIVER = ( + "import { pathToFileURL } from 'node:url';\n" + "const [modulePath, directory, command, api] = process.argv.slice(2);\n" + "const plugin = (await import(pathToFileURL(modulePath).href)).default;\n" + "let before;\n" + "if (api === 'v2') {\n" + " const hooks = {};\n" + " const hook = (domain) => async (name, callback) => {\n" + " hooks[`${domain}.${name}`] = callback;\n" + " return { dispose: async () => {} };\n" + " };\n" + " await plugin.setup({ location: { directory }, session: { hook: hook('session') }, tool: { hook: hook('tool') } });\n" + " before = () => hooks['tool.execute.before']({ tool: 'shell', sessionID: 's', input: { command } });\n" + "} else {\n" + " const hooks = await plugin.server({ directory });\n" + " before = () => hooks['tool.execute.before']({ tool: 'bash', sessionID: 's' }, { args: { command } });\n" + "}\n" + "try { await before(); process.stdout.write('allowed'); }\n" + "catch (error) { process.stdout.write('blocked:' + error.message); }\n" + ) + + def opencode_gate(self, module: Path, command: str, api: str) -> str: + driver = self.cwd / "opencode-gate.mjs" + driver.write_text(self.OPENCODE_GATE_DRIVER, encoding="utf-8") + return subprocess.run([NODE, str(driver), str(module), str(self.cwd), command, api], + capture_output=True, text=True, env=self.env, check=True).stdout + @unittest.skipIf(NODE is None, "node is not on PATH") def test_opencode_plugin_fails_closed_without_loader(self) -> None: plugin_dir = self.cwd / "orphan/opencode" plugin_dir.mkdir(parents=True) shutil.copy(PLUGIN, plugin_dir / PLUGIN.name) - driver = self.cwd / "orphan.mjs" - driver.write_text( - "import { pathToFileURL } from 'node:url';\n" - "const [modulePath, directory] = process.argv.slice(2);\n" - "const hooks = await (await import(pathToFileURL(modulePath).href)).default({ directory });\n" - "try { await hooks['tool.execute.before']({ tool: 'bash' }, { args: { command: 'gh issue create --body hi' } });\n" - " process.stdout.write('allowed'); } catch (e) { process.stdout.write('blocked:' + e.message); }\n", - encoding="utf-8", - ) - out = subprocess.run([NODE, str(driver), str(plugin_dir / PLUGIN.name), str(self.cwd)], - capture_output=True, text=True, env=self.env, check=True).stdout - self.assertTrue(out.startswith("blocked:AgentsMD could not run its Elon check"), out) + for api in ("v1", "v2"): + with self.subTest(api=api): + out = self.opencode_gate(plugin_dir / PLUGIN.name, "gh issue create --body hi", api) + self.assertTrue(out.startswith("blocked:AgentsMD could not run its Elon check"), out) @unittest.skipIf(NODE is None, "node is not on PATH") def test_opencode_plugin_throws_on_blocked_call(self) -> None: - driver = self.cwd / "driver.mjs" - driver.write_text( - "import { pathToFileURL } from 'node:url';\n" - "const [modulePath, directory, command] = process.argv.slice(2);\n" - "const hooks = await (await import(pathToFileURL(modulePath).href)).default({ directory });\n" - "try {\n" - " await hooks['tool.execute.before']({ tool: 'bash', sessionID: 's' }, { args: { command } });\n" - " process.stdout.write('allowed');\n" - "} catch (error) { process.stdout.write('blocked:' + error.message); }\n", - encoding="utf-8", - ) - - def run(command: str) -> str: - return subprocess.run([NODE, str(driver), str(PLUGIN), str(self.cwd), command], - capture_output=True, text=True, env=self.env, check=True).stdout - - self.assertTrue(run("gh issue create --body hi").startswith("blocked:AgentsMD blocked")) - self.assertEqual(run("gh issue create --body " + shlex.quote(RECORD)), "allowed") - self.assertEqual(run("ls"), "allowed") - self.assertTrue(run("gh api repos/o/r/issues -f title=x").startswith("blocked:AgentsMD blocked")) - + for api in ("v1", "v2"): + with self.subTest(api=api): + def run(command: str) -> str: + return self.opencode_gate(PLUGIN, command, api) + + self.assertTrue(run("gh issue create --body hi").startswith("blocked:AgentsMD blocked")) + self.assertEqual(run("gh issue create --body " + shlex.quote(RECORD)), "allowed") + self.assertEqual(run("ls"), "allowed") + self.assertTrue(run("gh api repos/o/r/issues -f title=x").startswith("blocked:AgentsMD blocked")) class ElonContractTests(unittest.TestCase): diff --git a/tests/test_opencode_plugin.py b/tests/test_opencode_plugin.py index 57a0db1..2568a99 100644 --- a/tests/test_opencode_plugin.py +++ b/tests/test_opencode_plugin.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 -"""Node seam proof that the OpenCode plugin transports the loader payload.""" +"""Node seam proof that the OpenCode plugin transports the loader payload +on both OpenCode plugin APIs.""" from __future__ import annotations @@ -19,25 +20,62 @@ ROUTING = ROOT / "bin/operations-routing" NODE = shutil.which("node") LOG_PREFIX = "agentsmd-project-direction:" +# OpenCode 1.x calls `server`; OpenCode 2.x calls `setup`. +APIS = ("v1", "v2") DRIVER = """ import { pathToFileURL } from "node:url"; -const [modulePath, directory, calls] = process.argv.slice(2); +const [modulePath, directory, calls, api] = process.argv.slice(2); const module = await import(pathToFileURL(modulePath).href); -const hooks = await module.default({ directory, worktree: directory }); -const output = { system: [] }; -for (let call = 0; call < Number(calls); call += 1) { - await hooks["experimental.chat.system.transform"]( - { sessionID: "ses_fixture", model: { id: "fixture" } }, - output, - ); +const plugin = module.default; +let system; +if (api === "v2") { + // OpenCode 2.x: setup registers hooks; the context hook edits system parts. + const registered = {}; + const hook = (domain) => async (name, callback) => { + registered[`${domain}.${name}`] = callback; + return { dispose: async () => {} }; + }; + await plugin.setup({ + location: { directory, project: { directory } }, + session: { hook: hook("session") }, + tool: { hook: hook("tool") }, + }); + const request = { + sessionID: "ses_fixture", + system: [{ type: "text", text: "host" }], + messages: [], + }; + for (let call = 0; call < Number(calls); call += 1) { + await registered["session.context"](request); + } + const added = request.system.slice(1); + if (added.some((part) => part.type !== "text" || Object.keys(part).length !== 2)) { + throw new Error("unexpected system part shape: " + JSON.stringify(added)); + } + system = added.map((part) => part.text); +} else { + // OpenCode 1.x: server returns hooks; the transform edits system strings. + const hooks = await plugin.server({ directory, worktree: directory }); + const output = { system: [] }; + for (let call = 0; call < Number(calls); call += 1) { + await hooks["experimental.chat.system.transform"]( + { sessionID: "ses_fixture", model: { id: "fixture" } }, + output, + ); + } + system = output.system; } process.stdout.write(JSON.stringify({ - system: output.system, - supported: module.default.supportedOpenCodeVersion, + system, + id: plugin.id, + supported: plugin.supportedOpenCodeVersions, exports: Object.fromEntries( Object.entries(module).map(([name, value]) => [name, typeof value]), ), + members: Object.fromEntries( + Object.entries(plugin).map(([name, value]) => [name, typeof value]), + ), })); """ @@ -88,10 +126,10 @@ def git(self, *arguments: str) -> None: text=True, ) - def transform(self, directory: Path, module: Path = PLUGIN, calls: int = 1): + def transform(self, directory: Path, module: Path = PLUGIN, calls: int = 1, api: str = "v1"): result = subprocess.run( # Bun runs OpenCode plugins; the flag only silences Node module notices. - [NODE, "--no-warnings", str(self.driver), str(module), str(directory), str(calls)], + [NODE, "--no-warnings", str(self.driver), str(module), str(directory), str(calls), api], capture_output=True, text=True, env=self.environment, @@ -123,9 +161,13 @@ def routing_context(self) -> str: return json.loads(result.stdout)["hookSpecificOutput"]["additionalContext"] def test_triad_repository_payload_reaches_the_system_prompt(self) -> None: - report, stderr = self.transform(self.repository) + for api in APIS: + with self.subTest(api=api): + self.check_triad_payload(api) + + def check_triad_payload(self, api: str) -> None: + report, stderr = self.transform(self.repository, api=api) self.assertNotIn(LOG_PREFIX, stderr) - self.assertEqual(report["supported"], "1.18.32") self.assertEqual(len(report["system"]), 2) self.assertEqual(report["system"][0], self.loaded_context(self.repository)) self.assertEqual(report["system"][1], self.routing_context()) @@ -139,7 +181,12 @@ def test_triad_repository_payload_reaches_the_system_prompt(self) -> None: self.assertEqual(report["system"][0].count(REMINDER), 1) def test_directory_outside_a_repository_carries_the_loader_verdict(self) -> None: - report, stderr = self.transform(self.outside) + for api in APIS: + with self.subTest(api=api): + self.check_outside(api) + + def check_outside(self, api: str) -> None: + report, stderr = self.transform(self.outside, api=api) self.assertNotIn(LOG_PREFIX, stderr) self.assertEqual(len(report["system"]), 2) self.assertEqual(report["system"][0], self.loaded_context(self.outside)) @@ -149,37 +196,63 @@ def test_directory_outside_a_repository_carries_the_loader_verdict(self) -> None self.assertNotIn("files", payload) self.assertNotIn("Make agent work purposeful.", report["system"][0]) - def test_every_module_export_is_a_plugin_function(self) -> None: - # OpenCode calls every export of a plugin module, so a value export fails to load. + def test_default_export_serves_both_plugin_apis(self) -> None: + # OpenCode 2.x requires a default object with `id` and `setup`, and + # rejects a function default; OpenCode 1.x loads `{id, server}` from the + # default export alone. Any other export would be a second 1.x plugin. report, stderr = self.transform(self.repository, calls=0) self.assertNotIn(LOG_PREFIX, stderr) self.assertEqual(report["system"], []) - self.assertTrue(report["exports"]) - self.assertEqual( - sorted(set(report["exports"].values())), - ["function"], - report["exports"], - ) + self.assertEqual(report["exports"], {"default": "object"}) + self.assertEqual(report["id"], "agentsmd-project-direction") + self.assertEqual(report["members"]["server"], "function") + self.assertEqual(report["members"]["setup"], "function") + self.assertNotIn("tui", report["members"]) + self.assertIn("1.18.32", report["supported"]) + self.assertIn("2.3.2", report["supported"]) def test_installed_link_resolves_the_canonical_loader(self) -> None: plugins = self.base / "opencode/plugins" plugins.mkdir() link = plugins / PLUGIN.name link.symlink_to(PLUGIN) - report, stderr = self.transform(self.repository, module=link) - self.assertNotIn(LOG_PREFIX, stderr) - self.assertEqual( - report["system"], - [self.loaded_context(self.repository), self.routing_context()], + for api in APIS: + with self.subTest(api=api): + report, stderr = self.transform(self.repository, module=link, api=api) + self.assertNotIn(LOG_PREFIX, stderr) + self.assertEqual( + report["system"], + [self.loaded_context(self.repository), self.routing_context()], + ) + + def test_setup_without_session_and_tool_hooks_registers_nothing(self) -> None: + # OpenCode 1.x also calls `setup`, with a context lacking session and + # tool hooks; `server` covers 1.x, so setup must be a silent no-op. + driver = self.base / "reduced.mjs" + driver.write_text( + "import { pathToFileURL } from 'node:url';\n" + "const plugin = (await import(pathToFileURL(process.argv[2]).href)).default;\n" + "const result = await plugin.setup({ options: {}, agent: {}, skill: {} });\n" + "process.stdout.write(String(result));\n", + encoding="utf-8", ) + result = subprocess.run( + [NODE, "--no-warnings", str(driver), str(PLUGIN)], + capture_output=True, text=True, env=self.environment, check=False, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, "undefined") + self.assertEqual(result.stderr, "") def test_unreachable_loader_leaves_the_system_prompt_unchanged(self) -> None: detached = self.base / "detached/agentsmd-project-direction.js" detached.parent.mkdir() shutil.copyfile(PLUGIN, detached) - report, stderr = self.transform(self.repository, module=detached) - self.assertEqual(report["system"], []) - self.assertIn(LOG_PREFIX, stderr) + for api in APIS: + with self.subTest(api=api): + report, stderr = self.transform(self.repository, module=detached, api=api) + self.assertEqual(report["system"], []) + self.assertIn(LOG_PREFIX, stderr) def test_failing_loader_leaves_the_system_prompt_unchanged_and_logs_once(self) -> None: clone = self.base / "clone" @@ -190,13 +263,15 @@ def test_failing_loader_leaves_the_system_prompt_unchanged_and_logs_once(self) - loader.chmod(0o755) module = clone / "opencode/agentsmd-project-direction.js" shutil.copyfile(PLUGIN, module) - report, stderr = self.transform(self.repository, module=module, calls=2) - self.assertEqual(report["system"], []) - # One line for Project Direction and one for the missing routing command. - lines = stderr.splitlines() - self.assertEqual(len(lines), 2, stderr) - self.assertIn("status 3", lines[0]) - self.assertIn("operations pointer was not loaded", lines[1]) + for api in APIS: + with self.subTest(api=api): + report, stderr = self.transform(self.repository, module=module, calls=2, api=api) + self.assertEqual(report["system"], []) + # One line for Project Direction and one for the missing routing command. + lines = stderr.splitlines() + self.assertEqual(len(lines), 2, stderr) + self.assertIn("status 3", lines[0]) + self.assertIn("operations pointer was not loaded", lines[1]) if __name__ == "__main__": diff --git a/tools/versionctl/pyproject.toml b/tools/versionctl/pyproject.toml index 38e90c8..285bf06 100644 --- a/tools/versionctl/pyproject.toml +++ b/tools/versionctl/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "toolboxmd-versionctl" -version = "17.4.9" +version = "17.5.0" description = "Deterministic repository version mechanics for coding agents" readme = "README.md" requires-python = ">=3.11"