Skip to main content

AI-native software engineering tools with design-by-contract verification

Project description

Invar

PyPI version Python 3.11+ License

Don't hope AI code is correct. Know it.

Invar is a verification framework for AI-assisted development. It provides contracts, verification, and a structured workflow methodology.

from invar_runtime import pre, post

@pre(lambda items: len(items) > 0)
@post(lambda result: result >= 0)
def average(items: list[float]) -> float:
    """
    >>> average([1, 2, 3])
    2.0
    """
    return sum(items) / len(items)

Experience Tiers

Platform Experience Features
Claude Code Full USBV workflow + skill automation + MCP integration
Cursor/Windsurf Basic INVAR.md protocol + CLI verification
Other editors Minimal CLI verification tools only

Why tiers? The skill system (/develop, /review, etc.) requires Claude Code's sub-agent capabilities. Other editors receive the protocol document and CLI tools.


Installation

Two Packages, Different Purposes

┌─────────────────────────────────────────────────────────────────┐
│  Your Project                                                   │
│  ├── src/                                                       │
│  │   └── from invar_runtime import pre, post  ← Runtime        │
│  │                                                              │
│  └── Development (not shipped with your code)                   │
│      └── uvx invar-tools guard  ← Tools                         │
└─────────────────────────────────────────────────────────────────┘
Package Install Purpose
invar-tools uvx invar-tools <cmd> Development: verification, init, MCP server
invar-runtime pip install invar-runtime Production: add to your project's dependencies

Quick Install

# Development tools (recommended: use without installing)
uvx invar-tools guard
uvx invar-tools init --claude

# Runtime contracts (add to your project)
pip install invar-runtime

Why uvx is recommended:

  • Always uses latest version
  • Doesn't pollute project dependencies
  • Automatically accesses your project's venv dependencies (numpy, pandas, etc.)
  • If your project has invar-tools installed, uvx will detect and use it

When to use pip install instead:

  • CI/CD environments where uvx isn't available
  • Projects with C extensions AND Python version mismatch between uvx and project

Quick Start

# 1. Initialize your project
cd your-project
uvx invar-tools init --claude    # Full experience (Claude Code)
uvx invar-tools init             # Basic experience (other editors)

# 2. Write code with AI (AI follows INVAR.md protocol)

# 3. Verify code quality
uvx invar-tools guard            # Runs static analysis + doctests + property tests

The USBV Workflow

AI agents follow a four-phase development cycle:

┌───────────┐    ┌───────────┐    ┌───────────┐    ┌───────────┐
│ Understand│ → │  Specify  │ → │   Build   │ → │ Validate  │
│           │    │           │    │           │    │           │
│ Intent    │    │ @pre/@post│    │ Implement │    │ invar     │
│ Inspect   │    │ Doctests  │    │ leaves    │    │ guard     │
│ Constraints    │ Design    │    │ first     │    │           │
└───────────┘    └───────────┘    └───────────┘    └───────────┘

Key insight: Specify contracts BEFORE implementation. The contract becomes the specification.

See INVAR.md for complete protocol.


Session Protocol

Every AI session follows this format:

First message (Check-In):

✓ Check-In: [project] | [branch] | [clean/dirty]

Last message (Final):

✓ Final: guard PASS | 0 errors, 2 warnings

Check-In shows project context. Guard verification runs during VALIDATE phase and Final, not at Check-In.


Core/Shell Architecture

Invar enforces separation between pure logic and I/O:

