Implement opencode adapter.

Co-Authored-By: win0na <winnie@winneon.moe>

feat(lib.sh): add install_plugins helper for opencode JS plugins

build(adapters): opencode adapter skeleton with capability/event tables

build(opencode): adapter_translate_dispatcher (DISPATCHER.md → AGENTS.md)

build(opencode): adapter_translate_references and adapter_translate_skills

Implements Task 4 and Task 5:
- adapter_translate_references: Copies reference markdown files to .opencode/references/
- adapter_translate_skills: Copies skill SKILL.md files to .opencode/skills/<name>/ with exclude filtering

Both functions respect framework filtering via should_include().

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(opencode): adapter_translate_agents with capability→permission mapping

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(opencode): bash-executor template for spawning hook scripts

build(opencode): plugin-stub template for mbifc-hooks.js

build(opencode): adapter_translate_hooks with JS plugin generation

Implements _oc_hook_registry_json and adapter_translate_hooks in the
opencode adapter. Copies hook scripts to .opencode/hooks/, generates a
single .opencode/plugins/mbifc-hooks.js by inlining bash-executor.js and
synthesising a hook registry from *.hook.yaml files. Uses python3 for
template substitution to safely handle multi-line JS content. Adds 3
unit tests (copies scripts, registry entries, noop when no hooks dir).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

build(opencode): adapter_translate_mcp with local/remote handling

build(opencode): adapter_finalize and complete adapter_build wiring

Add adapter_finalize placeholder and wire adapter_translate_mcp into
adapter_build; add end-to-end integration test (14/14 pass).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

feat(launchme): branch on --framework for opencode install layout

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

feat(updateme): branch on --framework for opencode install layout

Mirror the same case "$FRAMEWORK" block from launchme.sh: framework-specific
DIST_COMPONENTS_DIR, VAULT_COMPONENTS_DIR, DISPATCHER_SRC/DST, MCP_SRC/DST,
HAS_PLUGINS; conditional install_plugins; conditional install_settings;
framework-aware vault-setup check; framework-neutral summary messages.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
nunziati
2026-04-08 21:51:37 +00:00
parent 24b84ca414
commit 3f5d89bee3
7 changed files with 972 additions and 28 deletions

370
adapters/opencode/adapter.sh Executable file
View File

