# Relations & Page 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:<targetId>` 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=<id>`), 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[<field>][<op>]=<value>` (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).
