# How OvertCMS Works

> How OvertCMS Core separates Delivery, Agent, Admin, and Worker planes over a single authoritative Core Engine, supporting both single-node and split-listener topologies.

OvertCMS Core is engineered around **strict plane isolation over one authoritative domain engine**. Every API surface is separated by trust boundary, authentication model, caching behavior, and scaling profile, while sharing a single Go domain layer (`core.Engine`) so invariants can never drift between planes.

## The Four Planes

```mermaid
flowchart TB
    subgraph Internet["Public Edge / CDN"]
        FE["Client (Web / Mobile / SSG / Service)"]
    end
    subgraph Automation["Agent & MCP Network"]
        AI["AI Agents / MCP Clients / CI"]
    end
    subgraph Internal["Private Editorial Network"]
        AdminUI["Admin UI / Human Operators"]
    end

    subgraph Runtime["OvertCMS Core Process(es)"]
        D["Delivery Plane\nRead-Only • Surrogate-Key • L2 Cache"]
        AG["Agent Plane\nScoped API Keys • MCP • Idempotency"]
        AD["Admin Plane\nHuman JWT/Cookie • RBAC • Step-Up MFA"]
        W["Worker Plane\nDistributed Leases • Scheduler • Outbox"]
        E["core.Engine"]
    end

    FE --> D
    AI --> AG
    AdminUI --> AD
    D --> E
    AG --> E
    AD --> E
    W --> E
```

### 1. Delivery Plane (`delivery`)

- **Mount prefix**: `/delivery/v1/*`
- **Role**: High-throughput, strictly read-only public content and media delivery.
- **Data boundary**: Reads **only** `publishedData` (unless a single-entry, time-limited `X-Preview-Token` is presented, which bypasses all caches and returns `draftData`). Internal metadata, AI instructions, and unpublished drafts are never exposed.
- **Auth**: Public by default. Set `OVERTCMS_DELIVERY_REQUIRE_API_KEY=true` to require a Bearer API key with the `delivery:read` scope (which switches responses to `Cache-Control: private, max-age=60` with `Vary: Authorization` and suppresses `Surrogate-Key` headers).
- **Performance**: Backed by an L2 tag-versioned cache (in-memory LRU or Redis/Valkey), conditional `ETag` / `If-None-Match` (`304 Not Modified`), and CDN `Surrogate-Key` headers.

### 2. Agent Plane (`agent`)

- **Mount prefix**: `/.well-known/agent-cms.json`, `/llms.txt`, `/agent/v1/*`, `/mcp`
- **Role**: Purpose-built programmatic and AI-agent interface with schema discovery, tailored system prompt generation, site settings & SEO/AEO visibility management, native 14-tool Streamable HTTP MCP, batch mutations, and dry-run validation.
- **Strict credential boundary**: Accepts **only** scoped Bearer API keys (`ocms_live_...` or `ocms_test_...`). Human Access JWTs and browser cookies (`overtcms_access`) are unconditionally rejected—even if `OVERTCMS_AUTH_REQUIRED=false`.
- **No privilege escalation**: The Agent Plane contains zero user login, role management, or API key issuance routes.
- **Safety guardrails**: Enforces per-key presets/scopes, per-post-type read/write allowlists, CIDR IP allowlists, RPM and daily write/media quotas, `If-Schema-Fingerprint` drift checks, `Idempotency-Key` deduplication, and the site-level `agentWritesPaused` kill switch.

### 3. Admin Plane (`admin`)

- **Mount prefix**: `/admin-api/v1/*`
- **Role**: Full human editorial, schema governance, team management, API key issuance, webhook configuration, and audit log inspection API.
- **Strict credential boundary**: Accepts **only** human Access JWTs (`Authorization: Bearer <jwt>`) or `HttpOnly` `SameSite=Lax` cookies (`overtcms_access`) with CSRF `Origin` + `Sec-Fetch-Site` enforcement on mutating methods. API keys (`ocms_...`) are unconditionally rejected.
- **Access control**: Enforces 5-role RBAC (`owner`, `admin`, `editor`, `writer`, `viewer`), writer ownership (`entry:edit_own` vs `entry:edit_all`), per-user `allowedPostTypes`, organization MFA policy, and fresh Step-Up MFA for high-risk actions.

### 4. Worker Plane (`worker`)

