Skip to main content

opencode-arch

Architecture extraction and validation for Python codebases.

Mechanically verify that your architecture model matches your code. Compress entire repositories into ~430 tokens for AI agents. Produce training data for LLM fine-tuning.

PyPI Python Tests License


Why

Problem Solution
Architecture docs drift from code Mechanical representativeness scoring — know exactly when your model is wrong
AI agents burn tokens reading every file Token arbitrage — full repo AST compressed to ~430 tokens of dense context
No structured architecture data for training Produces (code, model, metrics) triples ready for fine-tuning
Manual component boundary decisions Auto-groups modules by import affinity, name prefix, and subdirectory

Features

  • Representativeness Scoring — File coverage, relationship accuracy, boundary coherence, behavioral coverage. Four mechanical sub-scores that tell you if your model is accurate.
  • Token Arbitrage — Compress a full repository's AST into a dense context string within any token budget. Agents reason about the whole codebase without reading every file.
  • Living Documentation — Components, relationships, behaviors, and event chains extracted directly from code and stored as .architecture-model.yaml.
  • Training Data Export — Structured triples in .architecture/ for LLM fine-tuning pipelines.

Installation

pip install opencode-arch

With MCP server support (for AI agent integration):

pip install opencode-arch[mcp]

Requires Python 3.11+.

Quick Start

# Launch interactive architecture-aware development
opencode-arch

# Or target a specific repo
opencode-arch /path/to/your/repo

This scans the codebase (<1s), loads/bootstraps the architecture model, injects compressed context into your session, and launches OpenCode with full architecture awareness.

# One-shot commands also available:
opencode-arch extract /path/to/repo    # Extract architecture
opencode-arch export-data              # Export training data

After extraction, your repo contains:

.architecture-model.yaml     # Component model (YAML)
.architecture/
├── manifest.json            # Full AST scan (modules, functions, imports)
└── metrics.json             # Representativeness scores + telemetry

CLI

Command Purpose
opencode-arch Launch interactive session (default — scans, injects context, opens OpenCode)
opencode-arch extract <repo> Extract architecture model from a repository
opencode-arch generate <repo> Generate code with test-guided verification
opencode-arch bench <repo1> <repo2> ... Benchmark extraction across multiple repos
opencode-arch metrics View extraction history and scores
opencode-arch export-data Export training corpus (JSONL)

Options for extract:

opencode-arch extract /path/to/repo \
  --budget=4000 \        # Token budget for context compression
  --focus=all \          # Focus: "all", F-block ID, layer name
  --target-score=80      # Minimum validation score to accept

MCP Integration

Register as an MCP server for use with AI coding agents:

opencode mcp add

9 Tools

Tool Purpose
architect_scan AST scanning — returns modules, functions, classes, imports
architect_slice Token-compressed context (the core innovation)
architect_validate Structural validation, returns score 0–100
architect_extract Store validated model + record telemetry
architect_generate Run test suite against generated code
architect_group Auto-group modules into logical components
architect_check Verify representativeness (4 sub-scores)
architect_require Capture functional requirements from conversation
architect_feedback Record corrections, ratings, and training data

Typical Agent Workflow

scan → slice → (agent produces YAML) → validate → check → extract

The agent calls scan to understand the repo, slice to get compressed context, produces an architecture model, then validate + check gate quality before extract persists it.

How It Works

┌─────────────────────────────────────────────────┐
│  AI Agent (frontier model)                      │
│  Receives ~430 tokens of compressed context     │
│  Produces architecture YAML                     │
└────────────────────┬────────────────────────────┘
                     │ MCP Protocol
┌────────────────────▼────────────────────────────┐
│  opencode-arch (FastMCP server)                 │
│  scan → slice → validate → check → extract     │
└────────────────────┬────────────────────────────┘
                     │
┌────────────────────▼────────────────────────────┐
│  architecture-model-standard (library)          │
│  AST scanning │ YAML parsing │ Validation       │
│  Context formatting │ Model slicing             │
└─────────────────────────────────────────────────┘

Key design decision: The agent IS the oracle. Tools never call external models — they provide compressed context to the frontier model already in the conversation.

Benchmarks

Achieved automatically with no human tuning:

Repository Modules Components Overall Score
FastAPI 25 9 98.1%
Pydantic 69 40 98.0%
httpx 23 10 96.0%
Requests 19 9 94.2%
Flask 6 6 100.0%
Celery 161 23 84.0%

Scores are composite representativeness: file coverage × relationship accuracy × boundary coherence × behavioral coverage.

Training Data

Each extraction produces a structured triple:

(.architecture-model.yaml, manifest.json, metrics.json)

This enables:

  • Fine-tuning models on architecture extraction tasks
  • Evaluating model quality with mechanical ground truth
  • Building datasets across many repositories with bench

Export with:

opencode-arch export-data --format=jsonl

Architecture Model Schema

meta:
  project: my-project
  schema_version: '1.3'
entities:
  components:
    - id: COMP-1
      name: APILayer
      status: ACTIVE
  capabilities:
    - id: CAP-F1
      name: RequestHandling
      status: ACTIVE
relationships:
  - from: COMP-1
    to: CAP-F1
    type: realizes

Relationship types: realizes, uses, constrains, contains, triggers, depends_on, implements, exposes.

Development

git clone https://github.com/anomalyco/opencode-arch
cd opencode-arch
pip install -e ".[dev]"
pytest tests/ -v  # 278 tests, ~20s

Contributing

See CONTRIBUTING.md for guidelines.

License

MIT

Metadata

Release files for opencode-arch 1.1.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 opencode-arch 1.1.0
File Size Uploaded
opencode_arch-1.1.0.tar.gz 2.4 MB Details

Built distribution (wheel)

Table of built distributions (wheels) for opencode-arch 1.1.0
File Interpreter ABI Platform
opencode_arch-1.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 2.6 MB

Release files / opencode_arch-1.1.0.tar.gz

Download URL opencode_arch-1.1.0.tar.gz
Size 2.4 MB
Tags Source
SHA-256 checksum
How to use checksums
55f050c57387ac9a2b3de24ddd094da63fc5b546b5c2766caecc013f75b870c3
BLAKE2b-256 checksum
How to use checksums
e44a5e6b26de065ba7644e67f7067a116056804f3f3e1b104d54d10e696533ab
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.7

Release files / opencode_arch-1.1.0-py3-none-any.whl

Download URL opencode_arch-1.1.0-py3-none-any.whl
Size 273.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
467038187473a00e81548d9ec0b971821740a569bcb3ff5e049058f94d9b5631
BLAKE2b-256 checksum
How to use checksums
76836d42f625c74db8db2f6c296f9b6724dbbd26ba17b09e77a290e7e2eda6f5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.7

Release history Release notifications | RSS feed

This release

1.1.0 This release

2 release files

1.0.0

2 release files

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