Skip to content
aaminashihabPublic

About

Evidence-Based Repository Verification Platform that audits, tests, and verifies technical claims about codebases using FAISS hybrid vector search, Tree-sitter AST call-graphs, multi-agent LLM-as-Judge reasoning, and automated guardrails.

Topics

Resources

Code of conduct

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

RepoLens Logo

RepoLens

The AI that doesn't just read your code — it fact-checks it.

RepoLens is an Evidence-Based Code Verification Platform that answers the questions every engineering team is afraid to ask:

"Is our authentication actually secure?" "Does this pull request really fix the bug — or just hide it?" "Is SQL injection possible in our search endpoint?"

Instead of giving you an AI opinion, RepoLens finds the most relevant lines of code that support or contradict your claim — with citations, confidence scores, and built-in guardrails that refuse to answer when evidence is insufficient.


Live Demo Tests Python FastAPI CI



RepoLens Demo Video

Try It in 30 Seconds

1. Go to → https://repolens-x7b8.onrender.com/
2. Paste any public GitHub repo URL
3. Ask: "Does this codebase sanitize user input before database writes?"
4. Get a full evidence report (speed depends on repo size and LLM provider)

Or run it locally:

git clone https://github.com/aaminashihab/repoLens.git
cd repoLens
python -m venv .venv
# Windows (PowerShell / cmd)
.venv\Scripts\activate
# macOS / Linux
source .venv/bin/activate
pip install -r requirements.txt
# Add your API key to .env (see Configuration section)
uvicorn app.main:app --reload
# Open http://localhost:8000

What Can You Ask RepoLens?

You ask in plain English. RepoLens searches your codebase and answers with proof.

Your Question RepoLens Verdict
"Does this auth system prevent privilege escalation?" Likely True — app/api/dependencies.py:L45-52 confirms role-check middleware
"Is SQL injection possible on the search endpoint?" Uncertain — insufficient evidence in indexed files to confirm
"Does PR #42 fix Issue #101 without regressions?" Likely False — tests/test_auth.py contradicts the claimed fix

Evidence-grounded answers — and an explicit "Uncertain" verdict when evidence isn't strong enough to conclude.



4-Stage Verification Pipeline

POST /verify { index_id, claim }
│
├─ [Stage 1] Input Validation & Guardrails
│   Pydantic enforces: ≥10 chars · rejects chatbot patterns · requires domain keywords
│
├─ [Stage 2] Hybrid Retrieval Engine
│   ├─ FAISS L2 dense vector search (Top-K=5, threshold ≥ 0.15)
│   │   similarity = 1 / (1 + L2_distance)
│   └─ AST N-Hop Call-Graph Expansion (Tree-sitter for Python, Regex for JS/TS)
│       Exponential depth decay: hop-1=0.75 · hop-2=0.6375 · hop-3=0.5418
│
├─ [Stage 3] Hypothesis-Driven LLM-as-Judge
│   Deconstructs claim → atomic hypotheses → independent evaluation per hypothesis
│   Generates supporting + contradicting citations per hypothesis
│
└─ [Stage 4] Refusal Guardrail Validator
    Rule 1: evidence completeness < 70% → force UNCERTAIN, cap confidence at 49%
    Rule 2: LIKELY_TRUE with 0 citations → force UNCERTAIN
    Rule 3: strip phantom file paths from citations
    → Structured VerificationReport

Indexing Pipeline

POST /index-repository { repo_url }
│
├─ [CloneService]     URL regex allowlist (github.com only) · shallow clone (depth=1) · tmpdir auto-cleanup
│                     Token sanitized (allowlist chars, 512-byte cap) · GIT_TERMINAL_PROMPT=0
├─ [ChunkService]     Budget: 5,000 files · 512 KB/file · 50 MB total
│                     Python → Tree-sitter AST symbols + call graph edges
│                     All other langs → structured line-block fallback chunker
├─ [EmbeddingService] Semaphore lock · ThreadPoolExecutor(5) · batch_size=100
│                     Inter-batch delay: 0.5s (env: EMBEDDING_INTER_BATCH_DELAY)
│                     Exponential backoff (max 5 retries on 429, capped at 60s)
├─ [IndexService]     FAISS IndexFlatL2(1536) · persist to storage/indexes/{id}/
│                     index.faiss · metadata.json · graph.json
└─ [JobService]       Atomic state machine via tempfile.mkstemp + os.replace

Benchmark Results

RepoLens includes a built-in benchmark (RepoVerify-Bench) evaluated on 10 curated security claims against RepoLens's own codebase. These are fully reproducible — run them yourself with python scripts/run_benchmark.py.

Note: This benchmark uses a mock verification service with hand-crafted evidence reports to enable fast, deterministic, dependency-free evaluation. The numbers below reflect performance on this curated 10-claim suite — not a large-scale independent study with a live LLM.

