Metadata-Version: 2.4
Name: m1-m2-agent
Version: 0.3.0
Summary: Cost-Aware Hierarchical Coding Agent & Context Firewall — Universal MCP Server, CLI, and Python SDK
Author-email: Hamza <hamza@example.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 :: 4 - Beta
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: 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
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Dynamic: license-file

# m1-m2-agent — Cost-Aware Hierarchical Coding Agent & Context Firewall

> **Slash AI inference costs by up to 92% while making your frontier model smarter.**  
> A 3-layer agent architecture that routes heavy tool loops to a cheap DeepSeek worker,
> compresses raw outputs (80–98% CCR) through a Context Firewall, and returns clean
> structured evidence to your frontier model — with zero context window bloat.

[![PyPI](https://img.shields.io/pypi/v/m1-m2-agent)](https://pypi.org/project/m1-m2-agent/)
[![Python](https://img.shields.io/pypi/pyversions/m1-m2-agent)](https://pypi.org/project/m1-m2-agent/)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)
[![Tests](https://github.com/HamzaDevv/hierarchical-coding-agent/actions/workflows/publish.yml/badge.svg)](https://github.com/HamzaDevv/hierarchical-coding-agent/actions)

---

## Installation

```bash
# Recommended — standard pip install
pip install m1-m2-agent

# Zero-install ephemeral run (uv / uvx)
uvx --from m1-m2-agent m2-mcp-server

# Fallback — pipx
pipx run --spec m1-m2-agent m2-mcp-server
```

---

## Quickstart: Drop M2 into any project in 30 seconds

```bash
cd /your/project
m2-init
```

That's it. `m2-init` scaffolds 4 cognitive rule files (`AGENTS.md`, `.cursorrules`,
`CLAUDE.md`, `.continuerules`) and prints the exact MCP config JSON to paste into
your IDE. Any AI coding agent that reads those files will instantly know when and how
to delegate to M2.

**Example output:**
```
🚀 m2-init — scaffolding M2 Worker Agent integration into: /your/project

  ✅ Created  AGENTS.md
  ✅ Created  .cursorrules
  ✅ Created  CLAUDE.md
  ✅ Created  .continuerules

Generated 4 file(s): AGENTS.md, .cursorrules, CLAUDE.md, .continuerules

{
  "mcpServers": {
    "m2-worker-agent": {
      "command": "uvx",
      "args": ["--from", "m1-m2-agent", "m2-mcp-server"],
      "env": {
        "DEEPSEEK_API_KEY": "YOUR_DEEPSEEK_API_KEY_HERE",
        "DEEPSEEK_MODEL_NAME": "deepseek-chat",
        "WORKSPACE_ROOT": "/your/project"
      }
    }
  }
}
# Fallback if uvx/uv is not installed — use pipx:
# "command": "pipx", "args": ["run", "--spec", "m1-m2-agent", "m2-mcp-server"]
```

---

## Architecture

```
                          ┌───────────────────────────────┐
                          │              L2               │
                          │   Frontier Reasoner (M1)      │
                          │   Plan • Decide • Review      │
                          └───────┬───────────────┬───────┘
                                  │               │
                          Path A  │        Path B │ (Direct Precision Fallback)
                      (Delegated) │               │
                                  ▼               │
                          ┌───────────────┐       │
                          │      L1       │       │
                          │  Worker (M2)  │       │
                          │ Context F/W   │       │
                          └───────┬───────┘       │
                                  │               │
                                  ▼               ▼
                          ┌───────────────────────────────┐
                          │              L0               │
                          │  Deterministic Fast Execution │
                          │   AST • Ripgrep • Git • LSP   │
                          └───────────────────────────────┘
```

| Layer | Who | Role | Cost |
|-------|-----|------|------|
| **L2** | M1 (Gemini, Claude, GPT-4o, Cursor) | Strategic planning, architecture, review | Frontier $$$ |
| **L1** | M2 (DeepSeek V3/Chat) | Tool loops, search, compression, diagnosis | ~2% of L2 cost |
| **L0** | AST parser + git engine | Symbol extraction, diff indexing | **0 LLM tokens** |

---

## Three ways to use it

### 1. MCP Server — for IDEs with MCP support
Works with: **Antigravity, Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Continue.dev**

Paste the JSON from `m2-init` into your IDE's MCP config, restart, and the tools
(`delegate_to_m2`, `l0_ast_*`, `l0_git_*`) appear automatically in your agent's tool list.

```json
{
  "mcpServers": {
    "m2-worker-agent": {
      "command": "uvx",
      "args": ["--from", "m1-m2-agent", "m2-mcp-server"],
      "env": {
        "DEEPSEEK_API_KEY": "YOUR_DEEPSEEK_API_KEY_HERE",
        "DEEPSEEK_MODEL_NAME": "deepseek-chat",
        "WORKSPACE_ROOT": "/path/to/your/project"
      }
    }
  }
}
```

**IDE config file locations:**

| IDE | Config file |
|-----|-------------|
| Antigravity | `~/.gemini/settings.json` |
| Cursor | `.cursor/mcp.json` |
| Claude Desktop | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Cline / Roo Code | VS Code → Cline sidebar → Edit MCP Settings |
| Continue.dev | `~/.continue/config.json` (under `experimental.modelContextProtocolServers`) |

### 2. CLI — for terminal agents and bash scripts
Works with: **Aider, bash scripts, terminal workflows, custom pipelines**

```bash
# One-shot task with live streaming output
m1-m2-cli -p /your/project --task "Find all auth endpoints and summarize JWT validation logic"

# Interactive REPL mode
m1-m2-cli -p /your/project
```

### 3. Python SDK — for custom autonomous pipelines

```python
from m1_m2_agent import M1OrchestratorAgent

agent = M1OrchestratorAgent(workspace_root="/your/project")

# Path A: delegate heavy search to M2
result = agent.route_and_execute(
    objective="Locate all ASTParser class references and summarize their signatures"
)
print(result["result"])          # Compressed M2 answer
print(result["execution_path"])  # PATH_A_DELEGATED

# View cost telemetry
report = agent.get_telemetry_report()
print(f"Context Compression Ratio: {report['context_compression_ratio']}%")
print(f"Cost Reduction:            {report['cost_reduction_pct']}%")
```

---

## MCP Tools Reference

| Tool | Type | Description |
|------|------|-------------|
| `delegate_to_m2` | async | Delegate any task to M2 — multi-turn tool loop with live SSE streaming |
| `l0_ast_extract_symbols` | sync | Classes, methods, imports from a file in **0 LLM tokens** |
| `l0_ast_workspace_outline` | sync | Full structural map of all Python modules in **0 LLM tokens** |
| `l0_ast_find_definition` | sync | Exact file + line where any symbol is defined in **0 LLM tokens** |
| `l0_git_status_summary` | sync | Modified / untracked / staged / deleted files in **0 LLM tokens** |
| `l0_git_diff_summary` | sync | Diff statistics and hunk previews in **0 LLM tokens** |
| `inspect_transcript_step` | sync | Retrieve raw un-truncated output from M2's session transcript |
| `search_transcript` | sync | Search all recorded steps in M2's session for a query term |
| `get_m2_action_trace` | sync | Full human-readable Markdown trace of M2's working session |

---

## Core Features

* 🌐 **Live Webview HUD** (`http://localhost:4040`): Real-time SSE stream of M2's thoughts (🧠),
  actions (⚙️), and results (📋) — auto-collapsing cards, 0 tokens leaked to M1.
* ⚡ **L0 Zero-Token Layer**: AST parsing and git diff indexing at literally 0 LLM cost.
* 🔀 **Tri-Modal Routing**: Path A (delegated), Path B (direct precision), Path C (autonomous investigation).
* 📜 **Typed Contracts**: `TaskContract` / `ResultContract` with confidence scoring and evidence citations.
* 🚨 **Bidirectional Escalation**: M2 self-escalates when confidence < 0.80; M1 triggers Path B override.
* 📊 **Cost Telemetry**: Live FTAR, CCR, and DSR metrics.
* 💾 **Stateful Sessions**: M2 maintains memory across turns — Turn 2 reuses Turn 1 context, no re-searching.

---

## Configuration

Set via environment variables or `.env` file:

```env
DEEPSEEK_API_KEY=your-api-key-here
DEEPSEEK_BASE_URL=https://api.deepseek.com
DEEPSEEK_MODEL_NAME=deepseek-chat
WORKSPACE_ROOT=/path/to/your/project
```

Get a DeepSeek API key at [platform.deepseek.com](https://platform.deepseek.com).
DeepSeek V3/Chat costs ~$0.27 per million input tokens — roughly **40-50x cheaper** than GPT-4o or Claude Sonnet.

---

## Documentation

* 🏗️ [**ARCHITECTURE.md**](docs/ARCHITECTURE.md) — Full layer breakdown and sequence diagrams
* 📜 [**CONTRACTS_AND_ROUTING.md**](docs/CONTRACTS_AND_ROUTING.md) — Typed contracts, routing, escalation protocol
* 🛠️ [**REAL_WORLD_SETUP_GUIDE.md**](docs/REAL_WORLD_SETUP_GUIDE.md) — Step-by-step MCP + SDK setup
* 📊 [**ACHIEVEMENTS_AND_BENCHMARKS.md**](docs/ACHIEVEMENTS_AND_BENCHMARKS.md) — Empirical benchmarks, FTAR metrics, cost comparisons
* 🚨 [**INCIDENT_REPORT_001**](docs/INCIDENT_REPORT_001_TRANSCRIPT_FEEDBACK_LOOP.md) — Post-mortem: 8 GB Ripgrep Feedback Loop & Memory Explosion

---

## License

Apache 2.0 — see [LICENSE](LICENSE).
