Memory, routing, orchestration, cost — every piece in daily use, with the measurements attached.
← all explainers
· Yasaswy Nagavolu

OpenCode Obeys Your Orchestrator. Claude Code Treats It as a Suggestion. So I Built Route-Lock: Strict Mode for Claude Code.

OpenCode enforces agent routing by design; Claude Code doesn't. A forensic audit of 33 real Claude Code sessions found 15 non-compliant — so I built Route-Lock, a three-layer hook stack that makes delegation, not the model, decide the route.

ai-agentsautomationhooksdeveloper-tools

I run the same multi-agent orchestration setup in two coding-agent tools: OpenCode at work, Claude Code at home. In OpenCode it just works: every dispatch lands on the subagent and model tier I specified, every time. In Claude Code — the one I use daily, on a paid plan — it “works,” but the main agent quietly does the task itself a large fraction of the time, or spawns generic workers instead of the ones I defined. It still finishes the job. It also burns three to fifteen times the tokens doing it.

The standard advice for this is some mix of “write clearer rules,” “use hooks to hard-block the built-in fallback,” and “pin the model in each agent’s config.” All three are correct and all three are partial. The common verdict on why Claude Code stays broken here is blunter: there’s no strict orchestrator mode, and that’s by design — the main agent is model-driven, it decides when to delegate, and no amount of config changes that. I didn’t want to accept that. I wanted a number. So before changing anything I built an audit, and the audit is where this gets interesting.

Architecture: Route-Lock, in one loop

The name is Route-Lock: a message resolves a route exactly once, a lock file freezes that decision, and a dispatch-time guard enforces it — a real dispatch either matches the lock or gets denied with the exact fix named. When nothing matches, the loop doesn’t guess; it folds straight back to you in chat as UNCLASSIFIED. Click through the loop below — it runs the classified path once, then runs again to show the escape hatch firing for real:

Route-Lock
Hook Stack (Custom Skill)npx '@yasaswy.nagavolu/agents' install
STEP 1/12▸type
Σ 0 tok·$0.00Claude Sonnet 5
Route-Lock · clonable skill (forthcoming)
route
lock
verify
dispatch
review
gate
file
report
route
ask (unclassified)

Three hooks sit behind that loop, each catching what the one before it missed — none of them trust the model to route correctly on its own:

UserPromptSubmit  →  prompt-time router     resolves the route once, locks it in
        ↓
tool dispatch     →  dispatch-time guard    denies any mismatch, names the exact fix
        ↓
direct file edit  →  wall hook              blocks the main session from touching
                                             source directly while a route is active

Each layer is independent: the router can lock a route without the guard existing, the guard can deny without the wall, and the wall works even if the first two are disabled. That’s deliberate — a single misconfigured hook degrades enforcement, it doesn’t silently disable the whole stack.

Click through the build below — every stage has what I tried, what broke, and what I learned. Prose underneath fills in the detail for anyone who wants it.

Stage 0 — The pain
Tried

Ran the same multi-agent orchestration setup in OpenCode (work) and Claude Code (home).

Broke

OpenCode treated my agent definitions as control flow. Claude Code treated them as suggestions — the main loop improvised: did the work itself, or spawned generic workers instead of the ones I'd defined.

Learned

The common verdict on this is "there's no strict orchestrator mode in Claude Code, and that's by design." I wanted to test that claim instead of accepting it.

Try it yourself

The pattern doesn’t need my specific hooks — it needs three hook points Claude Code already exposes:

  1. UserPromptSubmit hook — inspect the prompt, resolve which agent/model tier should handle it, write that resolution somewhere the next two hooks can read (a temp file, an env var, a session-scoped store).
  2. PreToolUse hook — before any dispatch tool runs, compare the actual target against the locked resolution; deny (non-zero exit + a message naming the fix) on any mismatch.
  3. A wall hook on file-editing tools — while a route is locked, deny direct Edit/Write calls from the main session; only the dispatched delegate may touch source.

Wire these into ~/.claude/settings.json under hooks, pointing each at a small script that reads/writes the shared resolution store. Start with logging-only (exit 0, just print what would be denied) for a day before flipping any hook to actually block — that’s how the false-triggers in Stage 6 got caught before they cost real work.

The forensics, in code

The audit that produced the “15 of 33 non-compliant” number streams every session transcript (one JSON event per line, never loaded whole) and assigns each session a verdict: did the main session edit source directly, or did every implementation step go through a delegate?

# audit_compliance.py — clean-room sketch of the verdict logic
SOURCE_EXT = (".py", ".ts", ".gd", ".cs")   # counts as a direct-edit violation
DOC_EXT = (".md", ".json", ".txt")          # main session may touch these freely

if session.main_session_edited_source:
    verdict = "NON_COMPLIANT"