Zone Requirements Forbidden
Core (**/core/**) @pre/@post contracts, doctests I/O imports (os, pathlib, requests...)
Shell (**/shell/**) Result[T, E] returns -
# Core: Pure logic, receives data
def parse_config(content: str) -> Config:
    return Config.parse(content)

# Shell: Handles I/O, returns Result
def load_config(path: Path) -> Result[Config, str]:
    content = path.read_text()
    return Success(parse_config(content))

Commands

Guard (Primary)

invar guard              # Full verification (static + doctests + property tests)
invar guard --changed    # Only git-modified files
invar guard --static     # Static analysis only (~0.5s)
invar guard --coverage   # Collect branch coverage (doctest + hypothesis)

Flags:

Flag Purpose
--strict Treat warnings as errors
--explain Show rule explanations
--agent JSON output for AI tools
--coverage Branch coverage from doctest + hypothesis phases

Other Commands

invar sig <file>         # Show signatures + contracts
invar map --top 10       # Most-referenced symbols
invar rules              # List all rules
invar update             # Update managed files

Workflow Skills (Claude Code)

invar init --claude creates workflow skills in .claude/skills/:

Skill Trigger Purpose
/investigate "why", "explain", vague tasks Exploration, no code changes
/propose "should we", "compare" Decision facilitation with options
/develop "add", "fix", "implement" USBV implementation workflow
/review After develop, review_suggested Adversarial review with fix loop

Note: Skills are Claude Code exclusive. Other editors use INVAR.md protocol directly.


Configuration

pyproject.toml

[tool.invar.guard]
# Directory classification
core_paths = ["src/myapp/core"]
shell_paths = ["src/myapp/shell"]

# Or use patterns for existing projects
core_patterns = ["**/domain/**", "**/models/**"]
shell_patterns = ["**/api/**", "**/cli/**"]

# Size limits
max_file_lines = 500
max_function_lines = 50

# Contract requirements
require_contracts = true
require_doctests = true

# Doctest-heavy code
exclude_doctest_lines = true

# Rule exclusions
[[tool.invar.guard.rule_exclusions]]
pattern = "**/generated/**"
rules = ["*"]

Rules Reference

Rule Severity What It Checks
file_size ERROR File > max lines
function_size WARN Function > max lines
missing_contract ERROR Core function lacks @pre/@post
missing_doctest WARN Contracted function lacks doctest
forbidden_import ERROR I/O import in Core
shell_result WARN Shell function not returning Result
empty_contract ERROR Contract is lambda: True

Full list: invar rules --explain


MCP Integration (Claude Code)

invar init --claude automatically configures MCP:

{
  "mcpServers": {
    "invar": {
      "command": "uvx",
      "args": ["invar-tools", "mcp"]
    }
  }
}

MCP Tools:

Tool Replaces Purpose
invar_guard pytest, crosshair Smart verification
invar_sig Reading entire files Show contracts and signatures
invar_map grep for functions Symbol map with reference counts

Platform Support

Feature Claude Code Cursor/Windsurf Others
Smart Guard CLI
INVAR.md protocol
MCP integration
Workflow skills
Sub-agent review

Claude Code provides the full experience with automated workflow and independent review.

Other editors receive the protocol and CLI tools. Workflow adherence is manual.


File Ownership

File Owner Edit?
INVAR.md Invar No (invar update manages)
CLAUDE.md You Yes (project config)
.claude/skills/ You Yes (customize workflows)

Runtime Behavior

Contracts are checked at runtime via deal.

# Disable in production for performance
DEAL_DISABLE=1 python app.py

Learn More

In your project (created by invar init):

  • INVAR.md — Protocol v5.0 for AI agents
  • CLAUDE.md — Project configuration
  • .invar/examples/ — Reference patterns

Documentation:


License

Component License Purpose
invar-runtime Apache-2.0 Runtime contracts - use freely
invar-tools GPL-3.0 CLI tools - improvements shared
Documentation CC-BY-4.0 Share with attribution

See NOTICE for third-party licenses.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

invar_tools-1.3.0.tar.gz (626.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

invar_tools-1.3.0-py3-none-any.whl (217.3 kB view details)

Uploaded Python 3

File details

Details for the file invar_tools-1.3.0.tar.gz.

File metadata

  • Download URL: invar_tools-1.3.0.tar.gz
  • Upload date:
  • Size: 626.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for invar_tools-1.3.0.tar.gz
Algorithm Hash digest
SHA256 92aff032d0c9bb9957a709caeef093f3805c81599dd4801878e5fb104e5ab738
MD5 f3b1ce3c5b5673ec2d0fdd71d14b48e6
BLAKE2b-256 bb3f807a8543bdbb9074d2a6f301593c794500ca33d51eaad61751e4d0209d6b

See more details on using hashes here.

Provenance

The following attestation bundles were made for invar_tools-1.3.0.tar.gz:

Publisher: publish.yml on Tefx/Invar

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file invar_tools-1.3.0-py3-none-any.whl.

File metadata

  • Download URL: invar_tools-1.3.0-py3-none-any.whl
  • Upload date:
  • Size: 217.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for invar_tools-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 205e8115b960fe4006f0582af88adf5c86bea7a7079c202b83b774535e516ba2
MD5 21f5fbd875e9442681464c5a6161952a
BLAKE2b-256 d68dfb38170265cea4323949e888da54fd5bfc37f68c827801f5ac66693ea28c

See more details on using hashes here.

Provenance

The following attestation bundles were made for invar_tools-1.3.0-py3-none-any.whl:

Publisher: publish.yml on Tefx/Invar

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page