LLM-Powered Full-Repository Code Review: A Practical Guide

    This guide explains how to build an automated code review pipeline that uses repository-level context instead of reviewing diffs in isolation. It covers a four-stage architecture, context chunking and retrieval, structured prompt design, parameter tuning for deterministic output, model routing, security against prompt injection, evaluation, integration, and common pitfalls.

    1. Why Full-Repository Readability Is the Dividing Line for Automated Review

    Most teams stop at “diff-only” review: they feed the changed lines to a model and ask it to find problems. It is easy to implement, but it has a structural flaw. The model cannot see the actual implementation of the code being called, the interface contracts, or the configuration and dependency versions. As a result, its comments tend to be generic style remarks, or even false positives that conflict with project conventions.

    Valuable review requires repository-level context: who calls the changed function, which branches swallow exceptions, where a constant is defined repeatedly, and where a configuration default disagrees with the documentation. Giving the model this visibility is not about opening the context window as wide as possible. The core is a context supply mechanism.

    2. Overall Architecture: A Four-Stage Pipeline

    A practical design can be split into four decoupled stages that evolve independently:

    1. Change awareness: identify the review scope (changed files, affected modules, related tests).
    2. Context construction: split the repository into retrievable semantic units, index them, and recall on demand.
    3. Reasoning and generation: call the LLM for defect detection, risk assessment, and fix suggestions.
    4. Result governance: structured parsing, deduplication, severity grading, gating, and write-back to the review system.

    An illustrative configuration structure (neutral, expressing only generic parameter semantics):

    1. model:
    2. endpoint: ${MODEL_BASE_URL}
    3. api-key: ${MODEL_API_KEY}
    4. chat:
    5. model: general-purpose-chat
    6. temperature: 0.2 # Review requires determinism
    7. max-tokens: 8192 # Covers multi-file suggestions
    8. embedding:
    9. enabled: true # Disable if using a non-embedding model
    10. retrieval:
    11. chunk-size: 800
    12. chunk-overlap: 120
    13. top-k: 8

    3. Context Construction: Chunking, Indexing, and Recall

    Chunking should follow the structural boundaries of code rather than hard-cutting at a fixed character count. A workable strategy: use the file as the first-level unit, split by class, function, and configuration section as the second level, and attach metadata to each chunk (path, symbol name, language, last modified time, owning module). This metadata determines the precision of later recall.

    For recall, mix three signals. First, exact matching based on keywords and symbol names, which guarantees that “a function with the same name is always found.” Second, semantic recall based on vector similarity, which handles cases where the problem description and the code use different wording. Third, dependency-graph expansion, which brings in direct callers and interface definitions. After fusing the three sets of results, truncate by relevance. Usually 6–10 chunks are enough to cover what one review needs; going larger only dilutes attention and raises cost.

    For cost control, use tiered indexing: build fine-grained indexes for core modules that change frequently, and coarse-grained summaries for stable modules. For very large repositories, shard by module and perform deep recall only for the modules involved in this change.

    4. Prompt Design: Making Output Parseable and Actionable

    Free-text review comments cannot enter the pipeline and must be constrained to structured results. Ask the model to output strict JSON with fields for file, line range, severity, category, evidence reference, suggestion, and confidence. The prompt should state that “evidence must come from the given context” and require an empty list when evidence is insufficient rather than a guess.

    A compact system prompt skeleton:

    1. You are a code review assistant. Draw conclusions only from the provided code context.
    2. Output a JSON array with element fields:
    3. file, start_line, end_line, severity(blocker|critical|major|minor),
    4. category(correctness|security|concurrency|performance|maintainability),
    5. evidence(quoted code snippet), suggestion, confidence(0-1).
    6. Do not output issues that cannot be confirmed from the context.

    Also inject the project’s own conventions (naming rules, logging rules, exception handling conventions, prohibited patterns) as a “team rules” section. This often does more to reduce false positives than switching to a stronger model.

    5. Parameter Trade-offs: Determinism First

    Review is the opposite of creative work: it needs stable, reproducible output. Keep the temperature low (0.1–0.3) so the same code does not drift across multiple reviews. Generation length must cover cross-file suggestions while avoiding rambling; a limit of a few thousand tokens works well in practice. Top-p can stay at its default to reduce unnecessary randomness.

    If the model does not provide embedding capability, explicitly disable the embedding components in the configuration. Otherwise the service will abort during startup because initialization fails, one of the most common low-level failures during integration.

    6. Model Tiering and Routing: An Engineering Answer to Cost Efficiency

    You do not need the same model tier for every task. Build a two-tier route: use a fast, low-cost general-purpose chat model for routine incremental review, covering high-frequency issues such as style, null pointers, unreleased resources, and missing logs. When cross-module interface changes, concurrency model changes, or security-sensitive paths appear, escalate to a model with stronger reasoning for a second review. Routing signals can be the module labels of the changed files, risk keyword hits, and the confidence distribution of the first-tier output (a cluster of low confidence triggers escalation).

    The benefit is measurable: most requests stay in the low-cost tier, only a few high-risk changes pay the high cost, overall cost per review drops significantly, and recall in high-risk scenarios does not degrade.

    7. Security: Treat Repository Content as Untrusted Input

    Code comments, dependency manifests, and commit messages can all carry malicious instructions and form prompt injection. Key defenses: separate external content from instructions and clearly mark data boundaries; redact sensitive information from recalled content (keys, tokens, internal addresses); on the output side, forbid the model from emitting directly executable shell commands; validate links and dependency names in suggestions against a whitelist. In addition, the review pipeline should pull code with read-only credentials; the principle of least privilege cannot be skipped.

    8. Evaluation and Integration

    Evaluation must be independent of subjective impressions. Build a labeled defect set and track precision, recall, and false positive rate, while also measuring average review latency and cost per run. For rollout, start with “comment only, no blocking,” accumulate several weeks of data, and then enable gating for blocker-level issues, avoiding resistance caused by blocking delivery from day one.

    On the integration side, write results back as line-level comments in the review system, with evidence and a suggested patch; deduplicate repeated issues by fingerprint (file + symbol + category) to prevent flooding. If running on a container platform, split index construction and inference into separate jobs decoupled by a message queue, and use logging services and monitoring alerts to observe latency and failure rates, forming a sustainable operations loop.

    9. Common Pitfalls

    • Chunking only by character count, truncating functions so the model sees half the logic.
    • Recalling too many chunks, drowning key evidence in irrelevant code.
    • Not injecting team rules, producing many comments that conflict with project conventions.
    • Temperature too high, inconsistent conclusions across reviews of the same change, hard to enforce in gating.
    • Ignoring the embedding component switch, so the service fails at startup.
    • Forcing blocking merges from the start, causing the team to lose trust quickly.

    In summary, the key to repository-level automated review is not a “stronger model” but the coordination of context supply, output constraints, and tiered governance. Get these three solid, and automated review can move from a demo into the daily development workflow.