Published: September 11, 2026 21 min read
Same Agents, Two Tools: How I Keep OpenCode and Claude Code in Sync
My repo runs in both OpenCode and Claude Code. A generator translates the agents, a hook restores scoped permissions, and CI fails on any drift.

Someone recently asked me how my rules and workflows stay consistent when I switch between OpenCode and Claude Code. Short answer: scripts. One generates Claude Code equivalents from my OpenCode agents, and a PR check compares the two trees byte for byte and fails on any mismatch. Wherever I can, I turn a quality gate into a deterministic script instead of a convention I have to remember. This post is the long version, with all the code, and the full files are also up as a companion repo you can drop straight into your own project.
What I mean by agent harness
Quick definition first, since the word gets thrown around loosely. By “agent harness” I mean the CLI that actually hosts a coding agent: OpenCode, Claude Code, whatever reads your agent definition files, drives the model, and executes the tool calls. The repo this post is about gets developed in both, by me and by the agents themselves.
Both tools store agents the same way underneath: a markdown file, YAML frontmatter up top, a prompt body below. Claude Code’s subagent documentation says it outright: the body becomes the system prompt. OpenCode’s agent documentation shows the same shape by example, frontmatter configures the agent, the body is its persona. That shared shape is the only reason a sync is even possible. Where the two tools actually disagree is the frontmatter.
Keeping Claude Code around at all is a deliberate choice, and the reasons are practical, in my own words: “I sometimes fall back to Claude Code for different reasons: I need speed (Claude Code is faster than the Z.AI-provided models), I need a better or different model, or I simply want to be able to onboard other developers easily.”
Two tools, one set of agent definitions. That’s the entire problem this post is about.
The problem: same prompt, incompatible frontmatter
OpenCode reads AGENTS.md and .opencode/agents/. Claude Code reads CLAUDE.md and .claude/agents/. I already had a hand-tuned .opencode/agents/ tree I had zero intention of rewriting, plus, at the time, a repo-wide rule that denied every agent git rebase, git branch, git checkout, git switch, and any force-push (one agent has since earned a narrow rebase exception). Every rule I define on one side has to exist on the other side too, or the two tools stop being interchangeable.
The schemas just don’t line up. Here’s the frontmatter of one real agent, software-engineer, on the OpenCode side (shortened):
---description: >- The ONE implementation agent. Two modes, selected by what the caller hands it: (1) implement - validate a plan, orchestrate `worker` subagents with TDD, run the phase Verify; (2) fix-apply - apply review findings minimally, then verify once.mode: alltemperature: 0.2steps: 80permission: read: allow glob: allow grep: allow edit: "*": deny ".opencode/**": allow "AGENTS.md": allow "docs/*.md": allow bash: "*": allow---And here’s what the generator produces for Claude Code from that exact same file (also shortened):
---# AUTO-GENERATED from .opencode/agents/<name>.md by .opencode/scripts/sync-agents.ts - DO NOT EDIT by hand.# Regenerate: bun run .opencode/scripts/sync-agents.tsname: "software-engineer"description: "The ONE implementation agent. ..."tools: - "Read" - "Glob" - "Grep" - "Edit" - "Write" - "Bash" - "Skill" - "mcp__context7" - "mcp__docs" - "Agent(worker, resource-scout)"disallowedTools: - "mcp__internal-ci"hooks: PreToolUse: - matcher: "Bash" hooks: - type: command command: ".claude/hooks/enforce-scope.sh bash software-engineer" - matcher: "Edit|Write" hooks: - type: command command: ".claude/hooks/enforce-scope.sh edit software-engineer"maxTurns: 80---The body under both is identical, byte for byte. Everything above it isn’t. OpenCode scopes permissions with nested maps: edit maps path globs to allow and deny, bash maps command globs the same way, and rules apply in order with the last matching rule winning. Claude Code’s subagent frontmatter only has tools and disallowedTools, flat lists of tool names. It can say “this agent may use Bash.” It can’t say “except git push --force.” OpenCode’s steps becomes Claude’s maxTurns, and temperature just has no equivalent at all.
Six agents depended on this at the time. .opencode/agents/ holds eleven today. Hand-maintaining two formats across that many files is exactly how drift starts, and drift in a permissions file isn’t a style problem, it’s a security problem.
Why code generation beat symlinks, duplication, and an MCP bridge
For plain docs I already had an answer: symlinks. The repo’s convention, verbatim: “every AGENTS.md MUST have a sibling CLAUDE.md symlink (ln -s AGENTS.md CLAUDE.md) - create in the same commit as a new AGENTS.md, delete with the file. Never edit CLAUDE.md directly (it is a symlink).” The root CLAUDE.md -> AGENTS.md symlink landed less than two weeks after the sync work itself, and by late August there were ten of these symlinks scattered across the repo. Docs are schema-free markdown, so one file can serve both readers just fine.
Agent definitions can’t work that way, though. A symlink shares the whole file, byte for byte, and you can’t prepend different YAML frontmatter through a symlink. Frontmatter is exactly the part that doesn’t match between the two tools.
Manual duplication was the default answer, and the one I liked least of all. Two copies drift, and the failure mode is quiet, nobody actually reads a permissions file until something’s already broken.
An MCP server as a bridge was the third candidate, and it fails on category alone: MCP transports tools, not agent persona config. There’s no MCP operation for “install this subagent with these permissions.”
What actually settled it was a constraint baked into Claude Code itself. The subagent frontmatter field list is closed, no include field anywhere, so the prompt body has to be inline. My design log from the sync session says it plainly: “Claude Code forces the prompt body inline (no include field), so true DRY is impossible without writing the body into both files. Codegen is the only path; the body is copied verbatim, only frontmatter is translated.”
Worth stating the asymmetry exactly, because it’s easy to get wrong: OpenCode markdown agents have no include either, but OpenCode’s JSON config does support prompt: "{file:...}". Claude Code subagent files have no include equivalent, period.
So: code generation, one direction only, OpenCode as the source of truth. The reasoning, straight from the session log: “the repo already had a hand-tuned .opencode/agents/; treating it as canonical means zero change to how agents are authored today, and the prompt body is DRY by construction.” A neutral agents-src/ schema would’ve just been churn for no benefit, and a bidirectional sync would’ve been conflict-prone for nothing gained.
The whole mechanism, end to end:
.opencode/agents/*.md opencode.jsonc (source of truth: (global permission frontmatter + body) rules for ALL agents) | | | bun run .opencode/scripts/sync-agents.ts | - translate frontmatter (MODEL_ALIAS / PERM_TO_TOOL) | - mergeRules(): global-first + security re-append v v .claude/agents/*.md .claude/hooks/rules/<agent>.json (translated frontmatter, (ordered {pattern, action} body byte-identical) globs, last-match-wins) | | | tool allow/deny lists | PreToolUse v v Claude Code <---- enforce-scope.sh (exit 0 allow / 2 deny)
CI closes the loop: regenerate + git diff --exit-code -- .claudeThe generator: translate frontmatter, copy the body verbatim
sync-agents.ts is 598 lines and pulls in zero external dependencies. It runs on Bun, which ships Bun.YAML.parse as a built-in, and it handled the real frontmatter just fine: block scalars, nested objects, quoted glob keys, comments, all of it. The one JSONC file it reads, opencode.jsonc, goes through an in-house parseJsonc() that strips comments and trailing commas before handing it to JSON.parse. And if Bun.YAML isn’t there, the script just hard-exits.
The heart of it is three translation tables:
// OpenCode `provider/model-id` → Claude alias. Extend as you adopt models.// Anything not listed emits `inherit` (with an INFO note).const MODEL_ALIAS: Record<string, string> = { "anthropic/claude-sonnet-4-20250514": "sonnet", "anthropic/claude-opus-4-1-20250805": "opus", "anthropic/claude-haiku-4-20250514": "haiku",};
// OpenCode permission key → Claude tool name(s).// OC's single `edit` perm gates write + edit + apply_patch, hence both Edit and Write.const PERM_TO_TOOL: Record<string, string[]> = { read: ["Read"], glob: ["Glob"], grep: ["Grep"], edit: ["Edit", "Write"], bash: ["Bash"], todowrite: ["TodoWrite"], webfetch: ["WebFetch"], websearch: ["WebSearch"], skill: ["Skill"],};
// Permission keys with no Claude frontmatter equivalent (skipped + INFO).const NO_EQUIV = new Set([ "list", // Claude has no dedicated List tool; Glob covers dir listing "lsp", // MCP-scoped in Claude "external_directory", // Claude scopes FS via settings additionalDirectories "question", // AskUserQuestion isn't available to subagents in Claude "doom_loop", // OpenCode recovery-prompt gating]);MODEL_ALIAS maps provider model ids over to Claude aliases, and anything not in the table emits inherit plus an INFO note telling you to go add it. PERM_TO_TOOL is where the actual schema mismatch gets patched: OpenCode’s single edit permission gates write, edit, and apply_patch all at once, so it expands out to both Edit and Write. NO_EQUIV lists the permission keys with no Claude frontmatter equivalent at all, and those get skipped with an INFO note, never silently.
There are smaller rules around the tables too. Only an active steps value maps to maxTurns, deliberately ignoring OpenCode’s leading-dot disabled-key convention. A server_* permission key only emits an mcp__<server> tool if that server actually exists in opencode.jsonc’s mcp block, because OpenCode custom tools use that same server_ prefix shape and shouldn’t turn into phantom MCP tools. And nested task allowlists become Claude’s Agent(name, ...) tool syntax.
The security finding the first review caught
The sync was built and reviewed through my own agent pipeline, and that matters here: the finding that actually shaped the generator came out of a code review, iteration one, Must severity, tagged F-FAITH-1. opencode.jsonc carries global permission rules that get merged into every agent, secret-read denies included, and the translation was silently dropping them. Under last-match-wins, an agent’s broad "*": allow overrode those global denies, and the hook had no read mode at all, so generated agents could freely Read secret paths.
The fix came in two halves. The generator now parses the global permission block, merges it into every agent’s hook rules, and at the time also emitted a Read PreToolUse hook for every agent. The merge order needed real care, though: a plain global-first concat still failed its own verification, because the broad "*": allow still overrode the global denies while an explicit agent override like git commit still needed to win. The fix, verbatim from the session log: “Re-appending non-overlapping global rules at the tail keeps secrets protected AND preserves exact-pattern agent overrides.”
That’s what mergeRules() does:
// Merge GLOBAL + agent rules, global-first. A naive [global, ...agent] concat// would let a broad agent catch-all (e.g. "*": allow) silently drop GLOBAL// defense-in-depth denies the agent never re-asserts (e.g. "cat .env*": deny).// So non-overlapping global rules are RE-APPENDED at the END - last-match-wins// then guarantees a global rule the agent didn't explicitly override still// sticks, while patterns the agent DID re-assert (e.g. "git commit": deny) are// excluded from the re-append so the explicit override survives.function mergeRules( globalRules: ScopeRule[], agentRules: ScopeRule[],): ScopeRule[] { if (!globalRules.length) return agentRules; if (!agentRules.length) return globalRules; const agentPats = new Set(agentRules.map((r) => r.pattern)); const reassert = globalRules.filter((g) => !agentPats.has(g.pattern)); return [...globalRules, ...agentRules, ...reassert];}Iteration two of the review came back completely clean, zero findings. One thing’s changed since: opencode.jsonc no longer carries that nested global read deny. Secret reads get blocked now by a gitignore-based guard plus OpenCode’s own built-in default that still denies *.env on the read tool, so the generated files today carry no Read matcher at all.
Before any of it landed, the whole mechanism got a proper verification pass. --dry-run re-runs byte-identical, so regeneration is idempotent. A hook matrix exercised every deny path: secret reads exit 2 for every agent including the read-only scout, force-push exits 2, benign reads and builds exit 0, and fail-closed mode plus malformed JSON exits 2 while the default fail-open posture just lets it through. All six generated frontmatters parsed as valid YAML, and the prompt bodies came out byte-identical to their OpenCode sources, 3.6 to 15 KB each.
Stale cleanup and known losses
Regeneration can’t be allowed to eat hand-written files, so cleanup is marker-based. Every generated file contains GEN_MARKER (AUTO-GENERATED from .opencode/agents/), and only files carrying that marker get deleted from .claude/agents/. The rules directory is generated-only, so that one gets wiped wholesale, which means a removed or renamed agent never leaves an orphan rule file the hook would still load.
// Clean only previously-generated files (marker-based) so hand-written ones survive.let cleaned = 0;if (!dryRun) { for (const f of (await readdir(DST)).filter((f) => f.endsWith(".md"))) { const content = await readFile(join(DST, f), "utf8"); if (content.includes(GEN_MARKER)) { await rm(join(DST, f)); cleaned++; } } // RULES_DIR is a dedicated generated dir - wipe stale *.json so removed/renamed // agents don't leave orphan rule files that enforce-scope.sh would still load. for (const f of (await readdir(RULES_DIR)).filter((f) => f.endsWith(".json"), )) { await rm(join(RULES_DIR, f)); cleaned++; }}Some things just don’t survive the translation, and the generator says so out loud rather than pretending otherwise. ask becomes allow, since a PreToolUse hook can’t interactively prompt anyone. temperature gets dropped entirely, there’s no equivalent. Agent(...) allowlists only get honored on the claude --agent main thread; in subagent context the type list is just ignored (a SubagentStart hook would restore it, I just haven’t needed one yet). And inherited over-grants get translated faithfully, warts and all: a force-ref evades the force-push denies, an over-broad gh api * passes right through. Those originate in the OpenCode source rules, though, so fixing them belongs in .opencode/agents/*, not in the generator.
The whole thing landed in a single day, 2026-07-01: 17 files, 4,051 insertions, covering the generator, the hook, six generated agents, six rule files, the workflow, and the session log. Force-push and rebase are denied repo-wide, so it reached master through a fresh branch and a cherry-pick instead of a rebase. A couple of follow-ups came later: a mass regeneration after some generator tweaks, and the absolute-path fix described below.
Restoring scoped permissions with a PreToolUse hook
Translating nested permission maps down to flat tool lists loses the scoping entirely. OpenCode can express bash: {"git push --force*": deny} and edit: {"docs/**": allow}; Claude’s tools and disallowedTools just can’t. The session log named the consequence plainly: “Without hooks, generated agents are broadly over-permissioned (blast-radius regression).” I offered the fix in the PR summary. The reply was “do it.”
The fix is enforce-scope.sh, 157 lines living at .claude/hooks/enforce-scope.sh. Each generated agent’s frontmatter wires it into PreToolUse for Bash and Edit|Write, passing along a mode and the agent name. It reads that agent’s rules file, one JSON per agent, and re-applies the original OpenCode rules at runtime. The exit-code contract is Claude’s own: 0 lets the call through, 2 blocks it and shows stderr straight to the model.
#!/usr/bin/env bash# enforce-scope.sh - PreToolUse hook for generated Claude subagents.# ...# Usage (Claude Code pipes the tool-call JSON on stdin):# enforce-scope.sh <bash|edit|read> <agent-name>## Exit codes (Claude Code PreToolUse contract):# 0 allow / no-match / ask(→allow) - tool call proceeds# 2 deny - Claude blocks the call AND shows stderr## Fail posture: this hook FAILS OPEN by default - a malfunction (malformed JSON,# missing rules file, parse error, no-match) → exit 0, i.e. the call proceeds.# Security implication: a broken hook silently WIDENS permissions vs OpenCode# intent (e.g. a deleted rules file would let every denied path through). This# is a usability trade-off: a misconfigured hook should not lock out all tool# use. Set ENFORCE_SCOPE_FAIL_CLOSED=1 to flip to fail-closed - malfunction /# no-match / missing-rules → exit 2 (block).One rule set per agent, ordered for last-match-wins. Here’s the software-engineer’s, simplified:
{ "bash": [ { "pattern": "ls *", "action": "allow" }, { "pattern": "rg *", "action": "allow" }, { "pattern": "git commit", "action": "allow" }, { "pattern": "*", "action": "allow" }, { "pattern": "git push --force*", "action": "deny" }, { "pattern": "git push * --force*", "action": "deny" }, { "pattern": "git checkout*", "action": "deny" }, { "pattern": "git branch -D*", "action": "deny" }, { "pattern": "gh run *", "action": "deny" } ], "edit": [ { "pattern": "*", "action": "deny" }, { "pattern": ".opencode/**", "action": "allow" }, { "pattern": "AGENTS.md", "action": "allow" }, { "pattern": "docs/*.md", "action": "allow" } ]}The ordering is the whole mechanism, and it does double duty. The denies sitting after the agent’s own "*": allow are the agent’s own rules, placed deliberately so last-match-wins makes them stick. And in the real file, which runs much longer than this simplified version, the generator’s re-appended global rules come after everything else, so any global rule the agent never re-asserted still gets the last word.
Matching follows OpenCode’s own semantics: ** collapses down to *, and in bash’s [[ == ]] pattern test * spans directory separators too. jq handles the stdin JSON by preference, with a python3 fallback if it’s missing.
About that fail posture, since it’s the part I’d get called out for hiding if I didn’t say it myself: the hook fails open by default. Malformed JSON, a missing rules file, a parse error, or just no match at all, every one of those exits 0 and the call proceeds anyway. The header states the security implication outright: a broken hook silently widens permissions. That’s a deliberate trade-off on my part, a misconfigured hook shouldn’t lock the agent out of all tool use entirely. Set ENFORCE_SCOPE_FAIL_CLOSED=1 and every malfunction, missing rules file, and no-match flips to exit 2 instead.
One real bug came straight out of a runtime difference between the two tools. Edit and read rules are repo-relative globs, matching OpenCode’s own semantics, but Claude Code always resolves file_path to an absolute path before the hook ever sees it. Without stripping the repo root prefix off first, every relative allow-rule was silently falling through to the broader "*" deny. Here’s the normalization from the 2026-09-05 follow-up:
# edit/read rule patterns (e.g. "docs/reviews/**") are repo-relative, matching# OpenCode's own semantics - but Claude Code always resolves file_path to an# ABSOLUTE path before this hook sees it, so a relative pattern could never# match without this normalization (every relative allow-rule would silently# fall through to the broader "*" deny). bash's $FIELD is a command string,# not a path, so it's left untouched.if [[ "$MODE" == "edit" || "$MODE" == "read" ]]; then REPO_ROOT="$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel 2>/dev/null)" if [[ -n "$REPO_ROOT" && "$VALUE" == "$REPO_ROOT"/* ]]; then VALUE="${VALUE#"$REPO_ROOT"/}" fifiThe deterministic check: CI regenerates and diffs
This is the actually deterministic part: no convention to remember, just bytes compared.
There’s no git hook, and that’s a decision I made on purpose, recorded at the time: my instruction while building this was “create a script but with no githook.” Regeneration is a manual command, bun run .opencode/scripts/sync-agents.ts, and every generated file carries the DO-NOT-EDIT marker plus the regenerate command right in its first two lines, so drift is visible to anyone who opens the file.
Enforcement lives in CI instead. The agents-sync job just regenerates and diffs:
# Whitespace-safe: .gitattributes forces LF across .claude + .opencode, so byte-exact.- name: Regenerate Claude agents run: bun run .opencode/scripts/sync-agents.ts
- name: Fail if .claude is out of sync run: | if ! git diff --exit-code -- .claude; then echo "::error::Generated .claude/ is out of sync with .opencode/agents/. Regenerate locally and commit: bun run .opencode/scripts/sync-agents.ts" exit 1 fi echo ".claude is in sync with .opencode/agents/"If the committed .claude/ doesn’t match what the generator produces from .opencode/agents/, the job fails and the ::error:: annotation names the exact fix command right there. That job landed in the same commit as the sync itself, so the mechanism was never left unprotected, not even for a day.
The diff has to be byte-exact for any of this to work, which turns out to be a line-endings problem wearing a disguise. The repo sets eol=crlf for some Windows-typed files, *.json among them, and the rules files happen to be JSON. So .gitattributes forces text eol=lf across the source tree, the generator script, and the generated tree, and later attributes lines win over earlier ones, which is exactly the override behavior the gitattributes documentation specifies.
# OpenCode→Claude Code agent sync: the generator (.opencode/scripts/sync-agents.ts)# always writes LF. Force LF across the source (.opencode/agents) and generated# (.claude) trees so the CI drift check (git diff --exit-code .claude) is# byte-exact with no cross-platform CRLF/LF false positives. Later lines win# over the *.json eol=crlf rule above for the .claude JSON rule files..opencode/agents/** text eol=lf.opencode/scripts/sync-agents.ts text eol=lf.claude/** text eol=lfThe check also runs closer to the action than CI. My ship pipeline’s pre-PR gate (step 4c) instructs the delegated agent to regenerate .claude/ and, if anything changed, commit and push it, before the draft PR is created with gh pr create --draft. There’s a local mirror in scripts/fast-checks.sh. I’ll cover that pipeline itself in a future post.
The check’s firing record turns out to be short, and honestly my first memory of it was just wrong: there are no documented CI failures. What the record actually shows is one near-miss, 2026-07-25, a .claude/ scope-rule drift that got caught by the local pre-PR gate before the PR ever went up. The session log’s own words: “the agents-sync-check CI job would have failed without it. Lesson: even when the three test suites are green, the artifact-freshness gate is load-bearing; never skip step 4c.”
One honesty note on the current setup: the standalone CI workflow has been manual-dispatch-only since 2026-08-31. What actually runs on every change now is the per-ship run through step 4c.
The trade-offs I accepted
None of this comes free. ask degrades to allow. Agent() allowlists only bind on the main thread. The merge ends up stricter than OpenCode for pattern relaxation, which I file under benign, global denies are defense-in-depth and shouldn’t relax anyway. Inherited over-grants pass straight through unless I go fix them at the source. And the sync PR itself sat around as a draft for a while before I actually landed it.
What I get back for all that is determinism. The guardrails live in exactly one format, in one tree, and everything else is derived and compared as bytes. When Claude Code has the faster model and I fall back to it, or when a teammate onboards on Claude Code while I’m working in OpenCode, the agents actually running are the agents I tuned. And if that ever stops being true, a diff fails somewhere I’ll see it.
If you want the companion repo again, or the earlier post it builds on: how the validation feedback loops were rebuilt in OpenCode. The pipeline that runs this sync check on every ship gets its own deep dive in an upcoming post.
FAQ: keeping OpenCode and Claude Code agents in sync
Is the sync bidirectional?
No. OpenCode is the source of truth, and the generator only runs one way. I rejected bidirectional sync as conflict-prone, and a neutral intermediate schema would’ve just been churn for no real benefit.
Why is OpenCode the source of truth?
The .opencode/agents/ tree already existed and was already hand-tuned. Making it canonical meant zero change to how agents get authored, and the prompt body stays DRY by construction, it exists in exactly one place.
What happens if enforce-scope.sh breaks?
It fails open. Malformed input, a missing rules file, a parse error, any of those exit 0 and the tool call proceeds anyway, which means a broken hook silently widens permissions. Set ENFORCE_SCOPE_FAIL_CLOSED=1 and every malfunction, missing rules file, and no-match flips to exit 2 instead.
Why not a git hook that regenerates on every commit?
I turned that automation down when the sync was built, on purpose. The decision’s recorded as “create a script but with no githook.” Enforcement is deterministic where it actually counts instead: CI regenerates and diffs, and the ship pipeline runs that same check before any PR goes up.