Instead of burning 80,000 tokens per call on a single sluggish prompt, I built a modular mesh of six specialized subagents managed by an autonomous Conductor. Each subagent gets clean context and stripped-down tools, dropping response latency by 80.2% and slashing token costs by 76.8% across 700+ live runs.
Most enterprise AI workflows try to build a single "God Prompt". They paste a 50-page operating manual, 20 API tool schemas, and thousands of lines of code into one massive prompt, and pray the AI doesn't break things. In real life, that fails hard: the model gets confused and forgets rules, costs explode to $34+ a session, and asking it nicely not to delete files is wishful thinking. Here is how my Conductor-Subagent mesh fixes it.
How Most People Do It: Force one generalist AI to juggle product specs, coding standards, database schemas, and terminal execution all at once. Every follow-up query retransmits 80,000+ tokens of dead weight, driving costs to $34+ per session and triggering severe hallucination loops.
How Karol Builds It: An autonomous Conductor breaks work into bite-sized tasks, spawns single-purpose subagents with physically stripped tool manifests, and requires consecutive clean review passes before anything gets merged.
Conductor pulls the next task from Questimus REST API, checks dependencies, and drafts a scoped brief.
Code Builder spawns in a fresh 0-turn window, writes a failing test first, writes clean code, and proves green.
Two consecutive review rounds must pass 100% clean with zero defects. Whether it takes 2 rounds or 10, no code merges until back-to-back reviews come back completely green.
PreToolUse hooks verify linters and branch rules before atomic git commit and closing the ticket.
| Harness Environment | Frontier Reasoning Models Tested & Deployed | Primary Operational Role | Hook Enforcement Mechanism |
|---|---|---|---|
| Google Antigravity | Gemini 4 Argon, Gemini 3.8 Flash / Pro, Google AI Studio reasoning engines, plus earlier generational baselines (Gemini 1.5 Pro, and several older ones) | Visual application builds, multi-workspace refactoring, and interactive agent collaboration | PreToolUse & PostToolUse JSON IPC via .agents/hooks.json |
| Claude Code (Anthropic) | Sonnet 5, Sonnet 5.5, Opus 4.8, Opus 5, Opus 5.5, Fable 5, plus earlier frontier baselines (Claude 3 Opus, and several older ones) | Deep logic reviews, complex test suites, and autonomous conductor runs | PowerShell scripts registered in .claude/settings.json |
| DeepSeek Harness (DSH) | DeepSeek v4 Pro, DeepSeek v4 Flash, DeepSeek v3, GLM 5.3, GLM 5.3 Flash, local Ollama/Unsloth setups, plus earlier open-weight baselines (and several older ones) | Fast background checks, local test runs, and rapid code reviews | Headless CLI wrapper with strict standard output validation |
Beginner agent setups give every model full system access (Read, Write, Bash, Git, Network) and then try to tell it in plain English: "Please only review code, do not edit files." That is a complete joke. When an agent hallucinates or encounters an edge case, it will edit files anyway. In my setup, we use physical tool stripping: if an auditor agent does not need to edit files, the write_file tool is physically deleted from its manifest. Even if an adversarial prompt tries to hijack it, the tool literally does not exist.
| Subagent Role | Target Models | Sandboxed Tools Allowed | Physically Stripped Tools | Lifecycle Model |
|---|---|---|---|---|
| Conductor | Gemini Flash / Sonnet / Opus | Task planning, Questimus REST, subagent invoke | Direct code writes, raw git commits | Persistent (issue supervisor) |
| Code Builder | Model-inherited (Sonnet/Flash) | Scoped Read, Scoped Write, Test Runner | Git push, branch switches, external HTTP | Single-Task (1 task = 1 fresh turn) |
| Code Reviewer | Model-inherited (Opus/Sonnet) | File Read, Git Diff, Grep/Glob search | File Write, File Edit, Shell exec, Git push | Throwaway (Read-only review fork) |
| Security Reviewer | Frontier reasoning engine | AST Inspector, File Read, Secrets Scanner | File Write, File Edit, Shell, Network egress | Throwaway (Read-only pre-commit) |
| Test Writer | High-speed reasoning model | File Read, Scoped Test Dir File Write | Production source edits, Git operations | Single-Task (Sandboxed generator) |
| Research Subagent | High-efficiency model | Web Search, Documentation Read, Grep | File Write, Shell exec, Git operations | Background (Dies when search finishes) |
Real production specifications from AGENT.md and atomic specialist files. Notice the intentional architecture: high-leverage autonomous power (parallel specialist swarms, red-before-green TDD, Questimus REST state) paired with unbreakable boundaries (physically stripped write tools, zero git write access, strict scope locks).
.agents/agents/code-reviewer/AGENT.md (220-Line Production Contract) • Coordinates 12 atomic domain specialist subagents in parallel.
✅ Confirmed Fixed, 🟡 Partially Fixed, and ⚠️ New Regression across rounds.write_to_file and replace_file_content are literally deleted from allowed tools.agent grant is locked exclusively to specialist dispatch—cannot delegate its own review.
---
name: code-reviewer
description: Independent code review subagent — correctness, edge cases, security, performance.
model: inherit
tools:
- view_file
- run_command
- invoke_subagent
# NOTICE: write_to_file and replace_file_content are PHYSICALLY STRIPPED from tools
---
## Cold Review Mandate & Zero Rationalization
You are a staff-level code reviewer doing a pre-delivery review. You have no knowledge
of what the implementing session intended or rationalized. You review the code as it is,
cold. Never soften findings because the code "seems to work" or "is probably fine."
## Specialist Dispatch (On by Default — Parallel Subagent Swarm)
Beyond your own 7 Review Dimensions, decide which bundled specialist checklists in
<AGENT_DIR>/resources/specialists/ are relevant and dispatch EACH as a parallel subagent:
- security.md — auth/session/token/role changes or backend diff > 100 lines
- performance.md — algorithmic complexity, hot-path allocations, unindexed filters
- red-team.md — adversarial attack vectors, silent failures, trust boundary exploits
- error-handling.md — exception swallowing, unhandled promise rejections, recovery chains
- api-contract.md — API/OpenAPI/GraphQL breaking changes and backward compatibility
- data-migration.md — schema/migration changes, zero-downtime rollbacks
Dispatch relevant specialists in a SINGLE message so they execute in parallel.
Each specialist subagent returns strict JSON: {"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"...","line":N,...}
Merge specialist findings into your own 3-tier output; dedupe across all sources.
## Systemic Pattern Sweep (Mandatory on Defect Discovery)
The moment you flag a regex or algorithmic defect (e.g. an O(n²) pattern or bad complexity),
immediately grep the REST of the codebase for the same pattern before finishing the round.
A fix in one file never implies the pattern was swept everywhere else it appears.
## Follow-Up Round Comparison Engine
When a prior report is supplied, track state transitions explicitly:
- ✅ CONFIRMED FIXED — what was wrong, confirmed resolved with evidence
- 🟡 PARTIALLY FIXED — what changed, what's still incomplete or wrong
- 🆕 NEW INDEPENDENT — issue surfaced by this round's broadened scope
- ⚠️ NEW REGRESSION — defect directly introduced by a prior round's fix
.agents/agents/code-builder/AGENT.md (132-Line Production Contract) • Conductor Task Executor
node questimus.js get <id>.NEVER git add, NEVER git commit, NEVER push. Changes left unstaged.--- name: code-builder description: Implementation subagent for conductor workflows — one task per spawn, always a fresh context. model: inherit tools: - view_file - replace_file_content - write_to_file - run_command --- ## Authority & First Step: Direct Questimus REST Ingestion The brief's task block does not carry the task's full text: it carries the Questimus sub-issue identifier. Your FIRST STEP before any other work: read that exact sub-issue via the questimus skill: node <path-to-questimus.js> get <id> What you read directly from Questimus is authoritative and complete. ## Absolute Branch & Git Lockdown Work on the branch the brief states — never create, switch, or delete branches. YOU NEVER git add, NEVER git commit, NEVER push. The conductor reviews the working tree, stages, and commits. Leave every change unstaged. ## Scope Lock & Environment Freeze Build ONLY the task's declared Files. If you find the task genuinely cannot be done within that list, STOP and report that fact — do not expand scope to make it work. Fixes stay minimal and inside the Files list; unrelated bugs are reported, never fixed. The conductor's environment state is binding: if impossible, STOP and report. ## Mandatory Red-Before-Green TDD When the task prescribes TDD: write the failing test first and show it RED before implementing. The red run's output MUST be pasted in your Evidence — a red-before-green claim without the pasted red output is UNPROVEN and rejected. ## Non-Negotiable Output: DEBUG REPORT Block End every single run with exactly this structured block: ## DEBUG REPORT — <task id> **What was built**: <summary> **Files touched**: <exact list — must match task's declared Files> **Evidence**: - <command> → <pasted real output, truncated only for length, never summarized> **Status**: verified | best-effort | reverted
.agents/agents/code-reviewer/resources/specialists/*.md • Decoupled, single-responsibility review protocols executed in parallel.
security.md, red-team.md, performance.md, api-contract.md, data-migration.md, error-handling.md, etc.NO FINDINGS.
# Output Contract Across All 12 Specialists (Strict JSON Lines):
{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"security","summary":"...","fix":"..."}
If no findings: output `NO FINDINGS` and nothing else. No preamble, no commentary.
---
### Excerpt: security.md (Input Validation & Trust Boundaries)
Scope: When SCOPE_AUTH=true OR (SCOPE_BACKEND=true AND diff > 100 lines)
- Input Validation: query parameters used directly in file paths; unvalidated webhook payloads
- Auth & Authorization: endpoints missing auth middleware; checks defaulting to allow
- Role Escalation: user can modify their own role/permissions or access IDOR objects
- Injection Vectors: command injection via subprocess calls; SSRF via user-controlled fetch
- Cryptographic Misuse: weak hashing, non-constant-time comparisons on secrets/tokens
- Secrets Exposure: credentials in URLs; PII stored in plaintext
---
### Excerpt: red-team.md (Adversarial Stress Testing)
This is NOT a checklist review. This is adversarial analysis.
You have access to the other specialists' findings. Your job is to find what they MISSED.
Think like an attacker, a chaos engineer, and a hostile QA tester simultaneously:
1. Attack the Happy Path: What happens under 10x normal load? Two requests hit same resource?
2. Find Silent Failures: Catch-all blocks that swallow exceptions? Partial batch crashes?
3. Exploit Trust Assumptions: Data validated on frontend but trusted blindly on backend?
4. Find What Specialists Missed: Cross-category seams where two separate systems meet.
Natural-language guardrails (e.g. "You are a helpful assistant. Do not execute destructive commands") are wishful thinking. In complex codebases, recursive error loops, adversarial prompt injection, and hallucinations will eventually bypass text rules. Our rule is dead simple: Never trust an AI to self-police. Deterministic code must govern probabilistic models—put a real script in front of the model that slams the door shut.
Autonomous agent requests shell execution (e.g., run_command("rm -rf ./build")).
Harness intercepts execution request out-of-band and pipes JSON payload into STDIN of security-gate.ps1.
Hook parses command string against 19 destructive regex signatures (force-push, disk wipes, hard resets).
Destructive pattern detected: hook emits exit code 2 to stderr. The OS shell never spawns. Zero damage possible.
| Threat Category | Target Signature (Regex Pattern) | Operational Risk Mitigated | Hook Action |
|---|---|---|---|
| Filesystem Wipe | rm -rf, rm -fr, sudo rm | Irreversible deletion of build assets or project source trees | Exit Code 2 |
| Git History Destruction | git push --force, git push -f, git reset --hard | Overwriting remote commit history or uncommitted working state | Exit Code 2 |
| Branch Corruption | git branch -D | Force-deleting branches containing unmerged production code | Exit Code 2 |
| Working Tree Wipe | git checkout \., git restore \., git clean -f | Silently discarding uncommitted local engineering work | Exit Code 2 |
| Database Annihilation | DROP TABLE, DROP DATABASE, TRUNCATE TABLE | Catastrophic drop of relational tables in local or container databases | Exit Code 2 |
| Host System Damage & Fork Bombs | mkfs, dd if=, chmod -R 777, :\(\)\{:\|:&\};: | Filesystem corruption, permission stripping, and fork bombs | Exit Code 2 |
# security-gate.ps1 — PreToolUse hook, blocks destructive Bash / run_command commands
# Hook event: PreToolUse -> bash | run_command
# Exit 2 = hard block (Claude Code/DSH); Exit 0 with decision: "deny" (Antigravity)
$ErrorActionPreference = 'Stop'
$InputJson = [Console]::In.ReadToEnd()
$cmd = ''
$isAntigravity = $false
try {
$data = $InputJson | ConvertFrom-Json
if ($null -ne $data.tool_input -and $null -ne $data.tool_input.command) {
$cmd = [string]$data.tool_input.command
} elseif ($null -ne $data.toolCall -and $null -ne $data.toolCall.args -and $null -ne $data.toolCall.args.CommandLine) {
$cmd = [string]$data.toolCall.args.CommandLine
$isAntigravity = $true
}
} catch {
$cmd = ''
}
# 19 Patterns that are hard-blocked regardless of context (case-insensitive)
$patterns = @(
'rm -rf', 'rm -fr', 'git push --force', 'git push -f ', 'git push -f$',
'git reset --hard', 'git clean -fd', 'git clean -f', 'git branch -D',
'git checkout \.', 'git restore \.', 'DROP TABLE', 'DROP DATABASE',
'TRUNCATE TABLE', 'DELETE FROM .* WHERE 1=1', 'mkfs', 'dd if=',
'chmod -R 777', 'sudo rm', ':\(\)\{:\|:&\};:'
)
foreach ($pat in $patterns) {
if ($cmd -match "(?i)$pat") {
$msg = "BLOCKED by security-gate: destructive pattern detected ($pat)."
[Console]::Error.WriteLine($msg)
[Console]::Error.WriteLine(" Pattern: $pat")
[Console]::Error.WriteLine(" Command: $cmd")
[Console]::Error.WriteLine(" If this is intentional, run it manually in your terminal.")
if (-not $isAntigravity) {
exit 2 # Claude Code & DSH: Exit 2 halts execution immediately
}
@{ decision = "deny"; reason = "$msg Command: $cmd" } | ConvertTo-Json -Compress
exit 0
}
}
if ($isAntigravity) { @{ decision = "allow" } | ConvertTo-Json -Compress }
exit 0 # Verified clean: tool allowed
I have run over 1,000 autonomous agent sessions to date. The first few hundred were messy baby steps—lots of trial and error, breaking builds, testing crazy setups, and finding shit out the hard way. But the last 700+ sessions have run exclusively on this mature multi-agent architecture. Our full engineering library contains 16 specialized skills totaling 312 KB of instructions (~78,000 tokens). Statically stuffing all of that into every turn burns through your budget in minutes. Here is the real data from 700+ production sessions comparing the old monolithic approach to our dynamic injection engine.
~78,000 tokens across 16 specialized manuals (code review, database migrations, security audits, git release).
6.85 million tokens per 50-turn session ($34.25 API burn). Sluggish 24.2-second wait times per response.
1.59 million tokens per 50-turn session ($7.95 API cost). −76.8% cost cut and instant 4.8s response times.
| Operational Metric | Monolithic Baseline | Dynamic Subagent Mesh | Delta | Impact |
|---|---|---|---|---|
| Baseline Turn Context Size | 82,400 tokens | 4,200 tokens | -78,200 tokens | -94.9% |
| Total Tokens per 50-Turn Session | 6,850,000 tokens | 1,590,000 tokens | -5,260,000 tokens | -76.8% |
| Average Turn Response Latency | 24.2 seconds | 4.8 seconds | -19.4 seconds | -80.2% |
| Attention Retrieval Accuracy (Pass@1) | 61.4% | 94.2% | +32.8% | +53.4% |
| False-Positive Tool Invocations | 14.2% | 0.4% | -13.8% | -97.2% |
| Average Developer Session Cost | $34.25 | $7.95 | -$26.30 | -76.8% |
Large language models are stateless compute engines, not databases. If you keep 50 turns of back-and-forth chat in memory, the context window fills up with junk and the model starts drifting. In my architecture, we can wipe the agent's context completely to 0 tokens at any time without losing a single line of progress. All operational state is externalized to Questimus (our internal project management, ticketing and tracking tool) via REST API through a clean two-level continuity model.
Stores high-level system state, current release version, active git branch, verified test suites, and discovered landmines. Checked automatically at session start; serialized and committed via REST at session close.
Mid-task progress, failing test output, and fix evidence are appended directly into the active ticket description (safe description-only editing; never uneditable comments). Any fresh agent can resume mid-task without reading conversation logs.
# 1. Read macro session context at startup (restores state in <200ms) node .agents/skills/questimus-arsenal/scripts/questimus.js handoff # 2. Append in-flight atomic progress to active ticket description node .agents/skills/questimus-arsenal/scripts/questimus.js update TASK-104 --desc-file .tmp/progress.md # 3. Serialize end-of-session run state to persistent database node .agents/skills/questimus-arsenal/scripts/questimus.js handoff --write-file .tmp/handoff-state.md
A high-signal, 7-minute split-screen walkthrough demonstrating autonomous subagent delegation, live PreToolUse security gate interception, and dynamic skill injection against production codebases.
| Timestamp | Chapter Title | Core Demonstration & Key Insight |
|---|---|---|
| 0:00 – 1:15 | The Monolithic Prompt Trap | Why 90% of enterprise agent setups stall: attention degradation ("Lost in the Middle") and runaway API costs. |
| 1:15 – 3:15 | Subagents & The Conductor Pattern | Live demonstration of physical tool stripping: auditor agents operate with zero write or shell tools. |
| 3:15 – 4:45 | Deterministic OS Guardrails in Action | Simulating an agent requesting rm -rf; out-of-band PowerShell hook traps command at Exit Code 2. |
| 4:45 – 6:15 | Token Economics & Session Continuity | Dynamic skill injection slashing 76.8% of token burn, paired with 0-token context wipes via Questimus REST. |
| 6:15 – 7:00 | Strategic Operations Conclusion | Executive hiring takeaway: moving from fragile prompt experimentation to industrial software systems. |
Verifies code-reviewer manifest. Confirms write_to_file and replace_file_content are physically stripped.
Simulates agent attempting rm -rf ./production_build. Intercepted out-of-band: shell never spawns, Exit Code 2.
Measures 16 production skills: 312.4 KB (~78,000 tokens) decoupled from static prompts into lightweight on-demand triggers.
Breaking huge engineering roadmaps into bite-sized tasks that fresh subagents build and verify with back-to-back clean reviews.
Cutting API bills by 76.8% by feeding models only what they need, exactly when they need it, with zero memory bloat.
Stripping unneeded tools from subagents and running real OS hooks so an AI can never break production or wipe a drive.