Skip to main content

M2 Harness 🚀 — Cost-Aware Hierarchical Coding Agent & Context Firewall

PyPI Version Python Version License Tests MCP Ready Status

M2 Harness is a high-throughput, cost-aware Autonomous Worker and Context Firewall architecture. It enables Frontier Reasoners (M1) (such as Claude 3.7 Sonnet, Gemini 2.0 Pro, GPT-4o, Cursor, or Google Antigravity) to delegate noisy, token-heavy tool loops (deep searches, test iterations, multi-file refactoring) to a Cheap Worker (M2) (DeepSeek V4-Flash, OpenCode Zen, Claude Haiku, or local Ollama), filtering raw context by 80%–98% (CCR) before returning verified structured evidence to M1.


🏛️ Comprehensive Architecture

flowchart TD
    User([User Prompt / IDE Action]) --> M1[M1 Frontier Reasoner & Orchestrator]
    
    subgraph M1_Layer ["M1 Frontier Cognitive Layer (Claude 3.7 / Gemini 2.0 Pro)"]
        M1 --> Router{Tri-Modal Execution Router}
    end

    subgraph Path_A ["Path A: Standard Delegated Worker (85%+ of Tasks)"]
        Router -->|Heavy Search / Multi-file / Tests| Runtime[M2 Authoritative Runtime State Machine]
        Runtime --> StateMachine[INIT ➔ EXECUTING ➔ VERIFYING ➔ COMPLETED]
        
        subgraph Worker_Subsystems ["M2 Worker Subsystems"]
            StateMachine --> L0[Zero-Token L0 Layer: Polyglot AST & Git Diff]
            StateMachine --> Sandbox[Execution Sandbox & Symlink Jail]
            StateMachine --> Memory[Active Working Memory: Facts / Hypotheses / Actions]
            StateMachine --> Firewall[Context Firewall & Budget Manager: 80-98% CCR]
            StateMachine --> Providers[Model-Agnostic Providers: DeepSeek / Zen / LiteLLM]
        end
        
        subgraph Hard_Gates ["Hard Verification Gates"]
            StateMachine --> Verifier[CompositeVerifier: Syntax / Tests / Lint / Scope]
            Verifier --> Integrity[IntegrityOracle: Anti-Tampering Guard]
        end
        
        Hard_Gates --> ResultContract[Structured ResultContract JSON]
    end

    subgraph Path_B ["Path B: Direct Precision Fallback"]
        Router -->|Subtle Race / Exact Bytecode / Review| DirectEdit[Direct Tool Execution & File Edits]
    end

    subgraph Path_C ["Path C: Autonomous Diagnostic Loop"]
        Router -->|Investigate Bug / TDD Repro| DiagnosticLoop[M2 Diagnostic Hypothesis Loop]
        DiagnosticLoop --> TestOracles[Independent Test & AST Oracles]
        TestOracles --> DiagnosticFix[Minimal Verified Patch]
    end

    subgraph Observability ["Observability & Event Bus"]
        EventBus[Canonical EventBus V2: 16 Lifecycle Events + Secret Redaction]
        Telemetry[Telemetry V2: P50-P99 Latency + M1/M2 Attribution + Cache Hit Rate]
        HUD[Live Webview HUD Dashboard :4040]
    end

    Runtime -.-> EventBus
    EventBus -.-> Telemetry
    EventBus -.-> HUD

    ResultContract --> Synthesis[M1 Final Synthesis & Structured User Response]
    DirectEdit --> Synthesis
    DiagnosticFix --> Synthesis

⚡ Tri-Modal Execution Flow