elif session.dispatched_at_least_once:
    verdict = "COMPLIANT"
else:
    verdict = "PARTIAL"

The interesting failure wasn’t the 15 non-compliant sessions — it was the compliant ones. One session never touched source directly and delegated every step, and still cost more than it should have, because every worker it spawned silently inherited whatever model the main session happened to be running. Delegation compliance and model routing are separate failure modes. You can pass the first check completely and still be paying flagship prices for chore-tier work.

The registry: config becomes control flow

The fix for silent model inheritance is a generator, not a manual edit — a script that reads human-authored agent definitions and writes the registry the tool actually loads, resolving each agent’s model from a routing table in code instead of leaving it to whatever’s running:

# generate_roster.py — clean-room sketch, storefront-team analogy
ROUTING_TABLE = {
    "catalog-writer":  "mid-tier",   # writes code
    "checkout-coder":  "mid-tier",   # writes code
    "test-runner":     "small",      # chores only — never code generation
    "release-scribe":  "small",      # chores only
    "reviewer":        "flagship",   # plans and reviews, never writes code directly
}

def build_registry(agent_defs: list[AgentDef]) -> None:
    for agent in agent_defs:
        model = ROUTING_TABLE[agent.name]
        write_registered_agent(agent.name, model=model, body=agent.body)

The rule that survived contact with reality: never route code generation to the small/cheap tier. A rework pass from a cheap-tier mistake costs more tokens than the tier split saved in the first place. One gotcha found the hard way: Claude Code exposes an environment variable that force-overrides every agent’s configured model. It has to stay unset, or the whole registry becomes decorative again — OpenCode doesn’t have this failure mode at all, because frontmatter model is structurally enforced rather than one setting away from being silently bypassed.

Hooks as law, three layers

Registering agents with real model tiers doesn’t stop the main session from ignoring the registry — spawning something generic, editing source itself, or asking for a model that doesn’t match the agent it named. Three hooks close that, each a hard denial instead of a suggestion:

  1. Prompt-time router. Every message resolves a route in priority order — an explicit @tag, then a pattern match against known trigger phrases, then “unclassified.” The decision gets written to a lock file; nothing downstream re-decides it.
  2. Dispatch-time guard. Denies four shapes of drift: a requested model from a different tier than the named agent’s registered one, a full agent definition pasted into a generic dispatch call (the classic workaround for the tier-can’t-travel problem), a dispatch outside what the locked route allows, and any dispatch at all while the route is unclassified.
  3. Edit-time wall. The main session’s own edit tools are blocked from touching source; a single-use, logged escape hatch exists for genuine exceptions — used exactly twice the day it shipped, both times through the front door.

Try the router below. It’s the same classify-then-lock-then-guard shape as the real hooks, reduced to a fictional storefront team so the pattern is teachable without the implementation: explicit tag, pattern-matched bug report, no match at all, and the branch most setups forget — a relayed teammate report that looks like a user message but must never become a routing signal.

UserPromptSubmit hook
→
PreToolUse dispatch guard
→
test-runner

The fourth layer: forced accountability

Three hooks make the route deterministic. They don’t touch a different failure mode one layer downstream: a session reaching a real conclusion — “fixed,” “shipped,” “here’s the merge request” — and that claim being trusted on its word instead of checked. It happened for real: a session flatly reported a fix while its own transcript, read back afterward, showed the broken behavior still there. Nothing had forced the claim to be checked against anything before it reached anyone.

The fix is the same shape as the other three hooks, one stage later in the lifecycle — detect, then block, then file, all in code:

# conclusion_scribe.py — clean-room sketch, storefront-team analogy
CONCLUSION_RE = re.compile(r"\bfixed\b|\bshipped\b|merge request #\d+|commit [0-9a-f]{7,}", re.I)
SCRIBE_BLOCK_RE = re.compile(r"^SCRIBE:\s*\{.*\}\s*$", re.M)

def on_stop(final_response: str) -> HookResult:
    if not CONCLUSION_RE.search(final_response):
        return allow()                       # not conclusion-shaped, nothing to file
    if not SCRIBE_BLOCK_RE.search(final_response):
        return block("Attach a SCRIBE block: {summary, commits, tests, issue, tags}")
    record = parse_scribe_block(final_response)
    file_to_pattern_log(record)              # the hook files it — not the model
    write_to_memory(record)
    return allow()

The inversion is the whole point: the hook doesn’t trust the model to remember to log a conclusion — it refuses to let the turn end without one. The model still writes the summary; the filing — the tracker note, the memory write — happens in the hook script, deterministically, every time a conclusion-shaped response fires the regex. This is also what finally delivers the handoff-record idea from the top of this build: agents documenting what they did durably, instead of being believed on their word.

The session is the orchestrator

