Open Code Review (OCR) — Architecture Explainer

generated 2026-08-14 · onboarding companion, not the source of truth

Reading level:

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.

ReaderStart withThen
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)Quickstartsamples/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.

OCR_Context_DFD OCR — Context Diagram (DFD Level 0) dev Developer / CI job ocr OCR CLI dev->ocr ocr review / scan / delegate + config repo Local git repository (diffs / files under review) repo->ocr git diff / file contents provider LLM Provider API (Anthropic / OpenAI / custom) ocr->provider diff + prompt (HTTPS) agentprov User's own coding agent (Claude Code / Codex / Cursor) — delegation mode only ocr->agentprov rule groups + file selection (delegate mode) out Review output (terminal · SARIF · session files) ocr->out comments, SARIF, session JSONL browser Local browser ocr->browser session viewer pages provider->ocr review comments (JSON) agentprov->out review comments (agent's own LLM call) out->dev review browser->ocr HTTP (loopback only)

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.

OCR_Review_DataFlow OCR — `ocr review` Data Flow (DFD Level 1) repo git repo (workspace / range / commit) gdiff internal/diff GetDiff() repo->gdiff parsed []model.Diff (per-file unified diffs) gdiff->parsed filt Filter by rules/allowlist + size + budget pre-check parsed->filt dispatch Dispatch per file (bounded goroutines, default concurrency 8) filt->dispatch plan Plan phase (optional) 1 LLM call per file dispatch->plan per file manifest session.Manifest coverage: completed/reused/failed dispatch->manifest registerCoverage mainloop Main tool-use loop (llmloop.Runner.RunPerFile) plan->mainloop toolcall Tool call: file_read / file_find / file_read_diff / code_search mainloop->toolcall loop until task_done codecomment Tool call: code_comment (line-number resolve / re-location LLM call) mainloop->codecomment taskdone Tool call: task_done mainloop->taskdone jsonl Session JSONL (resumable checkpoint) mainloop->jsonl AppendTaskRecord collector tool.CommentCollector ([]model.LlmComment) codecomment->collector reviewfilter Review filter task (optional) drops low-value comments taskdone->reviewfilter collector->reviewfilter outtxt Terminal output reviewfilter->outtxt outsarif SARIF (CI mode) reviewfilter->outsarif manifest->jsonl Finalize

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)

OCR_Architecture Open Code Review (OCR) — System Architecture (High-Level Design) cluster_in Inputs cluster_diff Change selection (deterministic) cluster_tools Tools available to the model cluster_out Outputs repo Local git repo (workspace / range / commit) cli CLI (cmd/opencodereview) review · scan · delegate · session config · llm · rules · viewer repo->cli cfg config.json + rule.json (provider, model, rules, file filters) cfg->cli mcpin MCP servers (optional) external tools mcpin->cli diffpkg internal/diff git diff · hunk parse · gitignore line relocation cli->diffpkg rules internal/config/rules + allowlist file filter · rule matching by path cli->rules agentpkg internal/agent (review) plan + dispatch per file cli->agentpkg scanpkg internal/scan (full-file scan) enumerate + batch files cli->scanpkg delegatepkg internal/delegate rule-group export, no LLM call cli->delegatepkg diffpkg->agentpkg diffpkg->scanpkg rules->agentpkg rules->scanpkg rules->delegatepkg loop internal/llmloop.Runner shared tool-use loop memory compression · token accounting agentpkg->loop sessionpkg internal/session history · manifest · resume persistence (JSONL) agentpkg->sessionpkg scanpkg->loop scanpkg->sessionpkg comments Review comments (line-precise, categorized, severity) delegatepkg->comments via user's own coding agent, no OCR LLM call tools internal/tool file_read · file_find · file_read_diff code_search · code_comment · task_done loop->tools tool calls llmpkg internal/llm protocol resolve (anthropic/openai/ openai-responses) · retry · providers loop->llmpkg chat completion loop->comments loop->sessionpkg task records mcp internal/mcp external MCP tool adapters mcp->tools registers provider Configured LLM provider (Anthropic / OpenAI / custom) llmpkg->provider HTTPS sarif SARIF / CI annotations comments->sarif sessionout Session JSONL + manifest (coverage, resume, telemetry) viewer internal/viewer local web session browser (loopback + host allowlist) sessionout->viewer reads sessionpkg->sessionout
#ComponentPackageResponsibility
1CLIcmd/opencodereviewCobra commands: review, scan, delegate, session, config, llm, rules, viewer, completion. Resolves the LLM endpoint, loads config/rules, builds Args, dispatches.
2Diff engineinternal/diffRuns git diff (workspace / range / commit modes), parses unified diffs into hunks, respects .gitignore, resolves/relocates comment line numbers against the diff.
3Config / rulesinternal/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.
4Review agentinternal/agentOrchestrates diff review: loads diffs, filters, dispatches one goroutine per changed file (bounded concurrency), builds the manifest (coverage tracking for resume).
5Scan agentinternal/scanOrchestrates full-file review: enumerates files (whole repo or --path), same dispatch pattern, plus optional dedup and project-summary passes with no diff context.
6Delegateinternal/delegateDeterministic file selection + rule-group export for delegation mode — makes no LLM call itself; hands the work to the user's own coding agent.
7LLM loopinternal/llmloopThe 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.
8Toolsinternal/toolThe 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.
9MCP clientinternal/mcpConnects 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.
10LLM transportinternal/llmResolves 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.
11Sessioninternal/sessionPer-run history (JSONL), the coverage manifest (which files completed/reused/failed and why), resume support (re-run only what didn't finish).
12Viewerinternal/viewerA local-only web server that renders session JSONL as browsable HTML — comments, token usage, tool-call timeline.
13Telemetryinternal/telemetryOpenTelemetry 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):

