Metadata-Version: 2.4
Name: m1-m2-agent
Version: 0.6.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

[![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-221%20passed-brightgreen.svg)](tests/)
[![MCP Ready](https://img.shields.io/badge/MCP-FastMCP%20Ready-purple.svg)](https://modelcontextprotocol.io/)

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

---

## 🏛️ Architecture Overview

```mermaid
flowchart TD
    User([User Prompt / M1 Frontier]) --> Router{M1 Orchestrator Router}
    
    subgraph Path_A ["Path A: Delegated Worker (85%+ of Tasks)"]
        Router -->|Heavy Search / Multi-file / Test Loop| M2Runtime[M2 Worker Engine]
        M2Runtime --> L0[Zero-Token L0 Layer: AST & Git]
        M2Runtime --> SandboxedTools[Execution Sandbox & Symlink Jail]
        M2Runtime --> ContextFirewall[Context Firewall: 80-98% CCR]
        ContextFirewall --> ResultContract[Structured ResultContract JSON]
    end

    subgraph Path_B ["Path B: Direct Precision Fallback"]
        Router -->|Subtle Race / Exact Bytecode / Review| DirectInspection[Direct Inspection & Precision 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]
    end

    ResultContract --> Synthesis[M1 Final Synthesis & User Response]
    DirectInspection --> Synthesis
```

---

## 🌟 Key Features

1. **Context Firewall & Active Working Memory**: Filters thousands of characters of verbose logs, greps, and test traces down to high-signal structured evidence ($CCR \ge 80\%–98\%$).
2. **Zero-Token L0 Deterministic Layer**: Instant Python AST outlines, symbol definitions, and git diff summaries consuming **0 LLM tokens**.
3. **Tri-Modal Execution**:
   * **Path A (Delegated)**: Offloads heavy tool loops to cheap workers.
   * **Path B (Direct)**: Precision fallback for subtle race conditions or exact reviews.
   * **Path C (Diagnostic)**: Autonomous TDD failure reproduction and repair loops.
4. **Deterministic Tri-Level Replay**: 100% offline, zero-network regression testing across Provider, Runtime, and Semantic ($Hash_A = Hash_B = Hash_C$) layers.
5. **M2-Bench & Independent Oracles**: Multi-oracle evaluation (`TestOracle`, `ASTOracle`, `FileOracle`, `IntegrityOracle` anti-tampering) with mathematically rigorous metrics (VSR, FSR, Verification Gap, FTAR, ROI).
6. **Release-Grade Diagnostics (`m2 doctor`)**: Deep environment inspection across Python, Git, Tree-sitter parsers, sandbox jails, and providers.

---

## 📦 Installation

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

Or install from source:
```bash
git clone https://github.com/HamzaDevv/hierarchical-coding-agent.git
cd hierarchical-coding-agent
pip install -e .
```

---

## 🩺 Environment Diagnostics (`m2 doctor`)

Verify your environment and workspace health in one 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 to fail on any warning:
```bash
m2 doctor --strict --json
```

---

## 🚀 Quick Start (CLI)

```bash
# Execute one-shot task
m2 "Find all references to ResultContract and outline their symbols"

# Launch instant zero-token AST code outline (0 LLM tokens)
m2 outline

# Launch instant zero-token git diff summary (0 LLM tokens)
m2 diff

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

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

# Replay an execution trace offline
m2 replay tests/replay/golden_task --mode semantic

# Run benchmark suite
m2 bench run --suite dev --baselines C
```

---

## 🔌 Model Context Protocol (FastMCP) Integration

M2 exposes a high-performance FastMCP server for IDEs (Cursor, Windsurf, Claude Desktop, Antigravity):

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

---

## 🐍 Python SDK Usage

```python
from m1_m2_agent import M1OrchestratorAgent, TaskContract

# Initialize M1/M2 Hierarchical Agent
agent = M1OrchestratorAgent(workspace_root=".")

# Route and execute task through Context Firewall
result = agent.route_and_execute(
    objective="Analyze contracts/models.py and verify ResultContract fields"
)

print(f"Status: {result['contract']['status']}")
print(f"Evidence: {result['contract']['evidence']}")
print(f"Context Compression: {agent.get_telemetry_report()['context_compression_ratio']}%")
```

---

## 📊 Documentation Index

* 📐 [Architecture Guide](docs/architecture.md)
* ⚙️ [Runtime & Event Subsystem](docs/runtime.md)
* 🛡️ [Context Firewall & Memory](docs/context-firewall.md)
* ⚡ [Deterministic Replay](docs/replay.md)
* 🧪 [M2-Bench & Multi-Oracle Evaluation](docs/benchmarking.md)
* 🌐 [Model Providers](docs/providers.md)

---

## 📄 License

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