# AI Runtime — public contract

This is the authoritative statement of what the Runtime **guarantees**. Anything not stated here is an
implementation detail and may change within a minor release. Behavioural narratives live in the
[handbook](handbook/00-index.md); this file is the contract a consumer may rely on. Frozen invariants and
the enum members named below are pinned by tests (`tests/unit/one-router-invariant.test.ts`,
`tests/unit/contract-surface.test.ts`) — a silent change fails CI.

## 1. Frozen invariants

- **One router.** All model selection happens in exactly one router (`src/core/router`), constructed in
  exactly one place (`src/plugin/ai.ts`). `Runtime.run()` calls `AI.run()`; the Runtime never scores or
  selects, and there is no second selection engine. *(Guarded structurally.)*
- **`RuntimeContext` is the state container** and **`ExecutionPolicy` is the sole authority.** Permissions
  are resolved once per run and only ever narrow; untrusted content (repo/web/tool/MCP/model output) is
  data, never authority.
- **An agent is a bounded PlanStep** — its catalog, permissions, call/tool/time budgets are a ceiling it
  cannot exceed; there is no unbounded recursive agent execution.
- **MCP is an ordinary tool** routed through the same permission/approval/redaction path as any tool — not
  a second execution path.
- **Finding admission is ordered**: extract → output-contract validation → Finding validation → persist. A
  rejected finding is never threaded.

## 2. Result & status

`Runtime.run()` returns a normalized `RuntimeResult`. Two distinct fields:

- **`ok`** — did the Runtime *operation* succeed (no internal/router error)?
- **`status: RuntimeStatus`** — the *task* state.

| `status` | `ok` | meaning | terminal? |
|---|---|---|---|
| `completed` | `true` | the task finished | yes |
| `waiting_for_clarification` | `true` | the run needs an answer to proceed (not a failure) | resumable |
| `waiting_for_approval` | `true` | an execution step needs approval | resumable |
| `waiting_for_budget` | `true` | the plan exceeded the call/cost budget and paused | resumable |
| `failed` | `false` | the operation failed | yes |

A wait is **not** a failure: `ok` is `true` for `completed` and every `waiting_*`; `ok` is `false` only for
`failed`. This matrix is pinned by `tests/unit/contract-surface.test.ts`.

## 3. Error model

Errors are typed and branchable without string matching. Each enum is exhaustively pinned.

- **`ErrorCategory`** (`AIError.category`, 17 members) — the router/provider taxonomy: `AUTHENTICATION`,
  `AUTHORIZATION`, `RATE_LIMIT`, `QUOTA`, `MODEL_NOT_FOUND`, `CAPABILITY`, `INVALID_REQUEST`, `TIMEOUT`,
  `NETWORK`, `PROVIDER`, `RESPONSE_VALIDATION`, `BUDGET`, `PRIVACY_VIOLATION`, `NO_CAPABLE_PROVIDER`,
  `ALL_PROVIDERS_FAILED`, `CONFIG`, `UNKNOWN`. `AIError.retryable` says whether a retry could help.
  *Note:* `PRIVACY_VIOLATION` is reserved; a privacy denial today surfaces as a filter exclusion that
  yields `NO_CAPABLE_PROVIDER`, not a thrown `PRIVACY_VIOLATION`.
- **`ToolErrorCode`** (`ToolResult.error.code`, 7): `PERMISSION`, `JAILBREAK`, `INVALID_INPUT`, `NOT_FOUND`,
  `EXEC_FAILED`, `TIMEOUT`, `ABORTED`. A denial is always a structured result, never a thrown string.
- **`StepObservationCode`** (orchestration, 8): `cancelled`, `agent-failed`, `agent-timeout`,
  `agent-call-budget`, `agent-tool-budget`, `finding-contract`, `agent-not-enabled`, `agent-waiting`.
- **`StoreDecryptCode`** (3): `AUTH_FAILED` (wrong key **or** tampering **or** corruption — never a
  certainty of any one), `UNSUPPORTED_VERSION`, `CORRUPT`.
- **`HealthState`** — see §6. **`FinishReason`** (`stop`/`length`/`tool_calls`/`content_filter`/`error`).

**CLI:** `--json` prints the whole `RuntimeResult` (so `error.category` is machine-readable); a failed run
exits non-zero (`1`). Exit codes are binary (0 = ok, 1 = not-ok), not per-category.