Metric Score Notes
Precision 80.0% On the 10-claim curated suite
Recall 80.0% On the 10-claim curated suite
Hallucination Rate 0.0% No uncited LIKELY_TRUE verdicts in the suite
Citation Accuracy 100.0% All cited file paths matched actual repo files
Avg. Pipeline Latency ~0 ms Mock service only; excludes real LLM latency
Est. LLM Cost per Claim ~$0.0005 Using gpt-4o-mini; varies by provider

Hybrid Retrieval vs. Plain Vector Search

On the same 10-claim suite, adding AST call-graph expansion to vector search improved results:

Approach Precision Citation Accuracy
Vector Search Only 80.0% 100.0%
Hybrid (Vector + AST Call Graph) 80.0% 100.0%

The call-graph expansion traces caller/callee relationships, surfacing evidence that plain similarity search misses (e.g. memory_scan_service.py and verification_service.py were each only reachable via 2-hop traversal from their callers).


Security Hardening

Security is not an afterthought — it's in the architecture:

Attack Vector Defense
Timing side-channels hmac.compare_digest for constant-time key comparison
Zip bombs / DoS 50 MB total limit with early exit; 512 KB per-file cap
Path traversal .resolve().relative_to(repo_root) on every file operation
Symlink attacks os.walk prunes all symlinks during repository scanning
Log injection Structured logging via extra={} — no f-string user input
Credential leaks API keys auto-stripped from Git error tracebacks
Webhook spoofing HMAC-SHA256 verification on every POST /github/webhook
Cross-origin attacks CORS locked to localhost:8000, allow_credentials=False
Token URL-injection github_token allowlist-sanitized before splicing into clone URL
Oversized payloads 10 MB global body cap + 1 MB webhook cap (HTTP 413)
Prompt stuffing question ≤ 2 000 chars, chat turn ≤ 4 000 chars (Pydantic)
Clickjacking / XSS X-Frame-Options: DENY, Content-Security-Policy, X-Content-Type-Options on every response
Stale API-key bypass API key re-read from env on every request (not cached at import)
HTTPS downgrade Strict-Transport-Security: max-age=31536000 header

System Architecture

┌─────────────────────────────────────────────────────────────┐
│                       CLIENT LAYER                          │
│  Browser SPA (TypeScript)    GitHub Webhooks                │
│  • Claim verification UI     • PR / Issue events            │
│  • Index management          • HMAC-SHA256 verified         │
└──────────────────┬──────────────────────────────────────────┘
                   │  HTTP/REST
                   ▼
┌─────────────────────────────────────────────────────────────┐
│                  API GATEWAY (FastAPI)                      │
│  CORSMiddleware · SlowAPI rate limiter · X-API-Key auth     │
│  Lifespan: orphan-job recovery · TTL cleanup (asyncio)      │
└─────┬──────────────┬──────────────┬──────────────┬──────────┘
      │              │              │              │
      ▼              ▼              ▼              ▼
 ┌─────────┐  ┌──────────────┐  ┌──────────┐  ┌──────────┐
 │INDEXING │  │VERIFICATION  │  │ MEMORY   │  │  ASK /   │
 │PIPELINE │  │  PIPELINE    │  │  SCAN    │  │  STREAM  │
 └─────────┘  └──────────────┘  └──────────┘  └──────────┘
      │              │              │              │
      └──────────────┴──────────────┴──────────────┘
                            │
               ┌────────────▼────────────┐
               │    STORAGE (disk)       │
               │  storage/indexes/       │  ← FAISS + JSON
               │  storage/jobs/          │  ← Job state machine
               └─────────────────────────┘
                            │
               ┌────────────▼────────────┐
               │  EXTERNAL LLM PROVIDERS │
               │  OpenAI │ Google Gemini │
               └─────────────────────────┘

API Reference

Method Endpoint Description
POST /verify Submit a claim for verification against an indexed repo
POST /index-repository Index a GitHub repository (public or private)
GET /index-repository/{id} Poll background indexing job status
DELETE /index-repository/{id} Remove a repository index
GET /indexes List all indexed repositories
POST /ask/stream Stream grounded Q&A via Server-Sent Events
POST /github/webhook Automated verification on PR / Issue events
GET /health Server health check (used by Render deploy probes)
GET /ping Ultra-lightweight keep-alive probe (no auth, no I/O)

Verification Request & Response

curl -X POST http://localhost:8000/verify \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{
        "index_id": "your-index-id",
        "claim": "Does this authentication implementation prevent privilege escalation?"
      }'
