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.

Metadata

Release files for m2-harness 0.9.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for m2-harness 0.9.0
File Size Uploaded Provenance
m2_harness-0.9.0.tar.gz 505.6 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for m2-harness 0.9.0
File Interpreter ABI Platform
m2_harness-0.9.0-py3-none-any.whl Python 3 none any Details

Total release size: 912.7 kB

Release files / m2_harness-0.9.0.tar.gz

Download URL m2_harness-0.9.0.tar.gz
Size 505.6 kB
Tags Source
SHA-256 checksum
How to use checksums
1fbea1f0f1f41b86ee907a92e55343e01d1fb06ad1ef4dc35e6edcbd46c7f3a4
BLAKE2b-256 checksum
How to use checksums
d870ff4f0a27b311298dd814ed96b8dd03b30386f5138f48f37c977670d5f29c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.3

Release files / m2_harness-0.9.0-py3-none-any.whl

Download URL m2_harness-0.9.0-py3-none-any.whl
Size 407.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
53baab4fa09f68680e057d02bb49b490dff789c5fa4c9d9dd78b48d7959d253e
BLAKE2b-256 checksum
How to use checksums
8c88e7394f0076e0e31fb98609b7efbaaaec2b5309c06b6336796c756b17f64a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.3

Security for m2-harness 0.9.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page