LLM-Powered Whole-Repository Code Review: Architecture and Practices

    This article explains how to build a practical LLM-based code review system that reasons over an entire repository instead of isolated diffs. It covers a four-layer architecture, context construction through static analysis and layered retrieval, conservative model parameters, prompt design with structured JSON output, CI/CD integration, cost optimization, and common pitfalls to avoid.

    1. Why Whole-Repository Understanding Is the Real Barrier

    The pain point in daily code review is not reading a single file. It is that a change often has far-reaching effects. A seemingly local modification can break implicit contracts with callers, bypass unified exception handling, or introduce logic that conflicts with an existing caching strategy. Traditional static analysis tools are good at defects with clear rules, such as null pointers, unreleased resources, and concurrency out-of-bounds access. But they are nearly powerless against semantic questions like “does this follow the repository’s established design conventions?”

    After large language models entered the development workflow, most teams first tried pasting diffs into a chat window. This approach quickly exposes three bottlenecks: a limited context window, missing cross-file dependencies, and results that cannot be accumulated as traceable engineering assets. So the solution that actually works is not “a stronger model.” It is turning the repository into context the model can read.

    2. Overall Architecture: Four Layers

    A usable whole-repository review system can be split into four layers:

    1. Collection layer: pull the change set (diff), the full content of changed files, and the files they depend on from the code hosting platform.
    2. Context layer: build a repository knowledge index covering directory structure, module boundaries, dependency relationships, and historical review comments.
    3. Inference layer: call an LLM service with code understanding capability, reviewing in tiers from file level to module level to repository level.
    4. Delivery layer: output conclusions in a structured form, write them back as review comments, and plug into the CI pipeline as a gate.

    The key design principle is layering, not feeding everything in at once. Stuffing the whole repository into the context is both expensive and inefficient. The model’s attention gets diluted, which actually lowers recall.

    3. Context Construction: Letting the Model “See” Dependencies

    3.1 Start with Static Structural Analysis

    Before calling the model, use deterministic tools to do structured parsing first: parse the abstract syntax tree to extract functions, classes, and exported symbols; build the call graph and module dependency graph; and mark configuration entry points, shared utility packages, and the data access layer. This structured information is injected into the prompt as condensed text. It costs fewer tokens than raw code and is more accurate.

    3.2 Retrieval-Augmented Layered Recall

    For changed files, recall related context using three strategies:

    • Direct dependencies: callees, inherited base classes, and referenced constants and type definitions.
    • Reverse dependencies: upstream locations that call the function, used to judge compatibility impact.
    • Semantic similarity: vector retrieval to find existing code that implements similar functionality, serving as a reference for “how this repository usually does it.”

    Vector capability can be implemented through a general-purpose vector retrieval service on a cloud platform or a self-hosted vector store. If the model service you use does not provide an embedding endpoint, simply disable embedding-related capabilities in the configuration to avoid initialization failures at startup.

    3.3 Context Budget Control

    Set a hard budget. For example, cap a single file at a few thousand tokens and the total context at 70% of the model limit, leaving room for output. When over budget, trim by ranking on “proximity to changed lines + dependency weight” rather than simple truncation.

    4. Model Parameters and Invocation Strategy

    The objective function for review differs from that for creative work. Review demands determinism, reproducibility, and little divergence. So parameter choices should lean conservative.

    1. model-service:
    2. base-url: "https://your-endpoint.example"
    3. api-key: "${CODE_REVIEW_API_KEY}"
    4. chat:
    5. options:
    6. model: "code-review-flash"
    7. temperature: 0.2 # Review needs stable output; avoid divergence
    8. max-tokens: 8192 # Cover multi-file conclusions
    9. embedding:
    10. enabled: false # Disable when no embedding capability, to avoid init errors

    For model selection, prioritize a fast, low-cost lightweight tier for routine incremental review. Switch to a tier with stronger reasoning only for architecture-level assessment or cross-module refactoring impact analysis. This “dual-tier” strategy balances cost and quality and avoids paying a premium for high-frequency, low-difficulty tasks.

    5. Prompt Design: Encoding Review Standards in the System Prompt

    Model output quality depends heavily on how explicit the constraints are. The system prompt should contain four parts:

    • Role and goal: a senior reviewer that reports only reproducible issues.
    • Review dimension checklist: correctness, boundary conditions, concurrency safety, exception and resource management, security (input validation, permissions, hardcoded sensitive information), performance (complexity, N+1 access), maintainability, and consistency with the repository’s existing conventions.
    • Decision rules: must provide file and line number, trigger condition, impact scope, and fix suggestion; mark as “needs human confirmation” when uncertain; speculation is forbidden.
    • Output format: strict structured data that is easy for programs to parse.
    1. {
    2. "findings": [
    3. {
    4. "file": "src/service/order.ts",
    5. "line": 88,
    6. "severity": "high",
    7. "category": "correctness",
    8. "trigger": "When the upstream returns an empty list",
    9. "impact": "Null pointer causes the API to return 500",
    10. "suggestion": "Add an empty-collection short-circuit and add unit tests",
    11. "confidence": 0.86
    12. }
    13. ],
    14. "summary": "This change contains 1 high-severity correctness issue"
    15. }

    Structured output is the dividing line for whether the whole approach can be automated. Only when results are parseable can you deduplicate, aggregate, track trends, and set gate thresholds.

    6. Integration with the Development Pipeline

    Triggering at the merge request stage is recommended. The flow is: pull changes → build context → layered review → aggregate results → write back review comments → gate decision. For the gate, use a policy of “zero tolerance for high-severity issues, informational only for medium and low severity” so noise does not drown out real risk.

    Also build a feedback loop: developers mark each comment as “valid” or “false positive,” and false positive rates are tracked periodically and fed back into prompts and rules. Intelligent review without a closed loop gets switched off by the team within weeks.

    7. Cost and Performance Optimization

    • Incremental first: review only changes and their dependencies, not a full scan. Run full scans at low frequency overnight.
    • Cache reuse: cache review conclusions keyed by file content hash; unchanged files hit directly.
    • Batching and concurrency: call file-level reviews concurrently, aggregate module-level results serially, balancing throughput and consistency.
    • Observability: record token consumption, latency, and cache hit ratio for each call, connect to monitoring, alerting, and logging services, and build a cost dashboard.

    8. Common Pitfalls

    1. Insufficient context leads to “hallucinated” conclusions, showing up as references to nonexistent functions. Intercept them with structured validation.
    2. Overly loose prompts make the model output vague style suggestions. Enforce constraints with the dimension checklist and severity levels.
    3. Ignoring repository conventions and flagging patterns the team intentionally keeps as defects. Inject a coding standard summary into the system prompt.
    4. Lacking a human review step and merging automatically. Intelligent review should be positioned as a “copilot,” with the final decision kept with humans.

    9. Conclusion

    Making the model understand the whole repository is essentially context engineering: deterministic parsing as the foundation, layered retrieval to control the budget, conservative parameters for stability, structured output to support automation, and a feedback loop to maintain long-term effectiveness. Following this path, teams can gain continuous, traceable intelligent review capability at a controlled cost, and truly reserve review effort for judgments at the architecture and business semantics level.