## 4. Cancellation

Cancellation is best-effort and cooperative, at every boundary:

- **Caller** — pass `signal` on `RuntimeRunInput` / `RunRequest`. Aborting it aborts the in-flight model
  HTTP call (combined with the per-request timeout) and stops fallback from starting a further attempt.
- **Runtime** — `cancelExecution(id)` sets a persisted execution to `cancelled` and aborts its in-flight
  agent work; `pauseExecution(id)` pauses it. Terminal executions are refused.
- **Tool** — `ToolContext.signal`; the shell tool kills the whole **process group** (not just the direct
  child).
- **MCP** — an http call aborts the request (caller signal combined with the timeout); a stdio server is
  SIGTERM→SIGKILL'd on close.

**Terminal stickiness:** a `completed`/`failed`/`cancelled` execution (or agent task) can never be
re-driven to running — a late write from an aborted worker cannot reopen it. There is **no** `cancelled`
`RuntimeStatus`; a cancelled *execution* surfaces to a caller as `ok:false` / `status:failed` with the
execution record carrying `status:'cancelled'`.

## 5. Idempotency & resume

- **`requestId`** dedupes on the persisted orchestration path: a repeated `requestId` returns the existing
  execution's state and never re-plans or re-executes. (Chat/compare/dry-run are not persisted and not
  deduped.) The id triad is `requestId` (caller identity) / `runId` (one `run()` call) / `executionId` (one
  persisted execution).
- **Resume** reconciles then continues (completed steps are skipped) or replans on drift; the approval gate
  is preserved across resume.
- **At-least-once, not exactly-once.** A step interrupted *after* its side effect but *before* its success
  commit **will run again** on resume. Exactly-once is **not** guaranteed — side-effecting tools must be
  idempotent.
- **The lease is best-effort** (a heartbeat + ownership token, not a hard OS mutex). It recovers a
  dead owner's execution after the lease expires; it does not guarantee mutual exclusion against a
  wall-clock-frozen peer.

## 6. Provider lifecycle & availability

A provider/model moves through `HealthState` (12, pinned): `NOT_CONFIGURED`, `CONFIGURED`, `AVAILABLE`,
`DEGRADED`, `RATE_LIMITED`, `QUOTA_EXCEEDED`, `AUTH_FAILED`, `NETWORK_ERROR`, `MODEL_UNAVAILABLE`,
`CAPABILITY_MISMATCH`, `DISABLED`, `UNKNOWN`. The router skips a non-routable provider and records the
reason in `RoutingReport.filteredOut`. A `RATE_LIMITED`/`QUOTA_EXCEEDED` provider is put in a timed
cooldown and becomes routable again once it elapses (recomputed on read). `ProviderView.accessState`
(`deriveAccessState`) is the caller-facing projection; `AUTHENTICATED` is a declared value that the current
derivation does not emit (key-present collapses into `CONFIGURED`/`AVAILABLE`).

