# OvertCMS Docs > OvertCMS is an open-source, agent-native headless CMS written in Go featuring three isolated HTTP planes (Delivery, Agent + native 14-tool Streamable HTTP MCP, and Admin), strict schema contracts, SQLite/PostgreSQL parity, and built-in technical SEO & AEO. ## Quick Architecture Map - **Delivery Plane (`/delivery/v1/*`)**: Fast, read-only public content API, `/robots.txt`, `/sitemap.xml`, `/rss.xml`, `/llms.txt`, `/llms-full.txt`, and `/delivery/v1/visibility`. - **Agent Plane (`/agent/v1/*` & `POST /mcp`)**: Scoped API-key interface (`ocms_live_*` / `ocms_test_*`) with native 14-tool Streamable HTTP MCP (`2025-03-26`), schema management, site/visibility/redirect management, media uploads, batch writes, dry-run validation, and kill-switch protection. - **Admin Plane (`/admin-api/v1/*`)**: Human control plane for team RBAC, Passkeys/TOTP MFA, Step-Up MFA, OIDC SSO, API keys, kill switch, webhooks, and site backup/restore. - **Website**: https://overtcms.com | **Cloud Dashboard**: https://app.overtcms.com | **GitHub**: https://github.com/Weelkit --- # Welcome to OvertCMS URL: https://docs.overtcms.com/introduction > OvertCMS is a self-hosted, AI-native headless CMS built in pure Go—combining a clean editorial dashboard, fast public API, and safe MCP/Agent access in a single binary. **OvertCMS** is a self-hosted headless CMS built for both **human editorial teams** and **AI agents** (Claude, Cursor, and custom workflows). It consists of two clean, modular pieces: - **OvertCMS Core** (`overt-cms-core`) — A single-binary Go server with zero runtime dependencies. Start immediately on embedded SQLite and local disk, or scale out with PostgreSQL, Cloudflare R2 / S3, Redis / Valkey, and SMTP. - **OvertCMS Admin** (`overt-cms-admin`) — The official editorial dashboard with a visual Schema Studio, Google Docs-style real-time collaboration, rich text & `` editing, media library, live Delivery API Explorer, and team/RBAC controls. --- ## Choose Your Path Start OvertCMS Core + Admin locally, create your owner account, define your first Content Model, and publish your first entry. Query published posts, expand references (`?expand=author`), render reading stats, and preview drafts from Next.js, Astro, or any client. Create a scoped AI Agent key, plug OvertCMS directly into Claude Desktop or Cursor via `/mcp`, and stay protected with drafts-only presets and an instant kill switch. Configure PostgreSQL, Cloudflare R2 / S3 storage, optional SMTP email, 2FA/Passkeys, SSO, Redis caching, and backups. --- ## How OvertCMS Separates Traffic (3 APIs + 1 Worker) Instead of mixing public website reads, AI automation, and human admin logins on one messy endpoint, OvertCMS separates every audience into its own isolated **plane** backed by one shared engine: | Plane | Route Prefix | Who Uses It | Auth & Trust Boundary | | :--- | :--- | :--- | :--- | | **Delivery** | `/delivery/v1/*` | Public websites, mobile apps, CDNs, clients | Read-only **published content** only. Public by default (or optional Client API key). | | **Agent** | `/agent/v1/*`, `/mcp`, `/llms.txt` | Claude, Cursor, CI/CD, AI agents | **Scoped API keys only** (`ocms_...`). Human logins are rejected; zero access to users, auth, or secrets. | | **Admin** | `/admin-api/v1/*` | Human editors, admins, Admin UI | **Human sessions only** (JWT/cookies + 5-role RBAC + 2FA/Passkeys/OIDC). API keys are rejected. | | **Worker** | Background process | Scheduled jobs & deliveries | Runs scheduled publish/unpublish, CDN purges, and signed webhook retries automatically. | --- ## Key Capabilities Build structured Collections, Singletons, and `` components with strict validation, safe schema changes, and visual version history. Edit entries simultaneously like Google Docs with live avatars, named cursors, server-enforced Viewer read-only mode, and live AI agent sync. Store media on local disk or any S3/R2 bucket with configurable upload limits, and optionally enable pure-Go SMTP for invites and security alerts. 5-role RBAC, Argon2id passwords, rotating refresh sessions, TOTP & Passkeys, OIDC SSO, Step-Up MFA, and immutable NDJSON audit logs. --- # Quickstart URL: https://docs.overtcms.com/quickstart > Run OvertCMS locally in under 5 minutes, create your owner account, build your first content model, and fetch published content. Get OvertCMS running locally in minutes—either with the **single Go binary (SQLite, zero setup)** or **Docker Compose (PostgreSQL + Valkey)**. ## Prerequisites - **Go 1.23+** (to run from source) or **Docker** with Compose v2. - **Node.js 20+** (optional, to run the visual **OvertCMS Admin** dashboard locally). --- ## 1. Start OvertCMS Core Build and start Core with a 32+ byte `OVERTCMS_SECRET_KEY`. Set `OVERTCMS_COOKIE_SECURE=false` for local plain-HTTP development: ```bash git clone https://github.com/Weelkit/overt-cms-core.git cd overt-cms-core go build -o overtcms ./cmd/overtcms export OVERTCMS_SECRET_KEY="$(openssl rand -hex 32)" export OVERTCMS_COOKIE_SECURE=false ./overtcms serve ``` Out of the box, `overtcms serve`: - Creates SQLite at `./.data/overtcms.db` and runs all database migrations automatically. - Bootstraps the default organization and site (`default`, locale `en`, timezone `UTC`). - Starts all four planes (`delivery,agent,admin,worker`) on `http://localhost:8080`. - Stores uploaded media in `./.data/media`. Start the production-like stack (**OvertCMS Core** + **PostgreSQL 16** + **Valkey 8**): ```bash git clone https://github.com/Weelkit/overt-cms-core.git cd overt-cms-core docker compose up --build ``` In production, always set a persistent `OVERTCMS_SECRET_KEY` (32+ bytes) so sessions, API keys, and encrypted secrets survive restarts. Confirm Core is ready: ```bash curl -s http://localhost:8080/readyz ``` --- ## 2. Create Your Account & First Post You can use either the **Admin UI** (recommended for day-to-day work) or pure **HTTP / `curl`**. ```bash git clone https://github.com/Weelkit/overt-cms-admin.git cd overt-cms-admin npm install OVERTCMS_API_URL=http://127.0.0.1:8080 npm run dev ``` Open **`http://localhost:5173`** in your browser. Create your initial **Owner** account (email, display name, password). Once created, first-time setup automatically locks permanently. Open **Models** in the sidebar and either click **Starter Templates** (e.g., Blog Posts + Authors) or click **New Model** to build a custom Collection or Singleton. Open **Content → Posts → New Post**, write your article in the visual editor, and click **Publish**. Open **Webhooks & Logs → API Explorer**, pick **List Collection Entries → Posts**, and click **Run Request** to see the exact JSON and cache headers your client will receive! ```bash ADMIN_TOKEN=$(curl -s -X POST http://localhost:8080/admin-api/v1/auth/setup \ -H "Content-Type: application/json" \ -d '{ "email": "owner@example.com", "password": "correct-horse-battery-staple", "displayName": "Site Owner" }' | jq -r '.accessToken') ``` ```bash curl -s -X POST http://localhost:8080/admin-api/v1/sites/default/post-types \ -H "Authorization: Bearer $ADMIN_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "slug": "posts", "singularName": "Post", "pluralName": "Posts", "kind": "collection", "instruction": "Write clear technical blog articles in active voice.", "urlTemplate": "/blog/{slug}", "displayField": "title", "slugSourceField": "title", "fields": [ { "key": "title", "label": "Title", "type": "string", "required": true, "requiredOn": "draft", "filterable": true, "sortable": true }, { "key": "slug", "label": "Slug", "type": "slug", "required": true, "requiredOn": "publish", "unique": true }, { "key": "body", "label": "Body", "type": "rich_html", "required": true, "requiredOn": "publish", "constraints": { "disallowH1": true } } ] }' | jq '{slug: .postType.slug, schemaVersion: .postType.schemaVersion}' ``` ```bash AGENT_KEY=$(curl -s -X POST http://localhost:8080/admin-api/v1/sites/default/api-keys \ -H "Authorization: Bearer $ADMIN_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "Blog Automation Agent", "preset": "agent_publisher", "allowedPostTypes": { "posts": "write" } }' | jq -r '.plaintextKey') curl -s -X POST http://localhost:8080/agent/v1/collections/posts/entries \ -H "Authorization: Bearer $AGENT_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: create-hello-overtcms-001" \ -d '{ "status": "published", "slug": "hello-overtcms", "data": { "title": "Hello OvertCMS", "slug": "hello-overtcms", "body": "

Welcome

Published cleanly through the Agent Plane.

