hail-hydra-cc
v2.5.3
Published
Multi-agent orchestration framework for AI coding CLIs (Claude Code, Gemini CLI, Codex CLI). Routes tasks to specialized cheap/fast subagents while the frontier model orchestrates — inspired by speculative decoding. ~50% API cost reduction.
Maintainers
Readme
🧬 What is Hydra?
Hydra is a curated multi-agent toolkit for AI coding CLIs — Claude Code, Gemini CLI, Codex CLI, and GitHub Copilot CLI. It ships 10 specialized agents pinned to each host's cost-effective models (Haiku/Sonnet on Claude Code, Flash tiers on Gemini, Luna/Terra on Codex), 10 commands for direct invocation, and one automatic touchpoint that recommends integration verification after substantial code changes — plus an opt-in /hail-hydra skill on Copilot with the same 10 roles on native subagents and no automatic hooks.
Each agent runs on the smallest model that can do its job well. When invoked, Hydra typically cuts per-task cost by ~50% compared to running the same work on the orchestrator alone — while maintaining output quality through verification. That's the same ~50% you'll see everywhere Hydra is described, and it comes from one place: real session logs, via /hydra:stats (51.5% in the sample below).
Think of it this way:
Would you hire a $500/hr architect to carry bricks? No. You'd have them design the building and let the crew handle construction. That's the model Hydra follows when you invoke a specialized head.
New — GitHub Copilot CLI (opt-in): use /hail-hydra <task> inside your existing
Copilot session. Normal messages keep the normal agent. No second CLI, API key,
background service or model-default change is needed. See Copilot setup.
Multi-Host: One canonical source (content/) generates a native payload per
host. Invoke with /hydra:* on Claude Code and Gemini CLI, $hydra-* skills on
Codex CLI, or /hail-hydra <task> on Copilot.
Everything else Hydra is known for is still here: persistent agent memory, the codebase map with blast-radius lookups, the sentinel verification touchpoint after substantial edits, internal-thinking compression (/hydra:stfu), and real token tracking with /hydra:stats. Full version history lives in the CHANGELOG.
When to Use Hydra Explicitly
Hydra's biggest cost savings come from explicit invocation in scenarios where specialized handling genuinely helps:
| Scenario | How to Invoke | Why It Saves |
|----------|---------------|-------------|
| Broad codebase exploration | "use hydra-scout to find X" | Haiku reads files faster and cheaper than Opus |
| Multi-file changes | "use hydra-coder to update X across these files" | Parallel Sonnet dispatch beats sequential Opus |
| Security review | /hydra:guard | Pattern matching is Haiku-cheap |
| Environment validation | /hydra:preflight | Cross-references compatibility matrices on Sonnet |
| Codebase architecture review | /hydra:map | Dependency graph stored locally |
For one-off questions, simple edits, or conversational work, the host handles it directly. On Claude, Gemini and Codex, Hydra's only automatic intervention is the post-substantial-edit sentinel directive. Copilot has no automatic intervention.
🚀 Installation
One command. Done.
npx hail-hydra-cc@latestRuns the interactive installer — pick your CLI(s) (Claude Code, Gemini CLI, Codex CLI, GitHub Copilot CLI) and scope, and it deploys the agents, commands, hooks, and per-host wiring. Done in seconds.
Installation Options
# Claude Code, all projects — no prompts (v2-compatible default)
npx hail-hydra-cc --global
# Pick your agent(s) explicitly
npx hail-hydra-cc --agent=claude --global
npx hail-hydra-cc --gemini --global
npx hail-hydra-cc --codex --global
npx hail-hydra-cc --copilot --global
npx hail-hydra-cc --agent=claude,gemini,codex,copilot --global
# Every detected agent, fully non-interactive
npx hail-hydra-cc --all --global --yes
# This project only / both scopes
npx hail-hydra-cc --claude --local
npx hail-hydra-cc --claude --both
# Preview what would be written (writes nothing)
npx hail-hydra-cc --dry-run --all
# Check what's deployed
npx hail-hydra-cc --status
# Remove everything
npx hail-hydra-cc --uninstallAll flags: --agent=<list> (claude,gemini,codex,copilot) or the aliases --claude /
--gemini / --codex / --copilot / --all (every detected agent) · scope --global /
--local / --both · --yes non-interactive (requires an agent selection) ·
--dry-run · --config-dir <path> config-dir override (single agent only) ·
--status · --uninstall.
Per-Host Invocation
| Host | Commands | Notes |
|:-----|:---------|:------|
| Claude Code | /hydra:help, /hydra:stats, … | StatusLine + hooks registered in ~/.claude/settings.json |
| Gemini CLI | /hydra:help, /hydra:stats, … | Restart Gemini CLI (or run /commands reload) to pick up the new commands |
| Codex CLI | $hydra-help, $hydra-stats, … (skills with a $ trigger) | Required once: run /hooks inside Codex to review and trust the Hydra hooks — they stay inert until then |
| GitHub Copilot CLI | /hail-hydra <task> | Run /skills reload; instruction-gated explicit requests, no hooks or persistent agent switch |
GitHub Copilot CLI (opt-in)
Requires a Copilot CLI version that supports skills and explicit invocation.
npx hail-hydra-cc@latest --copilot --global --yes # ~/.copilot/skills/hail-hydra (or $COPILOT_HOME)
npx hail-hydra-cc@latest --copilot --local --yes # .github/skills/hail-hydra, this project onlyThe installer honors COPILOT_HOME for the global path; --config-dir <path> (Hydra's installer flag, not a Copilot setting) overrides it.
Then, inside the same Copilot session:
/skills reload
/hail-hydra Implement pagination for this API and update the tests
/hail-hydra --mode turbo Build product search and run the relevant checks
/hail-hydra --help/hail-hydra is an explicit skill invocation, not a sticky mode — a later message such as Explain this function uses the normal agent. The skill sets disable-model-invocation: false because some Copilot versions return Skill not found for explicit requests otherwise (copilot-cli#4438); accidental model-mediated loading must not trigger Hydra work.
Model defaults — each role dispatches through its tier's models list, in order; an admin-disabled or rejected entry falls through to the next. Your selected main model keeps substantive reasoning and final acceptance, and naming a model in the request overrides the default. Under Auto, workers may inherit the session model.
| Tier | Roles | models[0] | fallback | $/1M in/out |
|---|---|---|---|---|
| cheap | git, guard, preflight, runner, scout, scribe, sentinel-scan | claude-haiku-5.5 | gpt-6-luna | 0.10/0.50 · 0.10/0.50 |
| mid | analyst, coder, sentinel, architect, researcher | claude-sonnet-5.5 | gpt-5.6-terra | 2.00/10.00 · 2.00/12.00 |
Modes: /hail-hydra --mode <turbo|balanced|economy> <goal> (default balanced); Turbo puts speed first and costs more. Ceilings are instruction-level heuristics bounded by your Copilot plan's concurrency, not a scheduler guarantee.
Quality: substantial changes get an automatic in-task review via native code-review/security-review before completion is reported.
Continuity: treat a /model switch like a compaction boundary — write the session ledger before an anticipated switch, read it back before the next dispatch or decision.
Measuring savings: compare /usage before/after a normal run against a /hail-hydra run, then /hail-hydra --compare; not yet benchmarked on Copilot specifically.
Hooks are deferred until upstream hook reliability bugs are fixed (copilot-cli issues #4520, #1730, #2201, #4001, #4549); quality gates and --notify run in-task/manually for now.
.claude/collision: Copilot also loads a project's.claude/skills/and.claude/agents/. A repo-local Claude Code Hydra install (.claude/skills/hydra/, auto-activating, and.claude/agents/hydra-*.md) will also be visible inside Copilot — install Claude Hydra globally, or remove the local copy, in repos where you use/hail-hydra.
npx hail-hydra-cc --copilot --status # installed version + owned-file count
npx hail-hydra-cc --copilot --uninstall --yesSee /hail-hydra --help for the full command list.
What Gets Installed
Claude Code — ~/.claude/ (or ./.claude/ with --local):
~/.claude/
├── agents/ # 10 agent definitions (Haiku/Sonnet pinned, memory: project)
├── commands/hydra/ # 11 slash commands (/hydra:*)
├── hooks/ # 6 hook scripts + notification sound
│ ├── hydra-check-update.js # SessionStart — version check (background)
│ ├── hydra-statusline.js # StatusLine — status bar display
│ ├── hydra-token-math.js # Token parsing + savings math (shared library)
│ ├── hydra-auto-guard.js # PostToolUse — file change tracker
│ ├── hydra-notify.js # Notification — task completion sound
│ ├── hydra-sentinel-done.js # Sentinel tracking cleanup
│ └── hydra-task-complete.wav # Notification sound file
└── skills/
├── hydra/ # SKILL.md + VERSION + references/
└── stfu-agents/ # SKILL.mdHooks and the statusLine are registered in ~/.claude/settings.json — existing
entries are preserved, and a custom statusLine is never overwritten.
Gemini CLI — ~/.gemini/ (or ./.gemini/ with --local):
~/.gemini/
├── agents/ # 10 agent definitions (Flash-tier pinned)
├── commands/hydra/ # 11 TOML commands (/hydra:*)
├── hydra/ # SKILL.md, VERSION, references/, hooks/
└── GEMINI.md # Hydra marker block (appended, reversible)Hooks (AfterTool, SessionStart, Notification) are registered in ~/.gemini/settings.json.
Codex CLI — ~/.codex/ (or ./.codex/ with --local):
~/.codex/
├── agents/ # 10 agent definitions (*.toml, Luna/Terra pinned)
├── hydra/ # VERSION, references/, hooks/
├── hooks.json # Hook registrations — trust once via /hooks
├── config.toml # [features] hooks + notify chain (marker blocks, reversible)
└── AGENTS.md # Hydra marker block (appended, reversible)
~/.agents/skills/ # Skills: $hydra-help, $hydra-stats, $hydra-guard, …Local scope for Claude/Gemini/Codex (
--local): the per-project payload goes to./.claude/,./.gemini/, or./.codex/in your working directory. Hooks and host wiring (settings/hooks registration, context files, Codex skills) always stay user-level.
⚡ Slash Commands
The following command catalogue and automatic integrations describe Claude/Gemini/Codex. Copilot has the separate opt-in skill documented above.
Codex CLI: the same commands ship as skills invoked with a
$trigger —$hydra-help,$hydra-stats,$hydra-guard, … The/hydra:*form below is for Claude Code and Gemini CLI.
| Command | Description |
|---------|-------------|
| /hydra:help | Show all commands and agents |
| /hydra:status | Show installed agents, version, and update availability |
| /hydra:update | Update Hydra to the latest version |
| /hydra:guard [files] | Run manual security & quality scan |
| /hydra:quiet | Suppress dispatch logs for this session |
| /hydra:report | Report a bug, request a feature, or share feedback |
| /hydra:stfu | Compress internal thinking for every subagent in the session |
| /hydra:map | View codebase dependency map, query blast radius, rebuild |
| /hydra:preflight | Two-phase environment and compatibility check before starting a new project build |
| /hydra:stats | Show real token usage, delegation rate, and actual savings (parses the host CLI's own session logs — no AI estimation) |
/hydra:preflight — Environment Validation
Run before starting any new project build. Catches broken GPU stacks, missing env vars, and incompatible dependency pairs before they cost you hours of debugging.
/hydra:preflightHydra runs a two-phase check:
- Detection (Haiku): probes runtimes, CUDA stack, deps, env vars, services
- Analysis (Sonnet): cross-references against compatibility matrices, flags ✅ COMPATIBLE / ⚠️ KNOWN RISK / ❌ CONFIRMED BREAK
🖥️ Status Line
Claude Code only — Gemini CLI and Codex CLI have no statusline; use
/hydra:stats(or$hydra-stats) there instead.
After installation, your Claude Code status bar shows real-time framework info:
🐉 │ Opus │ Ctx: 37% ████░░░░░░ │ $0.42 │ my-project| Element | What It Shows | |---------|---------------| | 🐉 | Hydra is active | | Model | Current Claude model (Opus, Sonnet, Haiku) | | Ctx: XX% | Context window usage with visual bar | | $X.XX | Session API cost so far | | Directory | Current working directory | | ⚠ Warning | Compaction warning (only at 70%+ context usage) |
Context bar colors:
- 🟢 Green (0–49%) — plenty of room
- 🟡 Yellow (50–79%) — getting full, consider
/compact - 🔴 Red (80%+) — context nearly full,
/compactor/clearrecommended
Compaction warnings (appended automatically at 70%+):
🐉 │ Opus │ Ctx: 73% ███████░░░ │ $1.87 │ my-project │ ⚠ Auto-compact at 85%
🐉 │ Opus │ Ctx: 83% ████████░░ │ $3.14 │ my-project │ ⚠ Compacting soon!- ⚠ Auto-compact at 85% (70–79%) — heads-up that compaction is approaching
- ⚠ Compacting soon! (80%+) — compaction is imminent, consider
/compactnow
Note: If you already have a custom
statusLineconfigured, the installer keeps yours and prints instructions for switching to Hydra's.
🔔 Task Completion Sound
Hydra plays a short notification sound when the CLI finishes responding — so you know it's done even if you've tabbed away.
- Cross-platform — macOS (
afplay), Windows (PowerShell), Linux (paplay/aplay) - Non-blocking — the sound plays detached; it never delays the response
- Host-native and fully event-driven — Claude Code
Stophook, GeminiNotificationhook, Codexnotifychain that preserves your existing notifier; no prompt-level calls, so the model can't forget it
The notification hook is registered automatically during installation.
🔄 Auto-Update Notifications
Hydra checks for updates once per session in the background (never blocks startup). When a new version is available, you'll see it in the status bar:
🐉 │ Opus │ Ctx: 37% ████░░░░░░ │ $0.42 │ my-project │ ⚡ v2.6.0 availableUpdate with:
# From within Claude Code:
/hydra:update
# Or from your terminal:
npx hail-hydra-cc@latest --globalAfter updating, restart Claude Code to load the new files.
✨ Features
- Ten specialized heads — Haiku (fast) and Sonnet (capable) heads for every task type, including preflight detection for new projects
- Sentinel verification — the answer to "did the cheap model's output actually hold up?": a two-tier check (fast scan + deep analysis) runs after code changes and catches ~72% of integration bugs before runtime
- Persistent agent memory — Every agent remembers your codebase patterns, conventions, and past decisions across sessions
- Orchestrator memory — Opus maintains its own notes on fragile zones, routing patterns, and known issues via CLAUDE.md
- Verification touchpoint — after substantial code changes, the auto-guard hook injects a directive recommending a sentinel + guard verification wave before results are presented; trivial edits stay silent
- Auto-Guard — a PostToolUse hook tracks every file edit; hydra-guard (Haiku) scans the tracked files for security issues on demand (
/hydra:guard) or as part of the sentinel wave - Configurable modes —
conservative,balanced(default), oraggressivedelegation viahydra.config.md - Slash commands —
/hydra:help,/hydra:status,/hydra:update,/hydra:guard,/hydra:quiet,/hydra:reportfor full session control - Task completion sound — plays a notification when Claude finishes substantial tasks
- Quick commands — natural language shortcuts:
hydra status,hydra quiet,hydra map - Custom agent templates — Add your own heads using
templates/custom-agent.md - Session indexing — Codebase context persists across turns; no re-exploration on every prompt
- Speculative pre-dispatch — hydra-scout launches in parallel with task classification, saving 2–3 seconds per task
- Dispatch log — Transparent audit trail showing which agents ran, what model, and outcome
- Codebase Map — Persistent dependency graph built by hydra-scout. Maps every file's imports, dependents, risk score, env vars, and test coverage. Enables instant blast-radius lookups for sentinel — no more grepping the entire codebase.
- Risk-Based Verification — Files with more dependents get more thorough verification. Critical files always trigger deep sentinel analysis. Low-risk files get fast-tracked.
/hydra:map— Inspect the dependency map, query blast radius for any file, or force a rebuild- 🆕 Real Token Tracking —
/hydra:statsparses Claude Code session logs directly to show actual usage and savings. No AI estimation, no marketing fluff — just real numbers from Anthropic's API responses. - 🆕 Internal Compression — Subagent output and orchestrator responses are now compressed for efficiency. Sub-agent output is heavily compressed (only Opus reads it). Orchestrator responses drop filler and pleasantries while keeping natural prose.
🛡️ Sentinel — Integration Integrity
Most bugs don't come from bad code — they come from good code that doesn't fit together. A renamed export, a changed return type, a missing dependency after a refactor. These integration issues slip past linters, type-checkers, and even code review because no single file looks wrong.
hydra-sentinel catches them — the auto-guard touchpoint recommends a scan after every substantial edit, and the scan escalates to deep analysis only when it finds something.
How It Works
Code change lands (hydra-coder finishes)
│
▼
┌──────────────────────────────────────┐
│ 🟢 hydra-sentinel-scan (Haiku) │ ← Runs on EVERY code change (~1-2s)
│ Fast sweep: imports, exports, │
│ signatures, dependencies │
└──────────────┬───────────────────────┘
│
Issues found?
├── No: ✅ Pass — code proceeds to guard
│
└── Yes: Escalate
│
▼
┌──────────────────────────────────────┐
│ 🔵 hydra-sentinel (Sonnet) │ ← Only when scan flags issues (~20-30%)
│ Deep analysis: confirms real issues, │
│ dismisses false positives, │
│ proposes fixes │
└──────────────┬───────────────────────┘
│
Fix decision:
├── Trivial (import typo): Auto-fix
├── Medium (signature mismatch): Offer fix to user
└── Complex (architectural): Report with contextWhat Sentinel Catches
| Check Type | Priority | Example |
|:-----------|:---------|:--------|
| Import/export mismatches | P0 | Importing a function that was renamed or removed |
| Function signature changes | P0 | Caller passes 2 args, function now expects 3 |
| Type contract violations | P1 | Function returns string but caller expects number |
| Missing dependency updates | P1 | New import added but package not in package.json |
| Cross-file rename gaps | P1 | Variable renamed in definition but not all call sites |
| Circular dependency introduction | P2 | New import creates A → B → C → A cycle |
| Dead code from refactoring | P2 | Exported function no longer imported anywhere |
| Environment/config mismatches | P2 | Code references env var that isn't in .env.example |
Example Output
🛡️ Sentinel Report
──────────────────────────────────────
✖ P0: src/auth.js imports `validateToken` from src/utils.js
but src/utils.js now exports `verifyToken` (renamed in this session)
→ Fix: Update import to `verifyToken` [auto-fixable]
⚠ P1: src/api/routes.js calls createUser(name, email)
but src/models/user.js:createUser now expects (name, email, role)
→ Missing required parameter `role` added in this change
✔ 6 other integration points verified clean
──────────────────────────────────────Across the check types above, the estimated weighted detection rate is ~72% of integration bugs caught before runtime — highest for import/export and dependency mismatches (direct matching), lower for type contracts and config drift (heuristic).
Memory makes it better over time. Sentinel remembers past false positives and known fragile integration points in your project. The more you use it, the more accurate it gets.
🗺️ Codebase Map
Hydra builds a persistent dependency map of your codebase, giving every agent instant access to file relationships without scanning.
How It Works
hydra-scout builds the map on first run by extracting import statements
from every source file using grep (no external parsers required). The map
is stored at .claude/hydra/codebase-map.json.
Session 1: scout builds the full map (~10 seconds for 500 files)
Session 2: scout checks git hash → nothing changed → skip rebuild (instant)
Session 3: scout checks git hash → 3 files changed → update only those 3What the Map Contains
| Data | How It's Used | |:-----|:-------------| | File imports | "auth.ts imports user.ts and env.ts" | | Reverse imports | "auth.ts is imported by users.ts, admin.ts, middleware.ts" | | Risk score | low (0-1 deps) → medium (2-3) → high (4-6) → critical (7+) | | Env var index | "JWT_SECRET is used in auth.ts and middleware.ts" | | Test coverage | covered / partial / untested per file | | Git staleness | Hash comparison for instant freshness check |
Why This Matters
Without map — When auth.ts changes, sentinel greps the ENTIRE codebase looking for files that import it. In a 500-file project, that's 500 file reads. Takes 5-15 seconds, costs 3,000-8,000 tokens.
With map — Sentinel reads the JSON, looks up auth.ts's imported_by array,
gets [users.ts, admin.ts, middleware.ts] instantly. Reads only those 3 files.
Takes <2 seconds, costs 500-1,500 tokens.
Savings: 3-5× faster, 3-5× fewer tokens per sentinel scan.
Risk-Based Sentinel Triggering
The map's risk scores let Opus make smarter verification decisions:
| Modified File Risk | What Happens | |:-------------------|:------------| | 🔴 Critical (7+ deps) | Sentinel-scan + deep analysis (always) | | 🟠 High (4-6 deps) | Sentinel-scan, escalate if issues found | | 🟡 Medium (2-3 deps) | Sentinel-scan, escalate only for P0 issues | | 🟢 Low (0-1 deps) | Sentinel-scan, auto-accept if clean |
This means Hydra spends more verification effort where it matters most (high-risk files) and less where it doesn't (isolated utilities).
Inspect the Map
/hydra:map # Show summary — risk distribution, coverage stats
/hydra:map src/services/auth.ts # Show blast radius for a specific file
/hydra:map rebuild # Force a complete rebuildTechnical Notes
- The map is built using grep + regex — no Tree-sitter, no AST parsing, no external dependencies. Works with JS/TS, Python, Go, Java, Kotlin, Ruby, Rust.
- Supports relative import resolution (e.g.,
'./auth'→src/services/auth.ts) - Falls back gracefully — if the map doesn't exist, all agents use their original grep-based behavior. The map is an optimization, not a requirement.
- Stored at
.claude/hydra/codebase-map.json— add to.gitignore(machine-generated).
📊 Real Token Tracking
/hydra:stats shows actual token usage and savings for your session. No AI
estimation. The numbers are pulled directly from the host CLI's own session
logs — Claude Code JSONL, Gemini CLI chat records, or Codex CLI rollout files.
🐉 Hydra Stats
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Session: 7c3a9e21.jsonl
Turns: 38
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🟢 Haiku (24 turns): 142.3k in / 8.1k out → $0.183
🔵 Sonnet (9 turns): 67.4k in / 3.2k out → $0.250
🟣 Opus (5 turns): 45.1k in / 2.8k out → $0.296
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Delegation rate: 87.0% (33/38 turns)
Actual cost: $0.729
All-Opus baseline: $1.502
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💰 Saved: $0.773 (51.5%)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Reads the host CLI's session logs directly.
No AI estimation. Numbers are real.The "All-Opus baseline" is the hypothetical cost if every Hydra agent had
been Opus instead. The savings show what Hydra's model routing actually
saves you in this session. Implementation is pure Node.js — works on
Windows, macOS, and Linux. Respects CLAUDE_CONFIG_DIR env override.
🧠 Agent Memory
Without memory, every session starts cold. Agents re-discover your conventions, re-learn your project structure, and repeat the same questions. With memory, knowledge compounds.
| Aspect | Without Memory | With Memory | |:-------|:---------------|:------------| | First task | Agent explores from scratch | Agent recalls project patterns | | Conventions | May use wrong style | Remembers your naming, structure, patterns | | Known issues | No awareness of past bugs | Recalls fragile areas and past fixes | | Routing accuracy | Generic classification | Improved by past dispatch outcomes | | False positives | Same false alarms repeat | Sentinel suppresses known non-issues |
How It Works
Every agent has memory: project in its frontmatter. Claude Code automatically manages a
per-project memory directory (.claude/memory/) where agents store and retrieve learnings.
Agent memory is a Claude Code feature — Gemini CLI and Codex CLI have no equivalent, so the generator drops the
memoryfield on those hosts.
| Agent | What It Remembers | |:------|:------------------| | hydra-scout | Project structure patterns, key file locations, search shortcuts | | hydra-runner | Test commands, common failure patterns, build quirks | | hydra-scribe | Documentation style, preferred formats, terminology | | hydra-guard | Known false positives, project-specific security patterns | | hydra-git | Commit conventions, branch naming, merge preferences | | hydra-sentinel-scan | Known fragile integration points, past false positives | | hydra-coder | Coding style, architecture patterns, preferred libraries | | hydra-analyst | Common bug patterns, performance hotspots, review focus areas | | hydra-sentinel | Integration history, confirmed vs dismissed findings | | Orchestrator (Opus) | Fragile zones, routing accuracy, escalation patterns (via CLAUDE.md Hydra Notes) |
Memory Properties
- Automatic — agents read and write memory without any user action
- Project-scoped — each project has its own memory; no cross-contamination
- Persistent — survives across sessions; compounds over time
- Manageable — stored as plain markdown in
.claude/memory/; edit or delete anytime
The Compound Effect
Session 1: Agents learn your project. Session 5: They know your conventions. Session 20: They anticipate your patterns. The framework gets more efficient the more you use it — not because the models improve, but because context quality improves.
🤔 Why I Built This
After Opus 4 dropped, I noticed something frustrating — code execution felt slowww. Reallyyy Slow. Not because the model was worse, but because I was feeding everything through one massive model. Every file read, every grep, every test run, every docstring — all burning through Opus-tier tokens. The result? Frequent context compaction, more hallucinations, and an API bill that made me wince.
So I started experimenting. I switched to Haiku for the simple stuff — running commands, tool calls, file exploration. Sonnet for code generation, refactoring, reviews. And kept Opus only for what it's actually good at: planning, architecture, and the hard decisions. The result surprised me. Same code quality. Sometimes better — because each model was operating within a focused context window instead of one overloaded one.
Five agents. Five separate context windows. Each with a clearly defined job. They do the work, and only pass results back to the brain — Opus. The outcome:
- Longer coding sessions (less compaction, less context blowup)
- Drastically reduced API costs (Haiku is 5× cheaper than Opus)
- Faster execution (Haiku responds ~10× faster)
- Same or better code quality (focused context > bloated context)
- Zero manual model switching (this is the big one)
Because that was the real pain — manually switching between models for every task tier to save costs. Every. Single. Time. So I built a framework that does it for me. And honestly? It does it better than I did. That was hard to admit, but here we are.
I also didn't want it to be boring. So I gave it teeth, heads, and a battle cry. If you prefer something more buttoned-up, the spec-exec branch has the same framework with zero theatrics.
Hail Hydra. Have fun.
💡 The Theory (for nerds)
Speculative decoding (Chen et al., 2023) accelerates LLM inference by having a small draft model propose tokens that a large target model verifies in parallel. Since verifying K tokens costs roughly the same as generating 1 token, you get 2–2.5× speedup with zero quality loss.
Hydra applies this at the task level:
┌─────────────────────────────────┐
│ SPECULATIVE DECODING (tokens) │
│ │
│ Small model drafts K tokens │
│ Big model verifies in parallel │
│ Accept or reject + resample │
│ Result: 2-2.5× speedup │
└─────────────────────────────────┘
│
Same idea,
bigger scale
│
▼
┌─────────────────────────────────┐
│ 🐉 HYDRA (tasks) │
│ │
│ Haiku/Sonnet drafts the task │
│ Opus verifies (quick glance) │
│ Accept or redo yourself │
│ Result: 2-3× speedup │
└─────────────────────────────────┘The math is simple: if 70% of tasks can be handled by Haiku (10× faster, 5× cheaper) and 20% by Sonnet (3× faster, ~1.7× cheaper), your effective speed and cost improve dramatically — even accounting for the occasional rejection.
How the concepts map:
| Speculative Decoding Concept | Hydra Equivalent | |:-----------------------------|:-----------------| | Target model (large) | 🧠 The orchestrator (Opus / Gemini Pro / GPT-6.1 Sol) | | Draft model (small) | 🟢🔵 The cheap/mid-tier heads | | Draft K tokens | Heads draft the full task output | | Parallel verification | Orchestrator glances at the output | | Modified rejection sampling | Accept → ship it. Reject → orchestrator redoes it. | | Acceptance rate (~70-90%) | Target: 85%+ of delegated tasks accepted as-is |
Key papers:
- Accelerating Large Language Model Decoding with Speculative Sampling — Chen et al., 2023 (DeepMind)
- Fast Inference from Transformers via Speculative Decoding — Leviathan et al., 2022 (Google)
🏗️ Architecture
User Request
│
├──────────────────────────────────────────────────────┐
│ │
▼ ▼
┌─────────────────────────────┐ ┌──────────────────────────────┐
│ 🧠 ORCHESTRATOR (Opus) │ │ 🟢 hydra-scout (Haiku) │
│ Classifies task │ │ IMMEDIATE pre-dispatch: │
│ Plans waves │ │ "Find files relevant to │
│ Decides blocking / not │ │ [user's request]" │
└────────┬────────────────────┘ └──────────────┬───────────────┘
│ (unless Session Index already covers) │
└──────────────────────┬──────────────────────────┘
│ (scout + classification both ready)
[Session Index updated]
│
════════════════════════════════════════════════════════
Wave N (parallel dispatch, index context injected)
┌───────────────────┬──────────────────────────────────┐
│ SEQUENTIAL │ PARALLEL (wait for all) │
▼ ▼ │
[coder] [scribe] ──────────────────────────────┘
│
▼
ALL agents complete (Opus waits for every dispatched agent)
│
├── Raw data / clean pass? → AUTO-ACCEPT → (updates Session Index if scout)
└── Code / analysis / user-facing docs? → Orchestrator verifies
│
▼
┌─────────────────────────────────────────────────────┐
│ 🛡️ VERIFICATION WAVE (recommended by auto-guard) │
│ │
│ 🟢 sentinel-scan (Haiku) — fast integration sweep │
│ └── issues? → 🔵 sentinel (Sonnet) — deep │
│ 🟢 guard (Haiku) — security/quality scan │
│ │
│ Runs before results are presented to you │
└──────────────────────┬──────────────────────────────┘
│
▼
User gets result (single response, all agent outputs included)🐲 The Ten Heads
| Head | Model | Speed | Role | Personality | |:-----|:------|:------|:-----|:------------| | hydra-scout (Haiku) | 🟢 Haiku | ⚡⚡⚡ | Codebase exploration, file search, reading | "I've already found it." | | hydra-runner (Haiku) | 🟢 Haiku | ⚡⚡⚡ | Test execution, builds, linting, validation | "47 passed, 3 failed. Here's why." | | hydra-scribe (Haiku) | 🟢 Haiku | ⚡⚡⚡ | Documentation, READMEs, comments | "Documented before you finished asking." | | hydra-guard (Haiku) | 🟢 Haiku | ⚡⚡⚡ | Security/quality gate after code changes | "No secrets. No injection. You're clean." | | hydra-git (Haiku) | 🟢 Haiku | ⚡⚡⚡ | Git: commit, branch, diff, stash, log | "Committed. Conventional message. Clean diff." | | hydra-sentinel-scan (Haiku) | 🟢 Haiku | ⚡⚡⚡ | Fast integration sweep after code changes | "Imports check out. Signatures match. Clean." | | hydra-preflight (Haiku) | 🟢 Haiku | ⚡⚡⚡ | Environment detection, version probing, dep inventory | "Your PyTorch/CUDA pair is broken. Pin torch==2.7.0." | | hydra-coder (Sonnet) | 🔵 Sonnet | ⚡⚡ | Code implementation, refactoring, features | "Feature's done. Tests pass." | | hydra-analyst (Sonnet) | 🔵 Sonnet | ⚡⚡ | Code review, debugging, analysis | "Found 2 critical bugs and an N+1 query." | | hydra-sentinel (Sonnet) | 🔵 Sonnet | ⚡⚡ | Deep integration analysis (when scan flags issues) | "2 real issues confirmed. 1 false positive dismissed." |
Task Routing Cheat Sheet
Is it read-only? ─── Yes ──→ Finding files?
│ ├── Yes: hydra-scout (Haiku) 🟢
│ └── No: hydra-analyst (Sonnet) 🔵
│
No ──→ Is it a git operation? ─── Yes ──→ hydra-git (Haiku) 🟢
│
No ──→ Is it a security scan? ─── Yes ──→ hydra-guard (Haiku) 🟢
│
No ──→ Just running a command? ─── Yes ──→ hydra-runner (Haiku) 🟢
│
No ──→ Writing docs only? ─── Yes ──→ hydra-scribe (Haiku) 🟢
│
No ──→ Clear implementation approach? ─── Yes ──→ hydra-coder (Sonnet) 🔵
│
No ──→ Needs deep reasoning? ─── Yes ──→ 🧠 Opus (handle it yourself)
Code was just changed? ─── Yes ──→ hydra-sentinel-scan (Haiku) 🟢
│ │
│ Issues found?
│ ├── No: Done ✅
│ └── Yes: hydra-sentinel (Sonnet) 🔵⚙️ Configuration
The following config applies to Claude, Gemini and Codex. Copilot uses
task-local --mode turbo|balanced|economy instead; it does not read this config
or treat aggressive as an alias for Turbo.
Customize Hydra's behavior with an optional config file — create it by hand at
your host's config path (the installer doesn't write one, and --uninstall
leaves it alone):
| Host | Global | Project-level (overrides global) |
|:-----|:-------|:---------------------------------|
| Claude Code | ~/.claude/skills/hydra/config/hydra.config.md | .claude/skills/hydra/config/hydra.config.md |
| Gemini CLI | ~/.gemini/hydra/config/hydra.config.md | .gemini/hydra/config/hydra.config.md |
| Codex CLI | ~/.codex/hydra/config/hydra.config.md | .codex/hydra/config/hydra.config.md |
mode: balanced # conservative | balanced (default) | aggressive
dispatch_log: on # on (default) | off
auto_guard: on # on (default) | offRun /hydra:status ($hydra-status on Codex) to see what's currently loaded.
See content/config/hydra.config.md for the full reference with all options.
🧩 Extending Hydra
Add your own specialized head in three steps:
1. Fetch the template straight into the agents directory Hydra installed:
curl -o ~/.claude/agents/hydra-myspecialist.md https://raw.githubusercontent.com/AR6420/Hail_Hydra/main/templates/custom-agent.md
# project-level: curl -o .claude/agents/hydra-myspecialist.md https://raw.githubusercontent.com/AR6420/Hail_Hydra/main/templates/custom-agent.md2. Customize the agent — edit the name, description, tools, and instructions.
3. Restart your CLI — the new head is discoverable alongside the built-in ten.
The template uses the Markdown agent format shared by Claude Code and Gemini CLI
(~/.gemini/agents/); Codex CLI agents live in ~/.codex/agents/ as TOML.
See templates/custom-agent.md for the full template with
instructions on writing effective agent descriptions, output formats, and collaboration protocols.
📂 Repository Structure
hydra/
├── 📄 bin/cli.js # The npx installer (hail-hydra-cc)
├── 🧬 content/ # Canonical source — single origin for every host
│ ├── SKILL.md # Orchestrator instructions (full)
│ ├── skill-core.md # Compressed core for size-capped hosts
│ ├── agents/ # 10 agent definitions
│ ├── commands/ # 10 command definitions
│ ├── references/ # Routing guide + model capabilities
│ ├── config/hydra.config.md # User configuration template
│ └── skills/stfu-agents/ # STFU-Agents skill
├── ⚙️ src/
│ ├── generator/ # Emitters: content/ → dist/<host>/
│ ├── installer/ # Multi-host installer (hosts/claude|gemini|codex.js)
│ ├── hooks/<host>/ # Per-host lifecycle hooks
│ └── lib/ # Shared cores (token math, guard, sentinel state)
├── 📦 dist/ # Generated per-host payload (`npm run build` — gitignored)
├── 📋 templates/
│ └── custom-agent.md # Template for adding your own heads
└── 🧪 test/ # Node test suite (`npm test`)📊 Expected Impact
| Metric | Without Hydra | With Hydra | Improvement | |:-------|:-------------|:-----------|:------------| | Task Speed (per dispatch) | 1× (Opus for everything) | 2–3× faster | 🟢 Haiku heads respond ~10× faster | | API Cost (per dispatch) | 1× (Opus for everything) | ~0.5× per dispatch | ~50% cheaper when invoked | | Quality | Opus-level | Opus-level | Zero degradation | | User Experience | Normal | Normal | Explicit invocation; one automatic touchpoint (post-substantial-edit verification) | | Overhead per turn (Turn 2+) | Full re-exploration each turn | Session index reused | 🟢 2-4s saved per turn | | Scout/runner verification | Opus reviews every output | Auto-accepted for factual data | 🟢 ~50-60% of outputs skip review | | Integration bugs caught | 0% (no verification) | ~72% caught before runtime | 🟢 Sentinel auto-verification | | Session knowledge | Starts cold every time | Compounds across sessions | 🟢 Persistent agent memory | | Sentinel scan speed | 5-15 seconds (grep) | <2 seconds (map lookup) | 🟢 3-5× faster with codebase map | | Sentinel scan tokens | 3,000-8,000 per scan | 500-1,500 per scan | 🟢 3-5× fewer tokens per scan |
How the Savings Work
| Task Type | % of Work | Model Used | Input Cost vs Opus | Output Cost vs Opus | |:----------|:----------|:-----------|:----------------------|:-----------------------| | Exploration, search, tests, docs | ~50% | 🟢 Haiku | 2.5% ($0.10 vs $4/MTok) | 2.5% ($0.50 vs $20/MTok) | | Implementation, review, debugging | ~30% | 🔵 Sonnet | 50% ($2 vs $4/MTok) | 50% ($10 vs $20/MTok) | | Architecture, hard problems | ~20% | 🧠 Opus | 100% (no change) | 100% (no change) | | Sentinel scan (fast) | Auto (every code change) | 🟢 Haiku | 2.5% | 2.5% | | Sentinel deep (conditional) | ~20-30% of code changes | 🔵 Sonnet | 50% | 50% | | Blended effective cost | | | ~36% of all-Opus | ~36% of all-Opus |
Note: Prices are Haiku 5.5 / Sonnet 5.5 / Opus 5.5 (verified 2026-10). When Hydra is invoked across a representative mix of task types, blended input = (0.5×$0.10 + 0.3×$2 + 0.2×$4) / $4 = $1.45/$4 ≈ 36% of all-Opus. Haiku 5.5 prompts over 100K tokens bill at $0.50/$2.50, so long-context-heavy sessions save less.
Per-dispatch savings of ~50% or more are typical for Hydra-invoked work. Session-level savings depend on how often Hydra is invoked — run /hydra:stats for real numbers from your session.
On Gemini CLI and Codex CLI the same routing applies against that host's own
frontier model — Flash-tier heads measured against an all-Gemini-Pro baseline,
Luna/Sol heads against the session's main GPT model (default GPT-6.1 Sol) — landing around the same
~50% blended mark. /hydra:stats ($hydra-stats on Codex) reports real
per-host numbers.
Why Hydra Doesn't Hit the Subagent Cost-Explosion Problem
A fair objection to any subagent framework: naive fan-out can cost 3–7× more than a single-thread session, because every spawned agent re-bootstraps context and re-verifies work the orchestrator already understood. Hydra's design avoids that trap deliberately:
- Bounded, task-scoped dispatch — the orchestrator sends one agent per well-defined subtask with only the context slice it needs, not a wide swarm re-reading the repo in parallel
- Cheap tiers do the token-heavy work — the expensive model never pays frontier prices for exploration, test runs, or doc writing
maxTurnscaps on every agent — a runaway agent stops at 25 turns (cheap tier) or 50 (mid tier) instead of burning tokens indefinitely- The codebase map replaces re-exploration — blast-radius lookups cost ~500–1,500 tokens instead of a 3,000–8,000-token grep sweep per verification
- Receipts, not claims —
/hydra:statsparses the CLI's own session logs, so if dispatch overhead ever ate the savings, the number would show it
Measure Your Savings
The most accurate way to measure Hydra's impact — no estimation, real numbers:
- Start a Claude Code session without Hydra installed
- Complete a representative coding task
- Note the session cost from Claude Code's cost display
- Start a new session with Hydra installed
- Complete a similar task
- Compare the two costs
That's it. Real data beats theoretical calculations every time.
What to expect
When Hydra is actively invoked across a typical mix (50% Haiku, 30% Sonnet, 20% Opus):
- Input tokens: ~64% cheaper per dispatch ($1.45 vs $4.00 per MTok)
- Output tokens: ~64% cheaper per dispatch ($7.25 vs $20.00 per MTok)
- Per-dispatch blended: ~50%+ cost reduction on Hydra-invoked work
- Speed: 2–3× faster on delegated tasks
Session-level savings depend on invocation frequency. /hydra:stats reports real numbers from your session logs — no estimation.
Additional Savings from Codebase Map
The codebase map provides additional token savings on TOP of the model-routing savings above:
| Operation | Without Map | With Map | Savings | |:----------|:-----------|:---------|:--------| | Sentinel scan (per change) | 3,000-8,000 tokens | 500-1,500 tokens | ~3-5× | | Scout exploration (repeat session) | 5,000-15,000 tokens | 1,000-3,000 tokens | ~3-5× | | Blast radius computation | Grep entire codebase | JSON lookup | Instant |
These savings compound with every code change in a session. In a session with 5 code changes, the map saves roughly 10,000-30,000 tokens on sentinel scans alone.
🎯 Design Principles
🫥 Invisibility
The user should never notice Hydra operating. No announcements, no permission requests, no process narration. If a head does the work, present the output as if the orchestrator did it.
⚡ Speed Over Ceremony
Don't overthink classification. Quick mental check: "Haiku? Sonnet? Me?" and go. If you spend 10 seconds classifying a 5-second task, you've defeated the purpose.
🔀 Parallel Heads
Independent subtasks launch in parallel. "Fix the bug AND add tests" → two heads working simultaneously.
⬆️ Escalate, Never Downgrade
If a head's output isn't good enough, Opus does it directly. No retries at the same tier. This mirrors speculative decoding's rejection sampling — when a draft token is rejected, the target model samples directly.
🤔 FAQ
Removes all agents, commands, skills, hooks, and cache files, and reverses the
host wiring — hooks/statusLine in ~/.claude/settings.json, hooks in
~/.gemini/settings.json plus the GEMINI.md marker block, and Codex's
hooks.json, config.toml marker blocks, and AGENTS.md block. Your own
configuration (including any hydra/config/ files) is preserved.
npx hail-hydra-cc --uninstall # every host with Hydra installed
npx hail-hydra-cc --uninstall --gemini # just one host💬 Feedback
Found a bug? Have a feature idea? Want to share feedback?
From within Claude Code:
/hydra:reportOr directly on GitHub:
🤝 Contributing
Found a task type that gets misclassified? Have an idea for a new head? Contributions are welcome!
- Fork it
- Create your branch (
git checkout -b feature/hydra-new-head) - Commit (
git commit -m 'Add hydra-optimizer head for perf tuning') - Push (
git push origin feature/hydra-new-head) - Open a PR
📜 License
MIT — Use it, fork it, deploy it. Just don't use it for world domination.
...unless it's code world domination. Then go ahead.
Prefer a clean, technical version? See the
spec-execbranch — same framework, zero theatrics.