BoundaryRiskMitigation
Git repo → CLICrafted diff contentStrict 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 providerAPI key leakageKeys read only from environment variables; never logged, written to output, or sent anywhere but the configured endpoint.
LLM response → local filePath traversal from a model-suggested pathpathutil.WithinBase() validates every file-tool path against the repo root, before and after symlink resolution.
Browser → viewerDNS rebinding against the local session viewerHost-header allowlist rejects non-loopback origins by default (OCR_VIEWER_ALLOWED_HOSTS to override); strict CSP and security headers on every response.
NetworkMITM on the API callGo'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.

1 · Entry
CLI ▸in CLI args/flags, config.json, rule.json, environment variablesout a fully-populated agent.Args / scan.Args, dispatched to the right packageclick to expand

package: cmd/opencodereview/

Cobra command tree: review, scan, delegate, session, config, llm, rules, viewer, completion.

InputCLI args/flags, config.json, rule.json, environment variables
Outputa fully-populated agent.Args / scan.Args, dispatched to the right package
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

▼
2 · Change selection (deterministic)
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 endpointsclick to expand

package: internal/diff/

Everything about turning 'what changed' into a precise, per-file diff the agent can send to the model.

Inputgit repository + From/To refs, a commit SHA, or nothing (workspace mode)
Output[]model.Diff — one parsed unified diff per changed file, plus resolved commit endpoints
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.Templateclick to expand

package: internal/config/{rules,allowlist,template,toolsconfig}

Decides which files are even eligible for review, and which review-rule text each eligible file sees.

Inputrule.json (custom + project + global layers), config.json, embedded default rule/prompt/allowlist JSON
Outputa rules.Resolver + rules.FileFilter (which files are reviewed and which rule text applies to each), plus loaded prompt template.Template
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)

▼
3 · Orchestration
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 manifestclick to expand

package: internal/agent/

Runs ocr review end to end: load diffs, filter, dispatch one goroutine per file, finalize the manifest.

Inputagent.Args (repo dir, From/To/Commit, template, rules, LLM client, tool registry)
Output[]model.LlmComment + a persisted session with a coverage 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 summaryclick to expand

package: internal/scan/

Runs ocr scan: review whole files (no git diff needed) — for auditing unfamiliar code or directories without a meaningful diff.

Inputscan.Args (repo dir, optional --path, ScanTemplate)
Output[]model.LlmComment for whole files + an optional project-level Markdown summary
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 LLMclick to expand

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.

Inputthe same rule/file-selection engine as review/scan (rules.Resolver, FileFilter)
OutputMarkdown-rendered rule groups + a resolved file list — handed to the caller, not to an LLM
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

▼
4 · Execution loop
LLM loop (Runner) ▸in a rendered message list + tool definitions for one file's conversationout comments collected via tool.CommentCollector; a completion/stop classificationclick to expand

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.

Inputa rendered message list + tool definitions for one file's conversation
Outputcomments collected via tool.CommentCollector; a completion/stop classification
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

▼
5 · Tools & extensibility
Tools ▸in a tool call's JSON arguments from the modelout a result string appended back into the conversationclick to expand

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.

Inputa tool call's JSON arguments from the model
Outputa result string appended back into the conversation
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 toolsclick to expand

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.