// Illustrative example — actual output varies by repository and claim
{
  "claim": "Does this authentication implementation prevent privilege escalation?",
  "verification_status": "Likely True",
  "confidence_score": 78.5,
  "atomic_hypotheses": [
    {
      "hypothesis_id": "H1",
      "statement": "Middleware checks user role against required authorization before execution",
      "status": "VERIFIED"
    }
  ],
  "supporting_evidence": [
    {
      "file_path": "app/api/dependencies.py",
      "line_range": "L45-L52",
      "symbol_name": "require_role",
      "snippet": "async def require_role(required: str, user: UserContext = Depends(get_current_user)) -> None:",
      "relevance": "Checks authenticated user's role against the required authorization level and raises 403 on mismatch."
    }
  ],
  "potential_risks": [],
  "missing_information": [],
  "recommended_tests": []
}

Automated GitHub Webhook (PR Opened)

// Illustrative example
{
  "status": "verification_completed",
  "pr_number": "99",
  "index_id": "idx-456",
  "verification_status": "Likely False",
  "confidence_score": 71.0,
  "supporting_evidence_count": 1
}

Configuration

Create a .env file in the project root:

# ── LLM Provider ─────────────────────────────────────────
LLM_PROVIDER=openai                     # "openai" or "gemini"
OPENAI_API_KEY=sk-...
# OPENAI_CHAT_MODEL=gpt-4o-mini         # optional override
# OPENAI_EMBEDDING_MODEL=text-embedding-3-small

# Or switch to Gemini (cheaper, faster)
# LLM_PROVIDER=gemini
# GEMINI_API_KEY=...
# GEMINI_CHAT_MODEL=gemini-2.5-flash

# ── Security ──────────────────────────────────────────────
API_KEY=                                # X-API-Key for gated endpoints
GITHUB_WEBHOOK_SECRET=                  # HMAC secret for GitHub webhooks
GITHUB_TOKEN=                           # PAT for private repos + faster clones

# ── Performance ───────────────────────────────────────────
CLONE_TIMEOUT_SECONDS=120               # max seconds to wait for git clone
EMBEDDING_INTER_BATCH_DELAY=0.5        # seconds between embedding batches
MAX_REQUEST_BODY_BYTES=10485760         # 10 MB body cap (HTTP 413 above limit)

# ── Rate Limits ───────────────────────────────────────────
VERIFY_RATE_LIMIT=30/minute
INDEX_RATE_LIMIT=10/hour
GITHUB_RATE_LIMIT=30/minute

# ── Index Lifecycle ───────────────────────────────────────
INDEX_TTL_HOURS=168                     # auto-expire indexes after 7 days (0 = off)
INDEX_CLEANUP_INTERVAL_MINUTES=60       # background sweep frequency

Deploying on Render

RepoLens ships with a render.yaml Blueprint for one-click deployment:

  1. Fork or clone this repository.
  2. In the Render dashboard, click New → Blueprint and connect your repo.
  3. Set the required secret environment variables (OPENAI_API_KEY / GEMINI_API_KEY, API_KEY, GITHUB_TOKEN).
  4. Click Apply — Render reads render.yaml and creates the service automatically.

Cold Starts (Free Tier)

Render's free tier spins down services after ~15 minutes of inactivity, causing the first request after idle to take 30–60 seconds while the container restarts.

Fix — add a free uptime monitor:

Service URL Interval
UptimeRobot (free) https://repolens-x7b8.onrender.com/ping 14 minutes
cron-job.org (free) https://repolens-x7b8.onrender.com/ping every 14 min

The /ping endpoint is intentionally tiny (no auth, no filesystem I/O, no logging) — it exists purely for keep-alive probes.

Tip: Upgrade to Render's Starter plan ($7/mo) to keep the service always-on with zero configuration.


Testing & Quality Assurance

# Windows (PowerShell)
$env:PYTHONPATH="."; .venv\Scripts\pytest
# macOS / Linux
export PYTHONPATH=. && .venv/bin/pytest
======================= 102 passed, 1 warning in 9.91s =======================

The test suite covers:

  • Webhook HMAC signature verification & rate limiting
  • AST call graph construction & N-hop traversal
  • Guardrail refusal logic & semantic evidence completeness validation
  • API key constant-time comparison & route authentication
  • Benchmark precision, recall & citation accuracy

Reproduce Benchmark Results

python scripts/run_benchmark.py
==============================================================================
      RepoLens Verification Benchmark (RepoVerify-Bench v1.0)
==============================================================================

+-----------------------------------------+-----------------------------------+
| Metric                                  | Value                             |
+-----------------------------------------+-----------------------------------+
| Total Test Cases                        | 10                                |
| Precision                               | 80.0%                             |
| Recall                                  | 80.0%                             |
| Hallucination Rate (Uncited Claims)     | 0.0%                              |
| Citation Accuracy                       | 100.0%                            |
| Average Latency per Claim               | 0.0 ms                            |
| Est. Cost per Claim (USD)               | $0.000469                         |
+-----------------------------------------+-----------------------------------+

