Metadata-Version: 2.4
Name: githeri
Version: 1.0.48
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.fi
Project-URL: Documentation, https://githeri.fi/docs
Project-URL: Package, https://pypi.org/project/githeri/
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.11
Description-Content-Type: text/markdown
Requires-Dist: fastapi[standard]>=0.111.0
Requires-Dist: uvicorn[standard]>=0.23.0
Requires-Dist: typer>=0.12.0
Requires-Dist: rich>=13.0.0
Requires-Dist: requests
Requires-Dist: nicrypt>=0.0.3
Requires-Dist: httpx>=0.24.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: polar-sdk>=1.0.0
Requires-Dist: stripe>=7.0.0
Requires-Dist: cryptography>=42.0.0
Requires-Dist: ruff>=0.4.0
Requires-Dist: mcp>=2.0.0
Requires-Dist: pytest>=8.0.0
Requires-Dist: pytest-asyncio>=0.23.0
Provides-Extra: mcp
Requires-Dist: mcp>=2.0.0; extra == "mcp"
Provides-Extra: test
Requires-Dist: pytest>=8.0.0; extra == "test"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"

# Githeri

[![PyPI version](https://img.shields.io/pypi/v/githeri.svg?color=10a37f)](https://pypi.org/project/githeri/)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-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.fi)
[![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, type-safe TypeScript SDKs, and phased implementation plans. Prevent route drift, broken database schemas, and agent hallucinations before code merges.

---

## Why Githeri? (The Empirical Benchmark Proof)

AI coding agents (Cursor, Claude Code, Windsurf/Devin Desktop, Cline, VS Code / GitHub Copilot, OpenCode, ChatGPT, Antigravity, DeepSeek Harness, Hermes, Pi, 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.
- **Unbounded Scope Creep:** They alter unrelated endpoints, change authentication guards, or delete existing routes.

### 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]"
```
Confirm the CLI binary is ready:
```bash
githeri --version
# Output: githeri version 1.0.47
```

### Step 2: One-Command Autonomous Agent Launch (`githeri start`)
Launch your agent directly with an initialized workspace and synthesized contract in one terminal command:
```bash
# Launch Hermes agent with synthesized spec and plan
githeri start hermes "Add a POST /v1/notifications endpoint with rate limiting"

# Full-stack mode: scaffold backend contract and frontend UI plan in one command
githeri start cursor "Add stripe billing webhook and customer portal" --fullstack

# Lightweight terminal agent session with local Ollama model
githeri start pi "Add health check endpoint" --provider ollama --model nemotron-3-nano:4b
```

### Step 3: Scaffold Your IDE / CLI Agent (1-Second One-Time Setup)
If connecting from inside an existing IDE or terminal agent session:
```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 adds githeri to ~/.hermes/config.yaml
githeri init --agent hermes --register

# Pi Coding Agent: writes .pi/mcp.json + skills + APPEND_SYSTEM.md (flexible 8k-32k context)
githeri init --agent pi --register

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

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

# Windsurf / Devin Desktop: writes project .devin/mcp_config.json + global ~/.config/devin
githeri init --agent windsurf --register

# VS Code / GitHub Copilot: writes .vscode/mcp.json (servers), .mcp.json and instructions
githeri init --agent copilot   # alias: vscode

# Cline: installs project .clinerules/githeri.md and merges global cline_mcp_settings.json
githeri init --agent cline --register

# OpenCode: registers native MCP server and skills
githeri init --agent opencode

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

### Step 4: Prompt Your Agent Normally (Zero-Init)
Open Cursor, Antigravity, Claude, ChatGPT, Hermes, Pi, Windsurf/Devin Desktop, Cline, OpenCode, 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 generate "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: 16
  hermes --model nemotron-3-nano:4b
  ```
- **Pi Coding Agent (Terminal CLI Agent - Lightweight with flexible context):**
  > Works with any context size (8k, 16k, 32k) on local models without Hermes's 64k restriction. Full guide: [docs/PI_SETUP.md](docs/PI_SETUP.md).
  ```bash
  githeri init --agent pi --register
  pi                             # inside session: /mcp to view 16 Githeri tools
  ```
- **Cursor IDE:**
  ```bash
  githeri init --agent cursor
  ```
- **Claude Desktop:**
  ```bash
  githeri init --agent claude
  ```
- **Windsurf / Devin Desktop (IDE Agent):**
  > Devin Local reads project MCP servers from `.devin/mcp_config.json`; legacy Cascade reads the global `~/.codeium/windsurf/mcp_config.json`. Use `--register` to wire both globals.
  ```bash
  githeri init --agent windsurf --register
  ```
- **Cline (VS Code / JetBrains / CLI Agent):**
  > Cline reads MCP servers from a **global** settings file (`~/.cline/data/settings/cline_mcp_settings.json`, overridable via `CLINE_MCP_SETTINGS_PATH`). Project rules and skills land in `.cline/rules/`, `.clinerules/`, and `.cline/skills/`. You can also run `cline mcp add githeri --yes -- uvx --from "githeri[mcp]>=1.0.0" githeri mcp`.
  ```bash
  githeri init --agent cline --register
  ```

#### 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`) exposes **24 native Model Context Protocol tools, 4 resources, and 1 system prompt** directly into your agent's brain:

### 1. Contract Engine (6 Tools)

| Tool | Agent Input | Output & Action |
| :--- | :--- | :--- |
| `githeri_plan` | `prompt`, `context_dir`, `provider`, `model` | Refines prompt via Prompt Coach, validates YAML contract, and generates phased `.plan.md` checklist. |
| `githeri_synthesize_contract` | `feature_prompt`, `context_dir`, `provider`, `model` | Strips prompt noise/bug reports, validates OpenAPI/Pydantic schemas, auto-repairs model errors, and drops `.githeri/specs/<slug>.spec.yaml`. |
| `githeri_generate_plan` | `spec_slug_or_yaml`, `context_dir`, `provider`, `model` | Parses spec into phased implementation checklist with target files & verification commands at `.githeri/plans/<slug>.plan.md`. |
| `githeri_patch_router` | `router_file`, `entrypoint`, `context_dir` | Surgical AST surgery auto-mounts `app.include_router(...)` into entrypoint (`app/main.py` or Express) without whole-file rewrites. |
| `githeri_verify_drift` | `code_dir`, `specs_dir` | AST route scanner parses live router decorators and models against active specifications. Returns machine-readable pass/fail and missing routes. |
| `githeri_verify_executability` | `spec_yaml`, `plan_md`, `code_dir` | Statically assesses a 5-layer plan without executing code: spec schema, command safety, referenced paths, import syntax, and linter health. |

### 2. Brownfield Audit & Governance (3 Tools)

| Tool | Agent Input | Output & Action |
| :--- | :--- | :--- |
| `githeri_baseline_from_code` | `code_dir`, `dry_run` | Scans existing codebase routes (FastAPI, Flask, Django, Express, Go) and generates draft baseline specs (`.githeri/specs/baseline_*.spec.yaml`). |
| `githeri_audit_report` | `code_dir`, `specs_dir` | Generates a structured contract audit report (endpoint coverage, drift, unauthenticated mutations across monorepos). |
| `githeri_approve_spec` | `spec_pattern`, `approver`, `force`, `code_dir` | Promotes draft specifications to `status: active` with Git commit provenance logging in `.githeri/runs/audit_log.jsonl`. |

### 3. Specification Intake & Prompt Coach (11 Tools)

| Tool | Agent Input | Output & Action |
| :--- | :--- | :--- |
| `githeri_intake_start` | `name`, `problem_statement`, `project_dir` | Initializes an intake interview session, assesses CLEAR-SPEC readiness score, and returns initial diagnostic questions. |
| `githeri_intake_coach` | `prompt_or_file`, `project_dir`, `refine`, `provider`, `model` | Analyzes prompt against CLEAR-SPEC framework and 7 common agent pitfalls; can refine raw prompts into Level-4 structured contract briefs. |
| `githeri_intake_archetypes` | `project_dir` | Lists the 12 canonical task archetypes and available builtin or project-local profile templates. |
| `githeri_intake_template` | `archetype`, `profile`, `project_dir` | Renders the generic 9-section template or a specialized domain archetype/profile brief. |
| `githeri_intake_next_question` | `session_id`, `project_dir` | Evaluates requirements IR and returns the next highest-priority diagnostic question. |
| `githeri_intake_answer` | `session_id`, `question_id`, `answer_text` | Ingests answers to diagnostic questions, updates canonical IR, and returns remaining questions. |
| `githeri_intake_validate` | `session_id`, `project_dir`, `level` | Runs Level 1 (structural), Level 2 (semantic), and Level 3 (agent readiness) validation gates; returns blockers. |
| `githeri_intake_preview` | `session_id`, `format`, `project_dir` | Renders human-readable preview of the compiled spec in YAML, Markdown, or JSON. |
| `githeri_intake_confirm` | `session_id`, `project_dir` | Formally locks requirements and flips session state to confirmed. |
| `githeri_intake_compile` | `session_id`, `project_dir`, `force` | Compiles canonical IR to validated YAML spec; persists to `.githeri/specs/`. |
| `githeri_intake_submit` | `session_id`, `project_dir`, `force` | Submits intake session directly to Githeri contract engine without lossy regeneration. |

### 4. Project Continuity & Lineage (4 Tools)

| Tool | Agent Input | Output & Action |
| :--- | :--- | :--- |
| `githeri_project_status` | `context_dir` | Inspects project manifest and returns canonical root, active feature, stage progress, and drift status. |
| `githeri_continue_feature` | `feature_id`, `prompt`, `context_dir` | Extends existing feature, increments version with supersedes lineage, and generates plan. |
| `githeri_update_spec` | `spec`, `prompt`, `context_dir` | Surgically updates contract goals/endpoints with version bump. |
| `githeri_next_stage` | `feature_id`, `context_dir` | Advances to the next uncompleted stage in active feature plan. |

### MCP Resources (4 URI Schemes) & Prompt

| Resource URI | MIME Type | Description |
| :--- | :--- | :--- |
| `githeri://specs/active` | `application/yaml` | Active validated YAML contract specifications for current repository. |
| `githeri://context/blueprint` | `application/yaml` | Codebase AST architecture scan cache (routes, symbols, models). |
| `githeri://drift/report` | `application/json` | Live contract verification drift analysis and endpoint coverage. |
| `githeri://project/manifest` | `application/yaml` | Repository-level project manifest, active feature registry, and stage tracking. |

| Prompt Name | Description |
| :--- | :--- |
| `githeri_spec_generation` | System prompt used for Githeri deterministic contract generation and schema enforcement. |

---

## 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 start {agent} [prompt]`
Turnkey launcher: bootstraps `.githeri/` workspace, synthesizes the contract and phased plan, and boots your agent with native MCP tools mounted:
```bash
# Launch Hermes agent with synthesized spec and plan
githeri start hermes "Add POST /v1/checkout endpoint with JWT auth"

# Full-stack mode: scaffolds backend API and frontend UI runway
githeri start cursor "Add customer subscription billing" --fullstack

# Dry-run: scaffold workspace without spawning agent process
githeri start pi "Add health status check" --dry-run
```

### `githeri frontend {agent} [prompt]`
Compiles backend specification into a typed TypeScript API client & distinctive UI implementation plan, then boots the frontend specialist agent:
```bash
# Scaffold React frontend workspace from active backend spec
githeri frontend cursor "Design responsive dashboard for order fulfillment" --framework react

# Compile typed SDK and launch Pi agent
githeri frontend pi --framework nextjs --dir frontend
```

### `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 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 verify-exec`
Statically verify that a spec and plan are executable without running any commands. Performs structural checks: spec validation, plan structure, command safety (allowlist/blocklist), path integrity (referenced paths exist or are created), Python syntax/import validation, and optional deep static analysis (ruff/mypy). No commands are executed.
```bash
# Basic static verification
githeri verify-exec --spec spec.yaml --plan plan.md --code .

# With deep static analysis (ruff/mypy on embedded Python blocks)
githeri verify-exec --spec spec.yaml --plan plan.md --code . --deep

# Machine-readable output for CI/CD
githeri verify-exec --spec spec.yaml --plan plan.md --code . --json
```

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

### `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
```

### Task Archetypes & Specialized Domain Profiles

Every request is classified into one of **12 canonical task archetypes**. Each archetype provides a domain-specialized 9-section brief that steers the coding agent toward the architectural invariants that domain strictly requires — error models, isolation rules, atomic rollback, regression tests, or latency budgets:

| Archetype | Key Invariant & Focus | Loadable Profile / Aliases |
| :--- | :--- | :--- |
| `bugfix` | Reproduces named defect, repairs root cause, and locks with regression test | `bugfix.md` (`bug_fix`, `hotfix`) |
| `refactor` | Changes code structure without altering external contracts or observable behavior | `refactor.md` (`restructure`, `restructuring`) |
| `performance` | Measures baseline, isolates bottleneck, and proves throughput/latency budget | `performance.md` (`perf`, `optimization`) |
| `rest_api` | Versioned HTTP resources with Pydantic validation, error models, and auth checks | `rest_api.md` (`api`, `rest`, `http_api`) |
| `multi_tenant_app` | Tenant-scoped data schemas, RBAC guards, and hard cross-tenant isolation | `multi_tenant_app.md` (`multitenant`, `saas`) |
| `auth_security` | Sessions, JWT lifecycle, bcrypt hashing (passlib banned), and rate limiting | `auth_security.md` (`auth`, `security`, `identity`) |
| `transactional_ledger` | Balance-conserving mutations, atomic reservations, and idempotency guarantees | `transactional_ledger.md` (`ledger`, `accounting`, `billing`) |
| `cli_tool` | Composable CLI commands with stable stdout/stderr, exit codes, and dry runs | `cli_tool.md` (`cli`, `command_line`) |
| `data_pipeline` | Resumable ingestion pipelines with idempotent writes and data-quality checks | `data_pipeline.md` (`pipeline`, `etl`) |
| `background_job` | Queued worker tasks with exponential backoff, dead-letter queues, and graceful stop | `background_job.md` (`worker`, `queue`, `job`) |
| `docs_change` | Runnable, verified documentation or configuration changes with zero drift | `docs_change.md` (`docs`, `config_change`) |
| `generic_app` | Canonical 9-section template fallback when no specialized domain applies | Default generic schema |

Specialized domain profiles (e.g. `transactional_ledger.md`, `prediction_market.md`, `financial_trading`) can be customized or overridden on a per-project basis at `.githeri/profiles/<archetype>.md`.

```bash
# Discover all 12 canonical archetypes and loadable profiles
githeri intake archetypes

# Print or save a specialized brief template
githeri intake template --archetype rest_api --out requirements.md
githeri intake template --archetype transactional_ledger --out ledger_brief.md

# Declare the archetype during one-shot planning
githeri plan "Add tenant-scoped billing endpoints" --archetype multi_tenant_app
```

### Prompt Coach (`githeri intake coach`)

Evaluate any natural-language prompt or brief against the **CLEAR-SPEC framework** (Completeness, Limits, Entities, Acceptance criteria, Readiness) and the 7 common agent failure modes before feeding it to code generation:

```bash
# Analyze prompt for ambiguities, missing status codes, and unstated assumptions
githeri intake coach "Add customer notifications"

# Automatically refine a vague prompt into a structured Level-4 contract brief
githeri intake coach "Add customer notifications" --refine --provider gemini --model gemini-2.5-flash
```

### 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>
```

---

## Code Audit & Spec Approval (Sprint 17)

Audit a repository you did not write. The pipeline follows one rule: **machines draft,
humans approve, the hook enforces.** Nothing is promoted to an enforced contract
without an explicit, attributable approval.

### The 3-command entry point

```bash
# 1. Draft contracts from the live codebase (no LLM, no prompt)
githeri spec --from-code

# 2. Review them (interactive, or batch for CI)
githeri spec review

# 3. Approve reviewed specs — flips draft -> active with provenance
githeri spec approve --all
```

After approval, `githeri verify` (and the pre-commit hook) enforce these contracts.

### `githeri spec approve <spec|task_id|--all>`

Flips `status: draft` to `status: active` and records who approved it, when, and at
which commit:

```yaml
status: active
approval:
  approved_by: Ada Lovelace <ada@example.com>
  approved_at: '2026-10-07T02:16:25Z'
  approved_commit: 55fa435b7059e17069d1cda827a57586c9555cda
```

Two guards protect against accidental enforcement:

| Guard | Behaviour |
|---|---|
| **Drift guard** | Refuses a spec whose declared endpoints are missing from the code. Not bypassable — activating such a spec would create drift immediately |
| **Review guard** | Refuses a spec still byte-identical to generator output (no human touch). Bypass with `--force` |

Every approval appends a JSON line to `.githeri/runs/audit_log.jsonl`, so you can
always answer "who activated this contract and why".

```bash
githeri spec approve checkout-api          # by task_id
githeri spec approve .githeri/specs/x.yaml # by path
githeri spec approve --all                 # every draft, reporting per-spec outcome
githeri spec approve --all --force         # skip the review guard (not the drift guard)
githeri spec approve x --approver "llm:gemini/flash"   # custom provenance identity
```

### `githeri spec review`

Interactive walkthrough of every draft endpoint. For each route you see the detected
method, path, and any inferred detail (status, auth, body schema, rate limit), then
choose an action:

| Key | Action |
|---|---|
| `a` | approve-as-is |
| `e` | edit inline — opens the spec in `$EDITOR` and re-validates on save |
| `s` | skip |
| `f` | approve every endpoint declared by the same spec file |
| `q` | quit |

A progress table is printed at the end.

```bash
githeri spec review                        # interactive
githeri spec review --batch                # approve all endpoints without prompting
githeri spec review --file path/spec.yaml  # a single spec
```

Review records progress only — it never flips a spec to active on its own (rule R1).
Use `spec approve` for that.

### LLM-assisted review (`--agent`)

Both `spec review` and `spec approve` accept `--agent=<provider[:model]>`, where
provider is `gemini`, `ollama`, `deepseek`, or `chatgpt`. The reviewer model reads each
endpoint **together with its real handler code** (extracted via AST, not a placeholder)
and returns a structured record:

```json
{
  "endpoint": "POST /v1/notifications",
  "verdict": "approve | needs_human | reject",
  "rationale": "why",
  "patched_fields": {"expected_status": 200, "requires_auth": true}
}
```

```bash
githeri spec review --agent=gemini:flash       # stage suggestions for you to accept
githeri spec review --agent=chatgpt:gpt-4o --auto-approve-agent  # apply approved patches
githeri spec approve --agent=ollama:qwen2.5-coder:7b --all       # agent supplies provenance
```

Human-in-the-loop by default: suggestions are staged. With `--auto-approve-agent`,
only `approve` verdicts are applied, and only a whitelist of contract keys is ever
written (`expected_status`, `requires_auth`, `request_schema`, `response_schema`,
`rate_limit`) — a chatty model cannot inject arbitrary structure. Endpoints that are
not implemented in code are always forced to `reject`, and a reviewer failure degrades
to `needs_human` rather than aborting the run.

When the agent approves, provenance records the model identity:

```yaml
approval:
  approved_by: llm:gemini/flash
```

### Monorepos

`githeri audit report` detects workspace layout (containers like `packages/`, `apps/`,
`services/`, plus nested build manifests) and adds a per-package coverage table, so a
monorepo root report shows each member's contract state:

```bash
githeri audit report            # includes a "Monorepo Packages" table automatically
```

Programmatic access:

```python
from githeri.audit.harden import detect_monorepo, summarize_monorepo
detect_monorepo(".")        # {"is_monorepo": True, "members": [...], ...}
summarize_monorepo(".")     # per-package coverage rows
```

### `githeri audit report`

Renders a shareable summary of a repository's contract surface — useful for onboarding
a new engineer or a security reviewer.

```bash
githeri audit report                      # Markdown to stdout
githeri audit report -o AUDIT.md          # write to file
githeri audit report -o audit.json -f json
```

The report contains coverage (matched vs missing), endpoints grouped by spec, coverage
by functional area, a per-package table for monorepos, and **suspicious patterns** —
currently mutation endpoints (`POST`/`PUT`/`DELETE`/`PATCH`) with no detectable auth
guard in their declaring file.

It also includes a **before/after review diff**: the baseline state (everything `draft`)
versus the current state, listing which specs were activated, by whom, at which commit,
and which contract fields were tightened. That is the view a reviewer wants when asking
"what changed since we baselined this repo?"

### `githeri audit harden`

Repo-agnostic scanning setup: deduplicated ignore rules (`.githeriignore`, `.gitignore`,
plus defaults for venvs, `node_modules`, build output, model weights, and secrets),
framework detection beyond FastAPI (Flask, Django, Express, Go chi/gin), and a bounded
file walk so large repositories stay fast.

```bash
githeri audit harden                      # scan the current repo
githeri audit harden --root ./service     # scan a specific directory
githeri audit harden --max-files 5000     # cap the walk
```

### Design rules

| Rule | Meaning |
|---|---|
| **R1** | Machines never auto-promote a draft to `active` — only an explicit `approve` does |
| **R2** | Untouched generator output is refused unless `--force`; the value gate is human review |
| **R3** | Works on any git repo: no framework assumptions, no pre-existing `.githeri/` required |
| **R4** | Approval provenance is recorded (who/what/when/which commit) and appended to the audit log |

### Tests

```bash
pytest tests/test_sprint17_audit.py -v    # 27 unit/integration tests covering R1-R4
pytest tests/test_sprint17_e2e.py -v      # 14 end-to-end tests
```

The E2E suite runs the whole pipeline against three repository shapes — a FastAPI
service, an Express app, and a mixed monorepo — including approving drafts, installing
the blocking hook, introducing drift, and asserting the gate catches it. The LLM
reviewer is exercised against a stubbed model so CI needs no provider key.

---

## Corpus-Scale Benchmark (Sprint 18)

Githeri includes a built-in corpus-scale benchmark harness to evaluate model performance on spec/plan generation at scale.

### Quickstart: 115-Prompt Balanced Sample
```bash
# Run 115 prompts (5 per category × 23 categories) with static verification
python scripts/run_corpus_proof.py --corpus data/corpus/prompts_sampled.jsonl \
  --model nemotron-3-nano:4b \
  --verify-exec \
  --code-dir . \
  --workers 4 \
  --output data/corpus/proof_runs.jsonl
```

### Full 475-Prompt Corpus (Full Benchmark)
```bash
# Full 475-prompt corpus (5 per category × 23 categories + 56 original)
python scripts/run_corpus_proof.py --corpus data/corpus/prompts_475.jsonl \
  --model nemotron-3-nano:4b \
  --verify-exec \
  --code-dir . \
  --workers 4 \
  --output data/corpus/proof_runs_full.jsonl
```

### Resumable & Resilient
- **Resumable**: `--start` index + `--limit` + output file appended incrementally
- **Resumable**: `--output` file appended per completion; re-run with same `--output` to resume
- **Unreachable models**: Logged as FAIL with reason, never silently omitted

### Results (115-Prompt Balanced Sample, nemotron-3-nano:4b)
| Metric | Vanilla (bare) | Githeri Pipeline | Delta |
|--------|----------------|------------------|-------|
| Spec Valid | 0.0% | **88.7%** | +88.7pp |
| Plan Proxy (structural) | 0% | **95.7%** | +95.7pp |
| YAML Extraction | 97.4% | 97.4% | — |
| Mean Quality Score | n/a | **0.8727** | — |
| Mean Duration | 132s | 471s | — |

| Metric | Vanilla (95% CI) | Githeri (95% CI) |
|--------|------------------|------------------|
| Spec Valid | [0.0%, 3.2%] | [81.6%, 93.3%] |
| Plan Proxy | [0.0%, 3.2%] | [90.2%, 98.1%] |
| Quality Score | — | [0.846, 0.900] |

> **Note:** Plan "executability" is a **structural heuristic** (stages + command markers + length), not actual code execution. No commands are executed. No live MCP transport tested. See `docs/features/empirical-proof-corpus/SUMMARY.md` for full methodology and limitations.

### Full 475-Prompt Corpus (Run When Ready)
```bash
# Estimated time: ~10h @ 4 workers, ~30h @ 1 worker (shallow); ~4 min deep @ 4 workers
python scripts/run_corpus_proof.py --corpus data/corpus/prompts_475.jsonl \
  --model nemotron-3-nano:4b \
  --verify-exec \
  --code-dir . \
  --workers 4 \
  --output data/corpus/proof_runs_full.jsonl
```

---

## Founder Studio (`studio.githeri.fi`)

Githeri also powers **Founder Studio**, a companion browser-based studio for founders and engineering teams to transform natural language product concepts into production full-stack web applications:

- **Turnkey Full-Stack Inception:** Generates typed FastAPI backends and modern React + Tailwind CSS v4 frontend workspaces directly from user prompts.
- **Dynamic Entity CRUD:** Automatically extracts domain entities (e.g. `Project`, `Booking`, `Invoice`) and scaffolds custom list views, creation modals, detail drawers, and status badges—never generic placeholder scaffolds.
- **Phased Build Progress:** Real-time visual tracking across 4 build stages (Schemas & DB Models, Route Controllers, Test Suites, Drift Verification).
- **Zero-Lockin Export:** Download turnkey ZIP archives (bundled with Vite build configuration and runnable tests) or export directly into your development workflow.
- **Cloud Persistence:** Multi-tenant project persistence powered by Turso distributed databases.

Access Founder Studio at [studio.githeri.fi](https://studio.githeri.fi) or launch the frontend compiler locally via `githeri frontend`.

---

## 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 completely local and need no key or internet connection.

| Tier | Cloud Specs / month | Rate Limit | Pricing & Notes |
| :--- | :--- | :--- | :--- |
| **Free** | **15** | 20 req/hr | Unlimited local CLI (BYOK/Ollama); 15 hosted cloud specs/month (hard cap) |
| **Solo** | **500** | 100 req/hr | Unlimited local validation + 500 cloud specs/mo ($0.04/spec overage). $10/mo annual ($7.50 effective monthly / $12 monthly) |
| **Team** | **5,000** | 500 req/hr | Up to 5 seats, GitHub Actions CI PR Gate (`check-pr`). $49/mo annual ($41.67 effective monthly / $60 monthly) |
| **Platform** | **20,000** | 2,000 req/hr | OEM API & Agent SDK integration, or $0.02/spec metered. $299/mo annual ($399 monthly) |
| **Unlimited** | No cap | 2,000 req/hr | Internal developer tier, issued server-side only |

### Pay-As-You-Go Metered Credit Wallet (Zero Subscription Lock-In)

For developers and agent pipelines that prefer usage-based billing over recurring monthly subscriptions:
- **Starter Pack ($5.00)**: 125 specs ($0.04 / spec). Non-expiring balance.
- **Pro Pack ($20.00)**: 500 specs ($0.04 / spec). Non-expiring balance.
- **Enterprise / OEM Metered**: High-volume $0.02 / spec rate.
- Minimum transaction threshold: $1.50 (guards against high fixed per-transaction payment processing fees).

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 or top up credits at githeri.fi |
| `credits_exhausted` | Credit wallet depleted ($0.00) and no active quota | Top up credit wallet at githeri.fi |
| `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 user@example.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`, `NOUSRESEARCH_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
pip install -e ".[mcp,test]"
pytest tests/
```

## License

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