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.

OptionMeaning
vcsThe VcsAdapter for the change: where the diff and files come from, and where publish sends the review
runtimeThe AgentRuntime that runs one isolated review task at a time
reviewersThe reviewers to run (default: correctness alone); the registry's, or your own ReviewerDefinitions
reviewerOverridesPer reviewer: enabled, minTier, and its own effort and models chain (Models per agent)
rolesPer role (verifier, judge, helper): its own effort and models chain
effortReasoning effort per model tier (Effort)
modelsThe tier chains the runtime was given (it takes them in RuntimeOptions.models), so provenance.agents can record each agent's chain
rulesPath-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
readTrustedWhere 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
selectionWhich files are reviewed: include, exclude, maxPatchChars (200,000); each one left out keeps its default
limits.concurrency, limits.taskTimeoutMs, limits.runTimeoutMsParallel 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.judgeFact-check findings against the diff, and merge, filter and recalibrate them across reviewers (both default on)
limits.maxCostUsd, limits.maxTasksThe 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.fullReview every file although the platform reports what changed since the previous review
mode.ultraRecall over cost (Modes)
sarifParsed SARIF logs (parseSarifLog) whose results on the change join the review (SARIF input)
signalAn AbortSignal: the run stops, keeps what it found and writes a partial report
onEventReceives each ReviewEvent as the run progresses
identity.runIdNames 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)
resumeA 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, typed ReportOutput and validated by reportOutputSchema (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_concerns nobody overrode. Gate on these as the CLI's exit codes do, never on verdict alone. For the details, coverageGaps(report) gives how many selected files were not reviewed, whether nothing was, and in incomplete how many were partly reviewed, by how their task ended (step_cap, stopped_early); report.unverifiedCriticals counts 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.

CodeMeaning
CONFIG_INVALIDConfiguration 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_MISSINGA token or model key the run needs is not set
INPUT_USAGEA command line ocra cannot run (the CLI's usage errors)
INPUT_INVALIDInput given to ocra that it cannot read, such as a SARIF log or a list of commit ids
ACCESS_DENIEDThe access policy refused a path: a secret, git internals, a symbolic link where ocra writes
PLUGIN_INVALIDA plugin that cannot be loaded or registers something twice or after start, or a name no plugin registered
VCS_GIT_FAILEDA git command failed
VCS_API_FAILEDThe GitHub or GitLab API failed or answered something unexpected; GitHubApiError and GitLabApiError carry the HTTP status
VCS_REF_UNKNOWNA commit or ref that is not in the repository and could not be fetched
VCS_NOT_READYThe platform has not prepared the change yet, such as a merge request without a diff; try again shortly
CLOUD_API_FAILEDThe CLI could not reach ocra Cloud for ocra login or ocra whoami, or ocra Cloud answered something it cannot use
RUNTIME_START_FAILEDThe agent runtime could not start (no OpenCode binary, a server that did not come up)
RUNTIME_FAILEDA model call failed on every model of its chain (CompletionError, which carries the usage the attempts spent)
RUNTIME_INVALID_OUTPUTA model answered something that does not match the expected schema
BUDGET_EXHAUSTEDThe spend limit was reached (SpendLimitReached, the reason running tasks were stopped)
INTERNALA 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() and ReviewOptions; what it returns (ReviewReport, Finding and the types they are made of), coverageGaps(), isIncompleteReview(), isBlocking(), toReportOutput() with ReportOutput, reportOutputSchema, reportJsonSchema() and REPORT_VERSION; parseSarifLog(); the plugin interface (OcraPlugin and its contexts, startPlugins(), PluginRegistry, the built-in reviewer plugins and sessionJsonlPlugin); the contracts a plugin implements (VcsAdapter, AgentRuntime and the types they use, ToolDefinition, ReviewerDefinition, RepoRule); what a runtime builds on (ChainRunner with ModelAttempts, 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, LocalGitOptions and GitError. vcs-github and vcs-gitlab: githubPlugin and gitlabPlugin, resolveGitHubTarget and resolveGitLabTarget with GitHubSettings and GitLabSettings, and their API errors. runtime-opencode and runtime-direct: opencodeRuntimePlugin and directRuntimePlugin.
  • @open-cr-agent/cli: run(argv), the ocra command with its arguments (no node or script path), writing to stdout and stderr and resolving to the exit code.
  • @open-cr-agent/vcs-platform is 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.

Edit on GitHub

On this page