Metadata-Version: 2.4
Name: m2-harness
Version: 0.8.0
Summary: Cost-Aware Hierarchical Coding Agent & Context Firewall — Universal MCP Server, CLI, and Python SDK
Author-email: Hamza <ameerhamzakhan1305@gmail.com>
License: Apache-2.0
Project-URL: Homepage, https://github.com/HamzaDevv/hierarchical-coding-agent
Project-URL: Repository, https://github.com/HamzaDevv/hierarchical-coding-agent
Project-URL: Documentation, https://github.com/HamzaDevv/hierarchical-coding-agent/tree/main/docs
Project-URL: Bug Tracker, https://github.com/HamzaDevv/hierarchical-coding-agent/issues
Keywords: ai-agent,mcp,coding-agent,context-firewall,deepseek,hierarchical-agent,model-context-protocol,llm
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: openai>=1.0.0
Requires-Dist: mcp<2.0.0,>=1.2.0
Requires-Dist: litellm>=1.30.0
Requires-Dist: diskcache>=5.6.0
Requires-Dist: tree-sitter>=0.24.0
Requires-Dist: tree-sitter-python
Requires-Dist: tree-sitter-javascript
Requires-Dist: tree-sitter-typescript
Requires-Dist: tree-sitter-go
Requires-Dist: tree-sitter-rust
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: wheel>=0.40.0; extra == "dev"
Requires-Dist: twine>=4.0.0; extra == "dev"
Provides-Extra: providers
Requires-Dist: anthropic>=0.18.0; extra == "providers"
Requires-Dist: google-genai>=0.1.0; extra == "providers"
Dynamic: license-file

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

[![PyPI Version](https://img.shields.io/pypi/v/m2-harness.svg?color=blue)](https://pypi.org/project/m2-harness/)
[![Python Version](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue.svg)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-Apache%202.0-green.svg)](LICENSE)
[![Tests](https://img.shields.io/badge/tests-255%20passed-brightgreen.svg)](tests/)
[![MCP Ready](https://img.shields.io/badge/MCP-FastMCP%202.0-purple.svg)](https://modelcontextprotocol.io/)
[![Status](https://img.shields.io/badge/status-production--stable-success.svg)](https://github.com/HamzaDevv/hierarchical-coding-agent)

**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

```mermaid
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

```mermaid
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

```bash
pip install m2-harness
```

Or install in development mode from source:
```bash
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:

```bash
m2 doctor
```

```text
=========================================================================
   🩺 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:
```bash
m2 doctor --strict --json
```

---

## 🚀 CLI Command Matrix

```bash
# 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`)
```json
{
  "mcpServers": {
    "m2-worker-agent": {
      "command": "m2-mcp-server",
      "env": {
        "DEEPSEEK_API_KEY": "sk-...",
        "WORKSPACE_ROOT": "/path/to/your/project"
      }
    }
  }
}
```

### Cursor (`.cursor/mcp.json`)
```json
{
  "mcpServers": {
    "m2-worker-agent": {
      "command": "uvx",
      "args": ["--from", "m2-harness", "m2-mcp-server"],
      "env": {
        "DEEPSEEK_API_KEY": "sk-..."
      }
    }
  }
}
```

### Google Antigravity (`~/.gemini/settings.json`)
```json
{
  "mcpServers": {
    "m2-worker-agent": {
      "command": "m2-mcp-server",
      "env": {
        "WORKSPACE_ROOT": "${workspaceFolder}"
      }
    }
  }
}
```

---

## 🐍 Python SDK Quickstart

```python
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

* 📐 [Architecture Guide](docs/architecture.md) — System design, tri-modal paths, and L0 design
* ⚙️ [Runtime & Event Subsystem](docs/runtime.md) — State machine lifecycle and canonical EventBus
* 🛡️ [Context Firewall & Working Memory](docs/context-firewall.md) — Token compactor & structured memory
* ⚡ [Deterministic Replay](docs/replay.md) — Tri-level replay, versioned traces, semantic hashing
* 🧪 [M2-Bench & Multi-Oracle Evaluation](docs/benchmarking.md) — Evaluator, oracles, anti-tampering
* 🌐 [Model Providers Guide](docs/providers.md) — Configuration for DeepSeek, OpenCode Zen, LiteLLM

---

## 📄 License

Licensed under the [Apache License, Version 2.0](LICENSE).