- **Mount prefix**: None (background polling loop; no HTTP listener required)
- **Role**: Executes asynchronous and scheduled background tasks safely across multi-node clusters using distributed mutual-exclusion leases in `worker_leases`.
- **Three leased jobs per tick** (default interval `5s`):
  1. `worker:scheduler` — Auto-publishes due scheduled entries (`scheduled_at <= now`), auto-unpublishes due entries (`unpublish_at <= now`), and cleans up expired ephemeral media and stale `pending_upload` intents.
  2. `worker:outbox_fanout` — Invalidates L2 delivery cache tags, fires optional CDN `Surrogate-Key` purge webhooks, and enqueues matching outbound webhook deliveries.
  3. `worker:webhook_delivery` — Delivers HMAC-SHA-256 signed webhooks with SSRF protection, exponential retry backoff, and Dead-Letter Queue (`dead_letter`) transitions after 5 attempts.

---

## Deployment Topologies

OvertCMS Core adapts from a single binary on a laptop to an air-gapped multi-plane production cluster using only `OVERTCMS_PLANES` and bind flags.

<Tabs>
  <Tab title="Single-Node Combined (Default)">
    All four planes run inside one process on `:8080` backed by SQLite and local disk storage.

    ```bash
    overtcms serve \
      --planes=delivery,agent,admin,worker \
      --bind=:8080
    ```
  </Tab>

  <Tab title="Split-Listener Process (Network Isolation)">
    One binary binds three isolated TCP listeners so your reverse proxy or firewall can expose Delivery publicly while restricting Agent and Admin to private VPC subnets or VPNs.

    ```bash
    overtcms serve \
      --planes=delivery,agent,admin,worker \
      --delivery-bind=0.0.0.0:8081 \
      --agent-bind=10.0.1.10:8082 \
      --admin-bind=10.0.1.10:8083
    ```

    Each dedicated listener mounts **only** its own plane routes plus `/healthz` and `/readyz`. Requesting `/admin-api/v1/*` on the Delivery port returns `404 not_found`.
  </Tab>

  <Tab title="Horizontally Scaled Micro-Fleet">
    Run separate stateless container deployments per plane sharing PostgreSQL, S3/R2, and Redis/Valkey:

    ```bash
    # Public Delivery fleet (autoscale to N replicas behind CDN)
    overtcms serve --planes=delivery --bind=:8080 --db-driver=postgres --redis-url="$REDIS_URL"

    # Private Agent & MCP fleet
    overtcms serve --planes=agent --bind=:8080 --db-driver=postgres --redis-url="$REDIS_URL"

    # Private Admin fleet
    overtcms serve --planes=admin --bind=:8080 --db-driver=postgres --redis-url="$REDIS_URL"

    # Dedicated Worker fleet (2+ replicas for HA; worker_leases ensures mutual exclusion)
    overtcms serve --planes=worker --db-driver=postgres --redis-url="$REDIS_URL"
    ```
  </Tab>
</Tabs>

## Shared Middleware & Health Endpoints

Every HTTP listener (whether combined or isolated) installs the same foundational middleware stack:

1. **`X-Request-ID`**: Preserves a safe caller-provided `X-Request-ID` (printable ASCII, `<= 128` chars) or generates a UUID, echoes it on the response, and logs it on every request.
2. **Request metadata propagation**: Captures client IP (`RemoteAddr`), `User-Agent`, and `Idempotency-Key` into request context for automatic audit logging.
3. **Structured `slog` logging**: Emits `http_request` logs with `plane`, `method`, `path`, `status`, `bytes`, `duration_ms`, `request_id`, and `remote_addr`.
4. **Panic recovery**: Catches handler panics, logs stack traces, and responds with a canonical `500 internal_error` JSON envelope.
5. **Strict JSON decoding**: Control-plane bodies are bounded to **1 MiB** (`MaxJSONBodyBytes`), disallow unknown fields, preserve exact JSON number precision (`UseNumber`), and reject trailing payloads.

### Liveness & Readiness Probes

- `GET /healthz` — Returns `200 OK` with current `status`, `database` (`ok` or `unavailable`), `driver`, active `planes`, and `version`.
- `GET /readyz` — Pings the database with a 2-second timeout. Returns `200 OK` (`status: "ready"`) when healthy, or `503 service_unavailable` when the database is unreachable.

## Multi-Tenancy Model

OvertCMS Core organizes data in a two-level hierarchy:

- **Organization**: Top-level tenant owning human users, team invitations, audit logs, and organization-wide MFA policy (`optional`, `required_for_publishers_and_admins`, or `required_for_all`).
- **Site**: Belongs to an organization and owns its own `locales`, `defaultLocale`, `baseUrl`, `timezone`, site-level `instruction`, `agentWritesPaused` kill switch, Components, PostTypes, Entries, MediaAssets, APIKeys, Webhooks, and Redirects.

All database primary keys use **time-ordered UUIDv7** (`domain.NewID()`), giving B-tree index locality and natural chronological ordering without sequential integer leakage.