" } }' | jq '{id: .entry.id, status: .entry.status, publicUrl: .entry.publicUrl}' ```
```bash curl -i -s "http://localhost:8080/delivery/v1/posts/hello-overtcms?include=wordCount,readingTime,headings" ```
--- ## Where to Go Next Learn how to query collections, expand references, and preview drafts from your client. Connect Claude Desktop, Cursor, or your own AI workflow via `/mcp` or REST. Switch media uploads from local disk to Cloudflare R2 or Amazon S3. Enable optional outbound email for team invites and security alerts. --- # How OvertCMS Works URL: https://docs.overtcms.com/concepts/architecture > 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 `) 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. 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 ``` 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`. 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" ``` ## 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. --- # Content Models & Blocks URL: https://docs.overtcms.com/concepts/schema-and-evolution > PostTypes, reusable Components, immutable field IDs, deterministic SHA-256 schema fingerprinting, breaking-change drift guards, and AI instruction coverage. OvertCMS Core treats content schemas as **versioned, cryptographically fingerprinted contracts**. Both human administrators and AI agents can inspect the exact schema contract, evolve it safely with automated breaking-change detection, and guard every write against silent schema drift. ## Schema Building Blocks ### PostTypes (`collection` and `singleton`) A **PostType** defines a content model on a site: - **`kind`**: Either `collection` (many entries, default) or `singleton` (at most one active non-trashed entry per locale). - **`slug`**: Must match `^[a-z][a-z0-9_-]{0,63}$`. Reserved system slugs (`site`, `redirects`, `media`, `singletons`, `sitemap`, `components`, `post-types`) are rejected with `reserved_post_type_slug`. - **`capabilities`**: Explicit feature flags (`draft`, `publish`, `schedule`, `delete`, `localize`). New PostTypes default to `draft: true`, `publish: true`, `schedule: true`, `delete: true`, `localize: false`. - **`urlTemplate`**: Optional path template such as `/blog/{slug}` or `/{locale}/docs/{slug}` used to compute `publicUrl` and automatic 301 redirects. - **`displayField`** & **`slugSourceField`**: Reference top-level field keys used for display labels and automatic slug derivation. - **`instruction`**: Up to **4,000 characters** of editorial guidance exposed to AI agents. - **`fields`**: Ordered slice of typed `FieldDefinition` items chosen from the [19 canonical field types](/fields/overview). ### Reusable Components A **Component** is a named, reusable group of fields that can be embedded in: - `object` fields via `constraints.componentRef` - `list` fields via `constraints.of.componentRef` or discriminated union `constraints.of.variants[].componentRef` - `rich_html` fields via `constraints.allowedComponents` and `` elements Components carry their own `instruction` (up to **2,000 characters**) and an `aiWritable` boolean flag (defaults to `true`). Setting `aiWritable: false` prevents API-key and MCP actors from inserting or modifying that component while still allowing human editors to manage it. ### Structural Guardrails & Limits | Rule | Limit / Pattern | | :--- | :--- | | PostType / Component slug | `^[a-z][a-z0-9_-]{0,63}$` | | Field key | `^[a-z][a-zA-Z0-9_]{0,63}$` | | Reserved field keys | `__proto__`, `constructor`, `prototype`, `id`, `status`, `_meta`, `version`, `etag`, `createdAt`, `updatedAt`, `publishedAt`, `scheduledAt`, `unpublishAt`, `locale`, `translationGroupId` (and `slug` is allowed **only** on `type: "slug"`) | | Max nesting depth (PostType) | **4** (`MaxPostTypeNestingDepth`) | | Max nesting depth (Component) | **2** (`MaxComponentNestingDepth`) | | Circular Component refs | Strictly rejected across direct and mutual cycles | | Custom regex `pattern` | RE2-only, max **256 bytes**, no nested bounded quantifiers, max **1,000** combined quantifier expansion | | Instruction lengths | Site: `8,000` runes • PostType: `4,000` runes • Component/Field/Variant: `2,000` runes • Field description: `500` runes | ### Immutable Field Identities (`fieldId`) Every `FieldDefinition`—including nested fields inside `object` and `list` schemas—is automatically assigned an immutable **UUIDv7** `fieldId`. When updating a PostType or Component, existing fields matched by `fieldId` (or `key`) retain their `fieldId`, while newly added fields receive fresh UUIDv7s. --- ## Deterministic SHA-256 Fingerprints OvertCMS Core computes a canonical structural fingerprint (`sha256:<64-hex>`) for every Component, PostType, and Site (`schemaFingerprint`), alongside a monotonically increasing integer `schemaVersion`. **Included in the fingerprint:** - All structural definitions: slugs, kinds, capabilities, `urlTemplate`, `displayField`, `slugSourceField`, field keys, field types, `required`/`requiredOn`, `writable`/`readOnly`/`aiWritable`, `filterable`/`sortable`/`unique`/`localized`, `deprecated`/`replacedBy`, `defaultValue`, all constraints, and recursively resolved definitions of any referenced Components. **Deliberately excluded from the fingerprint (cosmetic-only):** - Display labels (`label`, `singularName`, `pluralName`), `description`, `instruction`, `ui` authoring hints (`group`, `order`, `placeholder`, `width`), select option labels/instructions, variant labels/instructions, timestamps, internal IDs, and `schemaVersion`. This separation means editing an editorial prompt or reordering UI groups **never** invalidates client or agent schema fingerprints. --- ## Breaking-Change Drift Detection Every update to a Component or PostType runs `ClassifyComponentDrift` / `ClassifyPostTypeDrift`, partitioning all differences into `breakingChanges` and `nonBreakingChanges`. | Breaking Changes (require `confirmBreakingChange: true`) | Non-Breaking Changes (applied immediately) | | :--- | :--- | | Removing a PostType, Component, or field | Adding a PostType, Component, or optional field | | Changing a field's `type` or PostType `kind` | Adding a required field **with** a `defaultValue` | | Adding a required field **without** a `defaultValue` | Making a required field optional | | Making an optional field required, or tightening `requiredOn` (`publish` -> `draft`) | Relaxing `requiredOn` (`draft` -> `publish`) | | Disabling `writable`, enabling `readOnly`, or disabling `aiWritable` | Enabling `writable`, `aiWritable`, `filterable`, `sortable`, or `capabilities.*` | | Enabling `unique`, changing `localized`, or disabling `filterable` / `sortable` / `capabilities.*` | Removing `unique`, `pattern`, `disallowHtml`, `disallowH1`, or relaxing min/max bounds | | Tightening bounds (raising `min*`, lowering `max*`), removing allowed select options, reference targets, or HTML blocks/marks | Adding new select options, reference targets, allowed HTML blocks/marks, or `allowCustom` | | Changing `select.multiple` or `reference.multiple`, or tightening `integrity` (`weak` -> `strong`) or `strictness` (`sanitize` -> `strict`) | Deprecating a field (`deprecated: true`, `replacedBy: "newKey"`) | | Enabling `requireAlt`, `integer`, `disallowH1`, `disallowHtml`, or switching `lengthUnit` (`graphemes` -> `utf16`) | Updating `label`, `description`, `instruction`, `ui`, `urlTemplate`, `displayField`, or `slugSourceField` | ### Confirmation Flow for Breaking Changes When a schema update introduces any breaking change without `"confirmBreakingChange": true`, OvertCMS Core aborts the mutation and returns `409 Conflict` (`breaking_schema_change_confirmation_required`) with an impact report including `affectedEntriesCount`: ```json { "error": { "code": "breaking_schema_change_confirmation_required", "message": "updating post type \"posts\" introduces breaking schema changes; pass confirmBreakingChange: true to apply", "retryable": false, "applied": false, "details": { "breaking": true, "breakingChanges": [ { "field": "summary", "kind": "field_made_required", "breaking": true, "message": "field \"summary\" changed from optional to required", "oldValue": false, "newValue": true } ], "nonBreakingChanges": [], "affectedEntriesCount": 42, "confirmField": "confirmBreakingChange" } } } ``` Deleting a PostType with existing entries or deleting a Component still referenced by a PostType is similarly guarded. ### Schema Version History & `If-Schema-Fingerprint` Every structural schema change records an immutable snapshot in `post_type_schema_versions` and `site_schema_versions`. Callers (especially AI agents and CI pipelines) can pass their cached fingerprint on write requests via the `If-Schema-Fingerprint` header: ```mermaid flowchart LR Req["Write Request with\nIf-Schema-Fingerprint"] --> Check{"Compare against\ncurrent site schema"} Check -->|"Exact Match"| OK["Proceed cleanly"] Check -->|"Non-Breaking Gain Only"| Warn["Proceed + return\nX-Schema-Warning &\nX-Schema-Fingerprint"] Check -->|"Breaking Drift or Unknown"| Fail["409 schema_drift_detected\n(applied: false)"] ``` - **Exact match**: Proceeds transparently. - **Non-breaking drift only** (e.g., an optional field was added since the caller fetched the schema): Proceeds safely, attaches `X-Schema-Warning` and the latest `X-Schema-Fingerprint` response headers, and includes `schemaWarnings` in the response payload so the caller knows to refresh its cache. - **Breaking drift or unrecognized fingerprint**: Short-circuits with `409 schema_drift_detected` before touching the database. --- ## Safe Field Deprecation To evolve a field without breaking existing agents or clients: 1. Add the new field (e.g., `summary`) as optional or with a `defaultValue`. 2. Mark the old field (e.g., `excerpt`) with `"deprecated": true` and `"replacedBy": "summary"`. - Validation ensures `replacedBy` requires `deprecated: true`, cannot reference itself, must point to an existing field in the same field list, and cannot point to another deprecated field. 3. Marking a field `deprecated` is always classified as **non-breaking**. 4. Migrate entries, then remove the deprecated field in a confirmed breaking update once consumers have switched. ## AI Instruction Coverage Auditing Every `GET /agent/v1/schema` and Admin schema contract includes an `instructionCoverage` audit computed across the site, every Component, every PostType, every field (including nested object/list fields), and every list variant: ```json { "instructionCoverage": { "totalItems": 14, "documentedItems": 12, "undocumentedItems": 2, "coveragePercent": 85.71, "missingPaths": [ "components.callout.fields.tone", "postTypes.posts.fields.canonicalUrl" ] } } ``` Use `missingPaths` to close instruction gaps so AI agents produce publication-ready content on the first try. --- # Entries, Drafts & Publishing URL: https://docs.overtcms.com/concepts/entries-and-lifecycle > The 5-state entry lifecycle, dual draft/published snapshots, optimistic locking, explicit null/clear semantics, scheduling, version history, redirects, and draft previews. OvertCMS Core models every content item with a **pure 5-state lifecycle** and **dual-snapshot isolation** (`draftData` vs. `publishedData`), ensuring in-progress edits never leak to public visitors and concurrent editors never silently overwrite each other. ## The 5-State Entry Lifecycle Every entry is in exactly one of five canonical states: `draft`, `scheduled`, `published`, `archived`, or `trashed`. ```mermaid stateDiagram-v2 [*] --> draft: Create (default) [*] --> scheduled: Create (status=scheduled) [*] --> published: Create (status=published) draft --> scheduled: Schedule (scheduledAt > now + 30s) draft --> published: Publish draft --> archived: Archive draft --> trashed: Trash scheduled --> published: Worker Auto-Publish or Publish Now scheduled --> draft: Unpublish / Failed Auto-Publish Demotion scheduled --> archived: Archive scheduled --> trashed: Trash published --> published: PATCH (updates draftData ONLY) / Re-Publish (promotes draftData) published --> draft: Unpublish (confirmUnpublish=true) / Worker Auto-Unpublish published --> archived: Archive (confirmUnpublish=true) published --> trashed: Trash (confirmUnpublish=true) archived --> draft: Restore archived --> trashed: Trash trashed --> draft: Restore (checks slug & singleton uniqueness) trashed --> [*]: Purge (permanent delete, Admin) ``` ### Dual-Snapshot Isolation (`draftData` vs. `publishedData`) Every `Entry` stores two independent JSON snapshots: - **`draftData`**: Always holds the latest working copy. Updated by `PATCH`. - **`publishedData`**: Holds the live immutable snapshot served by the Delivery Plane. Populated or promoted **only** when `PublishEntry` runs (or on `CreateEntry` with `status: "published"`). When an entry is `published` and an editor or AI agent calls `PATCH`: 1. `draftData` is updated, `version` increments, and an immutable `EntryVersion` is recorded. 2. `publishedData`, `entry.slug`, and `entry.publicUrl` remain **strictly pinned** to the live published version—so public Delivery URLs and search/filter indexes (`entry_field_index`) never leak unfinished edits. 3. Calling **Publish** re-validates `draftData` in strict `publish` mode (checking `requiredOn: "publish"` fields and `image` alt text), promotes `draftData` -> `publishedData`, updates the public slug/URL, creates an automatic 301 redirect if the live slug changed, and purges Delivery caches. **Validation strictness by mode:** - Creating or patching a `draft` runs in `draft` mode—fields with `"requiredOn": "publish"` may be omitted while drafting. - Creating/transitioning to `published` or `scheduled` (and patching a `scheduled` entry) runs in `publish` mode—all required fields, image `requireAlt` rules, and reference targets are strictly enforced. --- ## Optimistic Locking & Concurrency Control All mutating operations on existing entries (`PATCH`, `publish`, `schedule`, `unpublish`, `archive`, `trash`, `restore`) support optimistic concurrency control to prevent lost updates: - Pass the `If-Match` HTTP header with the entry's current `ETag` (for example, `If-Match: "v3-..."`), **or** - Pass `expectedVersion` (integer) or `expectedEtag` in the JSON request body. If another editor or agent modified the entry in the meantime, OvertCMS Core rejects the write with `409 Conflict` (`version_conflict`) and guarantees `applied: false`. ### No-Op Detection If a `PATCH` produces identical canonical `draftData`, `slug`, and `unpublishAt` compared to the current entry, OvertCMS Core detects the no-op and returns `changed: false` **without** bumping `version`, inserting a redundant `EntryVersion`, or emitting an outbox event. --- ## Partial PATCH, Null Semantics & `clearFields` By default, OvertCMS Core uses **safe partial-merge semantics** on `PATCH` so omitted or `null` fields from an LLM or form never accidentally wipe existing content: | Input | Default Behavior | With `X-Null-Semantics: clear` | | :--- | :--- | :--- | | Key omitted from `data` | Unchanged | Unchanged | | `"subtitle": null` in `data` | Ignored (unchanged) | Clears `subtitle` | | `"clearFields": ["subtitle"]` | Explicitly clears `subtitle` | Explicitly clears `subtitle` | - Setting a field in both `data` and `clearFields` in the same request is rejected with `field_both_set_and_cleared`. - For surgical edits inside long `rich_html` bodies without resending the entire article, use `bodyPatches` (`replace_exact`, `append_after`, `prepend_before`)—see [Rich HTML & ``](/concepts/rich-html-and-blocks#targeted-body-patching). --- ## Live Takedown Confirmation To prevent accidental outages from automated scripts or hasty clicks, taking down a currently `published` entry via **Unpublish**, **Archive**, or **Trash** requires explicit confirmation: ```json { "expectedVersion": 4, "confirmUnpublish": true, "commitMessage": "Retiring Q1 promo landing page" } ``` Omitting `confirmUnpublish: true` on a published entry returns `409 live_takedown_confirmation_required` with `details.confirmField = "confirmUnpublish"`. --- ## Scheduling & Automatic Unpublishing - **Minimum lead time**: Both `scheduledAt` (when scheduling) and `unpublishAt` (when publishing) must be strictly more than **30 seconds** in the future (`minScheduleLeadTime`). - **Ordering invariant**: When both are set, `unpublishAt` must be strictly after `scheduledAt`. - **Early publish rule**: Manually publishing a `scheduled` entry before its `scheduledAt` time clears `scheduledAt` and resets `publishedAt = now()`. - **Worker execution**: The Worker Plane's `worker:scheduler` job keyset-paginates due entries across all sites (preventing starvation even if individual entries fail). - If an entry's `unpublishAt` already passed before the scheduler ran, it transitions straight to `draft` without ever going live. - If a scheduled entry fails publish-mode validation at publish time (for example, after a breaking schema update), the scheduler safely demotes it back to `draft` with `diffSummary: "schedule_failed_to_draft"` and records an `entry.schedule_failed` audit log so it does not spin forever. --- ## Automatic 301 Redirects & Chain Collapsing Whenever a **previously published** entry on a PostType with a `urlTemplate` is re-published with a **new slug**: 1. OvertCMS Core atomically inserts a `301` `Redirect` from the old public path (`/blog/old-slug`) to the new public path (`/blog/new-slug`). 2. **Chain collapsing**: Existing redirects pointing to `/blog/old-slug` are atomically collapsed to point directly to `/blog/new-slug` (preventing multi-hop redirect chains). 3. **Loop prevention**: If an entry is published at a path that previously had an outbound redirect (`fromPath == newPublicPath`), that stale redirect is automatically cleared. Public clients and edge routers fetch active redirects from `GET /delivery/v1/redirects` (cached with the `redirects` Surrogate-Key). --- ## Immutable Version History & Restoration Every create, update, publish, schedule, unpublish, archive, trash, and restore writes an immutable `EntryVersion` row containing: - `version`, `status`, full `dataSnapshot`, `diffSummary`, optional `commitMessage`, `actor`, `idempotencyKey`, and `createdAt`. Restoring a historical version rolls `draftData` back to that snapshot, creates a **new** monotonically increasing version (history is never rewritten), and leaves `publishedData` untouched until you explicitly publish. --- ## Localization & Singletons - **Locales**: Configured per site (`locales` and `defaultLocale`, default `["en"]`). Every entry belongs to a single validated `locale` and can optionally share a `translationGroupId` to link translated siblings across locales. - **Slug uniqueness**: Enforced atomically per `(site, postType, locale, slug)` among non-trashed entries. - **Non-slug `unique` fields**: Enforced atomically at the database level via `entry_unique_values` per `(site, postType, locale, fieldKey)`. - **Singletons**: PostTypes with `"kind": "singleton"` allow at most **one** non-trashed entry per locale (returning `409 singleton_already_exists` on duplicate create or trash restore). --- ## Single-Entry Signed Draft Previews To let editors or clients preview unpublished drafts without exposing drafts globally: 1. An Admin or authorized Agent requests a preview token for a specific entry (`POST .../entries/{id}/preview-token`, optional `ttlSeconds`, default **30 minutes**, max **24 hours**). 2. OvertCMS Core returns a one-time plaintext token (`pv_...`) and stores only its hash in `preview_tokens`. 3. The client fetches `GET /delivery/v1/{postType}/{idOrSlug}` (or `/delivery/v1/singletons/{slug}`) with the header: ```http X-Preview-Token: pv_... ``` 4. The Delivery Plane verifies the token matches **that exact entry ID** and has not expired, serves `draftData`, **bypasses the L2 cache completely**, omits `Surrogate-Key` headers, and sets `Vary: X-Preview-Token`. Preview tokens are automatically redacted (`[REDACTED_PREVIEW_TOKEN]`) if an idempotent operation receipt containing one is inspected later on the Admin Plane. --- # Rich Text & Embedded Blocks URL: https://docs.overtcms.com/concepts/rich-html-and-blocks > How OvertCMS Core parses, canonicalizes, secures, and projects rich_html fields using WHATWG HTML5 parsing, structured components, and targeted bodyPatches. OvertCMS Core stores rich editorial content in `rich_html` fields as **canonical semantic HTML5**—never proprietary editor JSON ASTs—parsed and validated on every write using Go's WHATWG-compliant HTML5 parser (`golang.org/x/net/html`). This gives clients clean, zero-transform semantic HTML, lets LLMs author naturally without brittle proprietary JSON node trees, and enforces airtight XSS protection at the storage boundary. ## Semantic HTML5 Allowlist ### Allowed Elements | Category | Permitted Tags | Notes | | :--- | :--- | :--- | | **Headings** | `h1`, `h2`, `h3`, `h4`, `h5`, `h6` | `h1` can be blocked via `constraints.disallowH1: true`. | | **Block prose** | `p`, `blockquote`, `footer`, `hr`, `pre` | `footer` is allowed **only** inside `blockquote`. | | **Lists** | `ul`, `ol`, `li` | Checklists (`ul[data-checklist]`, `li[data-checked]`) require `allowChecklists: true`. | | **Tables** | `table`, `caption`, `thead`, `tbody`, `tfoot`, `tr`, `th`, `td` | `colspan`/`rowspan` must be positive integers; `th[scope]` must be `row`, `col`, `rowgroup`, or `colgroup`. | | **Media** | `figure`, `figcaption`, `img`, `audio`, `video`, `source` | Gated by `allowInlineMedia` (default `true`). `source` is allowed **only** inside `audio` or `video`. | | **Embeds** | `iframe` | Disabled by default (`allowEmbeds: false`). Requires allowlisted HTTPS `src` and empty body. | | **Inline marks** | `strong`, `em`, `u`, `s`, `mark`, `sup`, `sub`, `code`, `a`, `br`, `time` | `code[class]` is allowed **only** inside `pre` and must match `^language-[a-zA-Z0-9_+-]+$`. | | **Structured blocks** | `` | Must reference an allowlisted Component via `type` and valid JSON in `data-props`. | ### Allowed Attributes Every attribute not explicitly listed below is rejected (in `strict` mode) or stripped with a warning (in `sanitize` mode). Event handlers (`on*`), inline `style`, and foreign XML/SVG/MathML namespaces are **always forbidden**: | Tag | Allowed Attributes | | :--- | :--- | | `a` | `href` (`http:`, `https:`, `mailto:`, `tel:`, `#anchor`, or root-relative `/path`), `title`, `rel` | | `img` | `src`, `alt`, `title`, `width`, `height`, `data-asset-id` | | `audio` | `controls` | | `video` | `controls`, `poster` | | `source` | `src`, `type` | | `iframe` | `src` (HTTPS allowlisted host only), `title`, `width`, `height`, `allowfullscreen` | | `code` | `class` (inside `pre` only, matching `language-*`) | | `ul` | `data-checklist` (`""`, `"true"`, `"false"`, when `allowChecklists: true`) | | `ol` | `start` (integer) | | `li` | `data-checked` (`"true"` or `"false"`, when `allowChecklists: true`) | | `th` | `colspan`, `rowspan`, `scope` | | `td` | `colspan`, `rowspan` | | `time` | `datetime` | | `cms-block` | `type`, `data-props` | ### Default `iframe` Embed Host Allowlist When `allowEmbeds: true`, `iframe[src]` must be `https://` without userinfo, have no child fallback content, and match the allowlist: - `youtube.com`, `www.youtube.com`, `youtu.be` - `player.vimeo.com` - `open.spotify.com` - `www.loom.com` - `codepen.io` - `datawrapper.dwcdn.net` --- ## Security Defenses & Strictness Modes ### `strict` (Default) vs. `sanitize` - **`strict` (default)**: Any forbidden tag (`script`, `style`, `svg`, `math`, `form`, `input`, `textarea`, `button`, `object`, `embed`), disallowed attribute, HTML comment, disallowed block/mark, or unsafe URL fails the write with a `422 validation_error` containing exact field diagnostics. Ideal for AI agents and APIs so issues are fixed rather than silently mutated. - **`sanitize`**: Drops entire subtrees of dangerous tags (`script`, `style`, `svg`, `math`, `object`, `embed`, `noscript`, `template`, `form`, `input`, `iframe` with bad `src`, etc.), unwraps benign unknown wrapper tags (like `div`/`span`) while keeping their text, strips disallowed attributes and comments, and returns non-fatal `warnings` alongside the canonical HTML. ### URL Obfuscation & Placeholder Link Guards - **Scheme obfuscation defense**: Strips ASCII control characters and whitespace before checking URLs so payloads like `java\tscript:alert(1)`, `data:`, `vbscript:`, or backslash tricks are unconditionally caught. - **LLM placeholder link guard**: Outside `
` blocks, `` rejects common LLM placeholders—such as `#`, `TBD`, `TODO`, `[insert link]`, `{{url}}`, `example.com`, `example.org`, `example.net`, and `placeholder.*`—with `placeholder_link_detected` in **both** `strict` and `sanitize` modes.