@@ -0,0 +1,370 @@
#!/usr/bin/env bash
# =============================================================================
# adapters/opencode/adapter.sh — Opencode framework adapter
# =============================================================================
# Sourced by scripts/build.sh AFTER adapters/lib.sh.
# Translates source files into a dist/opencode/ tree that mirrors what
# opencode expects in the user's vault.
# =============================================================================
FRAMEWORK="opencode"
# Capability → opencode permission key. Returns the permission key to set to
# "allow" for each capability, or empty string for capabilities that have no
# opencode equivalent (they are dropped).
#
# Reference (spec §"Capability vocabulary"):
# read → implicit, no permission needed
# write → edit: allow
# edit → edit: allow
# bash → bash: allow
# webfetch → webfetch: allow
# websearch → drop (no equivalent)
# notebook → drop
# task → drop (subagent invocation, not a permission)
# todo → drop
oc_capability_to_permission() {
local cap="$1"
case "$cap" in
read) echo "" ;; # implicit
write) echo "edit" ;;
edit) echo "edit" ;;
bash) echo "bash" ;;
webfetch) echo "webfetch" ;;
websearch) echo "" ;; # drop
notebook) echo "" ;; # drop
task) echo "" ;; # drop
todo) echo "" ;; # drop
*) echo "" ;;
esac
}
# Event vocabulary → opencode native event name.
oc_event_to_native() {
local event="$1"
case "$event" in
before-tool-use) echo "tool.execute.before" ;;
after-tool-use) echo "tool.execute.after" ;;
on-notification) echo "session.idle" ;;
on-session-start) echo "session.created" ;;
on-prompt-submit) echo "tui.prompt.append" ;;
*) echo "" ;;
esac
}
# CC-style short model name → opencode provider/model id. Conservative mapping:
# if the source model is already provider-prefixed (contains "/"), pass through
# unchanged. Otherwise look up in the table and fall back to the raw value.
oc_model_to_provider() {
local model="$1"
case "$model" in
*/*) echo "$model" ;; # already qualified
sonnet) echo "anthropic/claude-sonnet-4-5" ;;
opus) echo "anthropic/claude-opus-4-5" ;;
haiku) echo "anthropic/claude-haiku-4-5" ;;
*) echo "$model" ;; # unknown — pass through
esac
}
# adapter_translate_dispatcher <source_dispatcher_md> <dest_dir>
# Copies the source DISPATCHER.md to dest_dir/AGENTS.md (opencode's vault-root
# dispatcher filename). No content translation.
adapter_translate_dispatcher() {
local src="$1" dst="$2"
[[ -f "$src" ]] || return 0
mkdir -p "$dst"
cp "$src" "$dst/AGENTS.md"
}
# adapter_translate_references <source_refs_dir> <dest_root>
# Verbatim copy of *.md into dest_root/.opencode/references/.
adapter_translate_references() {
local src="$1" dst="$2"
[[ -d "$src" ]] || return 0
local out="$dst/.opencode/references"
mkdir -p "$out"
for f in "$src"/*.md; do
[[ -f "$f" ]] || continue
should_include "$f" "$FRAMEWORK" || continue
cp "$f" "$out/"
done
}
# adapter_translate_skills <source_skills_dir> <dest_root>
# Copies each skill directory's SKILL.md into dest_root/.opencode/skills/<name>/.
adapter_translate_skills() {
local src="$1" dst="$2"
[[ -d "$src" ]] || return 0
for skill_dir in "$src"/*/; do
[[ -f "${skill_dir}SKILL.md" ]] || continue
should_include "${skill_dir}SKILL.md" "$FRAMEWORK" || continue
local name; name="$(basename "$skill_dir")"
local out="$dst/.opencode/skills/$name"
mkdir -p "$out"
cp "${skill_dir}SKILL.md" "$out/SKILL.md"
done
}
# _oc_flatten_description <agent_file>
# Reads the description field from the source agent, collapsing any YAML
# folded continuation lines into a single line with whitespace normalised.
# Echoes the bare description text with no leading/trailing quotes.
_oc_flatten_description() {
local file="$1"
awk '
/^---$/ { fm++; next }
fm == 1 && /^description:/ {
sub(/^description:[[:space:]]*/, "")
desc = $0
in_desc = 1
next
}
fm == 1 && in_desc && /^[[:space:]]/ {
sub(/^[[:space:]]+/, "")
desc = desc " " $0
next
}
fm == 1 && in_desc { in_desc = 0 }
fm >= 2 { exit }
END {
# Collapse runs of whitespace
gsub(/[[:space:]]+/, " ", desc)
sub(/^[[:space:]]+/, "", desc)
sub(/[[:space:]]+$/, "", desc)
print desc
}
' "$file"
}
# adapter_translate_agents <source_agents_dir> <dest_root>
# For each *.md in source_agents_dir, translate the capabilities frontmatter
# into an opencode permission block, map the model, and write to
# dest_root/.opencode/agents/<name>.md.
adapter_translate_agents() {
local src="$1" dst="$2"
[[ -d "$src" ]] || return 0
local out_dir="$dst/.opencode/agents"
mkdir -p "$out_dir"
while IFS= read -r agent; do
[[ -f "$agent" ]] || continue
should_include "$agent" "$FRAMEWORK" || continue
local model_raw; model_raw="$(parse_frontmatter "$agent" model)"
local mode_raw; mode_raw="$(parse_frontmatter "$agent" mode)"
local caps; caps="$(parse_capabilities "$agent")"
local desc; desc="$(_oc_flatten_description "$agent")"
local model_out; model_out="$(oc_model_to_provider "$model_raw")"
local mode_out="${mode_raw:-subagent}"
# Build a unique permission list
local perms=""
for cap in $caps; do
local p; p="$(oc_capability_to_permission "$cap")"
[[ -z "$p" ]] && continue
# Dedupe: skip if already in $perms (space-delimited)
case " $perms " in
*" $p "*) ;;
*) perms="$perms $p" ;;
esac
done
perms="${perms# }"
local out_file="$out_dir/$(basename "$agent")"
{
echo "---"
echo "description: \"$desc\""
echo "mode: $mode_out"
echo "model: $model_out"
if [[ -z "$perms" ]]; then
echo "permission: {}"
else
echo "permission:"
for p in $perms; do
echo " $p: allow"
done
fi
echo "---"
echo ""
agent_body "$agent"
} > "$out_file"
done < <(enumerate_agents "$src")
}
# _oc_hook_registry_json <source_hooks_dir>
# Emits a JSON array literal representing the hook registry, suitable for
# substituting into the plugin template. Each entry: {name, script, triggers: [{event, matchTool}]}.
# Script paths are stored as "../hooks/<basename>" so the plugin (at .opencode/plugins/)
# can reach .opencode/hooks/ at runtime via __dirname + path join.
_oc_hook_registry_json() {
local src="$1"
local entries='[]'
while IFS= read -r yaml; do
[[ -f "$yaml" ]] || continue
should_include "$yaml" "$FRAMEWORK" || continue
local meta; meta="$(parse_hook_yaml "$yaml")"
local name; name="$(echo "$meta" | grep '^name=' | head -1 | cut -d= -f2-)"
local script; script="$(echo "$meta" | grep '^script=' | head -1 | cut -d= -f2-)"
local event; event="$(echo "$meta" | grep '^event=' | head -1 | cut -d= -f2-)"
local match_tool; match_tool="$(echo "$meta" | grep '^match-tool=' | head -1 | cut -d= -f2- || true)"
local oc_event; oc_event="$(oc_event_to_native "$event")"
# Build the matchTool JSON array (empty array if no filter)
local match_json='[]'
if [[ -n "$match_tool" ]]; then
match_json="$(echo "$match_tool" | jq -R 'split(" ") | map(select(length > 0))')"
fi
# Use ../hooks/<script> so the plugin at .opencode/plugins/ can resolve
# its sibling .opencode/hooks/ directory at runtime.
local script_rel="../hooks/$script"
entries="$(echo "$entries" | jq \
--arg name "$name" \
--arg script "$script_rel" \
--arg event "$oc_event" \
--argjson match "$match_json" \
'. += [{name: $name, script: $script, triggers: [{event: $event, matchTool: $match}]}]')"
done < <(enumerate_hooks "$src")
echo "$entries"
}
# adapter_translate_hooks <source_hooks_dir> <dest_root>
# Copies each hook's .sh script to dst/.opencode/hooks/ and generates a single
# dst/.opencode/plugins/mbifc-hooks.js plugin containing the vendored bash
# executor plus a hook registry synthesised from the source .hook.yaml files.
adapter_translate_hooks() {
local src="$1" dst="$2"
[[ -d "$src" ]] || return 0
local hooks_out="$dst/.opencode/hooks"
local plugins_out="$dst/.opencode/plugins"
mkdir -p "$hooks_out" "$plugins_out"
# Copy every referenced .sh script
local have_any=0
while IFS= read -r yaml; do
[[ -f "$yaml" ]] || continue
should_include "$yaml" "$FRAMEWORK" || continue
local meta; meta="$(parse_hook_yaml "$yaml")"
local script; script="$(echo "$meta" | grep '^script=' | head -1 | cut -d= -f2-)"
[[ -f "$src/$script" ]] || continue
cp "$src/$script" "$hooks_out/$script"
chmod +x "$hooks_out/$script"
have_any=1
done < <(enumerate_hooks "$src")
# If there were no hooks, skip plugin generation and clean up the empty dirs
if [[ $have_any -eq 0 ]]; then
rmdir "$hooks_out" "$plugins_out" 2>/dev/null || true
return 0
fi
# Load templates
local tpl_dir; tpl_dir="$(dirname "${BASH_SOURCE[0]}")/templates"
# Build the registry JSON
local registry; registry="$(_oc_hook_registry_json "$src")"
# Pretty-print registry (2-space indent)
local registry_pretty; registry_pretty="$(echo "$registry" | jq '.')"
# Use python3 to substitute placeholders — avoids awk/sed issues with
# multi-line JS content containing backslashes and ampersands.
local out="$plugins_out/mbifc-hooks.js"
local executor_file="$tpl_dir/bash-executor.js"
local stub_file="$tpl_dir/plugin-stub.js.tmpl"
python3 - "$stub_file" "$executor_file" "$out" "$registry_pretty" <<'PYEOF'
import sys
stub_path, executor_path, out_path, registry = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
with open(stub_path, 'r') as f:
content = f.read()
with open(executor_path, 'r') as f:
executor = f.read()
content = content.replace('__BASH_EXECUTOR__', executor)
content = content.replace('__HOOK_REGISTRY__', registry)
with open(out_path, 'w') as f:
f.write(content)
PYEOF
}
# adapter_translate_mcp <source_mcp_dir> <dest_root>
# Reads mcp/servers.yaml and writes dst/opencode.json with a top-level "mcp" key.
# Local servers → {type: "local", command: "<joined>", environment: {}}
# HTTP servers → {type: "remote", url: "..."}
adapter_translate_mcp() {
local src="$1" dst="$2"
local yaml="$src/servers.yaml"
[[ -f "$yaml" ]] || return 0
mkdir -p "$dst"
local out="$dst/opencode.json"
local json='{}'
local current_name="" current_cmd="" current_url="" current_type=""
_oc_flush_current() {
[[ -z "$current_name" ]] && return 0
if [[ "$current_type" == "local" || -n "$current_cmd" ]]; then
local cmd_str="${current_cmd// / }"
json="$(echo "$json" | jq --arg n "$current_name" --arg c "$cmd_str" \
'.[$n] = {type: "local", command: $c, environment: {}}')"
else
json="$(echo "$json" | jq --arg n "$current_name" --arg u "$current_url" \
'.[$n] = {type: "remote", url: $u}')"
fi
}
while IFS= read -r line; do
case "$line" in
*"- name:"*)
_oc_flush_current
current_name="$(echo "$line" | sed 's/.*- name:[[:space:]]*//' | tr -d '"')"
current_cmd=""
current_url=""
current_type=""
;;
*"type:"*)
current_type="$(echo "$line" | sed 's/.*type:[[:space:]]*//' | tr -d '"')"
# Opencode uses "remote" for HTTP; normalise the source "http" → "remote"
[[ "$current_type" == "http" ]] && current_type="remote"
;;
*"command:"*"["*)
current_cmd="$(echo "$line" | sed 's/.*command:[[:space:]]*\[//' | sed 's/\][[:space:]]*$//' | tr -d '"' | sed 's/,[[:space:]]*/ /g')"
;;
*"url:"*)
current_url="$(echo "$line" | sed 's/.*url:[[:space:]]*//' | tr -d '"')"
;;
esac
done < "$yaml"
_oc_flush_current
echo "$json" | jq '{mcp: .}' > "$out"
}
# adapter_finalize <source_root> <dest_root>
# Opencode has no per-framework manifest file; placeholder for future additions.
adapter_finalize() {
local src="$1" dst="$2"
return 0
}
# adapter_build <source_dir> <dest_dir>
# The single entry point invoked by scripts/build.sh.
adapter_build() {
local src="$1" dst="$2"
rm -rf "$dst"
mkdir -p "$dst"
adapter_translate_dispatcher "$src/DISPATCHER.md" "$dst"
adapter_translate_references "$src/references" "$dst"
adapter_translate_skills "$src/skills" "$dst"
adapter_translate_agents "$src/agents" "$dst"
adapter_translate_hooks "$src/hooks" "$dst"
adapter_translate_mcp "$src/mcp" "$dst"
adapter_finalize "$src" "$dst"
}

