> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kernite.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Introduction

> What Kernite is and why it exists.

## Overviews

### Introduction

Kernite is a policy engine to make your APIs LLM-ready.

It scans API schema, generates policies, and returns reproducible decision contracts with AI-operable reasons.

Unlike other general policy engines such as Casbin/OPA/Cedar, Kernite is purpose-built for making APIs policy-enforceable and ready for programmatic remediation with AI agents.

### Why Kernite

* Fast-to-enforce: scan API schema, generates policies, and apply them to endpoints in 60 seconds.
* Reason by Design: decision reasons are structured for programmatic remediation, not on    ly human logs.
* Contract-First: `decision`, `reason_codes`, `reasons`, `trace_hash` are required integration surfaces.
* Reproducible tracing: canonical input and policy context produce deterministic `trace_hash` output.
* Zero overhead: no runtime dependencies (`dependencies = []`).
* DSL not required: enforce your policy without learning a new language.
* Practical: `kernite check` for reviewing write-mutation, `observe` mode for collecting evidence before enforcement, and more.

### When should I use this?

Use Kernite if:

* Your API surface is large and you want policy coverage visibility from OpenAPI.
* You want machine-operable deny reasons for automated remediation and retry.
* You need deterministic evidence (`trace_hash`) that you can persist and replay.

Use Casbin/OPA/Cedar if:

* You want a mature policy language ecosystem with centralized governance tooling.
* You already have an established policy pipeline and need a dedicated PDP.

## Use Cases

* AI-assisted actions: gate tool calls and use `reason_codes` for automatic retry/remediation.
* Internal APIs: apply one deterministic write guard across UI/API/workers.
* SaaS multi-tenant systems: enforce tenant-scoped write decisions and persist evidence.

### Comparisons with other policy engines

| Topic                 | Kernite                                                                                     | Casbin/OPA/Cedar                                                                                                                 |
| --------------------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Primary goal          | Policy-gate APIs for AI operations and remediations (fix-and-retry with `reason_codes`).    | Human-authored policy enforcement and policy-language tooling.                                                                   |
| Decision contract     | Required structured contract (`decision`, `reason_codes`, `reasons`, `trace_hash`).         | Explanations exist, but the remediation contract is not standardized across integrations (codes/reasons/evidence vary by setup). |
| Reproducible evidence | Built-in deterministic evidence surface (`trace_hash`) plus conformance vectors for replay. | Strong policy engines; replay determinism depends on integration and policy/data pipeline discipline.                            |

While Casbin/OPA/Cedar/others are strong options for centralized policy-language workflows, **Kernite is purpose-built for app-embedded, machine-operable, write-path enforcement with a stable response contract.**

### Non-goals

* A general-purpose policy language / DSL runtime.
* Proxying or routing traffic (Kernite returns decisions; your app performs the write).
* Replacing your domain logic. Kernite decides and explains; your app enforces.

## Quickstart

### Install Kernite

First install kernite using UV:

```bash theme={null}
uv tool install kernite
```

### #1 Scan API schema

Start from your API project repo and run a Kernite scan. We'll use this repo in this Quickstart: `https://github.com/fastapi/full-stack-fastapi-template`

```bash theme={null}
git clone https://github.com/fastapi/full-stack-fastapi-template.git
cd full-stack-fastapi-template/backend
uv sync
```

Export OpenAPI schema (JSON) from the app code:

```bash theme={null}
mkdir -p .kernite
uv run python - <<'PY'
import json
from pathlib import Path
from app.main import app

Path(".kernite/openapi.json").write_text(
    json.dumps(app.openapi(), indent=2),
    encoding="utf-8",
)
PY
```

Run strict scan and write a machine-readable report:

```bash theme={null}
kernite check \
  --schema .kernite/openapi.json \
  --report-out .kernite/kernite-check.strict.json || true
```

Inspect what needs to be addressed:

```bash theme={null}
jq '.summary' .kernite/kernite-check.strict.json
jq '.violations[:10] | map({code, method, path, field})' .kernite/kernite-check.strict.json
```

From a real run on the template above (as of 2026-02-23), strict scan reported:

* `write_operations = 17`
* `violations = 34`
* top remediation codes: `missing_x_kernite`, `missing_policy_key`

This is the intended first checkpoint for large API surfaces: identify uncovered write operations before you enforce.

