A skill to stop your coding agent from burying the answer. ADHD-friendly output.
opencode: keep the V1 path alongside the V2 migration
opencode-agent1a311a817951
diff --git a/.opencode/plugins/i-have-adhd.mjs b/.opencode/plugins/i-have-adhd.mjsindex b409e58..82d8db5 100644--- a/.opencode/plugins/i-have-adhd.mjs+++ b/.opencode/plugins/i-have-adhd.mjs@@ -1,31 +1,26 @@-// i-have-adhd — OpenCode V2 plugin.+// i-have-adhd — OpenCode plugin.//// Mirrors the Claude Code / Codex behaviour for OpenCode: the skill in// `skills/i-have-adhd/SKILL.md` is the single source of truth for the ruleset.//-// • On demand → registers the skill plus a `/i-have-adhd` command so the-// ruleset applies for the rest of the session.-// • Always-on → when the opt-in flag file exists, the full ruleset is+// • On demand — registers the skills directory and a `/i-have-adhd`+// command so the ruleset applies for the rest of the session.+// • Always-on — when the opt-in flag file exists, the full ruleset is// appended to the system prompt every turn (the OpenCode// equivalent of the SessionStart hook in hooks/always-on.sh).//-// V2 migration notes:-// • The default export must be a definition object with an `id` and an-// `effect`/`setup` function. The V1 shape, a bare-// `export default async () => ({...})`, is rejected at load time with-// "Plugin must export a default definition with an id and an effect or-// setup function".-// • The V1 `config` mutation hook is gone. Skills and commands register-// through `ctx.skill.transform` and `ctx.command.transform`.-// • `experimental.chat.system.transform` is gone. System-prompt edits go-// through `ctx.session.hook("context", ...)`.-//// Opt in to always-on: touch ~/.config/opencode/.i-have-adhd-always// Opt back out: rm ~/.config/opencode/.i-have-adhd-always//-// Install — add to opencode.json(c). V2 requires a directory, and the field-// is plural:+// One default export serves both plugin APIs. V2 calls `setup(ctx)`; V1 calls+// `server()`. V1 object entrypoints require OpenCode 1.18.29 or newer, so+// 1.18.28 and older need the previous plugin file. The two APIs are separate —+// `server()` restates the V1 hooks rather than translating `setup`.+//+// V2 install — add to opencode.json(c), plural field, directory path:// { "plugins": ["/absolute/path/to/i-have-adhd"] }+// V1 install — add to opencode.json, singular field, file path:+// { "plugin": ["/absolute/path/to/i-have-adhd/.opencode/plugins/i-have-adhd.mjs"] }import fs from 'fs';import os from 'os';@@ -43,12 +38,15 @@ const FALLBACK_DESCRIPTION ='multi-step work, restate state across turns, suppress tangents, give ' +'specific time estimates, make wins visible.';-const FALLBACK_PROMPT =- 'Use the `i-have-adhd` skill and apply its ruleset to every response for the ' +- 'rest of this session: lead with the next action, number multi-step work, ' +- 'restate state across turns, suppress tangents, give concrete time estimates, ' +- 'and make wins visible. These rules persist until I say "stop adhd mode" or ' +- '"normal mode".';+// JSON is valid YAML frontmatter; share native command metadata without a YAML dependency.+// Returns the full definition: V1 registers it as `config.command[...]`, while V2+// reads only `description` because `Command.Info` has no other fields.+async function commandDefinition() {+ const raw = await fs.promises.readFile(commandPath, 'utf8');+ const match = raw.match(/^---[^\S\r\n]*\r?\n([\s\S]*?)\r?\n---[^\S\r\n]*(?:\r?\n|$)([\s\S]*)$/);+ if (!match) throw new Error('Missing command frontmatter');+ return { ...JSON.parse(match[1]), template: match[2].trim() };+}// Always-on opt-in flag, mirroring Claude Code's ~/.claude/.i-have-adhd-always// but under OpenCode's config dir so the two tools stay independent.@@ -58,14 +56,6 @@ const flagPath = path.join('.i-have-adhd-always',);-// JSON is valid YAML frontmatter; share native command metadata without a YAML dependency.-async function commandDefinition() {- const raw = await fs.promises.readFile(commandPath, 'utf8');- const match = raw.match(/^---[^\S\r\n]*\r?\n([\s\S]*?)\r?\n---[^\S\r\n]*(?:\r?\n|$)([\s\S]*)$/);- if (!match) throw new Error('Missing command frontmatter');- return { description: JSON.parse(match[1]).description, template: match[2].trim() };-}-// Read SKILL.md and strip a leading YAML frontmatter block (--- ... ---).// Regex and trailing-newline trim match hooks/always-on.mjs so always-on// injections behave identically across harnesses (see tests/test_always_on_hooks.py).@@ -76,9 +66,28 @@ function rulesetBody() {.replace(/(?:\r?\n)+$/, '');}+// Shared by both APIs: the text to inject, or null when the flag is absent or+// the ruleset cannot be read. The callers differ only in how they append — V1+// mutates the last string in `output.system`, V2 pushes a typed text part.+function alwaysOnInjection() {+ let on = false;+ try { on = fs.existsSync(flagPath); } catch (e) {}+ if (!on) return null;++ let body;+ try { body = rulesetBody(); } catch (e) { return null; }++ const header =+ 'ADHD MODE ACTIVE (always-on). The ruleset below applies to every ' ++ 'response. "stop adhd mode" or "normal mode" turns it off for this ' ++ 'session; delete ' + flagPath + ' to turn always-on off for good.';+ return header + '\n\n' + body;+}+export default {id: SKILL_ID,+ // OpenCode V2.async setup(ctx) {// Make the skill discoverable, so the `skill` tool and the /i-have-adhd// command can both load it.@@ -127,27 +136,45 @@ export default {// turns always-on off for good.try {await ctx.session.hook('context', (event) => {- let on = false;- try {- on = fs.existsSync(flagPath);- } catch (e) {}- if (!on) return;+ const injected = alwaysOnInjection();+ if (!injected) return;+ event.system.push({ type: 'text', text: injected });+ });+ } catch (e) {+ // Always-on injection is optional; never break plugin load.+ }+ },++ // OpenCode V1 (1.18.29+). The APIs are separate: this restates the V1 hooks+ // rather than translating `setup`.+ async server() {+ return {+ config: async (config) => {+ config.skills = config.skills || {};+ config.skills.paths = config.skills.paths || [];+ if (!config.skills.paths.includes(skillsDir)) config.skills.paths.push(skillsDir);- let body;+ // Global installs need a command entry; preserve native or user-defined commands.try {- body = rulesetBody();+ config.command = config.command || {};+ if (!config.command[SKILL_ID]) {+ config.command[SKILL_ID] = await commandDefinition();+ }} catch (e) {- return;+ // Missing or malformed command files must not break skill discovery.}+ },- const header =- 'ADHD MODE ACTIVE (always-on). The ruleset below applies to every ' +- 'response. "stop adhd mode" or "normal mode" turns it off for this ' +- 'session; delete ' + flagPath + ' to turn always-on off for good.';- event.system.push({ type: 'text', text: header + '\n\n' + body });- });- } catch (e) {- // Always-on injection is optional; never break plugin load.- }+ 'experimental.chat.system.transform': async (_input, output) => {+ const injected = alwaysOnInjection();+ if (!injected) return;++ if (output.system.length > 0) {+ output.system[output.system.length - 1] += '\n\n' + injected;+ } else {+ output.system.push(injected);+ }+ },+ };},};diff --git a/INSTALL.md b/INSTALL.mdindex 87e37eb..143c9cd 100644--- a/INSTALL.md+++ b/INSTALL.md@@ -514,6 +514,11 @@ OpenCode reads `skills/i-have-adhd/SKILL.md` natively, so the ruleset is availabto the `skill` tool with no plugin at all. The plugin adds two things on top: the`/i-have-adhd` slash command for a global install, and the always-on flag.+The plugin serves both OpenCode plugin APIs from one default export. OpenCode V2+calls `setup(ctx)`; OpenCode V1 calls `server()`. V1 object entrypoints require+OpenCode 1.18.29 or newer — on 1.18.28 and older, stay on the plugin file from the+previous release, which exports a bare plugin function.+## Install### Skill only (no plugin)diff --git a/tests/opencode_plugin_driver.mjs b/tests/opencode_plugin_driver.mjsindex fcc09c6..5177c5c 100644--- a/tests/opencode_plugin_driver.mjs+++ b/tests/opencode_plugin_driver.mjs@@ -1,17 +1,20 @@-// Test driver for the OpenCode plugin. Imports the plugin at argv[2], calls its-// V2 `setup` with a recording context, and runs one of the registered handlers-// depending on argv[3]:+// Test driver for the OpenCode plugin. Imports the plugin at argv[2], calls the+// API named by argv[3], and prints a JSON summary so tests can assert on it://-// (default) fires the `context` session hook against an empty system prompt-// and prints the resulting system text so tests can assert on the-// injected banner. Nothing is printed when the hook injects-// nothing (always-on flag absent).-// skill prints the registered skills as JSON.-// command prints the registered commands as JSON, with `template` holding-// the prompt the command would submit.+// skill V2: runs `setup(ctx)` and prints the registered skills.+// command V2: runs `setup(ctx)` and prints the registered commands, with+// `template` holding the prompt the command would submit.+// context V2: runs `setup(ctx)`, fires the `context` session hook against an+// empty system prompt, and prints the resulting system text.+// v1-config V1: calls `server()` and prints the config after its `config`+// hook runs twice, checking registration, overrides, and idempotency.+// v1-context V1: calls `server()` and fires+// `experimental.chat.system.transform` against an empty system+// prompt, printing the resulting system text.//-// V2 note: the plugin default-exports a definition object, so the driver awaits-// `setup(ctx)` instead of calling a bare function.+// One default export serves both APIs: V2 calls `setup(ctx)`, V1 calls+// `server()`. A `context` or `v1-context` run prints nothing when the hook+// injects nothing (always-on flag absent).import { pathToFileURL } from 'node:url';const pluginPath = process.argv[2];@@ -29,7 +32,7 @@ const editorFor = (store) => ({add: (entry) => store.set(entry.id ?? entry.name, entry),});-const ctx = {+const v2ctx = {skill: {transform: async (cb) => {cb(editorFor(skills));@@ -53,25 +56,41 @@ const ctx = {},};-await definition.setup(ctx);+const joined = (event) => event.system.map((part) => part.text ?? String(part)).join('\n---SEP---\n');-if (mode === 'skill') {- process.stdout.write(JSON.stringify([...skills.values()]));-} else if (mode === 'command') {- const out = [...commands.values()].map((command) => ({- name: command.name,- description: command.description,- }));- const entry = [...commands.values()][0];- if (entry) {- await entry.execute({ sessionID: "ses_test", prompt: { text: "" }, delivery: "steer" });- out[0].template = prompts[prompts.length - 1]?.text;+if (mode === 'v1-config' || mode === 'v1-context') {+ const v1 = await definition.server();+ if (mode === 'v1-config') {+ const config = JSON.parse(process.argv[4] || '{}');+ await v1.config(config);+ await v1.config(config);+ process.stdout.write(JSON.stringify(config));+ } else {+ const output = { system: [] };+ await v1['experimental.chat.system.transform']({}, output);+ process.stdout.write(output.system.join('\n---SEP---\n'));}- process.stdout.write(JSON.stringify(out));} else {- const handler = hooks.get('context');- if (!handler) process.exit(0);- const event = { system: [] };- await handler(event);- process.stdout.write(event.system.map((part) => part.text ?? String(part)).join('\n---SEP---\n'));+ await definition.setup(v2ctx);++ if (mode === 'skill') {+ process.stdout.write(JSON.stringify([...skills.values()]));+ } else if (mode === 'command') {+ const out = [...commands.values()].map((command) => ({+ name: command.name,+ description: command.description,+ }));+ const entry = [...commands.values()][0];+ if (entry) {+ await entry.execute({ sessionID: "ses_test", prompt: { text: "" }, delivery: "steer" });+ out[0].template = prompts[prompts.length - 1]?.text;+ }+ process.stdout.write(JSON.stringify(out));+ } else {+ const handler = hooks.get('context');+ if (!handler) process.exit(0);+ const event = { system: [] };+ await handler(event);+ process.stdout.write(joined(event));+ }}diff --git a/tests/test_opencode_plugin.py b/tests/test_opencode_plugin.pyindex 272b6e9..0594530 100644--- a/tests/test_opencode_plugin.py+++ b/tests/test_opencode_plugin.py@@ -9,14 +9,19 @@ from pathlib import PathROOT = Path(__file__).resolve().parents[1]+# The plugin default-exports one definition serving both APIs: V2 calls+# `setup(ctx)` and V1 calls `server()`. Always-on injection is shared, so it is+# asserted through both entry points.+INJECTION_MODES = ["context", "v1-context"]+@unittest.skipUnless(shutil.which("node"), "node is required for the OpenCode plugin")class OpenCodePluginTest(unittest.TestCase):"""Mirror tests/test_always_on_hooks.py for the OpenCode server plugin: thealways-on flag gates injection, and frontmatter stripping matches the hooks.- OpenCode V2 replaced the V1 `config` mutation hook with `ctx.skill.transform`- and `ctx.command.transform`, so registration is asserted through those."""+ V2 registers through `ctx.skill.transform` and `ctx.command.transform`; V1+ mutates the config object in its `config` hook. Both paths are covered."""def setUp(self):self.temp_dir = tempfile.TemporaryDirectory()@@ -28,7 +33,7 @@ class OpenCodePluginTest(unittest.TestCase):self.config_dir = Path(self.temp_dir.name) / "config"(self.config_dir / "opencode").mkdir(parents=True)- def run_plugin(self, mode=None):+ def run_plugin(self, mode=None, config=None):env = os.environ.copy()env["XDG_CONFIG_HOME"] = str(self.config_dir)args = [@@ -38,6 +43,8 @@ class OpenCodePluginTest(unittest.TestCase):]if mode:args.append(mode)+ if config is not None:+ args.append(json.dumps(config))return subprocess.run(args,check=False,@@ -52,25 +59,50 @@ class OpenCodePluginTest(unittest.TestCase):def write_skill(self, text):(self.plugin_root / "skills" / "i-have-adhd" / "SKILL.md").write_text(text)+ # --- always-on injection, asserted through both APIs ---+def test_silent_without_opt_in_flag(self):- result = self.run_plugin()- self.assertEqual(0, result.returncode, result.stderr)- self.assertEqual("", result.stdout)+ for mode in INJECTION_MODES:+ with self.subTest(mode=mode):+ result = self.run_plugin(mode)+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertEqual("", result.stdout)++ def test_injects_ruleset_when_opted_in(self):+ self.opt_in()+ for mode in INJECTION_MODES:+ with self.subTest(mode=mode):+ result = self.run_plugin(mode)+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertIn("ADHD MODE ACTIVE (always-on)", result.stdout)+ self.assertIn("Working memory is small", result.stdout)def test_strips_frontmatter_with_trailing_whitespace(self):self.write_skill("--- \nname: fixture\n--- \t\nFixture body.\n")self.opt_in()- result = self.run_plugin()- self.assertEqual(0, result.returncode, result.stderr)- self.assertNotIn("name: fixture", result.stdout)- self.assertIn("\n\nFixture body.", result.stdout)+ for mode in INJECTION_MODES:+ with self.subTest(mode=mode):+ result = self.run_plugin(mode)+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertNotIn("name: fixture", result.stdout)+ self.assertIn("\n\nFixture body.", result.stdout)def test_keeps_content_when_frontmatter_is_unclosed(self):self.write_skill("---\nname: fixture\nFixture body, fence never closed.\n")self.opt_in()- result = self.run_plugin()- self.assertEqual(0, result.returncode, result.stderr)- self.assertIn("Fixture body, fence never closed.", result.stdout)+ for mode in INJECTION_MODES:+ with self.subTest(mode=mode):+ result = self.run_plugin(mode)+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertIn("Fixture body, fence never closed.", result.stdout)++ def test_both_apis_share_the_same_injected_text(self):+ self.opt_in()+ v2 = self.run_plugin("context").stdout+ v1 = self.run_plugin("v1-context").stdout+ self.assertEqual(v2, v1)++ # --- V2 registration ---def test_setup_registers_the_slash_command(self):# Regression test for #140: a global install (plugin loaded from a@@ -116,6 +148,65 @@ class OpenCodePluginTest(unittest.TestCase):self.assertEqual(0, result.returncode, result.stderr)self.assertEqual("i-have-adhd", json.loads(result.stdout)[0]["id"])+ # --- V1 config registration ---++ def test_v1_config_hook_registers_the_slash_command(self):+ result = self.run_plugin(mode="v1-config")+ self.assertEqual(0, result.returncode, result.stderr)+ config = json.loads(result.stdout)+ command = config["command"]["i-have-adhd"]+ self.assertIn("ADHD", command["description"])+ self.assertIn("stop adhd mode", command["template"])++ def test_v1_config_hook_registers_the_skills_path(self):+ result = self.run_plugin(mode="v1-config")+ self.assertEqual(0, result.returncode, result.stderr)+ config = json.loads(result.stdout)+ self.assertIn(str(self.plugin_root / "skills"), config["skills"]["paths"])++ def test_v1_config_preserves_existing_command(self):+ custom = {"description": "User command", "template": "Keep this", "agent": "plan"}+ result = self.run_plugin("v1-config", {"command": {"i-have-adhd": custom}})+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertEqual(custom, json.loads(result.stdout)["command"]["i-have-adhd"])++ def test_v1_repeated_config_does_not_duplicate_skill_paths(self):+ result = self.run_plugin("v1-config")+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertEqual(+ [str(self.plugin_root / "skills")], json.loads(result.stdout)["skills"]["paths"]+ )++ def test_v1_command_preserves_metadata_and_trims_template(self):+ metadata = {"description": 'ADHD: "focus"\nnext line', "agent": "plan",+ "model": "fixture/model", "subagent": True}+ command = self.plugin_root / ".opencode/command/i-have-adhd.md"+ command.write_bytes(("--- \r\n" + json.dumps(metadata) ++ "\r\n--- \t\r\n\r\nUse the skill.\r\n\r\n").encode())+ result = self.run_plugin("v1-config")+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertEqual({**metadata, "template": "Use the skill."},+ json.loads(result.stdout)["command"]["i-have-adhd"])++ def test_v1_missing_command_keeps_skill_discovery(self):+ (self.plugin_root / ".opencode/command/i-have-adhd.md").unlink()+ result = self.run_plugin("v1-config")+ self.assertEqual(0, result.returncode, result.stderr)+ config = json.loads(result.stdout)+ self.assertNotIn("i-have-adhd", config["command"])+ self.assertEqual([str(self.plugin_root / "skills")], config["skills"]["paths"])++ def test_v1_malformed_command_does_not_leak_frontmatter_into_prompt(self):+ command = self.plugin_root / ".opencode/command/i-have-adhd.md"+ for text in ["---\n{broken}\n---\nBody", '---\n{"description":"unclosed"}\nBody']:+ with self.subTest(text=text):+ command.write_text(text)+ result = self.run_plugin("v1-config")+ self.assertEqual(0, result.returncode, result.stderr)+ config = json.loads(result.stdout)+ self.assertNotIn("i-have-adhd", config["command"])+ self.assertEqual([str(self.plugin_root / "skills")], config["skills"]["paths"])+if __name__ == "__main__":unittest.main()