---

## Structured Components with ``

Embed strongly typed, schema-validated Components anywhere inside a `rich_html` document using empty `` elements:

```html

Deployment Checklist

Before going live, verify your master secret key.

``` **Rules enforced on every ``:** 1. The `type` slug must be listed in the field's `constraints.allowedComponents` and exist on the site. 2. Only `type` and `data-props` attributes are allowed; `` must contain **no child elements or non-whitespace text** (`cms_block_non_empty_body`). 3. `data-props` is decoded strictly as a single JSON object, scanned for prototype-pollution keys (`__proto__`, `constructor`, `prototype`), and validated against the Component's `fields` schema (including nested references, media assets, and `aiWritable` checks). 4. Normalized props are re-serialized into deterministic canonical JSON inside `data-props`. 5. Maximum `` nesting depth is **4** (`maxCMSBlockDepth`). 6. Any `reference` or media field inside a `` is automatically indexed into `entry_references` and `entry_media_refs`! --- ## Automatic Inline Image Sideloading When an entry's `rich_html` field contains an external `` **without** a `data-asset-id` attribute: - On create, update, publish, or schedule (skipped during `dryRun`), OvertCMS Core automatically fetches the image through the SSRF-hardened `SafeFetcher` (up to **20** external inline images per entry), sniffs magic bytes, deduplicates by SHA-256, stores it in your media driver, and rewrites the `` tag with `data-asset-id=""` and your canonical media/CDN `src` URL. - If the request is authenticated with an API key, sideloaded bytes are charged against that key's `dailyMediaBytesCap`. --- ## Targeted Body Patching (`bodyPatches`) Rather than having an AI agent regenerate and resend a 5,000-word HTML article to fix one paragraph, `PATCH` requests accept `bodyPatches` keyed by field name. Patches run sequentially against the current `draftData` HTML and then pass through `CanonicalizeHTML`: ```json { "expectedVersion": 2, "bodyPatches": { "body": [ { "op": "replace_exact", "oldHtml": "