### #2 Generate Policy

Input format for v1 is OpenAPI **JSON only**.
YAML files are intentionally rejected with conversion guidance to keep the core runtime dependency-free.

Generate bundle + mapping + report:

```bash theme={null}
kernite policy generate \
  --schema ./.kernite/openapi.json \
  --out-dir ./.kernite
```

Generated artifacts:

* `policy-bundle.generated.json`
* `policy-map.generated.json`
* `policy-generation-report.json`

Check coverage (strict by default):

```bash theme={null}
kernite check \
  --schema ./.kernite/openapi.json \
  --mapping ./.kernite/policy-map.generated.json \
  --bundle ./.kernite/policy-bundle.generated.json \
  --report-out ./kernite-check-report.json
```

Exit codes:

* `0` valid coverage
* `1` coverage violations (strict)
* `2` input/parse errors

For CI gating patterns (PR checks, artifacts, strict/non-strict rollout), see `/integrations/ci-cd-policy-check`.

### #3 Implement Endpoint Using Generated Policy

After generation, wire your endpoint to `policy-map.generated.json` + `policy-bundle.generated.json`.
This avoids manual policy selection per route.

```python theme={null}
import json
from pathlib import Path

from kernite import evaluate_execute_controlled

POLICY_DIR = Path(".kernite")
bundle = json.loads((POLICY_DIR / "policy-bundle.generated.json").read_text(encoding="utf-8"))
mapping = json.loads((POLICY_DIR / "policy-map.generated.json").read_text(encoding="utf-8"))

policies = {p["policy_key"]: p for p in bundle.get("policies", [])}
operations = {(o["method"].upper(), o["path"]): o for o in mapping.get("operations", [])}


def evaluate_for_endpoint(*, method: str, path: str, principal_id: str, payload: dict):
    op = operations.get((method.upper(), path))
    if op is None:
        return {"allow_write": True, "governance": None}

    policy_key = op.get("policy_key")
    selected_policies = [policies[policy_key]] if policy_key in policies else []

    request_body = {
        "workspace_id": "workspace-demo",
        "principal": {"type": "token", "id": principal_id},
        "object_type": op["object_type"],
        "operation": op["operation"],
        "payload": payload,
        "policy_context": {
            "governed": bool(op.get("governed", False)),
            "selected_policies": selected_policies,
            "governed_scopes": bundle.get("governed_scopes", []),
            "policy_selection_reason_code": "policy_selected_workspace_default",
        },
    }

    return evaluate_execute_controlled(request_body, mode="observe")
```

Endpoint usage (FastAPI-style):

```python theme={null}
governance = evaluate_for_endpoint(
    method="POST",
    path="/api/v1/users/signup",
    principal_id=f"public:{user_in.email}",
    payload=user_in.model_dump(exclude_none=True),
)
if not governance["allow_write"]:
    raise HTTPException(status_code=403, detail=governance["governance"]["data"])
```

### #4 Observe Logs, Then Enforce

Start in observe mode:

```bash theme={null}
export KERNITE_MODE=observe
export KERNITE_SINK=jsonl
export KERNITE_SINK_PATH=./.kernite/decision-events.jsonl
```

After reviewing denies and remediation paths, switch to:

```bash theme={null}
export KERNITE_MODE=enforce
```

## Reference Docs

* Execute request/response examples and `policy_context`: `/api/execute`
* Runtime modes (`enforce`/`observe`/`skip`) and sink env vars: `/integrations/observe-mode`
* FastAPI write guard integration: `/integrations/fastapi-guard`
* Production hardening and persistence notes: `/integrations/persistence`
* Contract invariants and compatibility guarantees: `/concepts/compatibility`
* Policy authoring guide (PARC model): `/concepts/how-to-write-policy`

## Compatibility and Conformance

* Contract policy: `/concepts/compatibility`
* Conformance vectors: `/conformance/execute-vectors`
* Reason code semantics: `/conformance/reason-codes`

## Performance Check

Kernite includes a dependency-free benchmark harness.

```bash theme={null}
uv run python benchmarks/benchmark_execute.py --iterations 20000
```

This gives p50/p95 latency and throughput from your actual environment so language/runtime decisions are based on measured data.

Latest measured snapshot is tracked in `/concepts/performance`.
