Discover MCPs & agents
Loading MCPs and agents…
Loading MCPs and agents…
Codebase RAG that embeds what each file does, not what it says. Postgres is the queue: jobs claimed by compare-and-swap under five-minute leases, resumable across serverless timeouts.
Jump to setup instructionsFetched from the repository for this visit.
Codebase RAG built as infrastructure: retrieval runs over what each file means, indexing is a durable Postgres lease queue, and model spend on chat, diff analysis and indexing is metered per project.
Most of the work in understanding a codebase isn't reading the file you have open - it's finding the three files you didn't know to open. Onboarding to an unfamiliar repo means reconstructing a mental model that lives nowhere: which module owns auth, where the rate limit is configured, what actually runs on a cron. Grep finds strings; it doesn't find concepts. Documentation, when it exists, drifts from the code the day after it's written.
"RAG over a codebase" is the obvious answer and the obvious trap. The demo is easy: chunk the files, embed the chunks, retrieve top-k, call an LLM. It falls apart on contact with real repos for reasons that have nothing to do with prompting. Raw code embeds lexically - variable names and syntax - so a query like "how does authentication work" retrieves whatever file happens to share tokens with the question, not the file that implements the concept. And ingesting a whole repository is a systems problem, not a model problem: it has to survive serverless time limits, partial failures, and the fact that an LLM call per file turns "index this repo" into an unbounded bill.
RepoDoc takes four opinionated positions, and they're the reason it behaves differently from a generic RAG wrapper.
Embed what a file means, not what it says. During indexing, each file is summarized by an LLM into a ≤100-word description of its purpose (getSummariseCode), and that summary is embedded - gemini-embedding-001 at 768 dimensions - not the raw source. Retrieval is then a cosine search over intent (1 - (embedding <=> query) against pgvector, top-5). The alternative - chunking source by lines or AST nodes - embeds the wrong signal and ranks by surface similarity. The cost of this choice is an extra LLM call per file at index time and a hard dependency on summary quality; the payoff is that "where are rate limits configured" retrieves the rate limiter even when the query shares no tokens with it.
The database is the queue. Indexing is not a request; it's a job. RepoDoc models it as an IndexingJob row in Postgres with a lease, not as a call to SQS or Redis or BullMQ. A worker claims a job with an atomic compare-and-swap, holds a five-minute lease, and releases it on completion or failure. One datastore, transactional with the data it indexes, no extra infrastructure to operate. The tradeoff is that work is pulled (cron + on-demand kicks) rather than pushed, and this isn't built for tens of thousands of jobs per minute - but at this scale, a queue service would be operational overhead with no payoff.
Cost is a runtime constraint on the query path. Chat (/api/query) and diff analysis (/api/analyze-diff, /api/repo-changes) write a QueryMetrics row for every request that gets past the guards, and indexing writes one per file plus one for each summary attempt that comes back empty, since those are billed too (model, prompt/completion tokens, latency, estimated USD, retrieval and memory counts, cold-start and cache flags, success/error). /api/architecture writes a zero-cost row because it makes no model call. Project.monthlyCostLimitUsd is an optional cap: once 30 days of recorded spend crosses it, chat and diff requests return 402 before any model call. Nothing in the app sets that column yet, so the cap applies only where it has been written to the database directly. Stated precisely, because the gaps matter: indexing spend is recorded, and counts toward the 30-day total, but indexing never checks the cap; README generation, docs generation, document edits and memory extraction are neither metered nor budget-checked. README generation uses the most expensive model in the product (gemini-2.5-pro) and the largest payloads, and these paths can run past a project's limit without being counted. Closing that is the next real piece of work on this pillar, not something the current code does.
Durable repo memory, separate from retrieval. RepoDoc extracts facts from each Q&A exchange into a RepoMemory store and pulls the top matches back as secondary context on later questions - capturing intent and decisions that live in conversations, not in any file. It's labeled distinctly from code in the prompt, under one rule: when memory and code conflict, the code wins.
One more thing, stated precisely because precision is the point: all generation goes through OpenRouter, with the model picked per route - gemini-2.5-flash for chat (temperature 0.3), diff analysis, docs, document edits and memory extraction; gemini-2.5-flash-lite for per-file summaries during indexing; gemini-2.5-pro for README generation. The README, docs and docs-edit defaults can be overridden with OPENROUTER_README_MODEL, OPENROUTER_DOCS_MODEL and OPENROUTER_DOCS_MODIFY_MODEL. Gemini's API is called directly only for embeddings. This keeps model selection a one-line change. To be exact about what isn't here: there is no automatic cross-provider failover. The codebase earns the word "fallback" only in the cost model, which defaults unpriced models to the Gemini Flash rate so a request is never silently billed at zero.
Connect Index (background) Query
─────── ────────────────── ─────
GitHub URL ──▶ IndexingJob (queued) POST /api/query
│ │ │
│ ▼ triggers: ▼ auth → rate-limit → ownership → budget
│ • on project create │
│ • on query vs unindexed project embeddings == 0 ?
│ • daily Vercel cron (0 6 * * *) ├── yes ─▶ pre-index: live-fetch ≤22
▼ │ │ high-value files from GitHub
worker claims ◀───┘ │ (answer now, kick worker)
job via lease (CAS) └── no ─▶ pgvector top-5 + RepoMemory top-3
│ │
▼ per file: summarize → embed → store ▼
GitHub tarball, pinned SHA OpenRouter (gemini-2.5-flash)
│ summary → gemini-embedding-001 (768d) grounded answer + cited sources
▼ │
Postgres + pgvector (HNSW, cosine) ◀──────────────────────────────┘
│ write QueryMetrics, cache, extract memory
▼
IndexingJob.progress / status (retry, cancel, resume in UI)
The connect step stores the repo and an (optionally encrypted) GitHub token and enqueues a job. The worker - invoked on demand and by a daily cron backstop - claims a job, streams the repository's GitHub tarball at the commit pinned when the job started, and for each new or changed file summarizes then embeds then writes a pgvector row. Querying guards the request, then either answers from the index or, if indexing hasn't produced embeddings yet, live-fetches a curated set of files from GitHub so the project is useful immediately.
These are the parts that took real engineering, each tied to where it lives:
claimJob (indexing-worker-run.ts) is a conditional updateMany - it flips queued/stale-processing → processing and trusts the claim only when res.count === 1. Two workers that wake on the same job can't both win; it's a compare-and-swap on the row, no advisory locks.WORKER_BUDGET_MS), and when it runs out it writes a resumeAfter cursor, requeues the job, and re-kicks - so indexing makes forward progress across many short runs instead of dying at the platform timeout.processing with lockedAt older than that is reclaimable; @@index([status, lockedAt]) makes finding it cheap. A crashed worker's job is picked up by the next one and resumed from its cursor.queryCodebasePreindex fetches up to 22 high-value files (READMEs, configs, entrypoints) straight from the GitHub tree and answers from those, flagging the response preindex: true, while kicking the indexer in the background.isProjectOverBudget sums 30 days of QueryMetrics and, when a cap is set, short-circuits the chat and diff routes to 402 before any tokens are spent. The architecture route makes no model call and doesn't check the cap. The indexer's own needsResume is a time box (WORKER_BUDGET_MS, 45s), not a cost one - it exists to survive the serverless wall, and does not consult the budget.402 before chat and diff model calls), not mid-index. Why: AI cost is unbounded by default; a ceiling has to be live to matter. Tradeoff accepted: indexing records its spend but never checks the cap, so a large index can run past it. Jobs are resumable because of the serverless time box, not the budget.resumeAfter cursor. No stuck jobs, no re-embedding from scratch.preindex: true, so the user isn't blocked.402 with a clear message before calling a model. Indexing is unaffected - it records its spend but never checks the limit, so a large index can still run while the query path is closed.400, 401, 402 or 404 from OpenRouter is not retried, since it would fail identically. A file that still fails is counted as failed: a pass with failed files is requeued with backoff (1m, 5m, 15m, then 1h), and after the fifth attempt the job completes with a note recording how many files were skipped. A pass that throws is retried on the same schedule and marked failed after the fifth attempt, with the error string surfaced in the UI for retry; a private repo without the project's own token is marked failed at once, since retrying can't help.src/proxy.ts, Next 16's name for middleware) guards pages and API routes except an explicit public allow-list, and each API route re-checks the session and returns 401. Server actions pass through the proxy and check the session themselves; the two share-link readers (getPublicReadme, getPublicDocs) are public by design and look documents up by share token. Every request-path project lookup is scoped by owner and deletedAt: null. Three lookups omit the filter and are safe for a stated reason rather than by accident: two run server-side on a projectId already validated upstream (baseline-mirror.ts, the indexer), and the third resolves names for IDs that came out of an already owner-scoped set (analytics)./api/analytics has a privileged mode: an allow-list of admin emails (getAdminEmails()) switches the query scope from one owner to platform-wide. It is email-gated, not a separate credential.SELECT 1. Every one is a tagged template, so Prisma parameterizes it; $queryRawUnsafe/$executeRawUnsafe appear nowhere in the codebase.enc:v1:<base64(iv|tag|ciphertext)> (secret-crypto.ts), keyed by ENCRYPTION_KEY. Honest caveat: if ENCRYPTION_KEY is unset, the code falls back to storing plaintext so the app keeps working - set the key in every environment to actually get encryption.timingSafeEqual) shared-secret check.x-real-ip over the spoofable x-forwarded-for, returning 429 with Retry-After; it fails open under store failure - a deliberate availability-over-strictness tradeoff.Not claimed because it isn't built: there is no documented data-retention or training-data policy in the codebase, and no key rotation beyond the enc:v1: version prefix that makes it possible later.
Next.js 16.0.7 (App Router, React 19.2) · TypeScript 5 · Tailwind 4.1 · PostgreSQL + pgvector (HNSW, cosine) via Prisma 6.16 · Clerk 6.31 (auth) · OpenRouter for generation, Google gemini-embedding-001 for embeddings · Redux Toolkit · Zod 4 · Upstash Redis (rate limiting) · svix (webhooks) · Gumroad (billing) · Jest 29 · Vercel.
Vector search runs against an HNSW index on the embedding column with cosine distance (vector_cosine_ops) - an approximate-nearest-neighbour lookup, not an exact scan. The index SQL used to sit in a loose file outside any timestamped migration directory, so prisma migrate deploy never ran it; it now lives in 20260805000000_apply_orphaned_sql_and_vector_indexes and applies with the rest. No benchmark compares it against a sequential scan on real row counts, so no speedup figure is claimed here - only the mechanism.
QueryMetrics row and never consult monthlyCostLimitUsd; indexing writes rows but never consults the cap. Nothing in the app sets the cap either. The plumbing exists and the query path uses it; extending it to those paths is a known gap, called out here rather than left to be discovered.git clone https://github.com/parbhatkapila4/RepoDocs.git
cd RepoDocs
npm install
cp .env.example .env # then fill in the values below
npm run db:generate
npm run db:migrate
npm run dev # http://localhost:3000
Requires Node 20+ and a PostgreSQL instance with the pgvector extension.
CodebaseQueries has no Prisma model and is reached only through raw SQL. RepoMemory has a Prisma model, but its vector column is written and searched with raw SQL. Until 20260805000000_apply_orphaned_sql_and_vector_indexes, both tables were created only by loose files that migrate deploy skipped. That migration now creates both, so npm run db:migrate is sufficient on a clean database.
Environment variables actually read by the code:
DATABASE_URL= # Postgres (pooled)
DIRECT_URL= # Postgres (direct, for migrations)
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=
CLERK_SECRET_KEY=
CLERK_WEBHOOK_SECRET=
GEMINI_API_KEY= # embeddings
OPENROUTER_API_KEY= # all generation
ENCRYPTION_KEY= # 32-byte key; without it, stored tokens are NOT encrypted
CRON_SECRET= # authorizes the indexing-worker cron route
GITHUB_TOKEN= # optional; raises rate limits. Used only for public repos; private repos need the project's own token
UPSTASH_REDIS_REST_URL= # optional; distributed rate limiting/locking
UPSTASH_REDIS_REST_TOKEN=
RESEND_API_KEY= # contact form; without it /api/contact returns 503, never a false success
CONTACT_TO_EMAIL= # optional; defaults to parbhat@parbhat.work
CONTACT_FROM_EMAIL= # optional; defaults to onboarding@resend.dev - see caveat below
NEXT_PUBLIC_APP_URL=http://localhost:3000
One caveat on the contact form, because "it posts successfully" and "the mail arrived" are different claims: CONTACT_FROM_EMAIL defaults to onboarding@resend.dev, Resend's shared sender, which requires no domain verification but only delivers to the address registered on the Resend account. Mail reaches an arbitrary CONTACT_TO_EMAIL only once a domain is verified in Resend and CONTACT_FROM_EMAIL points at an address on it. A rejected send is surfaced - the route logs it and returns 502/503, and the form shows the error plus the direct email address, never a success toast. What is not covered: Resend accepting a message and bouncing it later is asynchronous, and with no delivery webhook wired up that failure is invisible to the sender.
195 tests across 30 suites (npm run test:ci), fully mocked - route guards on /api/query (401/400/402/403/404/200 and the pre-index path), the API guard and budget helpers, the private-repo token guard, RAG retrieval, answer generation and file-mention lookup, the GitHub tarball loader, the indexing worker's queue transitions and lease fencing, changed-file re-indexing, per-file summaries and their retry rules, project deletion cancelling its indexing job, the architecture graph's import resolver, smaller helpers (chat threads, docs sections, plan names, formatting), and a claim-drift guard that fails the build if an unbacked performance or capability claim reappears on a public surface. They cover behavior and error handling at the function and route-handler level; there is no live-DB integration or end-to-end coverage yet (see "not built yet").
Stated plainly rather than left to be discovered: that's ~17.7% line coverage against a 50% threshold configured in jest.config.js, so npm run test:coverage fails on the threshold while npm run test:ci passes. The tests that exist are the ones guarding the query path, the indexing queue and the public claims; the number is low because the suite is deliberately narrow, not because the threshold is aspirational.
Built by Parbhat Kapila - a full-stack engineer focused on production AI systems. More work at parbhat.dev.
GitHub checked 232h ago - refresh overdue. Recently viewed repositories target hourly refresh.
Find a documented setup for your client. No sign-in, installation, or tool execution.
If this MCP is also published on mcpchannel.ai, you can subscribe from Browse and use the gateway config there instead.