PostgreSQL 15 is supported.

", "newHtml": "

PostgreSQL 16 is supported.

" }, { "op": "append_after", "anchorHtml": "

Prerequisites

", "insertHtml": "

Make sure Go 1.23 or newer is installed.

" }, { "op": "prepend_before", "anchorHtml": "

Next Steps

", "insertHtml": "

You are now ready to deploy.

" } ] } } ``` ### Exact Single-Match Safety Every patch operation (`replace_exact`, `append_after`, `prepend_before`) enforces an **exact match count of 1**: - **0 matches** -> `422 patch_target_not_found` - **2+ matches** -> `422 patch_target_ambiguous` (caller must provide a more specific snippet) This eliminates silent mis-edits and makes automated editing deterministic and retry-safe. --- ## Derived HTML Projections (`?include=...`) On the Delivery Plane, request derived read-only metadata for every `rich_html` field via `?include=plainText,wordCount,headings,readingTime`: ```bash GET /delivery/v1/posts/hello-overtcms?include=plainText,wordCount,headings,readingTime ``` ```json { "id": "0193a8b2-...", "slug": "hello-overtcms", "data": { "title": "Hello OvertCMS Core", "body": "

Welcome

...

" }, "projections": { "body": { "plainText": "Welcome\nPublished from the Agent Plane with strict HTML5 validation.", "wordCount": 11, "readingTime": 1, "headings": [ { "level": 2, "id": "welcome", "text": "Welcome" } ] } } } ``` - **Unicode & CJK word counting**: Counts Latin/alphanumeric words (preserving internal apostrophes/hyphens like `don't` and `well-known`) and counts each CJK Han/Hiragana/Katakana character as one word. - **Reading time**: Computed as `ceil(wordCount / 225)` minutes (`(wordCount + 224) / 225`). - **Heading outline**: Extracts `h1`–`h6` in document order, strips NFD diacritics (e.g. `café` -> `cafe`), and automatically deduplicates repeated slugs (`setup`, `setup-2`, `setup-3`). - ``, `iframe`, `script`, and `style` elements are excluded from prose projections. --- # Relations & Page Trees URL: https://docs.overtcms.com/concepts/references-and-trees > Strong vs. weak referential integrity, cycle detection, searchable reference pickers, zero-N+1 batched Delivery expansion, self-referencing trees, and strict indexed filtering. OvertCMS Core maintains a normalized reference graph (`entry_references`) and typed field index (`entry_field_index`) atomically inside every entry transaction. This powers O(1) delete protection, cycle prevention, zero-N+1 inline expansion, hierarchical trees, and strictly indexed queries. ## Defining Reference Fields A `reference` field links an entry to one or more entries in allowed target PostTypes: ```json { "key": "author", "label": "Author", "type": "reference", "required": true, "requiredOn": "publish", "filterable": true, "constraints": { "targets": ["authors"], "multiple": false, "integrity": "strong" } } ``` - **`targets`** (required): Non-empty list of allowed target PostType slugs. Multi-target polymorphic references (e.g. `["articles", "guides"]`) are supported. - **`multiple`**: `false` (single entry ID string) or `true` (array of entry ID strings, optionally bounded by `minItems` / `maxItems`). - **`integrity`**: `"strong"` (default) or `"weak"`. --- ## Referential Integrity (`strong` vs. `weak`) OvertCMS Core tracks outgoing references separately for **both** `draft` and `published` snapshots in `entry_references`, so editing a draft never hides a live published dependency. ### Strong Integrity (`integrity: "strong"`) - **On write**: Every referenced entry ID must exist, belong to the same site, match one of `constraints.targets`, and not be `trashed`. - **On trash / purge**: OvertCMS Core checks incoming `strong` references in O(1) via `entry_references` (excluding trashed source entries). If any active entry holds a strong reference to the target, trashing is blocked with `409 Conflict` listing the exact `referencedBy` entries (`id`, `postType`, `field`). - **Admin force override**: Human users on the Admin Plane may pass `"force": true` to override strong reference protection; API keys and AI agents can **never** bypass strong references. ### Weak Integrity (`integrity: "weak"`) - **On write**: Referenced target IDs are still validated for existence and target PostType at write time. - **On trash / purge**: Target entries may be trashed or purged without blocking. When expanded on the Delivery Plane, deleted or unpublished weak targets gracefully resolve to `null` (for single references) or are omitted from arrays (for multi-references)—never leaking raw unpublished IDs. --- ## Cycle Detection Whenever an entry is updated, scheduled, or published, OvertCMS Core walks the outgoing reference graph (up to `maxCycleWalkNodes = 256` nodes) to prevent: 1. **Direct self-references** (`A -> A`), and 2. **Transitive cycles** (`A -> B -> C -> A`). If a cycle is detected, the write fails atomically with `422 reference_cycle_detected`. --- ## Searchable Reference Options & Empty-Search Rescue For both Admin UI pickers and AI agents looking up valid target IDs without hallucinating UUIDs, OvertCMS Core provides a dedicated options search endpoint for any `reference` field: - Agent Plane: `GET /agent/v1/collections/{postType}/fields/{fieldKey}/options?q=...&target=...&limit=...&cursor=...` - Admin Plane: `GET /admin-api/v1/sites/{siteSlug}/post-types/{postType}/fields/{fieldKey}/options` **Empty-search rescue**: If a search query `q` returns `0` matches on a target collection with `<= 50` total eligible entries (`emptyRescueThreshold`), OvertCMS Core automatically returns up to `10` `suggestedOptions` (`emptyRescueMaxResults`) alongside `totalEligible` so agents and editors can pick the right entry immediately instead of retrying blind queries. --- ## Zero-N+1 Batched Delivery Expansion On the Delivery Plane, pass `expand` and optional `depth` (`1` or `2`; capped at `maxDeliveryExpandDepth = 2`) to hydrate referenced entries inline: ```bash GET /delivery/v1/posts?expand=author,categories&depth=2 ``` **How OvertCMS Core avoids N+1 queries:** 1. Across the entire page of root entries, all level-1 referenced IDs are deduplicated and fetched in **one** batched `GetByIDs` database query. 2. When `depth=2`, all level-2 reference IDs across level-1 targets are fetched in **one** second batched `GetByIDs` query. 3. **Published-only safety**: Only targets with `status == "published"` and non-nil `publishedData` (and allowed by the Delivery API key's `allowedPostTypes`, if enabled) are hydrated. Unpublished or missing single references become `null`; multi-references omit them. 4. **Cycle-safe hydration**: Each ancestor path tracks visited IDs so graphs can never recurse infinitely. 5. **Automatic Surrogate-Keys**: Every expanded target ID is appended as `entry:` to the response `Surrogate-Key` header—so updating an author automatically invalidates every cached blog post page that expanded that author! --- ## Self-Referencing Hierarchies & Trees Any PostType that defines a `reference` field targeting **itself** (for example, `pages` with a `parent` reference whose `targets` includes `"pages"`, or `categories` with `parentCategory`) automatically unlocks hierarchical queries on the Delivery Plane: ### Filter by Parent - **Root nodes only** (where the self-reference field is null): ```bash GET /delivery/v1/pages?parent=root ``` - **Direct children of a specific entry ID**: ```bash GET /delivery/v1/pages?parent=0193a8b2-1c4f-7e20-9a11-000000000001 ``` ### Full Nested Tree Assembly (`tree=true`) ```bash GET /delivery/v1/pages?tree=true&sort=order&expand=heroAuthor ``` When `tree=true`: - OvertCMS Core loads root entries (or children of `parent=`), then performs breadth-first, level-by-level batched queries (chunked by 100 parent IDs) up to **depth 5** (`maxDeliveryTreeDepth`) and **1,000 total nodes** (`maxDeliveryTreeNodes`). - Each node receives its nested published descendants under the `children` array, sorted by the active `sort` order, with cycle protection and optional `expand`, `include`, and `fields` projection applied recursively. - Calling `?parent=...` or `?tree=true` on a PostType without a self-referencing field returns `400 self_reference_not_supported`. --- ## Strict Indexed Filtering, Sorting & Keyset Pagination OvertCMS Core rejects unindexed full-table scans on user-defined fields: - **Filtering**: Pass `filter[][]=` (for example, `filter[category][eq]=guides` or `filter[rating][gte]=4`). Only fields declared `"filterable": true` in the PostType schema (plus system fields) are accepted. `in` filters are capped at **100 values** (`maxFilterInValues`). - **Sorting**: Pass `sort=field` (ascending) or `sort=-field` (descending). Only fields declared `"sortable": true` (plus system timestamps like `publishedAt`, `createdAt`, `updatedAt`) are accepted. Delivery defaults to `-publishedAt`; Agent/Admin default to `-createdAt`. - **Keyset Cursor Pagination**: Every list endpoint uses opaque base64 cursors (`nextCursor`, `hasMore`) bound to the active sort order—**zero SQL `OFFSET`**—guaranteeing O(log N) deep pagination. Passing a cursor generated for a different `sort` order returns `400 invalid_cursor`. - **Field Projection**: On Delivery, pass `fields=title,slug,publishedAt` to trim each item's `data` payload to only the requested keys (plus any explicitly expanded keys). --- # Real-Time Collaboration URL: https://docs.overtcms.com/concepts/collaboration > Google Docs-style multi-user editing, live presence avatars and cursors, server-enforced read-only roles, and live AI agent sync over WebSockets. Multiple team members can open and edit the same entry or singleton at the same time in the OvertCMS Admin UI—with live avatars, named text cursors, and instant synchronization across rich text and structured fields. Everything runs inside the single Go binary (`overt-cms-core`) over standard WebSockets with zero external collaboration servers required. ## How It Works 1. **Presence & live cursors**: When you open an entry or singleton, the Admin UI opens a dedicated WebSocket room for that document. Every active teammate appears in the top presence bar with their name, avatar, role, and a color-coded cursor inside the rich text editor. 2. **Conflict-free concurrent edits (Yjs CRDT)**: Simultaneous edits in rich text (`rich_html`) and structured fields merge cleanly in real time without clobbering each other's keystrokes. 3. **Explicit save & publishing**: Live collaboration syncs your in-progress draft session across open browsers, while database persistence, version snapshots, and publishing still happen explicitly when someone clicks **Save Draft** or **Publish**—preserving optimistic locking (`ETag` / `version`) and clean version history. 4. **Live sync when an AI agent or teammate saves**: Whenever an entry is saved, published, unpublished, or restored from *any* source (another browser, an AI agent over REST, or an MCP tool), the server broadcasts an `entry.saved` event to every connected editor in that room so everyone stays in sync without stale conflicts. --- ## Security & Role Enforcement Collaboration rooms enforce the exact same RBAC rules as the rest of the Admin Plane: - **Single-use WebSocket tickets**: Before upgrading to WebSockets, the browser calls `POST .../collab-token` using its authenticated Admin session to receive a short-lived, single-use ticket scoped to that exact `(siteId, entryId)` pair. - **Origin & CSRF protection**: Cross-site WebSocket handshakes (`Sec-Fetch-Site: cross-site`) and disallowed `Origin` headers are rejected before the connection upgrades or consumes a ticket. - **Server-enforced read-only mode**: Users with the `viewer` role—or `writer` users viewing another author's entry—connect with `canEdit: false`. They can see live presence and watch edits in real time, while the server drops any incoming document mutations from read-only sockets. - **Instant ghost-cursor cleanup**: When a user closes their tab or loses connection, the server immediately clears their awareness/cursor state so stale cursors never linger. --- ## Collaboration Endpoints All collaboration endpoints live on the **Admin Plane** (`/admin-api/v1/*`) and require a human Admin session (API keys are never allowed). ### Collection Entries | Method | Path | Purpose | | :--- | :--- | :--- | | `POST` | `/admin-api/v1/sites/{siteSlug}/collections/{postType}/entries/{id}/collab-token` | Mint a single-use WebSocket ticket (`ticket`, `expiresAt`, `canEdit`, `wsPath`). | | `GET` | `/admin-api/v1/sites/{siteSlug}/collections/{postType}/entries/{id}/collab?ticket=...` | Upgrade to the Yjs binary + JSON presence WebSocket room. | | `GET` | `/admin-api/v1/sites/{siteSlug}/collections/{postType}/entries/{id}/presence` | List users currently connected to this entry (used by list views and editor headers). | ### Singletons | Method | Path | Purpose | | :--- | :--- | :--- | | `POST` | `/admin-api/v1/sites/{siteSlug}/singletons/{slug}/collab-token` | Mint a single-use WebSocket ticket for a singleton. | | `GET` | `/admin-api/v1/sites/{siteSlug}/singletons/{slug}/collab?ticket=...` | Upgrade to the singleton's real-time WebSocket room. | | `GET` | `/admin-api/v1/sites/{siteSlug}/singletons/{slug}/presence` | List users currently viewing or editing the singleton. | --- ## Reverse Proxy Setup (Nginx / Caddy / Cloudflare) When running behind a reverse proxy in production, make sure WebSocket upgrades (`Upgrade` and `Connection` headers) are forwarded on `/admin-api/v1/*`: ```nginx location /admin-api/ { proxy_pass http://127.0.0.1:8080; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_read_timeout 3600s; } ``` Set `OVERTCMS_WEBAUTHN_RP_ORIGIN=https://cms.yourdomain.com` if your Admin UI is hosted on a different origin than Core so WebSocket `Origin` verification accepts your Admin domain cleanly. --- # Media & File Uploads URL: https://docs.overtcms.com/concepts/media-pipeline > Magic-byte sniffing, SSRF-hardened URL sideloading, presigned upload quarantine, SHA-256 deduplication, local and pure-Go S3/R2 storage, and sandboxed Delivery streaming. OvertCMS Core treats every uploaded or sideloaded file as **untrusted binary input**. Files are verified by magic bytes (never by filename or declared `Content-Type`), deduplicated per site by SHA-256, quarantined during presigned uploads to eliminate TOCTOU tampering, and served with strict browser sandboxing headers. ## Allowed Media Types & Magic-Byte Sniffing OvertCMS Core verifies the first **64 KiB** of every payload (`mediaSniffReadHeadBytes`) in pure Go: | Kind | Allowed MIME Types | Canonical Extensions | Extracted Metadata | | :--- | :--- | :--- | :--- | | `image` | `image/jpeg`, `image/png`, `image/gif`, `image/webp`, `image/avif` | `.jpg`, `.png`, `.gif`, `.webp`, `.avif` | Pure-Go `width` & `height` (JPEG, PNG, GIF, WebP VP8/VP8L/VP8X) | | `audio` | `audio/mpeg`, `audio/ogg`, `audio/wav`, `audio/mp4`, `audio/webm` | `.mp3`, `.ogg`, `.wav`, `.m4a`, `.webm` | Verified via ID3/MPEG frame sync, `OggS`, `RIFF/WAVE`, `ftyp M4A`, EBML | | `video` | `video/mp4`, `video/webm` | `.mp4`, `.webm` | Verified via ISO-BMFF `ftyp` brands and EBML headers | | `document` | `application/pdf`, `text/csv`, `text/plain` | `.pdf`, `.csv`, `.txt` | `%PDF-` magic bytes; `text/plain` & `text/csv` accepted **only** when explicitly declared and verified safe UTF-8 | ### Unconditionally Rejected Payloads - **Executables & scripts**: PE/DOS (`MZ`), ELF (`\x7fELF`), Mach-O / Fat Mach-O binaries, and Unix shebang (`#!`) scripts. - **SVG & HTML**: ``, ``, `` is indexed in `entry_media_refs`. Attempting to delete an in-use asset is rejected unless no active entry references it. - **Ephemeral media**: Mark temporary uploads with `"isEphemeral": true` (default TTL **24 hours**, or custom `expiresAt`). The Worker Plane's `worker:scheduler` job periodically deletes expired ephemeral assets that are not referenced by any entry. - **Editorial metadata**: Every asset supports `defaultAlt`, `defaultCaption`, `defaultTitle`, `credit`, and normalized `focalPoint` (`x` and `y` in `[0, 1]`), editable via metadata `PATCH`. --- # All 19 Field Types URL: https://docs.overtcms.com/fields/overview > Reference for all 19 canonical OvertCMS field types, FieldDefinition properties, reserved keys, requiredOn lifecycle modes, and PATCH null semantics. OvertCMS enforces a closed, strongly typed schema system built on **19 canonical field types**. Every field inside a post type, reusable component, inline object, or list item uses one of these 19 types—there are no untyped escape hatches outside the explicit `json` field type. ## The 19 Canonical Field Types | Type | Wire Format (JSON) | `filterable` | `sortable` | `unique` | Primary Use Case | | --- | --- | --- | --- | --- | --- | | `string` | `string` | Yes (`eq`, `in`, `contains`, `gte`, `lte`) | Yes | Yes | Titles, names, emails, CSS colors, short labels | | `text` | `string` | Yes (`eq`, `in`, `contains`, `gte`, `lte`) | Yes | Yes | Multi-line plain text, excerpts, bios, summaries | | `slug` | `string` | Yes (`eq`, `in`, `contains`, `gte`, `lte`) | Yes | Built-in per locale | URL-safe entry identifiers (`kebab-case`) | | `rich_html` | `string` (canonical HTML5) | No | No | No | Long-form articles with semantic HTML5 and `` components | | `number` | `number` | Yes (`eq`, `in`, `gte`, `lte`) | Yes | Yes | Prices, ratings, counts, sort weights | | `boolean` | `boolean` | Yes (`eq`, `in`) | Yes | Yes | Feature flags, toggles, binary indicators | | `date` | `string` (`YYYY-MM-DD`) | Yes (`eq`, `in`, `contains`, `gte`, `lte`) | Yes | Yes | Calendar dates without time or timezone | | `datetime` | `string` (RFC3339 UTC) | Yes (`eq`, `in`, `gte`, `lte`) | Yes | Yes | Exact timestamps with timezone offset or `Z` | | `time` | `string` (`HH:mm` or `HH:mm:ss`) | Yes (`eq`, `in`, `contains`, `gte`, `lte`) | Yes | Yes | Wall-clock time of day without date or timezone | | `url` | `string` | Yes (`eq`, `in`, `contains`, `gte`, `lte`) | Yes | Yes | External links, canonical URLs, root-relative paths | | `select` | `string` or `string[]` | Yes (`eq`, `in`, `contains`, `gte`, `lte`) | Single-select | Single-select | Fixed enums, tags, categories with optional custom values | | `reference` | `string` or `string[]` | Yes (`eq`, `in`) | No | Single-reference | Strongly typed relations to entries in target post types | | `image` | `object` (`{ assetId, alt, ... }`) | No | No | No | Verified image assets with alt text and focal points | | `audio` | `object` (`{ assetId, ... }`) | No | No | No | Audio tracks with transcripts and durations | | `video` | `object` (`{ assetId, ... }`) | No | No | No | Video assets with poster images and durations | | `file` | `object` (`{ assetId, ... }`) | No | No | No | Downloadable documents (PDF, CSV, plain text) | | `object` | `object` | No | No | No | Nested inline field groups or reusable component references | | `list` | `array` | Primitive lists only | No | No | Ordered arrays of primitives, objects, components, or discriminated unions | | `json` | any valid JSON value | No | No | No | Semi-structured payloads bounded by `maxBytes` and optional `jsonSchema` | `slug` fields are always unique per `(site, postType, locale)` at the database level. Setting `unique: true` on other scalar fields (`string`, `text`, `url`, `date`, `time`, `datetime`, `number`, `boolean`, single `select`, single `reference`) enforces atomic uniqueness across all non-trashed entries in the same `(site, postType, locale)` via `entry_unique_values`. ### Explore Field Families - [Text & Rich HTML Fields](/fields/text-fields) — `string`, `text`, `slug`, `rich_html` - [Primitive, Date & URL Fields](/fields/primitive-and-date-fields) — `number`, `boolean`, `date`, `datetime`, `time`, `url` - [Select & Reference Fields](/fields/select-and-reference) — `select`, `reference` - [Media Fields](/fields/media-fields) — `image`, `audio`, `video`, `file` - [Composite & JSON Fields](/fields/composite-fields) — `object`, `list`, `json` --- ## `FieldDefinition` Reference Every field in a post type or component is defined by a `FieldDefinition` JSON object. When a post type or component is saved, OvertCMS automatically normalizes defaults and assigns an immutable UUIDv7 `fieldId` to every field (preserving `fieldId` across updates when matched by `fieldId` or `key`). ```json { "fieldId": "0195c8a2-7b4d-7f10-8e3a-6b2c1d4e5f6a", "key": "headline", "label": "Headline", "type": "string", "instruction": "Write an engaging, sentence-case headline under 80 characters.", "description": "Primary H1 displayed on the article page and social cards.", "required": true, "requiredOn": "publish", "writable": true, "readOnly": false, "aiWritable": true, "filterable": false, "sortable": true, "unique": false, "localized": true, "deprecated": false, "replacedBy": "", "defaultValue": null, "constraints": { "minLength": 10, "maxLength": 80, "lengthUnit": "graphemes", "trim": true }, "ui": { "group": "Header", "order": 1, "placeholder": "Enter a concise headline...", "width": "full" } } ``` ### Complete Property Reference | Property | Type | Default | Description | | --- | --- | --- | --- | | `fieldId` | `string` | Auto UUIDv7 | Immutable field identifier assigned by the server and preserved across schema updates. | | `key` | `string` | Required | JSON property name on entry `data`. Must match `^[a-z][a-zA-Z0-9_]{0,63}$` and must not be reserved. | | `label` | `string` | Required | Human-readable label shown in the Admin UI and validation error messages. | | `type` | `string` | Required | One of the 19 canonical field types listed above. | | `instruction` | `string` | `""` | AI & editorial authoring guidance (max **2,000** Unicode characters). Surfaced in `/agent/v1/prompt`, schemas, and validation issues. | | `description` | `string` | `""` | Short helper text (max **500** Unicode characters). | | `required` | `boolean` | `false` | Whether the field must have a non-empty value. Evaluated according to `requiredOn`. | | `requiredOn` | `"draft"` \| `"publish"` | `"publish"` | Lifecycle stage at which `required: true` is enforced. | | `writable` | `boolean` | `true` | If `false`, no API caller may write or clear this field (`field_read_only`). | | `readOnly` | `boolean` | `false` | If `true`, prevents all API writes or clears to this field (`field_read_only`). | | `aiWritable` | `boolean` | `true` | If `false`, API key and MCP actors cannot set, modify, or clear this field (`field_not_ai_writable`), while human Admin users still can. | | `filterable` | `boolean` | `false` | Indexes the field in `entry_field_index` (or uses `entry_references`) so queries can filter on it. | | `sortable` | `boolean` | `false` | Indexes the field for keyset-paginated `sort` queries. | | `unique` | `boolean` | `false` | Enforces atomic uniqueness across non-trashed entries per `(site, postType, locale)`. | | `localized` | `boolean` | `false` | Marks whether the field varies across locales on localized post types. | | `deprecated` | `boolean` | `false` | Flags the field as deprecated in schemas and prompts without breaking existing data. | | `replacedBy` | `string` | `""` | Key of a sibling, non-deprecated field replacing this field. Requires `deprecated: true`. | | `defaultValue` | `any` | `null` | Value applied automatically when a field is omitted or `null` (unless explicitly cleared on `PATCH`). | | `constraints` | `object` | `{}` | Type-specific validation and structural rules (`FieldConstraints`). | | `ui` | `object` | `null` | Cosmetic authoring hints (`group`, `order`, `placeholder`, `width`). Excluded from `schemaFingerprint`. | | `searchEndpoint` | `string` | Auto (for `reference`) | Server-populated Agent Plane URL (`/agent/v1/collections/{postType}/fields/{path}/options`) on `reference` fields. | **Instruction length limits across the schema hierarchy:** - Site instruction: max **8,000** characters - Post type instruction: max **4,000** characters - Component instruction: max **2,000** characters - Field instruction (and list variant instruction): max **2,000** characters - Field description: max **500** characters ### Deprecation Rules (`deprecated` and `replacedBy`) When evolving a schema without breaking agents or clients, mark an old field `deprecated: true` and optionally point `replacedBy` to a sibling field in the same field list: - Setting `replacedBy` while `deprecated: false` fails with `replaced_by_requires_deprecated`. - Pointing `replacedBy` to the field's own key fails with `invalid_replaced_by`. - Pointing `replacedBy` to a nonexistent sibling fails with `unknown_replaced_by`. - Pointing `replacedBy` to another deprecated field fails with `deprecated_replaced_by`. --- ## Reserved Keys and Slugs ### Reserved Field Keys Field keys must match `^[a-z][a-zA-Z0-9_]{0,63}$` and cannot collide with system entry properties or JavaScript prototype-pollution keys: | Category | Reserved Field Keys | | --- | --- | | Prototype-pollution keys (rejected at **every** nesting depth, including inside `json` and ``) | `__proto__`, `constructor`, `prototype` | | System entry envelope keys | `id`, `status`, `_meta`, `version`, `etag`, `createdAt`, `updatedAt`, `publishedAt`, `scheduledAt`, `unpublishAt`, `locale`, `translationGroupId` | | Conditional key | `slug` — **allowed ONLY** when `type` is `"slug"`; rejected with `reserved_field_key` for any other field type | ### Reserved Post-Type Slugs Post-type and component slugs must match `^[a-z][a-z0-9_-]{0,63}$`. Post-type slugs cannot collide with Delivery or Schema route namespaces: - `site` - `redirects` - `media` - `singletons` - `sitemap` - `components` - `post-types` Attempting to create a post type with any of these slugs returns `422` with issue code `reserved_post_type_slug`. --- ## `requiredOn: "draft" | "publish"` OvertCMS separates draft authoring from publication readiness using the `requiredOn` attribute: - **`"publish"` (default):** A field with `required: true` and `requiredOn: "publish"` may be omitted or empty (`""`) while creating or patching a `draft` entry. When the entry is published, scheduled, or created directly with `status: "published"` or `status: "scheduled"`, validation switches to publish mode and rejects missing or empty values with code `required`. - **`"draft"`:** A field with `required: true` and `requiredOn: "draft"` is enforced immediately on every `draft` create and update, as well as on publish/schedule. Use this for essential identifiers like `title` or `slug`. Updating a `scheduled` entry also validates in **publish mode** so a scheduled release can never drift into an unpublishable state before its `scheduledAt` timestamp fires. --- ## Write Permissions (`readOnly`, `writable`, `aiWritable`) OvertCMS enforces field- and component-level write guards on both full creates and partial `PATCH` updates: - **`readOnly: true` or `writable: false`:** Any attempt to set, change, or clear the field returns `422` with `field_read_only`. Existing values on untouched keys during a `PATCH` are preserved cleanly. - **`aiWritable: false`:** Blocks API key (`api_key`) and MCP (`mcp`) actors from writing, modifying, or clearing the field (`field_not_ai_writable`) or component (`component_not_ai_writable`). Human Admin users (`user` actors) can still edit these fields. - **Nested protection:** Clearing or overwriting an `object` or `list` that contains an existing protected child field is also rejected unless the protected child remains untouched. --- ## `PATCH` Null Semantics: `null`, `clearFields`, and `X-Null-Semantics: clear` LLM agents frequently serialize optional fields as `null` when constructing partial update payloads. To prevent accidental data loss, OvertCMS enforces **safe null semantics by default**: | Payload on `PATCH` | Default Behavior | With `X-Null-Semantics: clear` (or MCP `nullClears: true`) | | --- | --- | --- | | Key omitted from `data` | Unchanged | Unchanged | | `"summary": null` in `data` | **Unchanged** (ignored) | **Cleared** (removed from `draftData`) | | `"clearFields": ["summary"]` | **Cleared** (removed from `draftData`) | **Cleared** (removed from `draftData`) | ### Rules and Conflict Guards 1. **Explicit clearing via `clearFields`:** Pass the top-level field keys to erase in `clearFields: ["subtitle", "heroImage"]`. Cleared fields do **not** have their `defaultValue` re-applied on that `PATCH`. 2. **Conflict detection:** Providing the same field key as a non-null value in `data` (or targeting it in `bodyPatches`) **and** listing it in `clearFields` (or null-clearing it under `X-Null-Semantics: clear`) fails with `field_both_set_and_cleared`. 3. **Mixing `data` and `bodyPatches`:** Providing a non-null value in `data` **and** a `bodyPatches` entry for the same `rich_html` field fails with `field_both_set_and_patched`. 4. **Clearing protected or required fields:** Clearing a `readOnly` or `!aiWritable` field fails with `field_read_only` / `field_not_ai_writable`. Clearing a field that is currently required (e.g., `requiredOn: "draft"`, or any required field on a `scheduled` entry) fails with `required`. ```json { "expectedVersion": 3, "data": { "title": "Updated Article Title", "subtitle": null }, "clearFields": ["excerpt"] } ``` In the default request above, `title` is updated, `subtitle` is left **untouched**, and `excerpt` is explicitly **cleared**. --- # Text & Rich Text Fields URL: https://docs.overtcms.com/fields/text-fields > Complete specification for string, text, slug, and rich_html fields including length units, formats, RE2 regex safety, 301 redirects, components, and bodyPatches. OvertCMS provides four text-oriented field types: `string` (single-line), `text` (multi-line plain text), `slug` (URL identifier), and `rich_html` (canonical semantic HTML5 with embedded components and surgical patching). --- ## `string` Use `string` for single-line text values such as titles, author names, SKUs, email addresses, and CSS colors. ### Normalization - All C0 (`0x00`–`0x1F`), DEL (`0x7F`), and C1 (`0x80`–`0x9F`) control characters—including newlines and tabs—are stripped automatically. - If `constraints.trim` is `true`, leading and trailing whitespace is trimmed before emptiness, length, format, and pattern checks run. ### Constraints | Constraint Key | Type | Default | Description | | --- | --- | --- | --- | | `minLength` | `integer` | — | Minimum length (`>= 0`). Fails with `min_length`. | | `maxLength` | `integer` | — | Maximum length (`>= minLength`). Fails with `max_length`. | | `lengthUnit` | `"graphemes"` \| `"utf16"` | `"graphemes"` | `"graphemes"` counts Unicode UAX #29 extended grapheme clusters (so `"👨‍👩‍👧‍👦"` counts as 1); `"utf16"` counts UTF-16 code units (matching JavaScript `.length`). | | `format` | `"plain"` \| `"email"` \| `"color"` | `"plain"` | Built-in semantic format validator. | | `pattern` | `string` | — | Bounded Go RE2 regular expression. Fails with `pattern_mismatch`. | | `trim` | `boolean` | `false` | Strips leading and trailing whitespace before validation. | #### Built-in `format` Rules - **`"plain"` (default):** Any string matching length and `pattern` constraints. - **`"email"`:** Must contain no whitespace, parse cleanly via RFC 5322 (`mail.ParseAddress`) as a bare address (`addr.Address == s`), have a dot-separated domain with valid non-hyphen-bounded labels, and end in a TLD of at least 2 characters. Fails with `invalid_email`. - **`"color"`:** Accepts CSS hex (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`), `rgb()`/`rgba()` (either all 0–255 numeric channels or all 0–100% channels, optional alpha in `0–1` or `0–100%`), and `hsl()`/`hsla()` (hue `0–360` with optional `deg`, saturation `0–100%`, lightness `0–100%`, optional alpha). Fails with `invalid_color`. #### RE2 Regex Safety Guard (`pattern`) To guarantee linear-time validation and prevent compile-time ReDoS attacks, `constraints.pattern` is validated at both schema creation and runtime: - Maximum length: **256 bytes**. - Uses Go's RE2 syntax (no backreferences or lookarounds). - **No nested bounded quantifiers** (e.g., `(a{10}){10}` is rejected). - No single quantifier count above **1,000**, and combined quantifier expansion across the pattern must not exceed **1,000**. ### Schema & Payload Examples ```json { "key": "contactEmail", "label": "Contact Email", "type": "string", "required": true, "requiredOn": "publish", "filterable": true, "unique": true, "constraints": { "format": "email", "maxLength": 160, "lengthUnit": "graphemes", "trim": true } } ``` - **Valid:** `"editor@acme.example.dev"` (or `" editor@acme.example.dev "` which trims to `"editor@acme.example.dev"`) - **Invalid:** `"not-an-email"` (`invalid_email`), `"a@localhost"` (`invalid_email` — missing dot/TLD), `12345` (`invalid_type`) --- ## `text` Use `text` for multi-line plain text such as excerpts, meta descriptions, bios, or plain-text notes. ### Normalization - Converts `\r\n` and `\r` line endings to `\n`. - Strips C0/DEL/C1 control characters **except** `\n` and `\t`, which are preserved. - Trims leading/trailing whitespace if `constraints.trim` is `true`. ### Constraints | Constraint Key | Type | Default | Description | | --- | --- | --- | --- | | `minLength` | `integer` | — | Minimum length (`>= 0`). | | `maxLength` | `integer` | — | Maximum length (`>= minLength`). | | `lengthUnit` | `"graphemes"` \| `"utf16"` | `"graphemes"` | Grapheme cluster or UTF-16 code unit count. | | `pattern` | `string` | — | Bounded RE2 regex (same 256-byte / 1,000-quantifier limits). | | `trim` | `boolean` | `false` | Trims leading/trailing whitespace before validation. | | `maxLines` | `integer` | — | Maximum number of lines (`>= 1`, counted as `count("\n") + 1`). Fails with `max_lines`. | | `disallowHtml` | `boolean` | `false` | Runs an HTML5 tokenizer; rejects any start tag, end tag, self-closing tag, or HTML comment with `html_not_allowed`. | ### Schema & Payload Examples ```json { "key": "summary", "label": "Article Summary", "type": "text", "required": true, "requiredOn": "publish", "constraints": { "minLength": 20, "maxLength": 300, "maxLines": 3, "disallowHtml": true, "trim": true } } ``` - **Valid:** `"First line summary.\nSecond line with key takeaway."` - **Invalid:** `"

