Skip to main content
Glama
README.md
# git_advisor

**A fast, zero-GPU, causally calibrated repository impact advisor, smart test selector, and verified refactoring tool (CLI + MCP server) backed by real multi-language benchmarks.** *(v0.1.0)*

`git_advisor` indexes Git history into a single local SQLite database without touching your working tree, builds a file/symbol dependency graph, and gives both developers and AI coding agents six concrete capabilities:

1. **Impact & Risk Forecasting (`advise`)** — Given a natural-language task, predicts which files will change, estimates a calibrated conformal blast-radius interval, and surfaces hub-guarded historical risk precedents in ~330 tokens.
2. **Structure Optimization (`optimize-structure`)** — Detects cross-file and within-file AST-body code clones (clustered to prevent clique noise, flagging stack-sensitive APIs like `warnings.warn`), decorator-aware dead functions, directional TF-IDF misplaced modules, and hard import cycles vs. lazy runtime back-edges.
3. **Targeted Test Selection (`select-tests`)** — Combines reverse static imports, historical test↔source co-change, path stems, and symbol tokens to pick minimal regression test files (~89% suite reduction).
4. **Isolated Sandbox Verification (`verify-refactor`)** — Exports the base commit via `git archive` into a clean temporary directory, applies proposed edits, runs targeted tests + live dependency graph extraction, and certifies `CERTIFIED_SAFE` or rejects (`REJECTED_TESTS_FAILED`, `REJECTED_NEW_CYCLE`, `REJECTED_SYNTAX_ERROR`, `REJECTED_EDIT_ERROR`).
5. **Bounded Agent Loop (`agent-loop`)** — Runs a `Propose → Verify → Refine` loop (deterministic or backed by local Ollama / pluggable LLM) that feeds test failure output back on rejection and emits edits **only** when `CERTIFIED_SAFE`.
6. **Zero-Dependency MCP Server (`mcp-serve`)** — Exposes all tools over stdio JSON-RPC 2.0 (with dynamic per-call `database` switching) to Antigravity, Claude Code, Cursor, or Codex.

---

## 60-Second Quickstart

Requires **Python 3.10+** and **Git** (`numpy` is required for `advise` / `optimize-structure`).

```bash
pip install -e ".[embeddings]"

# 1. Index the last 100 commits of any local or remote Git repository
git-advisor --db repo.sqlite index /path/to/your-repo --limit 100

# 2. Forecast affected files & regression risk before editing (~330-token LLM context)
git-advisor --db repo.sqlite advise "fix token refresh expiry on login" --llm-context

# 3. Audit structural clones, dead code, misplaced files, and import cycles
git-advisor --db repo.sqlite optimize-structure --llm-context

# 4. Select minimal regression tests for a planned edit
git-advisor --db repo.sqlite select-tests --file src/auth/session.py

# 5. Verify a candidate refactoring in a clean isolated checkout (never mutates your repo)
git-advisor --db repo.sqlite verify-refactor --candidate dead-1 --record
```

---

## Connect as an MCP Server

Add this once to your MCP client config (for example `~/.gemini/config/mcp_config.json` in Antigravity). No hardcoded `--db` is needed—agents can discover indexes with `git_advisor_list_indexes` and pass `"database"` on any call:

```json
{
  "mcpServers": {
    "git_advisor": {
      "command": "python",
      "args": ["-m", "git_advisor", "mcp-serve"]
    }
  }
}
```

Use `--read-only` to expose only the 4 read-only analysis tools (`git_advisor_list_indexes`, `git_advisor_advise`, `git_advisor_optimize_structure`, `git_advisor_select_tests`) and disable sandboxed test execution (`git_advisor_verify_refactor`, `git_advisor_agent_loop`).

---

## Real-World Examples & Benchmarks

All benchmarks below were evaluated **strictly causally** (at `parent_sha`, zero future leakage) across **200 live stdio MCP calls spanning 11 real repositories** (`pytest`, `flask`, `httpx`, `click`, `packaging`, `fastapi-template`, `pythonQEPest`, `fonline`, `linux-kunit`, `linux-leds`, and `git_advisor`).

