# High-Level Design (HLD)

> Companion diagram: [`diagrams/01_architecture.svg`](../../diagrams/01_architecture.svg).
> Interactive version: [`architecture.html`](../../architecture.html) — click any module box
> in §7 there for a full paragraph per module: what actually happens, exactly how (or
> whether) a model is called, and which parts are deterministic vs. AI-driven.

Open Code Review (OCR) is a **command-line application**. You run one command (`ocr`) with
a subcommand (`review`, `scan`, `delegate`, ...) and it looks at your local git repository.
Internally, think of it as an editorial desk: an **intake clerk** (the CLI) decides which
files are even in scope and what the house style is for each one, a **desk editor**
(review/scan agent) hands one file at a time to a **staff writer** (the LLM tool-use loop),
who can call out to a **research assistant** (the tool registry — read a file, search the
codebase) before filing a comment, and every comment that comes back is fact-checked
against the real diff before it's accepted. In delegation mode, the desk editor instead
hands the assignment straight to a writer you already employ elsewhere (your own coding
agent) and never talks to a model itself.

```mermaid
flowchart TB
  IN["Inputs<br/>git repo · config.json · rule.json"] --> CLI["CLI (cmd/opencodereview)"]
  CLI --> DIFF["internal/diff<br/>git diff / hunk parse / relocation"]
  CLI --> RULES["internal/config<br/>rules · allowlist · templates"]
  DIFF --> AGENT["internal/agent (review)<br/>internal/scan (full-file)"]
  RULES --> AGENT
  CLI --> DELEGATE["internal/delegate<br/>no LLM call"]
  AGENT --> LOOP["internal/llmloop.Runner<br/>shared tool-use loop"]
  LOOP <--> TOOLS["internal/tool + internal/mcp<br/>file_read · search · code_comment"]
  LOOP <--> LLM["internal/llm<br/>protocol resolve · retry"]
  LLM <--> PROVIDER(["LLM Provider API"])
  LOOP --> SESSION["internal/session<br/>history · manifest · resume"]
  SESSION --> OUT["Comments · SARIF · session JSONL"]
  SESSION --> VIEWER["internal/viewer<br/>local web browser"]
  DELEGATE -. "via user's own agent" .-> OUT
```

## 1. Components and responsibilities

| # | Component | Package | Responsibility |
|---|---|---|---|
| 1 | **CLI** | `cmd/opencodereview` | Cobra command tree (`review, scan, delegate, session, config, llm, rules, viewer, completion`); resolves the LLM endpoint, loads config/rules, builds and dispatches to the right agent. |
| 2 | **Diff engine** | `internal/diff` | Git diff retrieval (workspace/range/commit), unified-diff parsing, `.gitignore` filtering, comment line-number resolution/relocation. |
| 3 | **Config & rules** | `internal/config/{rules,allowlist,template,toolsconfig}` | Path-based rule resolution, file-type allowlist, prompt templates (`task_template.json`, `scan_template.json`), tool enable/disable config. |
| 4 | **Review agent** | `internal/agent` | Orchestrates `ocr review`: load diffs → filter → dispatch per file → finalize the coverage manifest. |
| 5 | **Scan agent** | `internal/scan` | Orchestrates `ocr scan`: enumerate whole files → same dispatch pattern → optional dedup + project-summary passes. |
| 6 | **Delegate** | `internal/delegate` | Deterministic file selection + rule-group export for `ocr delegate` — makes no LLM call. |
| 7 | **LLM loop** | `internal/llmloop` | The shared tool-use conversation loop (`Runner.RunPerFile`) both agent and scan dispatch into; memory compression; token accounting. |
| 8 | **Tools** | `internal/tool` | The fixed toolset: `file_read, file_find, file_read_diff, code_search, code_comment, task_done`, plus the registry that also holds MCP tools. |
| 9 | **MCP client** | `internal/mcp` | Adapts external MCP-server tools into the same tool registry the built-ins use. |
| 10 | **LLM transport** | `internal/llm` | Resolves provider/protocol/model (env → config → preset); speaks Anthropic / OpenAI Chat Completions / OpenAI Responses; retries with backoff. |
| 11 | **Session** | `internal/session` | Per-run JSONL history + the immutable coverage manifest that powers `--resume`. |
| 12 | **Viewer** | `internal/viewer` | Local-only web server rendering a session's history as browsable HTML. |
| 13 | **Telemetry** | `internal/telemetry` | Opt-in OpenTelemetry spans/metrics — never load-bearing for a review's result. |

## 2. Technology stack

- **Language / runtime:** Go ≥ 1.25 (module `github.com/alibaba/open-code-review`).
- **Diff/VCS:** shells out to the system `git` (≥ 2.41) — no embedded git library; every
  invocation uses a hardcoded subcommand list and `--end-of-options`, never a shell.
- **AI transports:** `github.com/anthropics/anthropic-sdk-go`, `github.com/openai/openai-go/v3`,
  plus a raw OpenAI-Responses-protocol client — selected by `internal/llm`'s protocol
  resolution, not hardcoded to one vendor.
- **Extensibility:** Model Context Protocol (`github.com/modelcontextprotocol/go-sdk`) for
  externally-provided tools.
- **CLI:** `spf13/cobra` + `spf13/pflag`.
- **TUI:** `charm.land/bubbletea` / `bubbles` / `lipgloss` (the interactive provider/model
  setup wizard, `cmd/opencodereview/provider_tui.go`).