sequenceDiagram
    autonumber
    actor User
    participant M1 as M1 Frontier (Orchestrator)
    participant M2 as M2 Worker (Runtime Engine)
    participant L0 as Zero-Token L0 Tools
    participant Sandbox as Sandbox & Tools
    participant Gates as Hard Verification Gates
    participant Bus as Canonical EventBus

    User->>M1: "Refactor dispatcher to async and fix broken tests"
    M1->>Bus: TASK_CREATED
    M1->>M2: delegate_to_m2(task_description)
    
    M2->>L0: l0_ast_workspace_outline() [0 tokens]
    L0-->>M2: Module symbol tree
    M2->>Sandbox: Multi-turn tool execution (read/edit/test)
    Sandbox-->>M2: 50,000 chars raw terminal output
    
    M2->>M2: Context Firewall compresses output (97.4% CCR)
    M2->>Gates: CompositeVerifier (AST + Pytest + Diff Complexity)
    Gates-->>M2: Verified PASS (Score: 0.96, Integrity: Intact)
    
    M2->>Bus: TASK_COMPLETED (Redacted payload)
    M2-->>M1: ResultContract JSON (Status: SUCCESS, Confidence: 0.95, Evidence)
    M1-->>User: Final concise synthesis + Auto-collapsing trace

🌟 Core Pillars

Pillar Capability Technical Benefit
🛡️ Context Firewall Active working memory + dynamic compaction 80%–98% CCR (prevents context bloat & frontier token waste)
⚡ Zero-Token L0 Layer Instant Tree-sitter AST & Git diff summaries 0 LLM tokens for structural discovery & workspace diffs
🚦 Hard Verification Gates Syntax check, Pytest oracle, diff complexity, anti-tampering 0 False Successes (eliminates hallucinated task completion)
🌐 Model-Agnostic Engine DeepSeek V3/V4, OpenCode Zen, LiteLLM (Claude, GPT, Gemini, Ollama) Switch models instantly via CLI flag or config file
🔁 Tri-Level Deterministic Replay Provider, Runtime, and Semantic Hashing replay 100% offline regression testing with 0 API tokens
📊 Telemetry V2 & Pricing P50/P90/P95/P99 latency, M1 vs M2 cost attribution, cache hit rate Accurate historical auditability & ROI measurement
🩺 Release-Grade Diagnostics Deep system, git, sandbox, and parser checks via m2 doctor Instant verification for local environments and CI/CD pipelines

💰 Token Economics & Benchmark Comparison

Metric Raw Frontier Direct (Baseline A) Old M2 Agent Loop (Baseline B) M2 Harness (Production)
Verified Success Rate (VSR) 88.5% 76.2% 89.2% (Parity with Frontier)
False Success Rate (FSR) 8.2% 18.5% 0.0% (Enforced by Hard Gates)
Context Compression Ratio (CCR) 0.0% 45.0% 94.8%
Frontier Token Avoidance (FTAR) 0.0% 4.2x 18.6x
Average Cost per Task $0.380 $0.145 $0.042
Cost Savings (ROI) Baseline (0%) 61.8% 88.9% Reduction

📦 Installation

pip install m2-harness

Or install in development mode from source:

git clone https://github.com/HamzaDevv/hierarchical-coding-agent.git
cd hierarchical-coding-agent
pip install -e ".[dev]"

🩺 Diagnostics (m2 doctor)

Verify your environment health, Tree-sitter parsers, sandbox containment, and providers in one sub-100ms command:

m2 doctor
=========================================================================
   🩺 M2 WORKER DIAGNOSTIC HEALTH REPORT (m2 doctor)                    
=========================================================================
  [✓ PASS] Python Environment     : Python 3.13.3 with all dependencies ready
  [✓ PASS] Git & Workspace        : Workspace writable and valid Git repository
  [✓ PASS] L0 AST Engine          : L0 zero-token AST parser operational
  [✓ PASS] Security Sandbox       : Execution sandbox path jail and env sanitization active
  [✓ PASS] LLM Providers          : Providers ready (Replay, Zen, DeepSeek, Gemini)
  [✓ PASS] Deterministic Replay   : Deterministic replay fixtures and schema v2.0 verified
-------------------------------------------------------------------------
  Summary: 6 Passed | 0 Warnings | 0 Failures
  Overall Status: ✅ READY FOR PRODUCTION
=========================================================================

Use --strict in CI/CD pipelines:

m2 doctor --strict --json

🚀 CLI Command Matrix