### Concrete findings on `pytest` (40,331 LOC, 81 `src/` files, 97 test files)
- **Found a real upstream dead function:** `optimize-structure` flagged `src/_pytest/fixtures.py::is_visibility_more_specific` (23 lines, orphaned in commit `a84e5039c`) with **0 false positives** across 277 zero-static-caller functions (correctly sparing `@fixture(name="LineMatcher")` via decorator-alias parsing). Zero-config `verify-refactor --candidate dead-1` auto-selected 2 of 97 test files (`97.9%` suite reduction), ran **309 passing tests**, and issued **`CERTIFIED_SAFE`** (`-25 LOC`, `0` new cycles).
- **Verified real clone consolidations:** Caught `Dir.collect` ↔ `Package.collect` (`-13 LOC`, **198 passed**) and `_load_pytest_ini` ↔ `_load_ini_file` (`-6 LOC`, **25 passed**), with **0% false positives** across all 8 emitted clone clusters.
- **Caught a static-invisible behavioral trap:** `pytest`'s #1 cross-file AST clone (`collect_thread_exception` ↔ `collect_unraisable`, 35 identical lines) passed static analysis, yet `verify-refactor` rejected naive extraction (`REJECTED_TESTS_FAILED`) because `pytest` tests assert the exact `warnings.warn(...)` source line and `-Werror` traceback depth. `optimize-structure` now flags stack-sensitive APIs automatically.

### 200-Example Live MCP Benchmark Summary

| MCP Tool | Cases (`n`) | Pass Rate | p50 Latency | Measured Quality |
|---|---:|---:|---:|---|
| `git_advisor_list_indexes` | 10 | 100.0% | `32 ms` | Multi-directory discovery & error guards |
| `git_advisor_advise` | 65 *(8 repos)* | 100.0% | `1.14 s` | **80.0% Hit@5**, **66.4% Mean Recall@5**, **84.9% token reduction** (`330` vs `2,151` tokens) |
| `git_advisor_select_tests` | 60 *(6 repos)* | 100.0% | `366 ms` | **91.7% Hit@5**, **76.6% Mean Recall@5**, **89.1% suite reduction** |
| `git_advisor_optimize_structure` | 25 *(11 repos)* | 100.0% | `1.55 s` | Mean **525 tokens/plan**, `0` false hard import cycles across all 11 repos |
| `git_advisor_verify_refactor` | 20 *(4 repos)* | 95.0%* | `2.38 s` | All 5 verdicts certified (`CERTIFIED_SAFE`, `REJECTED_TESTS_FAILED`, `REJECTED_NEW_CYCLE`, `REJECTED_SYNTAX_ERROR`, `REJECTED_EDIT_ERROR`) |
| `git_advisor_agent_loop` | 10 *(6 repos)* | 100.0% | `1.13 s` | **0 uncertified patches leaked** across all runs |
| Protocol / `--read-only` | 10 | 100.0% | `0.8 ms` | JSONL + `Content-Length` framing, `-32601`, read-only isolation |

*\*The single miss in the 200-case run (`ver-05`) was a mutation test (`estimate_tokens -> 0`) that exposed a missing assertion in `tests/test_advise.py`, now fixed.*

### Cross-Repository Zero-Shot Transfer Benchmark (7 Unseen Non-Python Repos, `n = 1,387`)

To verify generalization beyond Python, a single `HybridImpactRanker` was trained **strictly on 6 Python repos** (`pytest`, `flask`, `httpx`, `click`, `packaging`, `fastapi` — 674 commits / 22,781 candidate rows) and evaluated **zero-shot and strictly causally** (only commits $< t$ and files existing before $t$) across **1,387 commits on 7 completely unseen non-Python repositories** (Java, Android Java/C++, JavaScript, TypeScript, C/C++, and Bash):

| Method | Training Data | Macro Hit@1 | Macro Hit@5 | Macro Hit@10 | Mean Recall@5 | MRR |
|---|---|---:|---:|---:|---:|---:|
| `cochange_only` | Target history only | 10.5% | 27.1% | 36.7% | 13.0% | 0.180 |
| `history_knn` | Target commit subjects only | 27.4% | 42.2% | 49.5% | 25.5% | 0.340 |
| `bm25_only` | Full causal file tree | 27.8% | 45.1% | 51.9% | 27.7% | 0.350 |
| **`zero_shot_py_transfer`** | **6 Python repos ONLY (frozen)** | **31.4%** | **51.1%** | **57.0%** | **31.2%** | **0.400** |
| **`online_in_repo`** | Target repo online causal refit | **32.9%** | **51.4%** | **57.4%** | **31.7%** | **0.410** |

