Embedding ocra
Run the review pipeline from your own program with review() from @open-cr-agent/core.
The ocra command is one caller of review() in @open-cr-agent/core; your bot, CI step or scheduled service can be another, with the same stages, trust rules, cost limits and report.
A complete call
import {
correctnessReviewerPlugin,
isBlocking,
isIncompleteReview,
review,
securityReviewerPlugin,
sessionJsonlPlugin,
startPlugins,
toReportOutput,
} from "@open-cr-agent/core";
import { opencodeRuntimePlugin } from "@open-cr-agent/runtime-opencode";
import { localGitPlugin } from "@open-cr-agent/vcs-local";
// 1. Plugins register adapters, runtimes, reviewers, rules, tools and listeners.
const registry = await startPlugins(
[localGitPlugin, opencodeRuntimePlugin, correctnessReviewerPlugin, securityReviewerPlugin, sessionJsonlPlugin],
{
env: process.env,
settings: { "session-jsonl": { dir: ".ocra/sessions", id: "my-run" } },
warn: (message) => console.warn(message),
},
);
// 2. Where the change comes from, and what runs the agents.
const vcs = registry.createVcs("local", {
cwd: process.cwd(),
target: { mode: "range", from: "main", to: "HEAD" },
});
const runtime = registry.createRuntime("opencode", {
models: {
top: ["google/gemini-3.1-pro-preview"],
standard: ["google/gemini-3.5-flash", "google/gemini-flash-lite-latest"],
light: ["google/gemini-flash-lite-latest"],
},
env: process.env,
});
// 3. The review.
try {
const report = await review({
vcs,
runtime,
reviewers: registry.reviewers,
rules: registry.rules,
limits: { maxCostUsd: 2 },
onEvent: (event) => registry.emit(event),
});
console.log(JSON.stringify(toReportOutput(report)));
if (isIncompleteReview(report)) process.exitCode = 3;
else if (isBlocking(report)) process.exitCode = 1;
} finally {
await runtime.dispose?.();
}startPlugins runs the plugins' lifecycle (Plugins) and returns a frozen registry; createVcs and createRuntime build the registered adapter and runtime by name; registry.emit hands events to the listeners (here the session log). These are the plugins the CLI uses; .ocra/config.json is a CLI convenience, not part of the library.
What review() takes
These ReviewOptions fields are a contract under the 0.x rule: a minor release may change them, and the changelog says how.
| Option | Meaning |
|---|---|
vcs | The VcsAdapter for the change: where the diff and files come from, and where publish sends the review |
runtime | The AgentRuntime that runs one isolated review task at a time |
reviewers | The reviewers to run (default: correctness alone); the registry's, or your own ReviewerDefinitions |
reviewerOverrides | Per reviewer: enabled, minTier, and its own effort and models chain (Models per agent) |
roles | Per role (verifier, judge, helper): its own effort and models chain |
effort | Reasoning effort per model tier (Effort) |
models | The tier chains the runtime was given (it takes them in RuntimeOptions.models), so provenance.agents can record each agent's chain |
rules | Path-scoped rules, the registry's plus yours (SourcedRule[]: a RepoRule with an optional source: repository, shared, account or plugin); provenance.rules lists them, .ocra/rules.json's as repository |
readTrusted | Where AGENTS.md, .ocra/rules.json and .ocra/memory.json are read from; default the revision under review. For a pull request, pass a reader of the trusted base |
selection | Which files are reviewed: include, exclude, maxPatchChars (200,000); each one left out keeps its default |
limits.concurrency, limits.taskTimeoutMs, limits.runTimeoutMs | Parallel tasks (4), the per-task timeout (10 minutes) and the run's (25 minutes); a timeout past 2^31 - 1 ms (about 24.8 days), Infinity included, is cut to that. review() refuses a concurrency that is not a whole number of at least 1, and a timeout that is not a positive number, with CONFIG_INVALID before it starts |
stages.verify, stages.judge | Fact-check findings against the diff, and merge, filter and recalibrate them across reviewers (both default on) |
limits.maxCostUsd, limits.maxTasks | The spend limit (--max-cost-usd) and the task cap; a negative or NaN limit, or a task cap that is not a whole number, is refused with CONFIG_INVALID |
mode.full | Review every file although the platform reports what changed since the previous review |
mode.ultra | Recall over cost (Modes) |
sarif | Parsed SARIF logs (parseSarifLog) whose results on the change join the review (SARIF input) |
signal | An AbortSignal: the run stops, keeps what it found and writes a partial report |
onEvent | Receives each ReviewEvent as the run progresses |
identity.runId | Names the run in the report, the events and what is posted; generated when absent. The CLI passes its session id |
identity.provenance | { ocraVersion, configHash, sampling?, accountSettings? }: the report's provenance then adds the system prompts' hash and the sampling applied (sampling is what you asked for; stableHash() hashes your configuration) |
resume | A ResumedRun: an earlier run's id, bundles and completed tasks (each with its key and the findings it reported), as the task_reported and task_finished events of its session give them. A task whose key matches is reused and costs nothing; its outcome has reusedFrom. The CLI's --resume reads it from a session, only from lines sealed with this machine's key (session-jsonl's optional sealKey setting, 64 hex digits, seals each line it writes). The key includes the base and head commits, and identity.provenance's version and sampling; without those, tasks of another ocra build or sampling can be reused. Reused tasks are taken before the spend limit is checked, since they cost nothing |
What it returns
A ReviewReport, with the content of the JSON report.
- Publish
toReportOutput(report), not the report: it is the versioned JSON the CLI writes, typedReportOutputand validated byreportOutputSchema(from which the type is derived) and the JSON Schema. The internal report's fields may change. - An incomplete review is not a pass.
isIncompleteReview(report)is true when the review left a selected file unfinished or a critical finding nobody could check, which is when the CLI exits 3;isBlocking(report)is true for a verdict that fails the run (exit 1):significant_concernsnobody overrode. Gate on these as the CLI's exit codes do, never onverdictalone. For the details,coverageGaps(report)gives how many selected files were not reviewed, whether nothing was, and inincompletehow many were partly reviewed, by how their task ended (step_cap,stopped_early);report.unverifiedCriticalscounts the critical findings nobody could check.
vcs.publish(report) posts the review as --publish does, under the platform's trust rules, and returns what it could not post as warnings.
Event shapes (onEvent) are not a contract: a listener should tolerate new types and fields.
Errors
review() rejects only when the run cannot start: no reviewers, an invalid .ocra/rules.json or .ocra/memory.json, or a change the VCS adapter cannot read. After that, failed tasks and helper calls, exhausted quotas and the spend limit are recorded in the report, not thrown.
ocra's packages throw OcraError (or a subclass) with a code: isOcraError(error, code?) checks it, OCRA_ERROR_CODES lists the codes, and an underlying error (a JSON parse error, a failed read) is the cause. Branch on the code, never the message, which may be reworded. A plugin's adapter or runtime may throw other errors; errorMessage(error) gives the message of any thrown value.
| Code | Meaning |
|---|---|
CONFIG_INVALID | Configuration that cannot be used: options, .ocra/config.json and what it extends, .ocra/rules.json, .ocra/memory.json, a model name, no reviewer, no model for a tier |
CONFIG_CREDENTIALS_MISSING | A token or model key the run needs is not set |
INPUT_USAGE | A command line ocra cannot run (the CLI's usage errors) |
INPUT_INVALID | Input given to ocra that it cannot read, such as a SARIF log or a list of commit ids |
ACCESS_DENIED | The access policy refused a path: a secret, git internals, a symbolic link where ocra writes |
PLUGIN_INVALID | A plugin that cannot be loaded or registers something twice or after start, or a name no plugin registered |
VCS_GIT_FAILED | A git command failed |
VCS_API_FAILED | The GitHub or GitLab API failed or answered something unexpected; GitHubApiError and GitLabApiError carry the HTTP status |
VCS_REF_UNKNOWN | A commit or ref that is not in the repository and could not be fetched |
VCS_NOT_READY | The platform has not prepared the change yet, such as a merge request without a diff; try again shortly |
CLOUD_API_FAILED | The CLI could not reach ocra Cloud for ocra login or ocra whoami, or ocra Cloud answered something it cannot use |
RUNTIME_START_FAILED | The agent runtime could not start (no OpenCode binary, a server that did not come up) |
RUNTIME_FAILED | A model call failed on every model of its chain (CompletionError, which carries the usage the attempts spent) |
RUNTIME_INVALID_OUTPUT | A model answered something that does not match the expected schema |
BUDGET_EXHAUSTED | The spend limit was reached (SpendLimitReached, the reason running tasks were stopped) |
INTERNAL | A broken invariant or a misused object, such as one OpenCode runtime used for two runs: a bug in ocra or in its caller |
Subclasses for instanceof: CompletionError, SpendLimitReached, AccessDeniedError, SarifError and PluginError (@open-cr-agent/core), GitError (@open-cr-agent/vcs-local), GitHubApiError and GitLabApiError (the platform adapters). No error message carries a token or model key; both runtimes redact them from provider answers before quoting.
The codes are a contract under the 0.x rule: a minor release may add one, and the changelog says when one is renamed or removed. The CLI prints the code of an error ending a run with exit 2, as in ocra [CONFIG_INVALID]: .ocra/config.json is invalid: ….
Pull requests and merge requests
githubPlugin (@open-cr-agent/vcs-github) and gitlabPlugin (@open-cr-agent/vcs-gitlab) register the github and gitlab adapters.
resolveGitHubTarget and resolveGitLabTarget find a pull or merge request as --pr and --mr do. Each takes ref (the number, plus repository or project if you name it), env (the CLI's token, repository and API variables), origin() (the checkout's origin, read only when needed), warn and an optional fetch. Each returns the base and head commits, the refspecs that fetch the head, the change request's web page, and createVcs(registry, local, settings), which makes the adapter once the commits are in your clone: local gives the code and history, settings is GitHubSettings (botLogin, requestChanges) or GitLabSettings (none yet). Fetching commits and reading configuration, guidelines and rules from the base (readTrusted) are up to you, as in packages/cli/src/commands/review/target.ts. The adapters' own createVcs options are not a contract; go through these functions.
Trust
Your program is the trust boundary. Load only plugins you trust, never ones the reviewed tree names; pass model keys through env, of which the runtime forwards only what the configured providers need (Security); for a pull request, read guidelines, rules and memory from the base through readTrusted. Agents get read-only tools and no shell, whoever calls review().
The public API
The main entry of each package is its public API, a contract under the 0.x rule:
@open-cr-agent/core:review()andReviewOptions; what it returns (ReviewReport,Findingand the types they are made of),coverageGaps(),isIncompleteReview(),isBlocking(),toReportOutput()withReportOutput,reportOutputSchema,reportJsonSchema()andREPORT_VERSION;parseSarifLog(); the plugin interface (OcraPluginand its contexts,startPlugins(),PluginRegistry, the built-in reviewer plugins andsessionJsonlPlugin); the contracts a plugin implements (VcsAdapter,AgentRuntimeand the types they use,ToolDefinition,ReviewerDefinition,RepoRule); what a runtime builds on (ChainRunnerwithModelAttempts,AttemptOutcome,QuotaError, the review tools, the step cap and the other helpers Plugins lists); and the error model.@open-cr-agent/vcs-local:localGitPlugin,LocalTarget,LocalGitOptionsandGitError.vcs-githubandvcs-gitlab:githubPluginandgitlabPlugin,resolveGitHubTargetandresolveGitLabTargetwithGitHubSettingsandGitLabSettings, and their API errors.runtime-opencodeandruntime-direct:opencodeRuntimePluginanddirectRuntimePlugin.@open-cr-agent/cli:run(argv), theocracommand with its arguments (no node or script path), writing to stdout and stderr and resolving to the exit code.@open-cr-agent/vcs-platformis what ocra's platform adapters share; it is not a contract yet.
Every name and type shape is in the package's API report in etc/; CI fails when an entry changes without its report.
/internal entries (@open-cr-agent/core/internal and others) are shared between ocra's packages and are not a contract: any release, a patch included, may change them. Build on the main entries only.