**3.0.1 routing knobs** (weightOverrides, qualityFloor, CapabilityRequirement.weight, minimumConfidence,
`models:'auto'`, always-on context-fit, multimodal estimation) are documented in
[router.md](router.md#301-routing-knobs).

## 7. Artifacts & evidence

`ArtifactStore.put` stores content with a **sha256 checksum** and `type`/`source`/`metadata`, returning an
`ArtifactRef` (`id`, `type`, `source`, `contentRef`, `checksum`, `size`, `metadata`). Retrieval is by id;
retention is opt-in (`AI_*_RETENTION_DAYS`, cleaned by `cleanup`). Evidence on a Finding is **typed**
(`FindingEvidence[]`), never a free string, and a finding with no evidence has confidence 0 — arbitrary
tool/agent output cannot silently become trusted evidence (§1 admission chain). *Current scope:* large tool
output is clamped, not automatically offloaded to an artifact; artifact provenance is the `source` string.

## 8. Observability

Every `RuntimeEvent` carries `runId`; agent events additionally carry `agentTaskId`/`agentId`/`stepId` and,
when the agent runs inside a persisted execution, `executionId`. The `Execution` record carries the
`runId` that created it — the durable join key from an event to its execution. Telemetry is **metadata
only and redacted**: no prompt text, no secret value ever reaches an event, a telemetry sink, an error
message, or the store (secret redaction covers telemetry/CLI; the finding clamp covers persisted findings).

## 9. Persisted-state compatibility (upgrade / downgrade)

- State is stamped with a store schema version (`meta.json`), and records are checksummed and written
  atomically (temp→rename).
- **Forward:** a record written by a **newer** store version fails closed on read — it is never
  reinterpreted as the current layout. A legacy record with no version is read as v1.
- **Backward (downgrade caveat):** encryption-at-rest uses the `aienc2` envelope; a pre-3.0.1 runtime
  cannot read `aienc2` records. Records upgrade lazily on rewrite; there is no bulk migration and no
  chmod-repair of pre-existing files (new files are created `0600`/`0700` on POSIX).

## 10. Security boundaries

Deny-by-default permissions; a filesystem jail (realpath-canonicalized, rejecting traversal / out-of-root
absolutes / symlink-junction-UNC escapes); a shell allowlist with an eval-capable escalation to approval;
env-scrubbed, timeout-bounded, process-group-killed command execution; untrusted content fenced; MCP schema
sanitized against prototype pollution; secrets named by env var only (never values) and redacted from every
egress. See [security.md](security.md) for the full model and its documented best-effort limits.

## 11. Execution groups & evaluation (3.2.0)

`executeGroup` runs N normalized `RunRequest` tasks as one bounded unit; `evaluate` judges a candidate
against a rubric with one model. Both are generic primitives — the Runtime knows no Council/role/verdict
semantics; those belong to the consuming product.

- **Own status unions, not `RuntimeStatus`.** An `ExecutionGroupResult` is NOT a `RuntimeResult`.
  `ExecutionGroupStatus` (`created|queued|running|completed|partial|failed|cancelled|timed_out`, 8) and
  `ExecutionGroupTaskStatus` (`pending|running|retrying|completed|failed|timed_out|cancelled`, 7) are NEW
  standalone unions. `RuntimeStatus` is unchanged at 5, and §4 still holds: there is no `cancelled`
  `RuntimeStatus`. A group's `cancelled`/`timed_out`/`partial` live on the group record/result only.
- **One router.** Every task executes through `AI.run()` — the same router, filters, budget and cancellation
  a single run uses. There is no second selection engine and no direct provider-SDK call. A group is never a
  weaker privilege boundary than one run: routing exclusions apply as a floor, budgets only tighten policy,
  and permissions/redaction are the single-run rules per task.
- **Partial failure never fails the group.** `quorumReached` is orthogonal to status. The Runtime signals
  quorum; the caller chooses (`onQuorum: 'continue' | 'cancel-remaining'`). A quorum cancel-remaining yields
  `completed` (the declared goal was met), never `cancelled`.
- **Cancellation** is best-effort and cooperative (the §4 model): group → per-task `AbortController` →
  `RunRequest.signal` → provider fetch; no new work starts after a cancel. An in-flight HTTP abort surfaces
  as a `TIMEOUT` error and may take the transport's retry/backoff to unwind, so a group derives
  `cancelled`/`timed_out` from its own state, never from the error category.
- **Resume** (the §5 model): completed tasks are never re-run; every non-successful task (failed, timed_out,
  cancelled, or interrupted mid-flight) re-runs. Resume binds a persisted task to its request by a content
  hash — a record whose stored request no longer matches is failed closed, never executed. At-least-once,
  not exactly-once: a task that succeeded but crashed before its terminal commit will run again. The lease is
  best-effort; `completed`/`cancelled` groups are sticky and resume returns their stored result unchanged.
- **Budgets & usage.** A group budget only ever tightens Runtime policy (env/config remain the ceiling).
  `UsageSummary` on the result is accounting, not a resume-blocking cap (a spent group is still resumable);
  in 3.2.0 it reports tokens and calls, not cost (cost is not observable above the router — the per-task
  `maxCostUsd` ceiling is enforced by the router's own tracker).
- **Observability.** Every `execution_group.*` event carries `runId` + `groupId` (and `taskId` on task
  arms) and is metadata-only — ids, counts, states, timings; never request, response, or rubric text.
- **`evaluate`** fences both the candidate and the rubric as untrusted data, demands a closed-set JSON
  verdict, clamps the model-authored reason, and degrades to `inconclusive` rather than throwing.
