Skip to main content

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

Project description

Invar

PyPI version Python 3.11+ License: MIT

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

Invar is a framework that helps developers ensure AI-generated code is reliable through contracts, verification, and mechanical checks.

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)

Installation

Development Tools

# Recommended: use without installing
uvx invar-tools guard

# Or install globally
pip install invar-tools

Runtime Contracts (for your project)

pip install invar-runtime

Packages:

Package Size Purpose
invar-runtime ~3MB Runtime contracts (@pre, @post, etc.)
invar-tools ~100MB Development tools (guard, map, sig, MCP)

Quick Start

cd your-project
invar init          # Creates INVAR.md, CLAUDE.md, .invar/
invar guard         # Verify code quality

Multi-Agent Support: invar init auto-detects and configures:

AI Tool Configuration
Claude Code Creates CLAUDE.md + MCP server
Cursor Adds to .cursorrules
Aider Adds to .aider.conf.yml
Others Add "Follow INVAR.md" to system prompt

Core/Shell Architecture

Invar enforces separation between pure logic and I/O:

Zone Requirements Forbidden
Core @pre/@post contracts, doctests I/O imports (os, pathlib, requests...)
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 (default)
invar guard --changed    # Only git-modified files
invar guard --static     # Static only (~0.5s)

Flags:

Flag Purpose
--strict Treat warnings as errors
--explain Show rule limitations
--agent JSON output for AI tools
--pedantic Show all rules including off-by-default

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

Verification Levels (DX-19)

Level Command Checks When to Use
STATIC --static Rules only (~0.5s) Debugging static analysis
STANDARD (default) Rules + doctests + CrossHair + Hypothesis (~5s) Everything else

Zero decisions: Default runs full verification. Incremental mode makes it fast (~5s first, ~2s cached).


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

# Purity overrides
purity_pure = ["pandas.DataFrame.groupby"]
purity_impure = ["my_module.cached_lookup"]

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

# Severity overrides
[tool.invar.guard.severity_overrides]
redundant_type_contract = "off"

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
param_mismatch ERROR Lambda params ≠ function params

Full list: invar rules --explain


MCP Integration (Claude Code)

invar init automatically creates .mcp.json with smart detection of available methods:

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

Claude Code Integration:

# Full integration (recommended)
invar init --claude

# Specify MCP method
invar init --claude --mcp-method uvx      # Recommended
invar init --claude --mcp-method command  # Use PATH invar
invar init --claude --mcp-method python   # Use current Python

MCP Tools:

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

Manual setup: See .invar/mcp-setup.md after running invar init.


File Ownership

File Owner Edit?
INVAR.md Invar No (invar update manages)
CLAUDE.md You Yes (project config)
.invar/examples/ Invar No (reference only)

Runtime Behavior

Contracts are checked at runtime via deal.

# Disable in production
DEAL_DISABLE=1 python app.py

Troubleshooting

Guard is slow:

  • Use --changed for incremental checks
  • Use --static to skip doctests during debugging

Too many warnings:

  • Add exclusions for generated code
  • Override severity for noisy rules

CrossHair timeout:

  • Some code patterns don't work well with symbolic execution
  • Hypothesis fallback runs automatically

Learn More

In your project (created by invar init):

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

Documentation:


License

MIT

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.0.0.tar.gz (296.6 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.0.0-py3-none-any.whl (115.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: invar_tools-1.0.0.tar.gz
  • Upload date:
  • Size: 296.6 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.0.0.tar.gz
Algorithm Hash digest
SHA256 a7e230d6f1a6009c5c1cd40d5b4354d50c4271c8012d3f54c6e17cf3ded692d7
MD5 ee5b630f6fcb457f6388063178f2eafb
BLAKE2b-256 05e6746883a311250dbf5a636520ff7417ed4ea194b655ab6174d37fcec59e54

See more details on using hashes here.

Provenance

The following attestation bundles were made for invar_tools-1.0.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.0.0-py3-none-any.whl.

File metadata

  • Download URL: invar_tools-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 115.8 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.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7a10c2a9c52e0f557cd3077c7f026355e1df9116855881f23142fa54ed819781
MD5 154ce47c70dab4d4d31e42abf886c136
BLAKE2b-256 4cf8afd66b3d4cf7af7e9ff6c68faf4b9b0fa7d2e93d8b39733d2aac8d879b69

See more details on using hashes here.

Provenance

The following attestation bundles were made for invar_tools-1.0.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