| Unseen Target Repo | Language(s) | Tracked Files | Eval (`n`) | `BM25` Hit@5 | **`ZeroShot-PY` Hit@5** | `Online` Hit@5 | `LogCQR + ACI` 90% Cov. | `p50` Latency |
|---|---|---:|---:|---:|---:|---:|---:|---:|
| `DrKLO/Telegram` | Android Java / C++ | 10,386 | 187 | 52.9% | **69.0%** *(+16.1)* | 68.4% | **94.6%** | `1.5 ms` |
| `mrdoob/three.js` | JavaScript | 6,102 | 200 | 64.5% | **66.5%** *(+2.0)* | 66.0% | **93.5%** | `1.9 ms` |
| `dw-0/kiauh` | Bash / Shell | 488 | 200 | 56.0% | **66.0%** *(+10.0)* | 67.5% | **94.5%** | `1.8 ms` |
| `reactos/reactos` | C / C++ | 29,578 | 200 | 50.0% | **54.0%** *(+4.0)* | 53.0% | **96.5%** | `1.8 ms` |
| `eclipse-theia/theia` | TypeScript | 4,697 | 200 | 40.0% | **46.0%** *(+6.0)* | 46.0% | **97.0%** | `2.4 ms` |
| `microsoft/vscode` | TypeScript | 21,935 | 200 | 26.5% | **31.5%** *(+5.0)* | 32.0% | **97.0%** | `2.5 ms` |
| `openjdk/jdk` | Java / C++ | 72,315 | 200 | 25.5% | **24.5%** *(-1.0)* | 27.0% | **94.5%** | `3.2 ms` |

- **Zero-shot transfer beat `BM25` on 6 of 7 unseen repos** (`+6.0 pp` macro Hit@5) and captured **99.3% of full online in-repo retraining** (`51.1%` vs. `51.4%`) with zero target-repo tuning.
- **Conformal calibration (`LogCQRHurdle` + ACI)** maintained **93.5%–97.0%** empirical coverage across all 7 languages (90% target), and inverted-index BM25 kept query latency at **1.5–3.2 ms** even on 72k-file `openjdk/jdk`.
- **No pre-training required:** In normal use, `git-advisor advise` automatically fits the ranker and conformal calibrator on-the-fly from your repository's own Git history (zero weights or GPU needed).
- **Reproduce these benchmarks:** See [benchmarks/README.md](benchmarks/README.md) for self-contained scripts (`python benchmarks/mcp_benchmark.py` and `python benchmarks/cross_repo_transfer.py --eval-per-repo 200`).

---

## Honest Status & Limitations

- **What works best today:** Python repositories with $\ge 20$ commits and an automated `pytest` or `unittest` suite (for full AST refactoring & live verification), plus any Git repository in any language for causal impact ranking, co-change, and calibrated blast-radius intervals.
- **Why hybrid symbolic + statistical instead of a deep neural JEPA (yet):** Earlier offline experiments in this repo tested a learned temporal JEPA encoder (EMA + VICReg) and found deterministic AST/graph extractors, inverted-index BM25 + co-change, regularized logistic/GBDT rankers, log-space conformal calibration (`LogCQRHurdle` + ACI), and isolated sandbox execution consistently outperformed it on low-data repo histories with zero GPU overhead.
- **Ultra-large monorepos with terse issue-ID titles:** On 22k–72k file monorepos (`microsoft/vscode` at `31.5%` Hit@5, `openjdk/jdk` at `24.5%` Hit@5) where commit titles often say only `"Fix #241912"` or `"8341234: Fix C2 crash"`, title-only grounding hits a ceiling without issue bodies or learned symbol-level embeddings.
- **Multi-language AST depth:** Python has full AST-body cloning, decorator-aware dead-code detection, and dependency extraction. TypeScript (`npm ci`) and C/C++ (`pip install -e ".[native]"`) support semantic graph extraction, while `optimize-structure` falls back to `graph_only` mode on non-Python repos.
- **Cold-start latency:** Running `git-advisor --db repo.sqlite mine-outcomes --cache` once pre-caches SZZ history and speeds up repeated `advise` calls on large repos.

---

## Interactive Graph Viewer, Prospective Benchmarks & Advanced CLI

`git_advisor` also ships a local localhost web viewer (`git-advisor --db repo.sqlite view`) with an interactive architecture graph, 3D commit embedding trajectory, reuse planner, side-by-side plan comparison, and prospective forecast capture/scoring:

```bash
# Open the interactive graph viewer (or --forecast-only for read-only agent API)
git-advisor --db repo.sqlite view

# Pre-cache causal SZZ outcomes (reverts, Fixes: trailers, symbol-overlap follow-ups)
git-advisor --db repo.sqlite mine-outcomes --cache

# Run a chronological risk benchmark on mature commits
git-advisor --db repo.sqlite benchmark-outcomes

# Run a bounded Propose -> Verify -> Refine loop with a local Ollama model
git-advisor --db repo.sqlite agent-loop --candidate dedup-1 --ollama-model qwen2.5-coder:7b --record

# Run the full unit test suite (98 tests, zero external services required)
python -m unittest discover -s tests -v
```

For deeper documentation on the architecture graph, embeddings, prospective protocol, and local LLM plan review, see [docs/08-review-report/release.md](docs/08-review-report/release.md) and [docs/software-world-model.md](docs/software-world-model.md).

---

## License

[MIT](LICENSE)