+------------------------------+----------------------+----------------------+
| Strategy                     | Precision            | Evidence Recall      |
+------------------------------+----------------------+----------------------+
| Hybrid (Vector + AST Graph)  | 80.0%                | 80.0%                |
| Vector-Only Baseline         | 80.0%                | 55.0%                |
+------------------------------+----------------------+----------------------+

Codebase Structure

app/
├── main.py                     ← FastAPI app, CORS, rate limiting, lifespan hooks
├── api/
│   ├── dependencies.py         ← DI factories, X-API-Key auth, SlowAPI limiter
│   ├── router.py               ← Mounts all sub-routers
│   └── routes/
│       ├── repositories.py     ← Index CRUD + background indexing job dispatch
│       ├── verify.py           ← POST /verify → VerificationService
│       ├── ask.py              ← POST /ask/stream → AskService (SSE)
│       ├── memory_scan.py      ← POST /memory-scan → MemoryScanService
│       └── github.py           ← POST /github/webhook → HMAC + VerificationService
├── core/
│   ├── graph.py                ← RepositoryGraph, CodeNode, GraphEdge
│   ├── guardrails.py           ← GuardrailValidator (3 anti-hallucination rules)
│   ├── evaluator.py            ← RepoVerify-Bench evaluation framework
│   ├── memory_heuristics.py    ← MemoryHeuristicEngine (7 static regex rules)
│   └── validation.py           ← validate_safe_id() path traversal guard
├── services/
│   ├── clone_service.py        ← GitHub URL sanitization + GitPython clone
│   ├── chunk_service.py        ← Tree-sitter AST (Python) + block fallback chunker
│   ├── embedding_service.py    ← OpenAI/Gemini, batching, exponential backoff
│   ├── index_service.py        ← FAISS L2 build/load, metadata JSON, graph JSON
│   ├── job_service.py          ← Background job state (atomic tempfile + os.replace)
│   ├── retrieval_service.py    ← FAISS vector search + N-hop graph expansion
│   ├── verification_service.py ← Hypothesis-driven LLM-as-Judge (single structured call)
│   ├── ask_service.py          ← Grounded Q&A + SSE streaming
│   └── memory_scan_service.py  ← Static heuristics + LLM judge for memory issues
└── models/
    ├── verification.py         ← VerificationReport, EvidenceItem, AtomicHypothesis
    ├── repository.py           ← RepositoryIndexRequest / Response
    ├── ask.py                  ← AskRequest / AskResponse
    └── memory_scan.py          ← MemoryScanReport, MemoryFinding, MemoryVerdict

static/
├── index.html                  ← SPA entry (semantic HTML5 + ARIA)
├── styles.css                  ← Design system (indigo palette, glassmorphism)
├── app.js                      ← Compiled TypeScript output
└── src/app.ts + types.ts       ← TypeScript source (0 tsc errors)

Tech Stack

Layer Technology Notes
API Framework FastAPI (Python 3.10) Async REST, structured logging, health endpoint
AST Parsing Tree-sitter + Regex Full Python AST; JS/TS/Go/Rust/Java/C++ fallback
Call Graph Custom RepositoryGraph N-hop traversal with exponential depth decay
Vector Search FAISS CPU IndexFlatL2 Persistent .faiss + .json storage per index
LLM Reasoning OpenAI GPT-4o-mini / Gemini 2.5 Flash Configurable via .env
Frontend TypeScript SPA 0 tsc errors, DOMPurify XSS defense
Testing pytest 99 passing tests
CI GitHub Actions Auto-runs on push & PR

Roadmap — v2

The core pipeline, security layer, and verification engine are fully implemented and tested. The following are infrastructure improvements for large-scale cloud deployment:

Feature Status Notes
Distributed vector storage Planned pgvector / Qdrant for multi-node clusters
Distributed task queue Planned Celery + Redis (replaces in-process BackgroundTasks)
Streaming /verify endpoint Planned SSE for real-time verification progress
OpenTelemetry + Prometheus Planned Metrics for embedding latency, token usage
GitHub App authentication Planned Fine-grained installation tokens (vs. PATs)

Contributing

Pull requests are welcome! Please read CONTRIBUTING.md before submitting.

This project follows the Contributor Covenant Code of Conduct.


License

MIT License — see LICENSE for full details.


Built with structured evidence, explicit uncertainty, and reproducible benchmarks.

Try the Live Demo · Star on GitHub · Report a Bug

About

Evidence-Based Repository Verification Platform that audits, tests, and verifies technical claims about codebases using FAISS hybrid vector search, Tree-sitter AST call-graphs, multi-agent LLM-as-Judge reasoning, and automated guardrails.

Topics

Resources

Code of conduct

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages