---
title: "Kodema architecture: Kernel, Shell and Userland"
description: "How Kodema is built: a Kernel that runs ordered executions, a Shell that authorizes and records, Userland services, PostgreSQL, NATS and container runtimes."
canonical_url: https://optimi.com/en/docs/kodema/architecture
md_url: https://optimi.com/en/docs/kodema/architecture.md
language: en
alternates:
  - lang: fr
    url: https://optimi.com/fr/docs/kodema/architecture
    md_url: https://optimi.com/fr/docs/kodema/architecture.md
last_updated: 2026-11-14
---

# Architecture

Kodema is one Go module organized in three layers. **The Kernel executes. The
Shell coordinates and authorizes. Userland performs the work.**

| Layer | Responsibilities |
| --- | --- |
| **Kernel** | Executions, the lifecycles of container and request actions, the shared workspace, cancellation, action deadlines, recovery, logs and outputs |
| **Shell** | The control plane: tenants, projects, identity, authorization and verification, resource bindings, pipelines, tasks, the inbox, secrets, service accounts, persistence, events, push triggers, and one operation router with a REST edge and an MCP edge |
| **Userland** | The actual work and integrations: pipeline definitions, images, scripts, delivery recipes, adapters, the optional Git service, agents |

Dependencies point inwards: Userland depends on the Shell’s public contracts,
and the Shell on the Kernel. The Kernel knows nothing about tasks, roles, Git,
HTTP, SQL, NATS or agents. Userland services use the public API and scoped
events, never Shell internals, and only the Shell reads the database.

**One control plane, three layers**

![kodactl, REST and MCP clients and Userland services call the Shell inside the kodema server. The Shell drives the Kernel, stores state in PostgreSQL and publishes to NATS JetStream. The Kernel starts, observes and stops workloads on Podman or Kubernetes, and workloads call the Shell back with an execution token.](/diagrams/kodema/architecture-en.svg)

*The Kernel advances executions; PostgreSQL records facts; NATS distributes activity; the Shell authorizes operations and connects them.*

## What runs

| Process | Role |
| --- | --- |
| `kodema server` | The Shell and the Kernel in one process: the API, MCP, the controller loops, and the optional model gateway and MCP proxy |
| PostgreSQL | State, operation receipts, audit, the event table and the encrypted secrets |
| NATS JetStream | Distribution of events and live logs to services and clients |
| A container runtime | Podman on a single host, Kubernetes Jobs in production. One workload per container action |
| `kodema git serve` (optional) | The Git companion: smart HTTP, hooks, access rules, storage |
| `kodema services` (optional) | Service adapters: email, webhook, timer, responder |
| An OIDC provider | Your own in production. `kodema up` runs the built-in one, `kodema auth serve` |

The control plane runs as a single replica. Projects can run without Git, the
gateways or agents.

## Who owns which fact

| Owner | Facts |
| --- | --- |
| PostgreSQL | Tenants, projects, memberships, pipelines, executions, actions, tasks, decisions, receipts, verification records, events, secret ciphertext |
| NATS | Delivery, not truth. JetStream delivers and replays events at least once; Core NATS carries live logs. Execution progress never depends on it |
| The Git service | Git objects, refs, access rules and its receive journal |
| Your registry | Image and artifact bytes. Kodema records digest references |
| The key provider | The key that wraps the installation’s encryption key: a local keyfile in test, one cloud KMS in production |

A domain change commits its state, its audit record and its event in one
transaction. The event table is the durable stream; publication to NATS is
retried with the same event IDs. When NATS is down, execution progress, request
answers, push triggers, dispatch and deadlines continue from PostgreSQL, and a
publication backlog builds up visibly.

## The life of an execution

1. **Admission.** The Shell authenticates the caller, authorizes the start,
   validates the YAML, resolves images to digests and resolves timeouts. One
   transaction writes the queued execution, its actions, the receipt and the
   events. The queued execution is the dispatch record.
2. **Activation.** For a container action, the deadline is persisted, then one
   preparation step writes the read-only files under `/kodema`, attaches
   `/workspace`, resolves the declared secrets and issues the execution token.
   A preparation failure prevents the start.
3. **Run.** The runtime starts the image with a fail-fast script in place of
   its entrypoint. It supplies the exit status and the logs; the controller
   owns scheduling, cancellation and deadlines.
4. **Settlement.** Exit code zero succeeds the action and promotes its staged
   outputs. The Kernel then activates the next action.
5. **Request.** After the previous workload is confirmed stopped, the subject
   is resolved and persisted, the execution token is revoked, and the request
   becomes answerable. An authorized answer settles it; the Kernel never
   interprets roles.
6. **End and cleanup.** The terminal outcome never changes. Cleanup of the
   workload and the workspace is tracked separately, with its attempts and its
   last error.

### Recovery rules

- Before an effect the controller manages, it persists the intent and a stable
  resource identity. After a crash it observes and reconciles that workload.
- A launch is retried automatically only with evidence that the command never
  ran. An unknown outcome is never replayed blindly.
- Handing a workspace to the next action, activating a request and dispatching
  a replacement execution all wait for a **confirmed stop**. An expired lease
  or a deleted Kubernetes object is not enough.
- A lost workspace fails the execution visibly. It is never recreated.

## Identity and credentials

People authenticate through an external OAuth/OIDC provider. The Shell
validates the issuer, the signature, the audience and the expiry of the access
token, then resolves the current memberships on every call.

Workloads and services use bearer tokens the Shell derives with HMAC:

| Token | Principal | Lifetime |
| --- | --- | --- |
| `kodex.<execution-id>.<mac>` | A running execution | At most eight hours, bounded by the action’s deadline, and renewed in place during a long action |
| `kodsvc.<service-id>.<mac>` | A service account | An explicit expiry set at issuance; rotation replaces it at once |

Each tenant has one derivation key, stored encrypted. PostgreSQL stores neither
tokens nor token hashes, only a nonce and an expiry per principal.

- The execution token is cleared when a request starts waiting, on
  cancellation and at every terminal transition. A workload has **no authority
  during a request wait**.
- Rotating the tenant key invalidates every execution and service token of
  that tenant at once.
- All containers of an execution share its credential: the execution is the
  trust boundary.

## Authorization and verification

Every operation goes through one authorizer:

```text
Authorize(principal, operation, resource) → allow | deny
```

It is explicit code, not a policy language. Unknown operations, unknown
resources and invalid input are refused.

Services that own resources decide their own effects, and ask the Shell for
facts just before each one:

```text
POST /api/v1/verify
  actor      the credential presented to the service
  resource   a registered resource ID
  operation  the attempted effect and its subject
  approval   optional role/<role> the service’s rules require
→ principal, roles in the resource’s scope, approved, verification ID
```

Verification authenticates the calling service, checks that its binding covers
the resource and the operation, then verifies the actor separately. Approval
evidence is an earlier passed request **in the actor’s own execution**,
assigned to exactly that role, whose subject matches the operation, the
resource and every field the service supplied. Verification returns facts, not
decisions, and each one is recorded.

### A protected push, end to end

1. An execution pushes to `refs/heads/main` with its token.
2. The Git service’s `pre-receive` hook calls `verify` for every ref update of
   the push, asking for `approval: role/reviewer` because the rules say
   `option approve.refs/heads/main = reviewer`.
3. The Shell finds the passed review request of that execution with the same
   `ref`, `expected_base` and `candidate`, and answers `approved`.
4. Git applies the update atomically, only if the ref still equals the
   expected base, and journals it.
5. The service reports `git.ref.updated` with the verification ID. The Shell
   records the event; `on.push` pipelines react to it, except for pushes made
   by executions.

## Isolation

Tenant isolation applies to database records, execution, networking,
credentials, logs and events. PostgreSQL uses forced row-level security under a
runtime role that does not own the tables. On Kubernetes, each tenant has its
own namespace, resource limits and a default-deny network policy; workloads
reach Kodema, the configured Git service and what the installation’s policy
allows.

The trust model is **trusted project engineers running regular containers**.
Kodema makes no claim of isolation against hostile workloads.

## Environments

The environment is selected explicitly, and production refuses the development
and test adapters:

| Environment | State and messaging | Runtime | Keys |
| --- | --- | --- | --- |
| `development` | In memory | Host processes, for tests | Ephemeral |
| `test` | PostgreSQL and NATS | Podman or Kubernetes | Local keyfile |
| `production` | PostgreSQL (`sslmode=verify-full`) and NATS (`tls://`) | Kubernetes Jobs | One cloud KMS: AWS, GCP or Scaleway |

`kodema up` and the Podman bundle are `test` environments on one machine.

## Optional capabilities

- **Model gateway and streaming model proxy.** An OpenAI-compatible gateway
  with model allowlists and usage attribution, and a proxy for the native
  Anthropic and OpenAI protocols. Upstream credentials stay in the Shell.
- **MCP proxy.** Registered external MCP servers and allowed tools, called
  under the caller’s current authority.
- **Agents.** External harnesses run as container commands. The native
  `kodema agent` runtime adds planning, review, Git operations and Markdown
  skills. Both follow the same pipeline lifecycle and get no special
  permissions.

The detailed contracts are in the repository:
[KODEMA.md](https://github.com/optimiware/kodema/blob/master/KODEMA.md) and the
[specifications](https://github.com/optimiware/kodema/tree/master/docs/specs).

Next: **[Operations](/en/docs/kodema/operations)**.