Inputuser-configured MCP server definitions
Outputtool.Provider adapters registered into the same Registry as built-in tools
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

▼
6 · Model transport
LLM transport ▸in llm.ChatRequest (messages, tools, model, max tokens)out llm.ChatResponse (content, tool calls, usage) or a classified errorclick to expand

package: internal/llm/

Resolves which provider/protocol/model a run uses, and speaks all three supported wire protocols with retry.

Inputllm.ChatRequest (messages, tools, model, max tokens)
Outputllm.ChatResponse (content, tool calls, usage) or a classified error
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

▼
7 · Persistence & observability
Session & manifest ▸in per-task LLM request/response records, per-item completion/failure eventsout a resumable JSONL history + an immutable RunManifest (coverage snapshot)click to expand

package: internal/session/

The audit trail: what was reviewed, what was skipped, why, and what a --resume run can safely reuse.

Inputper-task LLM request/response records, per-item completion/failure events
Outputa resumable JSONL history + an immutable RunManifest (coverage snapshot)
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 HTTPclick to expand

package: internal/viewer/

A local-only web UI (`ocr viewer`) for browsing a past review session — comments, timeline, token usage — without re-running anything.

Inputa session's persisted JSONL + manifest
Outputrendered HTML pages served over local HTTP
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 collectorclick to expand

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.

Inputspans/events emitted by cli, agent, scan, llmloop, tool, diff
OutputOpenTelemetry traces/metrics/logs to a configured OTLP collector
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.

OCR_Module_Dependencies OCR — Module Dependency Graph (top 28 edges by call/reference weight, from CodeGraph index) cmd/opencodereview cmd/opencodereview internal/llm internal/llm cmd/opencodereview->internal/llm 492 internal/agent internal/agent cmd/opencodereview->internal/agent 44 internal/session internal/session cmd/opencodereview->internal/session 149 internal/tool internal/tool cmd/opencodereview->internal/tool 32 internal/model internal/model cmd/opencodereview->internal/model 41 internal/llm->internal/agent 48 internal/mcp internal/mcp internal/llm->internal/mcp 58 internal/llmloop internal/llmloop internal/llmloop->internal/llm 253 internal/llmloop->internal/session 47 internal/llmloop->internal/tool 134 internal/telemetry internal/telemetry internal/llmloop->internal/telemetry 29 internal/agent->internal/llm 176 internal/agent->internal/session 153 internal/agent->internal/tool 59 internal/agent->internal/model 116 internal/agent->internal/telemetry 48 internal/session->internal/llm 64 internal/tool->internal/llm 51 internal/scan internal/scan internal/scan->internal/llm 106 internal/scan->internal/agent 50 internal/scan->internal/session 88 internal/scan->internal/tool 76 internal/scan->internal/model 83 internal/mcp->internal/llm 31 internal/telemetry->internal/llm 55 internal/diff internal/diff internal/diff->internal/llm 30 internal/diff->internal/model 31 internal/config internal/config internal/config->internal/llm 29

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

OCR_Scan_Delegate OCR — `ocr scan` (full-file) and `ocr delegate` (no OCR-managed LLM call) cluster_scan ocr scan — internal/scan cluster_delegate ocr delegate — internal/delegate enum Enumerate files (whole repo or --path) scanitem []model.ScanItem (full file content, no diff) enum->scanitem splan Plan phase (optional) scanitem->splan sloop Main loop (same llmloop.Runner as review) splan->sloop sdedup Dedup task (optional) per-batch sloop->sdedup ssummary Project summary task (optional, post-run) sdedup->ssummary outcomments Review comments ssummary->outcomments dselect Deterministic file selection + rule resolution (same rules/allowlist engine) drules Rule groups (markdown-rendered) dselect->drules no OCR API key or LLM config needed dagent User's own coding agent (Claude Code / Codex / Cursor) runs the review with ITS OWN model drules->dagent no OCR API key or LLM config needed dagent->outcomments no OCR API key or LLM config needed repo git repo / files repo->enum repo->dselect no OCR API key or LLM config needed note Delegation mode never sends code to an OCR-configured LLM provider — OCR only computes which files and which rules apply; the user's own agent (already running against a model it controls) performs the review.
ModeCommandInput unitNeeds OCR-configured LLM?Extra phases vs. review
Diff reviewocr reviewper-file unified diffYes—
Full-file scanocr scanwhole file content, batchedYesoptional dedup task, optional project-summary task
Delegationocr delegaterule groups + file listNoreview itself runs inside the user's own coding agent