View File

@@ -0,0 +1,43 @@
// =============================================================================
// bash-executor.js — Spawn a bash script and pipe neutral JSON context to stdin
// =============================================================================
// This file is vendored verbatim into the generated mbifc-hooks.js plugin at
// build time. It must not require any npm modules beyond Node.js builtins so
// that opencode's embedded runtime can execute it without installation.
// =============================================================================
const { spawn } = require("node:child_process");
/**
* Run a bash script with a JSON payload on stdin.
*
* @param {string} scriptPath Absolute path to the .sh file.
* @param {object} payload Neutral-schema object to pipe in as JSON.
* @param {object} [env] Extra environment variables (merged with process.env).
* @returns {Promise<{exitCode:number, stdout:string, stderr:string}>}
*/
function runBashHook(scriptPath, payload, env = {}) {
return new Promise((resolve, reject) => {
const child = spawn("bash", [scriptPath], {
env: { ...process.env, ...env },
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
child.stdout.on("data", (d) => { stdout += d.toString(); });
child.stderr.on("data", (d) => { stderr += d.toString(); });
child.on("error", reject);
child.on("close", (exitCode) => {
resolve({ exitCode: exitCode ?? 0, stdout, stderr });
});
try {
child.stdin.write(JSON.stringify(payload));
child.stdin.end();
} catch (err) {
reject(err);
}
});
}
module.exports = { runBashHook };

View File

@@ -0,0 +1,88 @@
// =============================================================================
// Generated by adapters/opencode/adapter.sh — do not edit.
// mbifc-hooks.js — opencode plugin that dispatches events to bash hook scripts
// =============================================================================
// This file is generated at build time. It contains a vendored bash executor
// (from adapters/opencode/templates/bash-executor.js) and a hook registry
// synthesised from the source hooks/*.hook.yaml files.
// =============================================================================
// ── bash-executor.js (vendored) ─────────────────────────────────────────────
__BASH_EXECUTOR__
// ── Hook registry (generated) ───────────────────────────────────────────────
const HOOKS = __HOOK_REGISTRY__;
// ── Helpers ─────────────────────────────────────────────────────────────────
/**
* Build the neutral JSON payload from an opencode event context.
* The opencode event shapes vary per event; we extract the common fields and
* leave everything else under `args`.
*/
function buildPayload(eventName, input) {
const tool = (input && (input.tool || input.toolName)) || "";
const args =
(input && (input.args || input.toolInput || input.input)) ||
(input && input.title !== undefined ? { title: input.title, message: input.message } : {}) ||
{};
const neutralEvent = (() => {
switch (eventName) {
case "tool.execute.before": return "before-tool-use";
case "tool.execute.after": return "after-tool-use";
case "session.idle": return "on-notification";
case "session.created": return "on-session-start";
case "tui.prompt.append": return "on-prompt-submit";
default: return eventName;
}
})();
return {
event: neutralEvent,
tool,
args,
session_id: (input && input.sessionId) || "",
cwd: (input && input.cwd) || process.cwd(),
framework: "opencode",
};
}
/**
* Check whether a hook's match-tool filter (if any) matches the current tool.
*/
function matchesTool(hook, tool) {
const m = hook.matchTool;
if (!m || m.length === 0) return true;
return m.includes((tool || "").toLowerCase());
}
// ── Plugin entry point ──────────────────────────────────────────────────────
module.exports = async function mbifcHooksPlugin({ app, client }) {
// Group hooks by opencode event name
const byEvent = {};
for (const h of HOOKS) {
for (const trig of h.triggers) {
(byEvent[trig.event] ||= []).push({ ...h, matchTool: trig.matchTool });
}
}
// Register one handler per opencode event; dispatch to matching hooks.
const handlers = {};
for (const [event, hooks] of Object.entries(byEvent)) {
handlers[event] = async (input, output) => {
const payload = buildPayload(event, { ...input, ...output });
for (const h of hooks) {
if (!matchesTool(h, payload.tool)) continue;
const path = require("node:path");
const scriptAbs = path.isAbsolute(h.script)
? h.script
: path.join(__dirname, h.script);
const { exitCode, stderr } = await runBashHook(scriptAbs, payload);
if (exitCode === 2) {
// Documented opencode block mechanism for tool.execute.before
throw new Error(`[${h.name}] blocked: ${stderr.trim() || "exit 2"}`);
}
}
};
}
return handlers;
};

View File

@@ -90,14 +90,39 @@ bash "$SCRIPT_DIR/build.sh" --framework "$FRAMEWORK"
DIST_DIR="$REPO_DIR/dist/$FRAMEWORK"
[[ -d "$DIST_DIR" ]] || die "Build did not produce $DIST_DIR"
# ── Framework-specific install layout ────────────────────────────────────────
case "$FRAMEWORK" in
claude-code)
DIST_COMPONENTS_DIR="$DIST_DIR/.claude"
VAULT_COMPONENTS_DIR="$VAULT_DIR/.claude"
DISPATCHER_SRC="$DIST_DIR/CLAUDE.md"
DISPATCHER_DST="$VAULT_DIR/CLAUDE.md"
MCP_SRC="$DIST_DIR/.mcp.json"
MCP_DST="$VAULT_DIR/.mcp.json"
HAS_PLUGINS=0
;;
opencode)
DIST_COMPONENTS_DIR="$DIST_DIR/.opencode"
VAULT_COMPONENTS_DIR="$VAULT_DIR/.opencode"
DISPATCHER_SRC="$DIST_DIR/AGENTS.md"
DISPATCHER_DST="$VAULT_DIR/AGENTS.md"
MCP_SRC="$DIST_DIR/opencode.json"
MCP_DST="$VAULT_DIR/opencode.json"
HAS_PLUGINS=1
;;
*)
die "Unknown framework: $FRAMEWORK (install layout not defined)"
;;
esac
# ── Migrate legacy manifests (if any) ────────────────────────────────────────
manifest_migrate
# ── Deprecate agents/refs removed from repo (reinstall only) ─────────────────
DEP_COUNT=0
if [[ $EXISTING -eq 1 ]]; then
DEP_COUNT=$(deprecate_removed "agents" "$DIST_DIR/.claude/agents" "$VAULT_DIR/.claude/agents")
DEP_COUNT=$((DEP_COUNT + $(deprecate_removed "references" "$DIST_DIR/.claude/references" "$VAULT_DIR/.claude/references")))
DEP_COUNT=$(deprecate_removed "agents" "$DIST_COMPONENTS_DIR/agents" "$VAULT_COMPONENTS_DIR/agents")
DEP_COUNT=$((DEP_COUNT + $(deprecate_removed "references" "$DIST_COMPONENTS_DIR/references" "$VAULT_COMPONENTS_DIR/references")))
fi
# ── Ensure vault support dirs ─────────────────────────────────────────────────
@@ -105,19 +130,19 @@ mkdir -p "$VAULT_DIR/Meta/states"
# ── Install components ────────────────────────────────────────────────────────
info "Installing agents..."
AGENT_COUNT=$(install_agents "$DIST_DIR/.claude/agents" "$VAULT_DIR/.claude/agents")
AGENT_COUNT=$(install_agents "$DIST_COMPONENTS_DIR/agents" "$VAULT_COMPONENTS_DIR/agents")
success "Agents: $AGENT_COUNT installed/updated"
info "Installing references..."
REF_COUNT=$(install_refs "$DIST_DIR/.claude/references" "$VAULT_DIR/.claude/references")
REF_COUNT=$(install_refs "$DIST_COMPONENTS_DIR/references" "$VAULT_COMPONENTS_DIR/references")
success "References: $REF_COUNT installed/updated"
info "Installing skills..."
SKILL_COUNT=$(install_skills "$DIST_DIR/.claude/skills" "$VAULT_DIR/.claude/skills")
SKILL_COUNT=$(install_skills "$DIST_COMPONENTS_DIR/skills" "$VAULT_COMPONENTS_DIR/skills")
success "Skills: $SKILL_COUNT installed/updated"
info "Installing hooks..."
HOOK_COUNT=$(install_hooks "$DIST_DIR/.claude/hooks" "$VAULT_DIR/.claude/hooks")
HOOK_COUNT=$(install_hooks "$DIST_COMPONENTS_DIR/hooks" "$VAULT_COMPONENTS_DIR/hooks")
success "Hooks: $HOOK_COUNT installed/updated"
# ── Deprecate stale orchestra scripts on reinstall ──────────────────────────
@@ -158,10 +183,23 @@ fi
install_settings "$DIST_DIR/.claude/settings.json" "$VAULT_DIR/.claude"
install_dispatcher "$DIST_DIR/CLAUDE.md" "$VAULT_DIR/CLAUDE.md"
PLUGIN_COUNT=0
if [[ $HAS_PLUGINS -eq 1 && -d "$DIST_COMPONENTS_DIR/plugins" ]]; then
info "Installing plugins..."
PLUGIN_COUNT=$(install_plugins "$DIST_COMPONENTS_DIR/plugins" "$VAULT_COMPONENTS_DIR/plugins")
success "Plugins: $PLUGIN_COUNT installed/updated"
fi
# ── MCP servers ───────────────────────────────────────────────────────────────
if [[ -f "$DIST_DIR/.mcp.json" ]]; then
copy_if_changed "$DIST_DIR/.mcp.json" "$VAULT_DIR/.mcp.json"
# settings.json only exists for claude-code (hook config lives in the JS plugin on opencode)
if [[ -f "$DIST_COMPONENTS_DIR/settings.json" ]]; then
install_settings "$DIST_COMPONENTS_DIR/settings.json" "$VAULT_COMPONENTS_DIR"
fi
install_dispatcher "$DISPATCHER_SRC" "$DISPATCHER_DST"
# ── MCP / opencode.json ───────────────────────────────────────────────────────
if [[ -f "$MCP_SRC" ]]; then
copy_if_changed "$MCP_SRC" "$MCP_DST"
fi
# ── Done ──────────────────────────────────────────────────────────────────────

