Metadata-Version: 2.4
Name: githeri
Version: 0.4.8
Summary: Zero-Copy Contract Engine & Native MCP Protocol for AI Coding Agents (Cursor, Claude, Antigravity, Hermes).
Author-email: Karakana Labs <dev@karakanalabs.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://githeri.com
Project-URL: Documentation, https://githeri.com/docs
Project-URL: Repository, https://github.com/karakana-labs/githeri
Project-URL: Issues, https://github.com/karakana-labs/githeri/issues
Keywords: ai,agents,mcp,model-context-protocol,cursor,claude,antigravity,hermes,spec,fastapi,contract-testing,drift-detection,openapi
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Build Tools
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: typer>=0.12.0
Requires-Dist: rich>=13.0.0
Requires-Dist: requests>=2.28.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: ruff>=0.4.0
Provides-Extra: mcp
Requires-Dist: mcp>=2.0.0; extra == "mcp"

# Githeri

[![PyPI version](https://img.shields.io/pypi/v/githeri.svg?color=10a37f)](https://pypi.org/project/githeri/)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-green.svg)](https://opensource.org/licenses/Apache-2.0)
[![Contract Drift: 0%](https://img.shields.io/badge/route_drift-0%25-brightgreen.svg)](https://githeri.com)
[![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)

**Contract Engine for AI Coding Agents.**  
Turn natural language feature requests into deterministic, validated YAML specifications and phased implementation plans. Prevent route drift, schema breaks, and agent hallucinations before code merges.

---

## Why Githeri? (The Empirical Benchmark Proof)

AI coding agents (Cursor, Claude Code, ChatGPT, Antigravity, DeepSeek Harness, Aider) write code quickly, but lightweight and fast models (Gemini Flash, Claude Haiku, local 7B SLMs) frequently cheat:
- **Silent Route Drift:** They claim a feature is done, but implement `GET /` instead of the requested `POST /v1/bookings/`.
- **Hallucinated Endpoints on Crash Reports:** When given a bug report (e.g. *"website is slow, shows white screen"*), vanilla agents invent fake CRUD routes (`GET /fix`, `POST /optimize`) that solve nothing.
- **Phantom Imports & Broken Schemas:** They fabricate non-existent dependencies and database fields.

### The Receipts: Evaluated on `gemini-3.1-flash-lite`

Across benchmark torture tests with contradictory, vague, and chaotic prompts:

| Benchmark Gate | Vanilla Agent (Direct) | Githeri MCP Protocol | Impact |
| :--- | :--- | :--- | :--- |
| **Fluff & Noise Filtering** | Chases impossible constraints | **55 fluff snippets stripped** | Eliminates fantasy constraints |
| **Diagnostic Bug Interception** | Fabricates fake endpoints on crash reports | **100% Intercepted** | Halts wasteful code generation |
| **Contract Determinism** | 0% validated specifications | **100% Validated YAML Specs** | Architectural memory locked |
| **Silent Drift Detection** | Silent drift merged to production | **100% Caught by AST Verifier** | Trapped lazy agent route swaps |

---

## 60-Second Zero-Copy Quickstart (MCP)

No copy-pasting specs, YAML files, or commands from a dashboard. Developers configure their agent once in 1 second, add their API key, and talk to their agent in plain English. The agent calls Githeri tools natively over the **Model Context Protocol (MCP)**.

### Step 1: Install Githeri with MCP support
```bash
pip install "githeri[mcp]"
```

### Step 2: Scaffold your IDE Agent (1-Second One-Time Setup)
```bash
# Cursor: writes .cursor/mcp.json + contract sentinel pre_tool_hook.py
githeri init --agent cursor

# Claude Desktop: safely merges githeri into claude_desktop_config.json
githeri init --agent claude

# Google Antigravity: configures skill and global mcp_config.json
githeri init --agent antigravity

# Hermes Agent: writes .hermes/config.yaml + skill, and (with --register) adds githeri
# to your GLOBAL ~/.hermes/config.yaml. Hermes ignores project-level MCP config,
# so --register is what actually connects it. See docs/HERMES_SETUP.md
githeri init --agent hermes --register

# DeepSeek Harness: writes .deepseek/config.yaml + .deepseek/skills/githeri/SKILL.md
githeri init --agent deepseek

# ChatGPT / OpenAI-compatible clients: writes .chatgpt/config.yaml + skills
githeri init --agent chatgpt

# Or configure all supported agents at once
githeri init --agent all
```

### Step 3: Prompt Your Agent Normally (Zero-Init)
Open Cursor, Antigravity, Claude, ChatGPT, Hermes, or DeepSeek Harness chat in **any** project repository and prompt directly:
> *"Add a POST /v1/notifications endpoint with rate limiting."*

**No manual repo setup required:** On first invocation, Githeri auto-provisions `.githeri/`, validates the contract, generates the phased plan, and verifies route drift over native stdio MCP. (Manual `githeri init` is strictly optional for offline CLI-only workflows).

---

### Standalone Quickstart: Running Local Models (Ollama) Without Antigravity

Want to run completely local models (e.g. `nemotron-3-nano:4b`, `qwen2.5-coder:7b`) without Antigravity? Githeri supports full autonomous execution and MCP tool integration standalone:

#### Option 1: One-Command Autonomous Sandbox (`Path A`)
Run from natural language prompt to validated spec, phased plan, generated code, Ruff auto-formatting, and pytest verification in a single terminal command:
```bash
githeri run "Add a GET /health endpoint returning status 200" \
  --provider ollama \
  --model nemotron-3-nano:4b \
  --isolated
```
*Lifecycle executed automatically:*
1. **AST Codebase Scan:** Discovers routes, models, and auth guards into `.githeri/context.yaml`.
2. **Contract Synthesis:** Schema-validates YAML contract and auto-repairs model errors (up to 3 retries).
3. **Phased Plan:** Generates 4-phase runway with surgical integration anchors.
4. **Execution & Test:** Creates sandbox venv, writes code, runs `ruff check --fix`, patches entrypoints, and runs `pytest`.
5. **Drift Verification:** Audits codebase AST against the contract to guarantee 0% drift.

#### Option 2: Step-by-Step Granular CLI
```bash
# 1. Scan host repository architecture
githeri scan --code .

# 2. Synthesize validated contract
githeri spec "Add PKCE to OAuth2 flow" --provider ollama --model nemotron-3-nano:4b

# 3. Generate phased implementation plan
githeri plan "Add PKCE to OAuth2 flow" --provider ollama --model nemotron-3-nano:4b

# 4. Execute code stages & run tests
githeri exec --provider ollama --model nemotron-3-nano:4b --isolated

# 5. Check route & schema drift
githeri verify --strict
```

#### Option 3: Using Githeri MCP with Other Agents (`Path B`)
Configure other local or IDE agents to call Githeri MCP tools over stdio:
- **Hermes Agent (Terminal CLI Agent):**
  > Hermes reads MCP servers only from `~/.hermes/config.yaml` (global), so register with `--register`. Full guide: [docs/HERMES_SETUP.md](docs/HERMES_SETUP.md).
  ```bash
  githeri init --agent hermes --register
  hermes mcp test githeri        # expect: Tools discovered: 4
  hermes --model nemotron-3-nano:4b
  ```
- **Cursor IDE:**
  ```bash
  githeri init --agent cursor
  ```
- **Claude Desktop:**
  ```bash
  githeri init --agent claude
  ```

#### Option 4: Headless Python Script (Direct MCP Tools)
```python
from pathlib import Path
from githeri.mcp.server import synthesize_contract, generate_plan, verify_drift
from githeri.core.executor import execute_plan

MODEL = "nemotron-3-nano:4b"
PROVIDER = "ollama"

# 1. Synthesize contract
spec = synthesize_contract("Add GET /health endpoint", context_dir=".", provider=PROVIDER, model=MODEL)
assert spec["validated"], f"Errors: {spec['validation_errors']}"

# 2. Generate plan
plan = generate_plan(spec["spec_slug"], context_dir=".", provider=PROVIDER, model=MODEL)

# 3. Execute plan to code and test
report = execute_plan(plan_path=Path(plan["plan_path"]), code_dir=Path("."), provider=PROVIDER, model=MODEL, isolated=True)

# 4. Verify drift
drift = verify_drift(code_dir=".")
print(f"Contract pass: {drift['passed']}")
```

📖 *For full details and model tuning, see the [Local Model Standalone Guide](docs/LOCAL_MODEL_STANDALONE_GUIDE.md).*

---

## Native MCP Tools Reference

The Githeri MCP Server (`githeri-mcp` or `githeri mcp`) provides 4 native tools directly into your agent's brain:

| Tool | Agent Input | Output & Action |
| :--- | :--- | :--- |
| `githeri_synthesize_contract` | `feature_prompt`, `context_dir` | Filters prompt noise, validates contract, drops `.githeri/specs/<slug>.spec.yaml`. |
| `githeri_generate_plan` | `spec_slug_or_yaml` | Parses spec into phased implementation checklist at `.githeri/specs/<slug>.plan.md`. |
| `githeri_patch_router` | `router_file`, `entrypoint` | Surgical AST surgery auto-mounts `app.include_router(...)` into `app/main.py`. |
| `githeri_verify_drift` | `code_dir` | AST route scanner matches code against spec. Returns machine-readable pass/fail and missing routes. |

---

## Two Execution Paths

| Feature | Path A: Autonomous Sandbox Executor | Path B: Native MCP Agent Protocol (Primary) |
| :--- | :--- | :--- |
| **Target Engine** | Standalone headless execution loop | Cursor, Claude Desktop, ChatGPT, Antigravity, Hermes, DeepSeek Harness, Windsurf |
| **Command / Protocol** | `githeri run --isolated` | JSON-RPC over stdio (`githeri-mcp`) |
| **Developer Interaction**| Terminal CLI output | Natural language chat in IDE |
| **Code Polish** | Auto-runs `ruff check --fix --ignore B008` | Agent / IDE formatters |
| **Router Mounting** | Surgical AST insertion | `githeri_patch_router` MCP tool |
| **Drift Verification** | Evaluated automatically at end of run | `githeri_verify_drift` MCP tool |

---

## Terminal Power Suite (For CLI & CI/CD)

Built for engineers who live in `tmux`, `Neovim`, and automated CI/CD pipelines.

### `githeri plan <prompt>`
Generate spec and phased plan directly in the terminal:
```bash
githeri plan "Add POST /v1/checkout endpoint with JWT auth"
```

### `githeri run --isolated`
Execute plan stages in a disposable sandbox virtual environment with Ruff polish and 0% drift assertion:
```bash
githeri run --isolated
```

### `githeri doctor`
Diagnose your local Python runtime, active virtualenv, Ruff installation, Git hooks, and contract registry:
```bash
githeri doctor
```

### `githeri diff [run-id] [--patch]`
Inspect exactly what was generated or modified in any recorded run:
```bash
githeri diff                         # Summary table of files and router mounts
githeri diff --patch                 # Git-style unified colored diffs (+/-)
```

### `githeri watch`
Continuous contract sentinel. Watches `app/`, `src/`, and `tests/` in real-time. Whenever an AI agent saves a file, Githeri validates contracts in milliseconds:
```bash
githeri watch
# [14:22:01] ⚡ Change detected in app/routers/checkout.py
# ✔ CONTRACT PASS: 3/3 endpoints matched. Zero drift.
```

### `githeri spec --from-code`
Audit existing code (no LLM needed). Scans live routes and writes one draft baseline spec per source file to `.githeri/specs/` — the fastest way to adopt Githeri on a codebase you didn't write:

```bash
githeri spec --from-code             # write draft specs for all live routes
githeri spec --from-code --dry-run   # preview without writing
githeri spec --from-code --json      # machine-readable summary for agents
```

Generated specs are marked `generated: true` / `status: draft` — they document what the code *does*, not what it *should* do. Review, tighten (status codes, request schemas, auth guards), flip to `status: active`, and `githeri verify` enforces them from then on.

### `githeri hook install`
Install a pre-commit contract gate into `.git/hooks/pre-commit`:
```bash
githeri hook install                 # mode=block (default): commit fails only when declared
                                     # spec endpoints are missing from code
githeri hook install --mode warn     # warn: prints drift summary, never blocks the commit
githeri hook install --mode strict   # strict (for CI): fails on missing OR undocumented routes
githeri hook status                  # Verify active enforcement
githeri hook remove                  # Uninstall
```


### `githeri check-pr` (CI/CD Quality Gate)
Enforce contracts in GitHub Actions. Exits `1` on contract violations:
```bash
githeri check-pr
```

```yaml
# .github/workflows/contract-gate.yml
name: Contract Gate
on: [pull_request]
jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - run: pip install "githeri[mcp]"
      - run: githeri check-pr
```

---

## Specification Anatomy

Generated specifications (`.githeri/specs/<name>.spec.yaml`) are deterministic, machine-readable contracts:

```yaml
task_id: checkout_service
summary: "Add POST /v1/checkout endpoint with JWT auth"
environment:
  required_packages:
    - "fastapi>=0.110.0"
    - "python-jose[cryptography]>=3.3.0"
local_goals:
  - id: L1
    description: "Checkout processing router"
    type: create
    target_file: "app/routers/checkout.py"
    verification:
      type: http
      method: POST
      url: "http://localhost:8000/v1/checkout"
      expect:
        status_code: 200
        response_schema:
          type: object
          required: ["status", "order_id"]
```

---

## Specification Intake (Sprint 16)

The `githeri intake` command provides an interactive, adaptive interview that transforms a raw feature request into a structured, validated Githeri spec — eliminating the "blank page" problem and ensuring no critical detail is missed.

### Why Intake?
Agents often hallucinate requirements when given vague prompts like "add auth." Githeri Intake guides the user through a structured interview, extracting concrete requirements, constraints, and acceptance criteria — then compiles them into a validated Githeri spec ready for planning and execution.

### Quickstart
```bash
# Interactive interview (prompts you question-by-question)
githeri intake start "Add a POST /v1/notifications endpoint with rate limiting"

# Non-interactive: load from structured file (YAML or Markdown)
githeri intake start --input requirements.md --non-interactive

# Resume a session later
githeri intake resume <session_id>

# List all sessions
githeri intake list
```

### The Adaptive Interview Flow
1. **Context** — Detects project type, framework, existing routes
2. **Problem** — Captures the raw feature request and motivation
3. **Goals** — Identifies primary and secondary objectives
4. **Requirements** — Extracts concrete capabilities (with LLM-assisted extraction, confirmed by you)
5. **Adaptive Branches** — Detects keywords and asks only relevant follow-ups:
   - **Auth** → asks about JWT/OAuth/session auth
   - **File Upload** → asks about formats, size limits, failure handling
   - **Payments** → asks about providers, currencies, webhooks
   - **Performance** → asks for concrete SLAs (p95, RPS)
6. **Constraints** — Technical, legal, deadline constraints
7. **Acceptance Criteria** — Captures Given/When/Then scenarios
7. **Review & Confirm** — Presents structured summary for confirmation

### Non-Interactive Mode (CI / Agent Pipelines)
```bash
# Load structured requirements from file (Markdown or YAML)
githeri intake start --input requirements.md --non-interactive
```
The file can be a structured Markdown document with sections like `## Requirements`, `## Constraints`, `## Acceptance Criteria`, or a YAML file with the same structure. Githeri parses it, runs validation, and produces a draft spec ready for `githeri intake compile`.

### Validation Gates (Three Levels)
| Level | Checks |
|-------|--------|
| L1 Structural | Required fields, valid IDs, enum values, duplicate IDs |
| L2 Semantic | Ambiguities ("fast", "secure"), contradictions, missing requirements |
| L3 Agent Readiness | Missing AC, unbounded scope, no verification path |

Only specs passing the configured level compile to Githeri specs.

### From Intake to Production
```bash
# 1. Run interactive interview
githeri intake start "Add a POST /v1/webhooks endpoint with HMAC verification"

# 2. Review & confirm at the end → saves to .githeri/intake/sessions/<id>.yaml

# 2b. Or compile immediately (validates readiness gate)
githeri intake compile <session_id> --force

# 3. Submit to Githeri Cloud (or local) for full spec + plan
githeri intake submit <session_id>

# Or use the compiled artifacts directly:
#   - .githeri/intake/out/<id>/SPEC.yaml  (validated contract)
#   - .githeri/intake/out/<id>/SPEC.md    (markdown for agents)
```

### Session Management
```bash
# List all intake sessions
githeri intake list

# Resume a paused session
githeri intake resume <session_id>

# View session details
githeri intake show <session_id>

# Validate a session (L1/L2/L3)
githeri intake validate <session_id> --level 3

# Preview the compiled spec
githeri intake preview <session_id> --format yaml

# Compile to Githeri spec artifacts
githeri intake compile <session_id> --out ./artifacts

# Submit to Githeri Cloud (runs full spec + plan generation)
githeri intake submit <session_id>

# Edit session manually (opens $EDITOR, re-validates on save)
githeri intake edit <session_id>
```

---

## API Key, Free Tier & Quota

Spec and plan generation (`githeri_synthesize_contract`, `githeri_generate_plan`) run on the Githeri Cloud API and **require an API key**. `githeri_verify_drift` and `githeri_patch_router` are local and need no key.

| Tier | Specs / month | Notes |
|---|---|---|
| Free | **15** | Counted per account, per calendar month (UTC) |
| Solo / Team / Platform / Metered | Paid plans | See pricing |
| Unlimited | No cap | Internal developer tier, issued server-side only |

Only successful generations count: a failed or invalid generation is refunded. Generating a plan for an existing spec does **not** use another spec.

### Setting your key (one time)
```bash
githeri init --agent hermes --register      # prompts: "Githeri API key (git_live_...), press Enter to skip"
githeri init --agent cursor --key git_live_xxx   # or pass it non-interactively
githeri login                                # or any time later
githeri status                               # shows tier and key
```
The key is validated, then saved to `~/.githeri/credentials.json` (or set `GITHERI_API_KEY`). The MCP server reads it from there, so it never needs to be pasted into your agent's config.

### What agents see without a key or over quota
Tools return a structured error instead of crashing, so the agent can tell you what to do:

| `error_code` | Meaning | Fix |
|---|---|---|
| `missing_api_key` | No key configured | Run `githeri login` in a terminal, then retry |
| `invalid_api_key` | Key wrong or revoked | `githeri login` with a valid key |
| `free_quota_exhausted` | 15/15 free specs used this month | Upgrade at githeri.com/pricing |
| `rate_limited` | Too many requests this hour | Wait and retry |

### Issuing an unlimited developer key (server admin)
Run on the machine hosting the backend database (set `DATA_DIR` for a non-default DB):
```bash
python scripts/issue_key.py --email rotich@duck.com --tier unlimited
githeri login --key <printed key>
```
The raw key is printed once; only its hash is stored. The `unlimited` tier cannot be minted over HTTP without `ADMIN_SECRET`.

---

## Configuration

Settings are resolved hierarchically:
1. CLI flags (`--provider`, `--model`, `--specs`, `--code`)
2. Local workspace: `.githeri/config.yaml`
3. Global credentials: `~/.githeri/credentials.json`
4. Environment variables: `GITHERI_API_KEY`, `GEMINI_API_KEY`, `OLLAMA_BASE_URL`

```bash
# Authenticate CLI with Githeri Cloud
githeri login --key git_live_...

# Display environment & license status
githeri status
```

---

## Contributing & Development

```bash
git clone https://github.com/karakana-labs/githeri.git
cd githeri
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[mcp,dev]"
pytest tests/
```

## License

Apache-2.0 © [Karakana Labs](https://karakanalabs.com)
