Metadata-Version: 2.5
Name: agent-arch
Version: 0.1.1
Summary: Deterministic codebase architecture guardrails and topology indexer for AI coding agents
Author: agent-arch team
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agent,architecture,ast,guardrails,static-analysis
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
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: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.9
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Requires-Dist: ruff>=0.4.0; extra == 'dev'
Provides-Extra: fast
Requires-Dist: orjson>=3.9.0; extra == 'fast'
Description-Content-Type: text/markdown

<div align="center">

# agent-arch

<p align="center">
  <img src="docs/images/icon.svg" alt="agent-arch: five architecture layers inside a shield" width="160" height="160">
</p>

**Deterministic codebase architecture guardrails & sub-15ms topology indexer for AI coding agents.**

[![CI](https://github.com/zenshay/agent-arch/actions/workflows/ci.yml/badge.svg)](https://github.com/zenshay/agent-arch/actions/workflows/ci.yml)
[![PyPI version](https://img.shields.io/pypi/v/agent-arch.svg)](https://pypi.org/project/agent-arch/)
[![Python versions](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![Code style: Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![Latency SLA](https://img.shields.io/badge/latency-sub--15ms-brightgreen.svg)](#benchmarks)
[![Token Cost](https://img.shields.io/badge/token_cost-0_tokens-success.svg)](#features)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

[繁體中文說明](README.zh-TW.md)

</div>

> [!IMPORTANT]
> **What this is NOT:**
> - ❌ **NOT an agent workflow orchestrator or state-graph engine** (this is not LangGraph, CrewAI, or AutoGen).
> - ❌ **NOT a Knowledge Graph or GraphRAG framework**.
> 
> **What this IS:**
> - ✅ A deterministic static AST guardrail and orientation map for your **Python codebase**. When you let AI coding agents edit code, it provides a lightweight safety net that stops reverse dependencies and prevents breaking changes to public APIs.

AI coding agents (Claude Code, Codex, Cursor) often edit files with local context only. This causes architectural erosion:
1. Low-level modules import high-level UI modules to save time.
2. Refactoring steps silently break exported symbols and APIs.
3. Reading whole repositories wastes tens of thousands of tokens per turn.

`agent-arch` provides a zero-token, sub-15ms AST safety net. It builds a deterministic topology map and enforces strict layering rules with a physical Git hook.

---

## Quick Start

Two commands to protect your codebase from AI coding agent erosion:

```bash
# 1. Query upstream and downstream dependencies for an agent (< 15ms)
uvx agent-arch --query <module_or_symbol>

# 2. Install Git pre-commit hook and AGENTS.md rules in one command
uvx agent-arch --init
```

---

![Five example layers with downward imports and an AST shield that blocks upward imports](docs/images/overview.svg)

The diagram uses example layer names. Configure layer ranks for your project.

The sub-15ms figure applies to cache reads. Local architecture checks use zero LLM tokens.
These checks cover layering and public APIs. They do not prove that all code is correct.
See the [benchmark report](docs/BENCHMARK_AND_VERIFICATION.md) and [image prompts and settings](docs/images/qwen/PROMPTS.md).

---

## Features

- **Sub-15ms Index Latency**: Deterministic AST scanning with compact JSON caching.
- **Zero Token Verification**: Check architectural rules locally with zero LLM API cost.
- **No Reverse Imports**: Prevent lower layers from importing upper layers.
- **Public API Safety Net**: Detect breaking changes and require backward-compatible facade shims.
- **Zero External Dependencies**: Pure standard library Python with optional `orjson` acceleration.

---

## Comparison with Existing Tools

| Tool | Primary Purpose | Latency | Token Cost | Architecture Guardrails | Agent Surgical Query |
| :--- | :--- | :--- | :--- | :---: | :---: |
| **`agent-arch`** (This tool) | AI Agent Orientation & Guardrail | **< 15 ms** | **0 tokens** | **YES** (Layering & API shims) | **YES** (< 30 lines Markdown) |
| **Aider `repo-map`** | Whole-repo symbol ranking for prompts | 500 ms - 2 s | High (prompt bloat) | NO (Architecture-blind) | NO (Dumps bulk symbols) |
| **Tach / Import Linter** | CI boundary enforcement for monoliths | 200 ms - 3 s | 0 tokens | YES (Module boundaries) | NO (No query API for agents) |
| **ast-grep (`sg`)** | Single-file AST structural pattern matching | < 50 ms | 0 tokens | NO (No global dependency graph) | NO (File-local only) |
| **arch-analyzer** | LLM-based architecture review wrapper | 30 s - 3 min | Very High (10k+ tokens) | Fuzzy / Probabilistic | NO (Heavy report generator) |

### Key Differences

1. **vs Aider `repo-map`**: Aider ranks symbols with PageRank to feed large context into LLM prompts, but it does not prevent architectural erosion. `agent-arch` enforces strict single-direction layering and API compatibility checks.
2. **vs Tach / Import Linter**: Tach and Import Linter target human CI pipelines with terminal error outputs. They lack a sub-15ms surgical query interface for agents to look up upstream dependencies and downstream callers on-demand.
3. **vs ast-grep**: `ast-grep` is a powerful single-file CST pattern matcher, but it cannot resolve imports across files or detect circular dependency cycles.
4. **vs arch-analyzer / LLM Reviewers**: Wrapping LLMs to review code is slow, expensive, and non-deterministic. `agent-arch` uses deterministic, zero-token local AST analysis that runs on every git commit.

---

## Installation

Run directly with `uvx` (no prior installation needed):

```bash
uvx agent-arch --query <symbol_or_module>
uvx agent-arch-guard --strict
```

Or install via `uv` / `pip`:

```bash
uv add --dev agent-arch
# or
pip install agent-arch
```

---

## Usage

### 0. One-Click Guardrail Installation (`--init`)

Enforce guardrails on any repository with a single command:

```bash
uvx agent-arch --init
```

This command automatically:
1. Installs a **Git pre-commit hook** (`.git/hooks/pre-commit`) that physically blocks any `git commit` violating architectural rules.
2. Appends architectural guidelines to **`AGENTS.md`** so AI agents (Claude Code, Codex, Cursor) know the constraints before writing code.
3. Initializes `.agent_arch/` cache and default `pyproject.toml` settings.

### 1. Query Codebase Topology (Surgical Agent Orientation)

Display a clean architectural summary of your codebase:

```bash
agent-arch
```

Query a specific module to inspect its layer, classes, upstream imports, and downstream callers:

```bash
agent-arch --query relabel.py
```

Locate a symbol across the entire repository:

```bash
agent-arch --query UserEntity
```

### 2. Verify Architecture Integrity (CI & Preflight Guardrails)

Run layering and compatibility checks:

```bash
agent-arch-guard
```

Compare API compatibility across Git revisions:

```bash
agent-arch-guard --base origin/main
```

Compare two files directly:

```bash
agent-arch-guard --compare-files old_module.py new_module.py
```

---

## Configuration

Add an optional `[tool.agent-arch]` section to your `pyproject.toml` to customize layers and scanned directories:

```toml
[tool.agent-arch]
scan_dirs = ["src"]
exclude_dirs = [".git", ".venv", "tests", "dist"]
cache_path = ".agent_arch/index.json"
cache_ttl = 300.0

[tool.agent-arch.layers]
0 = { name = "Domain", description = "Base entities and types", match = ["domain", "models", "types"] }
1 = { name = "Storage", description = "Database and file I/O", match = ["storage", "io", "db"] }
2 = { name = "Core", description = "Business logic and algorithms", match = ["services", "core", "algorithms"] }
3 = { name = "Workflow", description = "Controllers and handlers", match = ["controllers", "handlers"] }
4 = { name = "UI", description = "User interface and entrypoints", match = ["ui", "views", "cli", "main"] }
```

---

## Benchmarks

See [BENCHMARK_AND_VERIFICATION.md](docs/BENCHMARK_AND_VERIFICATION.md) for stress test records across 2,300+ modules and sub-1ms cache latency measurements.

---

## License

MIT License.