View File

@@ -376,6 +376,30 @@ install_hooks() {
printf '%d' "$count"
}
# install_plugins <src_dir> <dst_dir>
# Copies *.js plugin files from src to dst. Mirrors install_hooks but for
# opencode plugins (the opencode framework expects JavaScript files under
# .opencode/plugins/). Tracked in the manifest under key "plugins".
install_plugins() {
local src_dir="$1" dst_dir="$2"
local count=0 manifest=()
[[ -d "$src_dir" ]] || { printf '0'; return 0; }
mkdir -p "$dst_dir"
for src in "$src_dir/"*.js; do
[[ -f "$src" ]] || continue
local name; name="$(basename "$src")"
local dst="$dst_dir/$name"
manifest+=("$name")
copy_if_changed "$src" "$dst"
if [[ $_LAST_CHANGED -eq 1 ]]; then
[[ $VERBOSE_COPY -eq 1 ]] && info "Updated plugin: $name" || true
count=$((count + 1))
fi
done
manifest_write "plugins" "${manifest[@]}"
printf '%d' "$count"
}
# install_settings <src_json> <dst_dir>
# Always syncs settings.json from src to dst when they differ.
# Creates a .bak of the previous version so users can recover custom entries.

View File

@@ -37,8 +37,13 @@ done
print_banner "Update "
# ── Check vault has been set up ───────────────────────────────────────────────
[[ -d "$VAULT_DIR/.claude/agents" ]] \
|| die "No .claude/agents/ found in $VAULT_DIR — run launchme.sh first"
case "$FRAMEWORK" in
claude-code) _SETUP_CHECK="$VAULT_DIR/.claude/agents" ;;
opencode) _SETUP_CHECK="$VAULT_DIR/.opencode/agents" ;;
*) _SETUP_CHECK="$VAULT_DIR/.claude/agents" ;;
esac
[[ -d "$_SETUP_CHECK" ]] \
|| die "No agents/ found in $VAULT_DIR for framework '$FRAMEWORK' — run launchme.sh first"
# ── Confirm ───────────────────────────────────────────────────────────────────
echo -e "${BOLD}This will update core agents, skills, references, hooks, and CLAUDE.md.${NC}"
@@ -60,12 +65,37 @@ bash "$SCRIPT_DIR/build.sh" --framework "$FRAMEWORK"
DIST_DIR="$REPO_DIR/dist/$FRAMEWORK"
[[ -d "$DIST_DIR" ]] || die "Build did not produce $DIST_DIR"
# ── Framework-specific install layout ────────────────────────────────────────
case "$FRAMEWORK" in
claude-code)
DIST_COMPONENTS_DIR="$DIST_DIR/.claude"
VAULT_COMPONENTS_DIR="$VAULT_DIR/.claude"
DISPATCHER_SRC="$DIST_DIR/CLAUDE.md"
DISPATCHER_DST="$VAULT_DIR/CLAUDE.md"
MCP_SRC="$DIST_DIR/.mcp.json"
MCP_DST="$VAULT_DIR/.mcp.json"
HAS_PLUGINS=0
;;
opencode)
DIST_COMPONENTS_DIR="$DIST_DIR/.opencode"
VAULT_COMPONENTS_DIR="$VAULT_DIR/.opencode"
DISPATCHER_SRC="$DIST_DIR/AGENTS.md"
DISPATCHER_DST="$VAULT_DIR/AGENTS.md"
MCP_SRC="$DIST_DIR/opencode.json"
MCP_DST="$VAULT_DIR/opencode.json"
HAS_PLUGINS=1
;;
*)
die "Unknown framework: $FRAMEWORK (install layout not defined)"
;;
esac
# ── Migrate legacy manifests (if any) ────────────────────────────────────────
manifest_migrate
# ── Deprecate agents/refs removed from repo ──────────────────────────────────
DEP_COUNT=$(deprecate_removed "agents" "$DIST_DIR/.claude/agents" "$VAULT_DIR/.claude/agents")
DEP_COUNT=$((DEP_COUNT + $(deprecate_removed "references" "$DIST_DIR/.claude/references" "$VAULT_DIR/.claude/references")))
DEP_COUNT=$(deprecate_removed "agents" "$DIST_COMPONENTS_DIR/agents" "$VAULT_COMPONENTS_DIR/agents")
DEP_COUNT=$((DEP_COUNT + $(deprecate_removed "references" "$DIST_COMPONENTS_DIR/references" "$VAULT_COMPONENTS_DIR/references")))
# ── Ensure vault support dirs ─────────────────────────────────────────────────
mkdir -p "$VAULT_DIR/Meta/states"
@@ -73,33 +103,43 @@ mkdir -p "$VAULT_DIR/Meta/states"
# ── Update components (per-file logging enabled) ─────────────────────────────
VERBOSE_COPY=1
AGENT_COUNT=$(install_agents "$DIST_DIR/.claude/agents" "$VAULT_DIR/.claude/agents")
REF_COUNT=$(install_refs "$DIST_DIR/.claude/references" "$VAULT_DIR/.claude/references")
SKILL_COUNT=$(install_skills "$DIST_DIR/.claude/skills" "$VAULT_DIR/.claude/skills")
HOOK_COUNT=$(install_hooks "$DIST_DIR/.claude/hooks" "$VAULT_DIR/.claude/hooks")
AGENT_COUNT=$(install_agents "$DIST_COMPONENTS_DIR/agents" "$VAULT_COMPONENTS_DIR/agents")
REF_COUNT=$(install_refs "$DIST_COMPONENTS_DIR/references" "$VAULT_COMPONENTS_DIR/references")
SKILL_COUNT=$(install_skills "$DIST_COMPONENTS_DIR/skills" "$VAULT_COMPONENTS_DIR/skills")
HOOK_COUNT=$(install_hooks "$DIST_COMPONENTS_DIR/hooks" "$VAULT_COMPONENTS_DIR/hooks")
install_settings "$DIST_DIR/.claude/settings.json" "$VAULT_DIR/.claude"
SETTINGS_CHANGED=$_LAST_CHANGED
PLUGIN_COUNT=0
if [[ $HAS_PLUGINS -eq 1 && -d "$DIST_COMPONENTS_DIR/plugins" ]]; then
info "Installing plugins..."
PLUGIN_COUNT=$(install_plugins "$DIST_COMPONENTS_DIR/plugins" "$VAULT_COMPONENTS_DIR/plugins")
success "Plugins: $PLUGIN_COUNT installed/updated"
fi
install_dispatcher "$DIST_DIR/CLAUDE.md" "$VAULT_DIR/CLAUDE.md"
SETTINGS_CHANGED=0
if [[ -f "$DIST_COMPONENTS_DIR/settings.json" ]]; then
install_settings "$DIST_COMPONENTS_DIR/settings.json" "$VAULT_COMPONENTS_DIR"
SETTINGS_CHANGED=$_LAST_CHANGED
fi
install_dispatcher "$DISPATCHER_SRC" "$DISPATCHER_DST"
CLAUDE_MD_CHANGED=$_LAST_CHANGED
# ── MCP servers ───────────────────────────────────────────────────────────────
if [[ -f "$DIST_DIR/.mcp.json" ]]; then
copy_if_changed "$DIST_DIR/.mcp.json" "$VAULT_DIR/.mcp.json"
# ── MCP / opencode.json ───────────────────────────────────────────────────────
if [[ -f "$MCP_SRC" ]]; then
copy_if_changed "$MCP_SRC" "$MCP_DST"
fi
# ── Summary ───────────────────────────────────────────────────────────────────
echo ""
TOTAL=$((AGENT_COUNT + REF_COUNT + SKILL_COUNT + HOOK_COUNT + SETTINGS_CHANGED + CLAUDE_MD_CHANGED))
TOTAL=$((AGENT_COUNT + REF_COUNT + SKILL_COUNT + HOOK_COUNT + PLUGIN_COUNT + SETTINGS_CHANGED + CLAUDE_MD_CHANGED))
if [[ $TOTAL -eq 0 && $DEP_COUNT -eq 0 ]]; then
success "Everything is already up to date!"
else
success "Updated $AGENT_COUNT agent(s), $SKILL_COUNT skill(s), $REF_COUNT reference(s), $HOOK_COUNT hook(s)"
success "Updated $AGENT_COUNT agent(s), $SKILL_COUNT skill(s), $REF_COUNT reference(s), $HOOK_COUNT hook(s)${PLUGIN_COUNT:+, $PLUGIN_COUNT plugin(s)}"
[[ $SETTINGS_CHANGED -eq 1 ]] && info "settings.json updated (backup saved as settings.json.bak)"
[[ $CLAUDE_MD_CHANGED -eq 1 ]] && info "CLAUDE.md updated"
[[ $DEP_COUNT -gt 0 ]] && warn "$DEP_COUNT file(s) deprecated (moved to .claude/deprecated/)"
[[ $CLAUDE_MD_CHANGED -eq 1 ]] && info "Dispatcher file updated"
[[ $DEP_COUNT -gt 0 ]] && warn "$DEP_COUNT file(s) deprecated (moved to deprecated/)"
fi
echo ""
echo -e " ${DIM}Restart Claude Code to pick up the changes.${NC}"
echo -e " ${DIM}Restart $FRAMEWORK to pick up the changes.${NC}"
echo ""