- **Observability:** `go.opentelemetry.io/otel` (OTLP gRPC/HTTP exporters), opt-in.
- **Build:** `CGO_ENABLED=0` — static binaries, no C attack surface, distributed via npm
  (`@alibaba-group/open-code-review`), an install script, and GitHub Releases.

## 3. Run / distribution model

OCR ships as a single static binary, installable via `npm install -g
@alibaba-group/open-code-review`, an install script, or a GitHub Release download — plus
integrations that don't require installing the binary at all: a **GitHub Action**
(`action.yml`), CI examples for GitLab/Bitbucket/Gerrit/CodeUp/GitFlic
(`examples/`), a **VS Code extension** (`extensions/vscode/`), and coding-agent plugins for
**Claude Code, Codex, Cursor, OpenCode, and QCA Forward** (`plugins/open-code-review/`).

Configuration resolves in this order (per `internal/llm/resolver.go`): environment
variables (`OCR_LLM_PROTOCOL` etc.) → `config.json`'s `llm.protocol` (or the legacy
`use_anthropic` boolean) or a named built-in provider preset (`anthropic`, `openai`, or a
custom provider entry) → the endpoint's model/token. `rule.json` layers custom → project →
global → system rule text, first match wins per file.

## 4. Trust boundaries & security posture (design-level)

Summarized from the project's own `ASSURANCE_CASE.md` (source-verified):

- **Every external process call is `git`, hardcoded, no shell.** Command injection via a
  crafted diff is mitigated by never building a shell command string — `exec.Command` always
  gets an explicit `git` + fixed subcommand + `--end-of-options`.
- **API keys never touch disk or logs.** Read only from environment variables; never
  written to config files, output files, or telemetry.
- **Every LLM-suggested file path is validated against the repo root** (`pathutil.WithinBase`,
  both before and after symlink resolution) before any tool reads or writes it — mitigates
  path traversal from a model hallucinating or being tricked into requesting `../../etc/passwd`.
- **The local session viewer defends against DNS rebinding**, not just XSS: a Host-header
  allowlist rejects non-loopback origins by default, on top of `html/template` auto-escaping
  and a strict CSP.
- **TLS 1.2+ with full certificate verification always** — `InsecureSkipVerify` is never set
  anywhere in the codebase.

## 5. Quality mechanisms

- **Deterministic + AI hybrid at every layer**, not just at the edges: file selection, rule
  matching, comment line-number resolution, and coverage/manifest bookkeeping are all plain
  code wrapped around the one AI-driven step (the tool-use loop) — see `architecture.html`
  §7 for the exact deterministic/AI split per package.
- **Optional review-filter pass** — a second LLM pass that can drop the model's own
  low-value comments before they're reported.
- **Bounded concurrency + per-run token budget** — `--max-tokens-budget` stops dispatching
  new files (not cancelling in-flight ones) once the projected total would exceed the cap,
  so an overrun is bounded by the concurrency limit (default 8), never a whole extra batch.
- **Resumability** — `--resume` matches a prior run's completed items by a content
  fingerprint (SHA-256 of mode + paths + diff text), so a moved/renamed ref or changed diff
  content correctly forces a re-review instead of silently reusing stale results.
- **90% test coverage enforced in CI** (`make coverage`, per `AGENTS.md`), plus `go vet`,
  `govulncheck`, and the Go race detector on every push/PR.

## 6. The shared execution engine — `internal/llmloop.Runner`

Both `ocr review` and `ocr scan` dispatch into the **same** per-file tool-use loop
(`internal/llmloop.Runner.RunPerFile`) rather than each having its own copy — this is the
one piece of machinery every review, of either mode, actually runs through.

In plain terms: think of the Runner as a single conversation moderator that both the
"diff review" desk and the "full-file scan" desk share. It doesn't know or care which desk
called it; it just runs the same loop — send the conversation, execute whatever tools come
back, track how big the conversation is getting, stop when the model says it's done or the
budget runs out — and reports back what happened.

- **Model/vendor selection** happens entirely in the caller (`agent.Args.Model` /
  `scan.Args.Model`, set once by the CLI from `internal/llm.ResolveEndpointWithOptions`) and
  is passed into `llmloop.Deps.Model` — the Runner itself makes no routing decision.
- **Permission story:** the Runner does not distinguish tool permissions by caller — every
  file review, whether from `agent` or `scan`, gets the same fixed toolset
  (`MainToolDefs`, built once at CLI startup from the enabled built-in tools plus any
  registered MCP tools). There is no read-only-vs-write-capable split the way a
  propose-a-fix agent would need, because OCR's tools are inherently read-only except for
  the one designed side effect, `code_comment` (append a finding), which never edits the
  file under review.
- **Loop/turn budget:** `Template.MaxToolRequestTimes` rounds, after which a final **grace
  round** offers the model only `code_comment` and `task_done` — a last chance to report
  findings it already has, not to keep investigating.
- **Context-size guardrail:** three-zone token compression at 60%/80% of `Template.MaxTokens`
  (`internal/llmloop/compression.go`) — synchronous once the hard threshold is hit,
  background otherwise — is what keeps a long tool-call conversation from silently
  exceeding the model's context window.

See [data-flow](data-flow.md) for the artifact-by-artifact flow through this loop, and
`architecture.html` §7 (`llmloop` box) for the exact stop conditions.