No HTML allowed

"` (`html_not_allowed`), `"Line 1\nLine 2\nLine 3\nLine 4"` (`max_lines`) --- ## `slug` Use `slug` for the canonical URL identifier of an entry. A field key literally named `"slug"` is **only permitted** when `type` is `"slug"`. ### Constraints | Constraint Key | Type | Default | Description | | --- | --- | --- | --- | | `minLength` | `integer` | — | Minimum slug length. | | `maxLength` | `integer` | — | Maximum slug length (system fallback cap is 255 characters when no `slug` field exists). | | `lengthUnit` | `"graphemes"` \| `"utf16"` | `"graphemes"` | Length unit. | | `pattern` | `string` | `^[a-z0-9]+(?:-[a-z0-9]+)*$` | Custom RE2 regex overriding the default lowercase kebab-case pattern. Fails with `invalid_slug` (default) or `pattern_mismatch` (custom). | | `trim` | `boolean` | `false` | Trims whitespace before validation. | ### Auto-Derivation, Uniqueness, and Automatic 301 Redirects 1. **Auto-derivation:** If `slug` is omitted on create and the post type defines `slugSourceField` (e.g., `"title"`), OvertCMS automatically generates a kebab-case slug from that field. 2. **Conflict guard:** If you supply both a top-level `slug` property and `data.` with different non-empty values, the request fails with `422 slug_mismatch`. 3. **Locale-scoped uniqueness:** Slugs are unique per `(site, postType, locale)` across non-trashed entries (`409 slug_already_exists`). 4. **Dual-snapshot pinning:** When you `PATCH` the slug of an already-`published` entry, the new slug is stored in `draftData` while `entry.slug` and `entry.publicUrl` remain pinned to the live published URL so production links never break mid-edit. 5. **Automatic 301 redirects on republish:** When you publish a previously published entry whose slug changed (and the post type has a `urlTemplate`), OvertCMS atomically records a `301` redirect from the old public path to the new public path, collapses any existing redirect chains pointing to the old path directly to the new path, and removes any stale redirect whose `fromPath` now matches the newly claimed path. Redirects are exposed at `GET /delivery/v1/redirects`. ### Schema & Payload Examples ```json { "key": "slug", "label": "URL Slug", "type": "slug", "required": true, "requiredOn": "draft", "filterable": true, "sortable": true, "constraints": { "minLength": 3, "maxLength": 120, "trim": true } } ``` - **Valid:** `"getting-started-with-overtcms-2"` - **Invalid:** `"Hello_World"` (`invalid_slug`), `"leading-hyphen-"` (`invalid_slug`) --- ## `rich_html` `rich_html` is OvertCMS's primary rich-content format. Every write is parsed with a full WHATWG HTML5 fragment parser (`golang.org/x/net/html`), validated against a strict semantic allowlist, checked for XSS and LLM placeholder links, and serialized back to canonical HTML5. ### Constraints | Constraint Key | Type | Default | Description | | --- | --- | --- | --- | | `minWords` | `integer` | — | Minimum Unicode-aware word count (counts CJK ideographs/Hiragana/Katakana individually; excludes `` and `