# 1. Execute an autonomous coding task
m2 "Find all references to ResultContract and outline their symbols"

# 2. Instant zero-token AST code outline (0 LLM tokens)
m2 outline

# 3. Instant zero-token git diff summary (0 LLM tokens)
m2 diff

# 4. Scaffold cognitive rule files (AGENTS.md, .cursorrules) into project
m2 init

# 5. Launch local Webview HUD live dashboard
m2 hud --port 4040

# 6. Replay a recorded execution trace 100% offline
m2 replay tests/replay/golden_task --mode semantic

# 7. Run M2-Bench benchmark evaluation
m2 bench run --suite dev --baselines C

# 8. Manage multi-provider configurations
m2 config set model deepseek/deepseek-chat
m2 config get

🔌 Model Context Protocol (FastMCP) Setup

M2 exposes a high-performance FastMCP server. Add it to your AI coding environment in seconds:

Claude Desktop / Claude Code (~/.claude.json or claude_desktop_config.json)

{
  "mcpServers": {
    "m2-worker-agent": {
      "command": "m2-mcp-server",
      "env": {
        "DEEPSEEK_API_KEY": "sk-...",
        "WORKSPACE_ROOT": "/path/to/your/project"
      }
    }
  }
}

Cursor (.cursor/mcp.json)

{
  "mcpServers": {
    "m2-worker-agent": {
      "command": "uvx",
      "args": ["--from", "m2-harness", "m2-mcp-server"],
      "env": {
        "DEEPSEEK_API_KEY": "sk-..."
      }
    }
  }
}

Google Antigravity (~/.gemini/settings.json)

{
  "mcpServers": {
    "m2-worker-agent": {
      "command": "m2-mcp-server",
      "env": {
        "WORKSPACE_ROOT": "${workspaceFolder}"
      }
    }
  }
}

🐍 Python SDK Quickstart

from m1_m2_agent import M1OrchestratorAgent, TaskContract

# Initialize Orchestrator
agent = M1OrchestratorAgent(workspace_root=".")

# Route and execute task through Context Firewall
result = agent.route_and_execute(
    objective="Analyze src/m1_m2_agent/events/bus.py and verify async subscription logic"
)

# Access structured result contract
print(f"Status: {result['contract']['status']}")
print(f"Confidence: {result['contract']['confidence']}")
print(f"Evidence: {result['contract']['evidence']}")

# Ingest telemetry KPIs
kpis = agent.get_telemetry_report()
print(f"Context Compression Ratio: {kpis['context_compression_ratio']}%")
print(f"P50 Latency: {kpis['latency_p50_s']}s")

📚 Technical Documentation


📄 License

Licensed under the Apache License, Version 2.0.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

m2_harness-0.8.0.tar.gz (243.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

m2_harness-0.8.0-py3-none-any.whl (228.5 kB view details)

Uploaded Python 3

File details

Details for the file m2_harness-0.8.0.tar.gz.

File metadata

  • Download URL: m2_harness-0.8.0.tar.gz
  • Upload date:
  • Size: 243.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for m2_harness-0.8.0.tar.gz
Algorithm Hash digest
SHA256 c6155f6fcb8f724236389c11a47bd62c41df22b0a8c788e8edcbadafe99cc4bc
MD5 861fa4addafacc0b11a1fa07d19d2046
BLAKE2b-256 14c542cfff766eaf806a3501f6b92ae8b9c6fc29b125b0dc94140a3b1728cd1a

See more details on using hashes here.

File details

Details for the file m2_harness-0.8.0-py3-none-any.whl.

File metadata

  • Download URL: m2_harness-0.8.0-py3-none-any.whl
  • Upload date:
  • Size: 228.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for m2_harness-0.8.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ca173059ee94ddeb92a9f3cc182910296085dc34104a29f485da4e461af418bf
MD5 61648d8ea13ee1dfb1d3b64e3b232717
BLAKE2b-256 ff8258deef887c7a5ea63131da851400f20287a6c41ee45a51bdd36a524c988e

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.8.0 This release

2 files

0.7.0

2 files

0.6.0

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page