1 · What OCR Is
Open Code Review (OCR, CLI command ocr) is an AI-powered code
review tool. It reads a git diff (or, in full-scan mode, whole files), sends the changed
code to a configurable LLM through an agent that can call tools (read other files, search
the codebase), and produces structured, line-precise review comments — the same assistant
that started as Alibaba's internal review tool and has reviewed code for tens of thousands
of developers, now open source.
Explain-it-simply
Think of OCR as a very disciplined reviewer who is handed one changed file at a time, a stack of "read the neighboring file", "search the codebase", and "leave a comment" index cards (its tools), and a strict rulebook for how to write each comment down. The reviewer can look around before commenting, but every comment it writes must point at a real line, and a supervisor (deterministic engineering code, not the AI) decides which files the reviewer even sees and checks the reviewer's math on where each comment landed.
The core design bet, stated directly in the project's own README: a purely language-driven agent (e.g. a general coding assistant given a "review this" skill) tends to skip files on large changesets, mis-locate its own comments, and vary in quality run to run. OCR's answer is deterministic engineering + agent, each doing what it's best at — file selection, bundling, rule matching, and comment-location checking are plain code with no model call in the loop; only the actual judgment of "is this a bug" is left to the model. See §7 for exactly where that line falls in each package.
2 · Who Should Read What
Every module box in §7 below answers four questions when expanded: what happens, what goes in/out, how the model (if any) is chosen, and what's deterministic vs. AI. Read at whichever depth you need — the Simple/Technical switch above changes every description on this page at once.
| Reader | Start with | Then |
|---|---|---|
| Non-technical (PM, analyst) | §1 Overview | §3 Context Diagram, then the "Explain-it-simply" boxes in §7 |
| Security analyst | §4 Data Flow | §6 Trust Boundaries, §7 (tool + llm + viewer modules) |
| Junior developer | §5 Architecture (HLD) | §7 Module Flow → docs/modules/README.md for per-file detail |
| Reviewer / architect | §5 HLD | §8 Module Dependency Graph (real data) → tool-outputs/ |
Operator (wants to run ocr) | Quickstart | samples/open-code-review/README.md |
3 · Context Diagram (Who Talks to OCR)
OCR runs entirely on the developer's machine (or a CI runner). It has exactly two outbound network relationships: the configured LLM provider (HTTPS) and, only in delegation mode, handing work to a coding agent the user already has running. Everything else is local files.
Click the diagram to zoom. Source: diagrams/src/03_context_dfd.dot.
4 · Data Flow — `ocr review`
This is the path one changed file takes through a normal ocr review run,
from git diff to a persisted comment.
Explain-it-simply
Every file gets its own mini-conversation with the AI. The AI can ask to see more code ("show me file X", "search for Y") before it decides to write a comment. Once it writes a comment, OCR double-checks the comment's line number against the real diff before accepting it — if the AI got confused about where something is, this catches it.
See §5 for the full-file scan (ocr scan) and delegation (ocr
delegate) variants of this flow.
5 · Architecture (High-Level Design)
| # | Component | Package | Responsibility |
|---|---|---|---|
| 1 | CLI | cmd/opencodereview | Cobra commands: review, scan, delegate, session, config, llm, rules, viewer, completion. Resolves the LLM endpoint, loads config/rules, builds Args, dispatches. |
| 2 | Diff engine | internal/diff | Runs git diff (workspace / range / commit modes), parses unified diffs into hunks, respects .gitignore, resolves/relocates comment line numbers against the diff. |
| 3 | Config / rules | internal/config/{rules,allowlist,template,toolsconfig} | Path-based rule matching (which review rules apply to which files), file-type allowlist, prompt templates (task_template.json, scan_template.json), tool enable/disable config. |
| 4 | Review agent | internal/agent | Orchestrates diff review: loads diffs, filters, dispatches one goroutine per changed file (bounded concurrency), builds the manifest (coverage tracking for resume). |
| 5 | Scan agent | internal/scan | Orchestrates full-file review: enumerates files (whole repo or --path), same dispatch pattern, plus optional dedup and project-summary passes with no diff context. |
| 6 | Delegate | internal/delegate | Deterministic file selection + rule-group export for delegation mode — makes no LLM call itself; hands the work to the user's own coding agent. |
| 7 | LLM loop | internal/llmloop | The shared tool-use conversation loop (Runner.RunPerFile) used by both agent and scan: sends messages + tool defs, executes returned tool calls, tracks tokens, compresses context near the token limit, runs a final "grace round" when the round budget is exhausted. |
| 8 | Tools | internal/tool | The fixed toolset the model can call: file_read, file_find, file_read_diff, code_search, code_comment, task_done, plus a registry that can also hold dynamically-registered MCP tools. |
| 9 | MCP client | internal/mcp | Connects to user-configured MCP servers and adapts their tools into the same tool.Registry the built-in tools use — the model cannot tell a built-in tool from an MCP one. |
| 10 | LLM transport | internal/llm | Resolves which provider/protocol/model to call (env vars → config.json → built-in provider presets), speaks Anthropic / OpenAI Chat Completions / OpenAI Responses protocols, retries with backoff, records a per-run retry report. |
| 11 | Session | internal/session | Per-run history (JSONL), the coverage manifest (which files completed/reused/failed and why), resume support (re-run only what didn't finish). |
| 12 | Viewer | internal/viewer | A local-only web server that renders session JSONL as browsable HTML — comments, token usage, tool-call timeline. |
| 13 | Telemetry | internal/telemetry | OpenTelemetry spans/metrics/events around diff parsing, LLM calls, and tool calls — opt-in observability, not a code path any review result depends on. |
6 · Trust Boundaries & Security Posture
From the project's own ASSURANCE_CASE.md (source-verified, not summarized
from marketing copy):
| Boundary | Risk | Mitigation |
|---|---|---|
| Git repo → CLI | Crafted diff content | Strict unified-diff parsing; every external process call is git with a hardcoded subcommand list and --end-of-options — no shell, no shell interpolation. |
| CLI → LLM provider | API key leakage | Keys read only from environment variables; never logged, written to output, or sent anywhere but the configured endpoint. |
| LLM response → local file | Path traversal from a model-suggested path | pathutil.WithinBase() validates every file-tool path against the repo root, before and after symlink resolution. |
| Browser → viewer | DNS rebinding against the local session viewer | Host-header allowlist rejects non-loopback origins by default (OCR_VIEWER_ALLOWED_HOSTS to override); strict CSP and security headers on every response. |
| Network | MITM on the API call | Go's default TLS 1.2+ with full certificate verification; InsecureSkipVerify is never set. |
CGO is disabled (CGO_ENABLED=0) — the release binaries are
memory-safe Go with no C attack surface, and the Go race detector runs in CI.
5b · Interactive Review Lifecycle
Click a stage to see its role and exactly which config key or absence of one decides
whether a model gets called. This is the per-file lifecycle both ocr review
and ocr scan run through (scan has no diff, so it works from whole-file
content instead — see §7's internal/scan box for what differs).
7 · Module Flow
Click any box below to expand what actually happens inside it, how its model (if any) is selected, and which parts are deterministic. Thirteen packages, grouped into seven layers from CLI entry down to persistence/observability.
CLI ▸in CLI args/flags, config.json, rule.json, environment variablesout a fully-populated agent.Args / scan.Args, dispatched to the right package
package: cmd/opencodereview/
Cobra command tree: review, scan, delegate, session, config, llm, rules, viewer, completion.
What actually happens here
root.go registers ten subcommands. review_cmd.go / scan_cmd.go resolve the LLM endpoint (internal/llm.ResolveEndpoint*), build the rule resolver and file filter from internal/config, construct the tool registry (registering built-ins then any configured MCP servers), and call agent.New(...).Run() or scan.NewAgent(...).Run(). config_cmd.go and provider_cmd.go/provider_tui.go drive the interactive provider/model setup wizard shown in the README's screenshot.
How the LLM / model version is chosen
No model call in the CLI layer itself — it only resolves *which* model/provider/protocol downstream calls will use, via internal/llm.ResolveEndpointWithOptions (env var OCR_LLM_PROTOCOL, or config.json llm.protocol / provider preset).
Deterministic (non-LLM) work in this module
All of it: flag parsing, config file loading and merge, endpoint resolution, tool registry assembly, and command dispatch are plain Go with no model call.
Depends on: diff, config_rules, agent, scan, delegate, session, llm, tool, mcp, viewer
Diff engine ▸in git repository + From/To refs, a commit SHA, or nothing (workspace mode)out []model.Diff — one parsed unified diff per changed file, plus resolved commit endpoints
package: internal/diff/
Everything about turning 'what changed' into a precise, per-file diff the agent can send to the model.
What actually happens here
diff.Provider (git.go) shells out to git diff for one of three modes — workspace (all staged+unstaged+untracked), range (merge-base against a target branch), or a single commit — and gitcmd.Runner bounds concurrent git subprocesses. parser.go splits the unified diff into hunks; gitignore.go filters paths git itself would ignore; resolver.go and relocation.go are what let a later code_comment tool call be checked against real line numbers, including finding a comment's new position when a hunk shifted lines around it.
How the LLM / model version is chosen
No model calls — pure git subprocess + text parsing.
Deterministic (non-LLM) work in this module
The entire package: diff retrieval, hunk parsing, gitignore filtering, and line-number resolution/relocation are all deterministic. This is the 'precise file selection' and 'external positioning module' the README's design philosophy calls out as engineering, not AI, work.
Depends on: gitcmd
Config, rules & allowlist ▸in rule.json (custom + project + global layers), config.json, embedded default rule/prompt/allowlist JSONout a rules.Resolver + rules.FileFilter (which files are reviewed and which rule text applies to each), plus loaded prompt template.Template
package: internal/config/{rules,allowlist,template,toolsconfig}
Decides which files are even eligible for review, and which review-rule text each eligible file sees.
What actually happens here
allowlist/ holds the supported-file-type and default-exclude-pattern JSON compiled into the binary. rules/system_rules.go resolves path-pattern rules (custom > project > global > system, first match wins per the resolver's own precedence) into the text injected as {{system_rule}} in the main prompt. template/ loads task_template.json / scan_template.json — the actual prompt text, tool-request budgets, and token limits — and can be overridden by a project's own template file.
How the LLM / model version is chosen
No model calls — this package supplies the *inputs* a model call will use (prompt text, rule text), it never calls one itself.
Deterministic (non-LLM) work in this module
Path-glob rule matching, file-extension allowlisting, and template-engine variable substitution are all deterministic — README calls this out explicitly as 'fine-grained rule matching...more stable and predictable' than doing the same selection purely via prompt instructions.
Depends on: (none — leaf package)
Review agent ▸in agent.Args (repo dir, From/To/Commit, template, rules, LLM client, tool registry)out []model.LlmComment + a persisted session with a coverage manifest
package: internal/agent/
Runs ocr review end to end: load diffs, filter, dispatch one goroutine per file, finalize the manifest.
What actually happens here
Agent.Run (agent.go) parses diffs via internal/diff, builds a read-only DiffMap tool input, filters by rule/size/budget, then dispatchSubtasks fans out to up to MaxConcurrency (default 8) goroutines, each calling executeSubtask (plan phase, then llmloop.Runner.RunPerFile for the main loop). A per-run token budget (MaxTokensBudget) is checked before each new file is scheduled, so an in-flight batch can overrun the cap by at most the concurrency limit, never a whole extra batch.
How the LLM / model version is chosen
Model/provider come from Args.Model/Args.Provider, set once by the CLI layer from the resolved LLM endpoint — every request in a run (plan, main loop, memory compression, re-location, review filter) uses that same value; there is no per-phase override.
Deterministic (non-LLM) work in this module
Diff loading/filtering, concurrency and per-file token-budget gating, manifest coverage registration (registerCoverage/Mark*), resume matching by content fingerprint (SHA-256 of mode+paths+diff text), and all error classification are deterministic; only the plan phase and the main tool-use loop inside each subtask are AI-driven (see llmloop).
Depends on: diff, config_rules, llmloop, tool, session, llm
Scan agent ▸in scan.Args (repo dir, optional --path, ScanTemplate)out []model.LlmComment for whole files + an optional project-level Markdown summary
package: internal/scan/
Runs ocr scan: review whole files (no git diff needed) — for auditing unfamiliar code or directories without a meaningful diff.
What actually happens here
scan.Agent enumerates files under RepoDir or --path into []model.ScanItem (whole file content, not a diff), then reuses the exact same llmloop.Runner the review agent uses (toLoopTemplate maps ScanTemplate onto the loop's template.Template fields). Adds two phases review mode doesn't have: an optional per-batch DEDUP_TASK and a post-run PROJECT_SUMMARY_TASK, both individually disableable via --no-dedup/--no-summary.
How the LLM / model version is chosen
Same Args.Model/Provider pattern as review — one model for the whole run, set by the CLI from the resolved endpoint.
Deterministic (non-LLM) work in this module
File enumeration and size filtering (MaxFileSizeBytes, default 2 MiB), toLoopTemplate's field mapping, and dispatch/budget gating mirror agent's — AI involvement is the plan phase, main loop, dedup task and project-summary task, each individually toggleable.
Depends on: config_rules, llmloop, tool, session, llm, agent
Delegate ▸in the same rule/file-selection engine as review/scan (rules.Resolver, FileFilter)out Markdown-rendered rule groups + a resolved file list — handed to the caller, not to an LLM
package: internal/delegate/
Powers ocr delegate: OCR does file selection and rule resolution only; the user's own coding agent (Claude Code, Codex, Cursor) performs the actual review with its own model.
What actually happens here
rulegroup.go groups files by which rule text applies to them (RuleGroupsMarkdown renders each group's applicable files + rule content as a Markdown section); delegate_cmd.go exposes this as `ocr delegate preview` (file/rule discovery) and `ocr delegate rule <paths>` (rule text for specific files). This is the one review-producing code path in OCR that never constructs an llm.LLMClient or calls CompletionsWithCtx.
How the LLM / model version is chosen
No model calls — explicitly, by design. This is the mechanism by which OCR can run with zero OCR-managed API key or LLM config: the review judgment happens inside whatever coding agent the user already has running.
Deterministic (non-LLM) work in this module
100% of this package: rule-group formation and Markdown rendering are plain string/slice logic reusing the same deterministic resolver as review/scan.
Depends on: config_rules
LLM loop (Runner) ▸in a rendered message list + tool definitions for one file's conversationout comments collected via tool.CommentCollector; a completion/stop classification
package: internal/llmloop/
The one shared tool-use loop underneath both internal/agent and internal/scan — sends messages, executes returned tool calls, manages context size.
What actually happens here
Runner.RunPerFile (loop.go) is the literal for-loop: send ChatRequest, get tool calls back, executeToolCall each one, append results, repeat until task_done, MaxToolRequestTimes rounds exhausted (triggers a final 'grace round' offering only code_comment/task_done), 3 consecutive rounds with no usable result, or context compression fails to bring the conversation back under budget. compression.go runs three-zone compression (soft 60% / warn 80% of Template.MaxTokens) synchronously or as a background job per conversation. pool.go is the CommentWorkerPool that can run code_comment's line-resolution off the critical path.
How the LLM / model version is chosen
Model/provider/template are all passed in via Deps from the calling package (agent or scan) — llmloop itself makes no routing decision; it just calls Deps.LLMClient.CompletionsWithCtx(Model, Messages, Tools). The optional re-location call (diff.ReLocateComment, when a comment's line number can't be resolved deterministically) uses the same Deps.Model.
Deterministic (non-LLM) work in this module
Round/budget bookkeeping, empty-round detection, three-zone token-threshold compression triggers, and tool-call dispatch routing (built-in vs. dynamic MCP) are deterministic; only the model's own responses (what to call, what to say) are AI-driven.
Depends on: llm, tool, session, model
Tools ▸in a tool call's JSON arguments from the modelout a result string appended back into the conversation
package: internal/tool/
The fixed toolset: file_read, file_find, file_read_diff, code_search, code_comment, task_done — plus the Registry that can also hold MCP-provided tools.
What actually happens here
definitions.go defines the reserved Tool set and a Registry (Register/Get/Freeze — frozen once dispatch starts so no tool can be added mid-run). file_read.go / file_find.go / code_search.go implement local, read-only filesystem access scoped to the repo (via internal/pathutil). file_read_diff.go answers questions about *other* changed files using the DiffMap injected by agent.injectDiffMap. code_comment.go + comment_collector.go parse and accumulate the model's findings.
How the LLM / model version is chosen
No model calls inside any tool implementation — every tool is a synchronous, local operation. (The one exception, the re-location LLM call for a comment whose line number can't be resolved deterministically, lives in internal/diff/internal/llmloop, not here.)
Deterministic (non-LLM) work in this module
Every built-in tool is fully deterministic: file reads are path-validated (pathutil.WithinBase, both pre- and post-symlink-resolution — the same mitigation the ASSURANCE_CASE.md cites for path traversal), code_comment argument parsing and validation is deterministic, and the Registry's known-name/frozen-state checks are deterministic.
Depends on: (none — leaf package)
MCP client ▸in user-configured MCP server definitionsout tool.Provider adapters registered into the same Registry as built-in tools
package: internal/mcp/
Lets a review extend its available tools with external MCP servers, without the model ever seeing a difference from a built-in tool.
What actually happens here
client.go manages the MCP session (stdio transport, per client_test.go/stdio_test.go). provider.go's RegisterAll copies each MCP tool into the shared tool.Registry as a Provider whose Execute calls client.CallTool, after checking two collision rules: a tool name can't shadow a built-in (tool.IsReserved) and can't shadow an already-registered tool — either logs a warning and skips rather than silently overriding.
How the LLM / model version is chosen
No model calls in this package — it is pure protocol/adapter plumbing between MCP servers and the tool.Registry.
Deterministic (non-LLM) work in this module
Tool-name collision resolution and JSON-schema-to-llm.ToolDef conversion (ToToolDef) are fully deterministic.
Depends on: llm, tool
LLM transport ▸in llm.ChatRequest (messages, tools, model, max tokens)out llm.ChatResponse (content, tool calls, usage) or a classified error
package: internal/llm/
Resolves which provider/protocol/model a run uses, and speaks all three supported wire protocols with retry.
What actually happens here
resolver.go's ResolveEndpointWithOptions is the single source of truth for 'which model gets called': it checks the OCR_LLM_PROTOCOL/OCR_LLM_* environment variables first, then config.json's llm.protocol (or the legacy use_anthropic bool) or a named provider preset from providers.go's built-in registry (anthropic, openai, and any custom provider entries). client.go/responses_client.go implement the three protocols (ProtocolAnthropic, ProtocolOpenAIChatCompletions, ProtocolOpenAIResponses); retry_boundary.go/retry_observer.go/retry_report.go add exponential-backoff retry and build the per-run retry report the CLI can print.
How the LLM / model version is chosen
This package *is* the model-selection mechanism for every other package: env var → config.json → provider preset, normalized to one of three canonical protocol names by NormalizeProtocol/ValidateProtocol. No other package re-implements this resolution.
Deterministic (non-LLM) work in this module
Protocol/endpoint resolution precedence, retry/backoff timing, and request/response marshaling are deterministic; the model's actual reply content is of course not.
Depends on: mcp
Session & manifest ▸in per-task LLM request/response records, per-item completion/failure eventsout a resumable JSONL history + an immutable RunManifest (coverage snapshot)
package: internal/session/
The audit trail: what was reviewed, what was skipped, why, and what a --resume run can safely reuse.
What actually happens here
history.go opens one JSONL file per run and appends TaskRecords (prompt, response, tool results) as the review progresses. manifest.go's ManifestBuilder is a strict state machine — RegisterSelected/SealSelected freezes the coverage denominator before any dispatch, then every item must transition through exactly one of MarkCompleted/MarkReused/MarkFailed before Finalize, or Finalize's validation catches the gap. resume.go matches a prior run's completed items to the current run by a content fingerprint (mode + paths + diff text, SHA-256), never by file path alone.
How the LLM / model version is chosen
No model calls — this package only records what other packages' model calls produced.
Deterministic (non-LLM) work in this module
All of it — this is the deterministic bookkeeping layer the architecture explicitly separates from the AI-driven review packages above it.
Depends on: llm
Session viewer ▸in a session's persisted JSONL + manifestout rendered HTML pages served over local HTTP
package: internal/viewer/
A local-only web UI (`ocr viewer`) for browsing a past review session — comments, timeline, token usage — without re-running anything.
What actually happens here
server.go starts an http.Server bound to localhost by default; hostguard.go enforces a Host-header allowlist (OCR_VIEWER_ALLOWED_HOSTS to widen it) specifically to block DNS-rebinding attacks against the local server, and securityheaders.go adds a strict CSP plus the standard clickjacking/sniffing headers to every response. handler.go / store.go load a session's JSONL and render it through html/template (auto-escaping, so no session content — including anything an LLM wrote — can inject markup).
How the LLM / model version is chosen
No model calls — purely a read/render layer over already-persisted session data.
Deterministic (non-LLM) work in this module
The entire viewer is deterministic: host allowlist checks, header injection, and template rendering. This is also where the ASSURANCE_CASE.md's XSS mitigation (html/template auto-escaping + CSP) actually lives.
Depends on: session
Telemetry ▸in spans/events emitted by cli, agent, scan, llmloop, tool, diffout OpenTelemetry traces/metrics/logs to a configured OTLP collector
package: internal/telemetry/
Opt-in observability — review duration, per-tool-call timing, token usage — layered on top of the functional code paths, never load-bearing for a review's result.
What actually happens here
config.go/provider.go set up the OTLP exporter from environment configuration (no telemetry runs unless configured); span.go/events.go/metrics.go are thin wrappers called from every other package's hot paths (StartSpan, Event, RecordToolCall, RecordLLMRequest) so instrumentation reads as ordinary function calls rather than a cross-cutting framework.
How the LLM / model version is chosen
No model calls — and telemetry data itself must never include secrets: API keys and auth headers are explicitly excluded from every event/span per ASSURANCE_CASE.md.
Deterministic (non-LLM) work in this module
All of it — span/event emission is deterministic instrumentation code with no influence on review outcomes.
Depends on: llm
8 · Module Dependency Graph (real data)
Rendered from a CodeGraph SQLite index of the actual repository (7,416 nodes, 23,976
edges across 435 files) — not hand-drawn. Top 28 module-to-module edges by call/reference
weight; full data in tool-outputs/codegraph/module_dependencies.json.
The heaviest edge, cmd/opencodereview → internal/llm (492), is
almost entirely the CLI's config/provider/TUI code exercising internal/llm's
endpoint-resolution types — expected, since the CLI owns provider setup. The next heaviest,
internal/llmloop → internal/llm (253) and internal/agent → internal/llm
(176), are the actual chat-completion call sites.
9 · The Three Review Modes, Side by Side
| Mode | Command | Input unit | Needs OCR-configured LLM? | Extra phases vs. review |
|---|---|---|---|---|
| Diff review | ocr review | per-file unified diff | Yes | — |
| Full-file scan | ocr scan | whole file content, batched | Yes | optional dedup task, optional project-summary task |
| Delegation | ocr delegate | rule groups + file list | No | review itself runs inside the user's own coding agent |