View File

@@ -0,0 +1,341 @@
#!/usr/bin/env bash
# Tests for adapters/opencode/adapter.sh
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
source "$ROOT/adapters/lib.sh"
source "$ROOT/adapters/opencode/adapter.sh"
test_oc_translate_dispatcher_renames_to_agents_md() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
cat > "$src/DISPATCHER.md" <<'EOF'
# Dispatcher
Some content
EOF
adapter_translate_dispatcher "$src/DISPATCHER.md" "$dst"
local result=0
[[ -f "$dst/AGENTS.md" ]] || { echo "AGENTS.md not created"; result=1; }
[[ ! -f "$dst/CLAUDE.md" ]] || { echo "CLAUDE.md should not exist"; result=1; }
[[ "$(cat "$dst/AGENTS.md")" == "$(cat "$src/DISPATCHER.md")" ]] || { echo "content mismatch"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_translate_references_copies_md_files() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
mkdir -p "$src/references"
echo "ref1" > "$src/references/one.md"
echo "ref2" > "$src/references/two.md"
adapter_translate_references "$src/references" "$dst"
local result=0
[[ -f "$dst/.opencode/references/one.md" ]] || { echo "one.md missing"; result=1; }
[[ -f "$dst/.opencode/references/two.md" ]] || { echo "two.md missing"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_translate_skills_copies_skill_md() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
mkdir -p "$src/skills/foo" "$src/skills/bar"
cat > "$src/skills/foo/SKILL.md" <<'SKILLEOF'
---
name: foo
description: Foo skill
---
body
SKILLEOF
cat > "$src/skills/bar/SKILL.md" <<'SKILLEOF'
---
name: bar
description: Bar skill
---
body
SKILLEOF
adapter_translate_skills "$src/skills" "$dst"
local result=0
[[ -f "$dst/.opencode/skills/foo/SKILL.md" ]] || { echo "foo missing"; result=1; }
[[ -f "$dst/.opencode/skills/bar/SKILL.md" ]] || { echo "bar missing"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_translate_skills_honors_exclude() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
mkdir -p "$src/skills/foo"
cat > "$src/skills/foo/SKILL.md" <<'SKILLEOF'
---
name: foo
description: Foo
exclude: [opencode]
---
SKILLEOF
adapter_translate_skills "$src/skills" "$dst"
local result=0
[[ ! -f "$dst/.opencode/skills/foo/SKILL.md" ]] || { echo "foo should be excluded"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_translate_agents_basic() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
mkdir -p "$src/agents"
cat > "$src/agents/scribe.md" <<'EOF'
---
name: scribe
description: Test scribe
model: sonnet
mode: subagent
capabilities: [read, write, edit]
---
You are the Scribe.
EOF
adapter_translate_agents "$src/agents" "$dst"
local out="$dst/.opencode/agents/scribe.md"
local result=0
[[ -f "$out" ]] || { echo "agent file missing"; result=1; }
grep -q '^description: "Test scribe"' "$out" || { echo "description missing or wrong quoting"; cat "$out"; result=1; }
grep -q '^mode: subagent' "$out" || { echo "mode missing"; result=1; }
grep -q '^model: anthropic/claude-sonnet-4-5' "$out" || { echo "model not mapped"; result=1; }
grep -q '^permission:' "$out" || { echo "permission block missing"; result=1; }
grep -q '^ edit: allow' "$out" || { echo "edit permission missing"; result=1; }
grep -q '^You are the Scribe' "$out" || { echo "body missing"; result=1; }
grep -q '^name:' "$out" && { echo "name: should be dropped"; result=1; }
grep -q '^capabilities:' "$out" && { echo "capabilities: should be dropped"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_translate_agents_bash_capability() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
mkdir -p "$src/agents"
cat > "$src/agents/architect.md" <<'EOF'
---
name: architect
description: Test arch
model: opus
capabilities: [read, write, edit, bash]
---
body
EOF
adapter_translate_agents "$src/agents" "$dst"
local out="$dst/.opencode/agents/architect.md"
local result=0
grep -q '^ edit: allow' "$out" || { echo "edit missing"; result=1; }
grep -q '^ bash: allow' "$out" || { echo "bash missing"; result=1; }
grep -q '^model: anthropic/claude-opus-4-5' "$out" || { echo "model not mapped"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_translate_agents_read_only_emits_empty_permission() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
mkdir -p "$src/agents"
cat > "$src/agents/seeker.md" <<'EOF'
---
name: seeker
description: Search only
model: sonnet
capabilities: [read]
---
body
EOF
adapter_translate_agents "$src/agents" "$dst"
local out="$dst/.opencode/agents/seeker.md"
local result=0
grep -q '^permission: {}' "$out" || { echo "expected 'permission: {}'"; cat "$out"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_translate_agents_dedupes_edit() {
# write+edit both map to "edit: allow" — must appear once, not twice.
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
mkdir -p "$src/agents"
cat > "$src/agents/scribe.md" <<'EOF'
---
name: scribe
description: Dedupe test
model: sonnet
capabilities: [read, write, edit]
---
body
EOF
adapter_translate_agents "$src/agents" "$dst"
local out="$dst/.opencode/agents/scribe.md"
local count; count="$(grep -c '^ edit: allow' "$out")"
rm -rf "$src" "$dst"
[[ "$count" == "1" ]] || { echo "expected 1 edit line, got $count"; return 1; }
}
test_oc_translate_hooks_copies_scripts() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
mkdir -p "$src/hooks"
cat > "$src/hooks/protect.hook.yaml" <<'EOF'
name: protect
script: protect.sh
triggers:
- event: before-tool-use
match-tool: [edit, write]
EOF
cat > "$src/hooks/protect.sh" <<'EOF'
#!/usr/bin/env bash
exit 0
EOF
adapter_translate_hooks "$src/hooks" "$dst"
local result=0
[[ -f "$dst/.opencode/hooks/protect.sh" ]] || { echo "protect.sh not copied"; result=1; }
[[ -f "$dst/.opencode/plugins/mbifc-hooks.js" ]] || { echo "mbifc-hooks.js not generated"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_translate_hooks_registry_has_entries() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
mkdir -p "$src/hooks"
cat > "$src/hooks/protect.hook.yaml" <<'EOF'
name: protect
script: protect.sh
triggers:
- event: before-tool-use
match-tool: [edit, write]
EOF
cat > "$src/hooks/notify.hook.yaml" <<'EOF'
name: notify
script: notify.sh
triggers:
- event: on-notification
EOF
touch "$src/hooks/protect.sh" "$src/hooks/notify.sh"
adapter_translate_hooks "$src/hooks" "$dst"
local plugin="$dst/.opencode/plugins/mbifc-hooks.js"
local result=0
grep -q '"name": "protect"' "$plugin" || { echo "protect not in registry"; result=1; }
grep -q '"name": "notify"' "$plugin" || { echo "notify not in registry"; result=1; }
grep -q '"event": "tool.execute.before"' "$plugin" || { echo "tool.execute.before event missing"; result=1; }
grep -q '"event": "session.idle"' "$plugin" || { echo "session.idle event missing"; result=1; }
grep -q '"matchTool":' "$plugin" || { echo "matchTool field missing"; result=1; }
grep -q 'spawn("bash"' "$plugin" || { echo "bash-executor not inlined"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_translate_hooks_no_hooks_dir_is_noop() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
# src has no hooks/ — should not error, should not create plugin file
adapter_translate_hooks "$src/hooks" "$dst"
local result=0
[[ ! -f "$dst/.opencode/plugins/mbifc-hooks.js" ]] || { echo "plugin should not exist when no hooks"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_translate_mcp_local() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
mkdir -p "$src/mcp"
cat > "$src/mcp/servers.yaml" <<'EOF'
servers:
- name: gmail
type: local
command: [npx, -y, "@anthropic-ai/gmail-mcp"]
env: {}
EOF
adapter_translate_mcp "$src/mcp" "$dst"
local out="$dst/opencode.json"
local result=0
[[ -f "$out" ]] || { echo "opencode.json missing"; result=1; }
jq -e '.mcp.gmail.type == "local"' "$out" >/dev/null || { echo "type wrong"; cat "$out"; result=1; }
jq -e '.mcp.gmail.command | startswith("npx")' "$out" >/dev/null || { echo "command wrong"; cat "$out"; result=1; }
jq -e '.mcp.gmail.environment == {}' "$out" >/dev/null || { echo "environment key missing"; cat "$out"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_translate_mcp_remote() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
mkdir -p "$src/mcp"
cat > "$src/mcp/servers.yaml" <<'EOF'
servers:
- name: Gmail
type: http
url: "https://gmail.mcp.claude.com/mcp"
env: {}
EOF
adapter_translate_mcp "$src/mcp" "$dst"
local out="$dst/opencode.json"
local result=0
jq -e '.mcp.Gmail.type == "remote"' "$out" >/dev/null || { echo "type should be remote"; cat "$out"; result=1; }
jq -e '.mcp.Gmail.url == "https://gmail.mcp.claude.com/mcp"' "$out" >/dev/null || { echo "url wrong"; cat "$out"; result=1; }
rm -rf "$src" "$dst"
return $result
}
test_oc_adapter_build_end_to_end() {
local src; src="$(mktemp -d)"
local dst; dst="$(mktemp -d)"
# Minimal source tree
echo "# Dispatcher" > "$src/DISPATCHER.md"
mkdir -p "$src/agents" "$src/hooks" "$src/skills/onboarding" "$src/references" "$src/mcp"
cat > "$src/agents/scribe.md" <<'EOF'
---
name: scribe
description: Test scribe
model: sonnet
capabilities: [read, write, edit]
---
body
EOF
cat > "$src/hooks/protect.hook.yaml" <<'EOF'
name: protect
script: protect.sh
triggers:
- event: before-tool-use
match-tool: [edit]
EOF
echo "#!/usr/bin/env bash" > "$src/hooks/protect.sh"
cat > "$src/skills/onboarding/SKILL.md" <<'EOF'
---
name: onboarding
description: Onboarding skill
---
body
EOF
echo "reference content" > "$src/references/policy.md"
cat > "$src/mcp/servers.yaml" <<'EOF'
servers:
- name: gmail
type: local
command: [npx, -y, "@anthropic-ai/gmail-mcp"]
env: {}
EOF
adapter_build "$src" "$dst"
local result=0
[[ -f "$dst/AGENTS.md" ]] || { echo "AGENTS.md missing"; result=1; }
[[ -f "$dst/.opencode/agents/scribe.md" ]] || { echo "agent missing"; result=1; }
[[ -f "$dst/.opencode/skills/onboarding/SKILL.md" ]] || { echo "skill missing"; result=1; }
[[ -f "$dst/.opencode/references/policy.md" ]] || { echo "reference missing"; result=1; }
[[ -f "$dst/.opencode/hooks/protect.sh" ]] || { echo "hook script missing"; result=1; }
[[ -f "$dst/.opencode/plugins/mbifc-hooks.js" ]] || { echo "plugin missing"; result=1; }
[[ -f "$dst/opencode.json" ]] || { echo "opencode.json missing"; result=1; }
rm -rf "$src" "$dst"
return $result
}