- Six Core Subsystems Investigated in
src/ag_harness/: While buildingm9g-agent-corps, we engineered and tested (1)ImmutablePrefixBuilderfor 95% Gemini implicit cache retention ($0.10/1Mvs.$2.00/1M), (2)HashlineEditor(4-char SHA-256 line hashes with ±25-line drift relocation and <1ms AST compile checks) +skeletonize_python_code()(75–90% AST token compression), (3) non-destructiveGIT_INDEX_FILEshadow Git snapshots (WorkspaceCheckpointManager) + SQLite WAL turn journaling (SessionStore), (4) a 5-tier self-healing hook pipeline (FiveTierHookPipeline,IntentGate,repair_json_arguments, andGitMemoryFaultSidecar), (5) topological multi-wave DAG orchestration (DAGEngine,TodoManager,BoulderEngine, andHarness2c1..c8surface validation), and (6) Windows↔WSL2 path/process bridging plus a Galois FieldGF(2^8)terminal QR remote PWA. - Why Our Standalone Harness Failed Against OmO, OpenCode, Claude Code, and Antigravity: A coding harness is governed by its tightest inner-loop coupling. Our custom orchestrator failed because (1) our best substrates in
argon_omo_substrate.pywere unwired from the livestream_turn()and worker loops, (2) subagents reported state via lossy prose-regex scraping (parse_from_markdowndefaulting missing headers toSUCCESS), (3) CLI subagents ran inside 300s blockingsubprocess.runblack boxes without live PTY streaming or mid-turn steering, (4) mandatory delegation ("Rule 1") imposed an 80s multi-hop latency tax on trivial 1–3 file edits, and (5) 12,000-character middle-out string slicing excised critical lines from source files and tracebacks. - The Architectural Pivot to
m9g-mcp: Rather than competing with mature inner loops (OmO's persistent JS/Python eval kernel + TTSR self-healing,OpenCode's Go/TS client-server session bus + LSP,Claude Code's native single-loop worktree engine, orAntigravity's container/IDE runtime), we extracted our seven deterministic substrates into a JSON-RPC 2.0stdioMCP server (m9g-power-tools) that any pre-existing harness can invoke natively.
The Hypothesis: Why We Tried to Build a New Multi-Agent Coding Harness
During our 1-billion-token weekend engineering sprint with gemini-4-argon and gemini-3.8-flash, we observed three recurring failure modes in standard LLM coding workflows: (1) context window bloat from reading entire source files into the frontier model's prompt history, (2) fragile file mutations where line-number drift across sequential edits corrupted source files, and (3) destructive workspace state where unverified agent edits polluted the developer's staged .git/index.
Our hypothesis was ambitious: if we constructed a dedicated 3-tier multi-agent coding harness from scratch—m9g-agent-corps (aliased as m9g-code and m9g)—that kept a frontier Higher Brain (APEX: gemini-4-argon / gemini-2.5-pro) strictly "above the weeds" while dispatching isolated Tier 2 (MIDDLE: gemini-2.5-pro-preview) and Tier 3 (WORKHORSE/SCOUT: gemini-3.8-flash / gemini-3.5-flash-lite) workers, we could achieve both 95% implicit cache savings and cleaner context isolation than general-purpose harnesses. Over several intensive iterations, we built 28 Python modules (~640 KB) in src/ag_harness/ and 17 test suites containing 169 unit and integration tests.
m9g-agent-corps (src/ag_harness/): Left — Tier 1 Executive Orchestrator (gemini-4-argon / APEX) with immutable prefix caching, 2-tier skill disclosure, and AST skeletonization; Center — Tier 2 (MIDDLE) and Tier 3 (WORKHORSE / SCOUT) workers; Right — the six structural failure modes that caused the standalone harness to underperform pre-existing harnesses (OmO, OpenCode, Claude Code, and Antigravity).
What We Investigated and Engineered Inside m9g-agent-corps
Before examining why the standalone harness failed as an end-to-end orchestrator, it is essential to document what we investigated while building D:\git\m9g-agent-corps. Rather than writing a thin prompt wrapper, we systematically investigated the eight core components of a modern coding harness (formalized in argon_omo_substrate.py:617 as HARNESS2_8_COMPONENTS: c1: system_prompt, c2: context_policy, c3: long_term_memory, c4: tool_guidance, c5: sub_agents, c6: skills_and_guardrails, c7: scripts, c8: hooks_and_plugins):
Immutable Prefix Caching & Tail-Only Dynamic Injection
In ImmutablePrefixBuilder (argon_omo_substrate.py:766) and corps.jsonc, we investigated why Gemini 2.5 Pro / 4 Argon's 95% implicit cache discount ($0.10/1M cached vs. $2.00/1M uncached) breaks in naive harnesses. We stripped dynamic regex patterns (**Generated:**, **Timestamp:**, Current git status:) from index 0, froze <immutable_system_prompt>, <immutable_agents_md>, sorted <immutable_tool_schemas>, and <immutable_repo_map> under a verified SHA-256 prefix_hash, and pushed all turn-varying state (<memory_sidecar_constraints>, <intent_gate_status>) to the user message tail while capping always-on text at 28,000 chars.
SHA-256 Hashline Editing & AST Skeletonization
In hashline_tools.py (508 lines), we built HashlineEditor: hashline_read() prefixes every line with a 4-char SHA-256 content hash (L{n}:{hash}|) and lazily surfaces parent-directory AGENTS.md files once per session (_SURFACED_DIR_AGENTS). hashline_edit() relocates drifted target spans within a ±25-line search window (_locate_matching_span), applies edits bottom-up (reverse=True) to prevent line-index shift, and runs a <1ms Python compile() AST syntax check. In context_controller.py, skeletonize_python_code() parses Python ASTs into signatures and docstrings, compressing token volume by 75%–90%.
Shadow GIT_INDEX_FILE Checkpoints & SQLite WAL Store
In checkpoint.py (685 lines), we investigated how to snapshot and roll back dirty worktrees (including untracked files) without touching the user's staged .git/index. WorkspaceCheckpointManager._capture_git_tree_sha() copies .git/index to an ephemeral tempfile.TemporaryDirectory, sets GIT_INDEX_FILE, runs git add -A and git write-tree to capture a 40-char tree SHA, and restores via git read-tree + git checkout-index -a -f (with a 250-file Copy-on-Write fallback). In session_store.py (1,508 lines), we built a thread-locked SQLite WAL state machine tracking turn states (CREATED → STREAMING → TOOL_PENDING → COMMITTED / ROLLED_BACK).
5-Tier Hook Pipeline, IntentGate & Git Fault Sidecar
In argon_omo_substrate.py, we engineered FiveTierHookPipeline: Tier 1 injects past fault rules from GitMemoryFaultSidecar (an isolated Git repo at .m9g/fault_memory); Tier 2 (IntentGate) classifies prompts (information, judgment, plan, build) and blocks mutating tools until prove_plan() is called; Tier 3 runs repair_json_arguments() to heal malformed LLM JSON and pre-verifies hashline spans; Tier 4 compresses tracebacks via extract_concise_stack_trace(); and Tier 5 commits resolved faults as YAML-frontmatter lessons (cue, lesson, evidence).
11-Agent Roster, 16 Categories, DAGEngine & Boulder
Inspired by OmO, we built gemini_roster.py (649 lines, 11 agents: sisyphus, oracle, metis, momus, hephaestus, flash-worker, qa-executor, explore, librarian, code-reviewer, gate-reviewer across 16 categories), ulw_engine.py (TodoManager + durable BoulderEngine + Superpowers directives), and dag_engine.py (450 lines, Kahn's topological wave sort with CyclicDependencyError, bounded semaphore concurrency, and upstream handoff injection).
WSL2 Bridge, GF(2⁸) Terminal QR PWA & System Doctor
In wsl_bridge.py (442 lines), we built bidirectional Windows↔WSL2 path translation (WSLPathTranslator), WSLENV credential forwarding, and POSIX process-group cleanup. In remote_control.py (849 lines), we implemented pure-Python Galois Field GF(2^8) Reed-Solomon QR encoding rendered in Unicode half-blocks (▀▄█) for mobile PWA pairing, alongside herdr_bridge.py IPC state reporting and an 8-pillar run_system_doctor() + AI-slop scanner (doctor.py).
Why Building a New Standalone Harness Failed in Practice: Six Root Causes
Every subsystem above passed its unit test suite (`169/169` tests passing across 17 test files). Yet when we used `m9g-agent-corps` as our primary coding harness on real multi-file engineering tasks, it consistently felt slower, more brittle, and more error-prone than pre-existing harnesses (`OmO`, `OpenCode`, `Claude Code`, and `Antigravity`). Auditing our own codebase revealed a fundamental systems lesson: **isolated subsystems do not make a reliable coding harness; the reliability of a harness is determined by the tightest feedback loop in its inner execution kernel.** Specifically, six architectural disconnects caused our standalone harness to fail:
Failure Cause 1 — The "Unwired Substrate" Disconnect (`argon_omo_substrate.py` vs. `main.py` & `agy_workers.py`)
We built `FiveTierHookPipeline`, `IntentGate`, `HashlineEditor`, `ImmutablePrefixBuilder`, and `TmuxSubscriptionWatcher` inside `argon_omo_substrate.py` (1,245 lines) and verified them via `run_argon_smoke_benchmarks()`. However, in the actual interactive REPL loop (`stream_turn()` in `main.py:124`) and worker dispatcher (`spawn_agy_worker()` in `agy_workers.py:427`), the agent ran on `google.antigravity.Agent(config=config)`—whose built-in runtime tools (`edit_file`, `replace_file_content`, `run_command`) bypassed `FiveTierHookPipeline` and `IntentGate` entirely! Workers were merely asked *in prose* to verify their edits, whereas in **OmO**, **OpenCode**, and **Claude Code**, the edit validator, permission gate, and LSP diagnostics sit directly inside the single mandatory tool-execution path.
Failure Cause 2 — Lossy Prose-Regex Handoffs Defaulting to False-Positive SUCCESS (`agy_workers.py:296-305`)
When our Tier-1 Higher Brain delegated a task to a Tier-2/Tier-3 worker, `WorkerHandoffReport.parse_from_markdown()` did not receive a structured tool-execution state object. Instead, it asked the worker to print a Markdown template at the end of its response and scraped it with regular expressions:
if status_match: status = status_match.group(1).upper()
elif not raw_text.strip() or raw_text.lstrip().startswith(("[Worker Execution Error", "Traceback")): status = "FAILED"
else: status = "SUCCESS"
Why this broke multi-wave DAGs: Whenever a worker hit its token ceiling, got truncated mid-stream, exited a CLI subprocess with a non-zero code (`check=False` at line 415), or phrased its conclusion conversationally without `## STATUS:`, `parse_from_markdown()` defaulted `status` to `"SUCCESS"` with `files_modified=[]`. `DAGEngine` treated the failed wave as completed and dispatched dependent nodes onto an unedited worktree.
Failure Cause 3 — 300-Second Black-Box CLI Subprocesses (`agy_workers.py:409-424`) vs. Live In-Process Kernels
To leverage external CLI workers (`agy.exe -p` or `omo.exe -p`), `spawn_agy_worker()` wrapped a synchronous `subprocess.run` inside `asyncio.to_thread`:
subprocess.run, cmd, cwd=abs_ws, capture_output=True, text=True, timeout=300, check=False
)
Why this failed against OmO and OpenCode: Buffering stdout/stderr via `capture_output=True` turned every subagent into a 5-minute black box. You could not inspect live progress (unlike OmO's `task_output(mode="tail")` or `monitor`), you could not steer a drifting worker mid-turn (unlike OmO's `task_send` or `bash_input`), and if a worker timed out at 300 seconds, `subprocess.TimeoutExpired` discarded all intermediate work.
Failure Cause 4 — The "Rule 1" Mandatory Delegation Tax & 19-Tool Prompt Bloat (`config.py:381-485`)
In `config.py:457`, our Higher Brain system prompt enforced **Rule 1 (Stay Above the Weeds)**: *"For any multi-file edit, UI build, reverse-engineering analysis, or test loop, you MUST NOT read 500-line files directly into your own context. Instead... dispatch `spawn_agy_worker`."* Simultaneously, `_resolve_agent_tools()` bound **19 Higher-Brain tools** plus up to `28,000` characters of static prompt prefix on Turn 1.
Why this tripled latency on routine tasks: For a 1-to-3 file bug fix, **Claude Code**, **OpenCode**, and **OmO** read the file, apply an exact edit, and run diagnostics in a single in-process loop (~15–25 seconds). In `m9g-agent-corps`, Rule 1 forced a multi-hop relay (`Higher Brain → cold-start worker process → re-read files from disk → compress to 300-word Markdown summary → Higher Brain`). Compressing cross-file type signatures into a 300-word prose summary stripped the exact invariants the Higher Brain needed when a test failed.
Failure Cause 5 — Destructive Middle-Out String Slicing (`hooks.py:23-25` & `subagents.py:34`)
To prevent token-per-minute (TPM) exhaustion, `cap_tool_output()` truncated any tool result exceeding `12,000` characters by keeping the first `4,000` characters and the last `8,000` characters, while `trim_context_for_tier2()` excised the middle of `file_context`:
file_context[:keep_chars // 2] + "\n...[TRIMMED]...\n" + file_context[-(keep_chars // 2):]
Why this caused hallucinated edits: In a 600-line source module or a pytest run with multiple failures, lines 120–380 sit squarely in the deleted middle. Because the model could not see the middle of the file, it hallucinated function bodies or entered repetitive read loops. Pre-existing harnesses (`OmO`, `OpenCode`, `Claude Code`) never slice the middle out of a file read; they enforce explicit line-indexed pagination (`offset` / `limit`) so the model knows exactly which line range it holds.
Failure Cause 6 — Hard-Kill Loop Breaking & Orchestrator-on-Orchestrator Friction (`agy_workers.py:557`)
When `StreamLoopMonitor` detected 3 identical tool calls, `_run_worker()` executed `break` on the stream and killed the turn with `STATUS: FAILED`. Worse, when `m9g-agent-corps` spawned `agy` or `omo` as a CLI subagent without stripping inner orchestration, we stacked an orchestrator on top of an orchestrator—paying double prompt overhead and risking $O(b^d)$ nested subagent branching. By contrast, **OmO** uses in-stream TTSR (`
Comparing m9g-agent-corps with Pre-Existing Harnesses: OmO, OpenCode, Claude Code, and Antigravity
Building `m9g-agent-corps` gave us a ground-truth lens into *why* pre-existing harnesses—**OmO (Oh-My-OpenAgent)**, **OpenCode**, **Claude Code**, and **Google Antigravity (`agy`)**—are architected the way they are. Below is our head-to-head systems comparison across execution substrates, edit mechanics, context management, and failure recovery:
| Architectural Dimension | m9g-agent-corps (Standalone v0.3) | OmO (Oh-My-OpenAgent) | OpenCode | Claude Code | Google Antigravity (agy) |
|---|---|---|---|---|---|
| Primary Execution Kernel | Python wrapper over google.antigravity.Agent + blocking CLI subprocesses |
Persistent JS (Bun) & Python eval kernels + PTY session manager |
Go/TypeScript client-server event bus + provider-agnostic tool loop | Tight single-process Node/TS agent loop with native shell & file tools | Remote Linux container (Interactions API) + Local IDE/Manager harness |
| File Read & Context Windowing | 12k middle-out slice (4k head + 8k tail deletes middle); built AST skeletonizer |
Line-indexed offset/limit + parallel batch reads inside eval |
Line-paginated file reads + automatic LSP symbol & diagnostic context | Line-numbered offset/limit reads + structural AST/ripgrep search |
Windowed file view + container filesystem tools + inline skill context |
| Code Mutation & Edit Safety | Built SHA-256 HashlineEditor (±25-line drift), but unwired in default worker loop |
Exact disjoint multi-hunk edit + immediate lsp_diagnostics gate |
Exact string replacement / patch application with automatic LSP check | Exact uniqueness-checked string replacement after mandatory file read | Container/workspace file mutation + test runner execution |
| Subagent Delegation & Handoffs | Rule 1 mandatory delegation; regex on trailing prose (defaults missing status to SUCCESS) |
Typed async task / workpool + CoW worktree isolation + task_output peek |
Scoped child session tasks sharing the local server event bus | Targeted Task subagents for parallel exploration; direct main-loop edits |
Dynamic subagents in Manager mode, or stateless leaf worker via agy -p |
| Long-Running Process & Terminal Control | Blocking 300s subprocess.run (capture_output=True); no mid-turn steering |
Live PTY sessions (bash_output, bash_input, monitor event wakes) |
Streaming command runner with user interrupt & output tailing | Background bash jobs with live stdout/stderr polling | Sandboxed Linux container shell or local auto-mode command runner |
| Loop Recovery & Verification Gate | Hard break kills worker on 3 repeats; verification gates built in sidecar but unwired |
In-stream TTSR self-healing + enforced V1/V2/V3 diagnostic/test gates | LSP error injection into tool result + interactive turn rollback | In-loop tool-error feedback + pre-commit hook & test verification | Built-in policy hooks + container test verification |
The Engineering Pivot: Extracting Our Best Substrates into the m9g-mcp Power-Tool Server
The post-mortem of m9g-agent-corps taught us a decisive lesson: do not build a competing outer agent loop when pre-existing harnesses (`OmO`, `OpenCode`, `Claude Code`, `Antigravity`) already provide battle-tested inner loops, live PTY management, and native tool recovery. At the same time, several deterministic substrates we engineered during our investigation solved real pain points that pre-existing harnesses still face (such as 75–90% AST token compression, non-destructive shadow Git index checkpoints, and SHA-256 drift-tolerant batch edits).
In commit cfa9395 (ag_harness/agy_mcp_server.py, 662 lines), we pivoted m9g-agent-corps from a monolithic competitor harness into an open-source **Model Context Protocol (MCP) Power-Tool Server (`m9g-mcp` / `m9g-power-tools`)** over JSON-RPC 2.0 `stdio` (`m9g --install-agy-mcp -w .`). Instead of wrapping `OmO`, `OpenCode`, `Claude Code`, or `Antigravity` from the outside, those harnesses now mount `m9g-power-tools` from the inside as seven deterministic tools:
m9g_skeletonize(`context_controller.py`): AST structural compression stripping Python function/method bodies into signatures and docstrings (75%–90% token reduction before reading full files).m9g_checkpoint(`checkpoint.py`): Non-destructive workspace snapshots (`create`, `list`, `diff`, `undo`, `rollback`) using an isolated temporary `GIT_INDEX_FILE` (`git write-tree` / `git read-tree`) that never touches the user's staged `.git/index`.m9g_hashline_read(`hashline_tools.py`): Line-ranged file reader annotating every line with a 4-character SHA-256 hash (`L{n}:{hash}|`) and lazily surfacing subdirectory `AGENTS.md` instructions once per session.m9g_hashline_edit(`hashline_tools.py`): Bottom-up, hash-verified multi-file batch editor with automatic `±25`-line drift relocation and sub-millisecond Python AST syntax verification.m9g_code_intel(`hashline_tools.py`): Multi-language structural symbol search (`ast_grep`), definitions, references, document symbols, and hover docstrings across Python, TypeScript, JavaScript, Rust, and Go.m9g_memory(`memory_store.py`): Persistent YAML-frontmatter Markdown memory blocks (`decisions`, `architecture`, `learnings`) with automatic wikilink refactoring.m9g_gemini_media(`gemini_api_cli_bridge.py`): Stateless multimodal generation (`tts`, `image`, `video`) writing binary outputs directly to disk (`output_path`) so base64 payloads never enter the LLM context window.
This technical article (M9G-TR-2026-02), the 28-module m9g-agent-corps architecture (src/ag_harness/), the six-cause harness failure post-mortem, the five-harness comparative matrix (m9g-agent-corps vs. OmO, OpenCode, Claude Code, and Antigravity), and the m9g-mcp power-tool server design constitute original published prior art by Minsu Chang, Ph.D. (장민수 / M9G). This work is published exclusively as a web-native technical research disclosure on mincasurong.github.io. Unauthorized reproduction, paraphrasing, or conversion of this systems analysis, taxonomy, or telemetry into third-party conference papers or arXiv preprints is strictly prohibited.