# Content Models & Blocks

> 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 `<cms-block type="..." data-props="...">` 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.
