# Entries, Drafts & Publishing

> 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.

<Tip>
  **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.
</Tip>

---

## 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 & `<cms-block>`](/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`.

<Note>
  Preview tokens are automatically redacted (`[REDACTED_PREVIEW_TOKEN]`) if an idempotent operation receipt containing one is inspected later on the Admin Plane.
</Note>