OpenCode’s answer to “who is acting right now” is Tab-select: the human picks the persona at the prompt, every turn. I went looking for the Claude Code equivalent and found something better for my case — the feature I was missing turned out to already exist. Claude Code lets a session boot directly as a named persona with its own pinned model (a config field, or a launch flag), instead of needing an external wrapper or a per-turn human pick. Combine a pinned flagship-tier planning persona at boot with a cheap-mode override mid-session, and the hooks keep enforcing regardless of which model happens to be answering at the moment — enforcement lives in the hooks, not in the model, and not in a human re-selecting a tab every turn.

Why pay flagship prices for a seat that only routes and plans? Public multi-agent research from one of the major labs found a strong-planner/cheap-worker split beating a single-model baseline by roughly 90% quality at around 15× the token cost of a single agent — the tier split is the cost control, not a nice-to-have. A seat that never writes code justifies the stronger model because its output is cheap (route decisions, not diffs) and its mistakes are expensive (a wrong route wastes an entire worker’s dispatch).

What shipping it revealed

The stack surfaced three bugs the same day it went live, and a fourth one after that. Full detail in the Stage 6 and Stage 7 cards above; short version — a relayed message accidentally name-matching an undispatchable persona caused a deadlock, plain-text mentions elsewhere were hijacking routing, and a review-pass trigger table had a stale reference that had been silently degrading the majority of one workflow to “unclassified” for a while. Every one of these shipped with the exact failing message captured as a permanent regression test. Enforcement code needs the same test discipline as the code it enforces — a hook that silently misclassifies is worse than no hook, because it looks like safety.

Who chose the model — before and after

Session-inherit (before)Registry-everywhere (after)
Worker model sourcewhatever the main session happened to be runningthe agent’s own registered tier
Cross-agent consistencyaccidental — one model, one sessioneach agent pinned independently
Escalation pathnone — silently follows the sessiondenied at dispatch, with the exact mismatch named
Failure mode when wronginvisible — everything “works,” costs 3× morea denial, immediately, with the fix

Two harnesses, side by side

OpenCode gets more of this right by default than Claude Code does. That’s not a knock on Claude Code — it’s the reason the audit was worth running. Click a row for what the other harness’s user can port over:

OpenCode
Claude Code

If you use both

Claude Code users: the whole recipe above is what you’re missing — a generated registry instead of hand-authored frontmatter, the three-hook stack (route, dispatch, edit), and route locking so nothing downstream re-decides what a prompt-time hook already resolved.

OpenCode users: the thing Tab-select doesn’t give you is automatic classification — a human still has to notice which persona a message belongs to and pick it. Worth stealing from this build even though your enforcement is already better: a deterministic message-to-agent classification table so routine messages route themselves, an explicit UNCLASSIFIED fallback that asks a human instead of guessing when nothing matches, audit probes that verify compliance after the fact instead of trusting the harness, and a route-lock file as the accountability record for “who decided this, and why” — a tab-click leaves no paper trail.

Technicals

The real stack behind this build, on record:

  • Agentic harness: Claude Code, run daily and audited here; compared throughout against OpenCode, the harness where the same orchestration setup already enforces by design.
  • Skill: Route-Lock — the three-layer hook stack (prompt-time router, lock file, dispatch-time guard) described above, plus a conclusion-scribe Stop hook that blocks a session’s final response from ending until a conclusion-shaped claim ships with a filed record.
  • Memory/RAG system: one-brain, a local memory MCP — preferences and past decisions recalled at session start, not a hosted vector store.
  • Install: not shipped yet — Route-Lock will install via npx '@yasaswy.nagavolu/agents' install, the same way every clonable skill from this blog is distributed, alongside a forthcoming follow-up.

The cheat sheet

  • Boot as the planner persona with the model pinned in its own config — not a wrapper script.
  • Cheap mode, hooks intact — switch models mid-session; enforcement lives in hooks, not in whichever model is currently answering.
  • Route a message with an explicit tag — the only routing signal that should ever fire; prose mentions and relayed reports are deliberately excluded.
  • Change a model tier with a one-line commit to the routing table, reviewed like any other code change — never a per-dispatch escalation, which the guard should deny outright.
  • Keep any subagent-model override env var unset — it silently beats every agent’s own config.
  • Every unclassified miss becomes a commit: add the pattern, add the regression test using the exact message that missed.

OpenCode treats agent definitions as real control flow by default. Claude Code didn’t ship that — but it shipped every primitive needed to build it: a persona a session can boot as, model tiers agents can register, and hooks that can hard-deny instead of merely suggest. Permissive-by-default is fixable. The registry generator, the three-hook stack, and the regression-test discipline above are project-agnostic — steal them for whichever coding-agent tool you’re tired of paying flagship prices for chore-tier work in, and steal the classification table back in the other direction if your harness already enforces well but still leaves the routing decision to a human every single turn.