# Select & Reference Fields

> Enumerated select fields (single/multi, allowCustom, per-option instructions) and relational reference fields (integrity modes, cycle guards, searchable /options rescue, and batched expand).

`select` models finite enumerations and tags defined inside the schema, while `reference` models relational links between content entries across post types.

---

## `select`

Use `select` when values come from a curated set of options (such as article category, callout tone, or difficulty level), optionally allowing custom values.

### Constraints

| Constraint Key | Type | Default | Description |
| --- | --- | --- | --- |
| `options` | `SelectOption[]` | `[]` | Array of `{ value, label, instruction? }` objects. At least one option is required unless `allowCustom: true`. Duplicate or empty `value` entries are rejected at schema save (`duplicate_select_option`). |
| `multiple` | `boolean` | `false` | When `false`, the value is a single `string`. When `true`, the value is a `string[]` array. |
| `allowCustom` | `boolean` | `false` | When `true`, permits non-empty custom string values not listed in `options`. |
| `minItems` | `integer` | — | Minimum array length when `multiple: true` (`>= 0`). Fails with `min_items`. |
| `maxItems` | `integer` | — | Maximum array length when `multiple: true` (`>= minItems`). Fails with `max_items`. |

### Exact Validation Behavior

- **Case-sensitive exact matching:** Option values are matched strictly by exact string equality (`"Guide"` does not match `"guide"`). Unlisted values fail with `invalid_option` and return `constraint.allowedValues`.
- **No empty values:** Empty strings are rejected in multi-select arrays and in `allowCustom: true` single-select fields (except when `requiredOn: "publish"` allows an empty draft).
- **No duplicates in multi-select:** Repeating the same option inside a `multiple: true` array fails with `duplicate_select_value`.
- **Per-option `instruction`:** Each `SelectOption` can include an `instruction` string explaining *when* an AI agent or editor should choose that option.
- **Indexing:** When `filterable: true`, multi-select fields write one `entry_field_index` row per selected value, so `filter[tags][eq]=go` and `filter[tags][in]=go,rust` match any entry containing that tag.

### Schema & Payload Examples

```json
{
  "key": "difficulty",
  "label": "Difficulty Level",
  "type": "select",
  "required": true,
  "requiredOn": "publish",
  "filterable": true,
  "sortable": true,
  "constraints": {
    "multiple": false,
    "allowCustom": false,
    "options": [
      {
        "value": "beginner",
        "label": "Beginner",
        "instruction": "Use for introductory guides requiring no prior OvertCMS experience."
      },
      {
        "value": "intermediate",
        "label": "Intermediate",
        "instruction": "Use for workflows involving schemas, webhooks, or API keys."
      },
      {
        "value": "advanced",
        "label": "Advanced",
        "instruction": "Use for split-plane production architecture and custom integrations."
      }
    ]
  }
}
```

- **Valid:** `"intermediate"`
- **Invalid:** `"Intermediate"` (`invalid_option` — case-sensitive), `["beginner"]` (`invalid_type` — `multiple` is `false`)

---

## `reference`

Use `reference` to link an entry to one or more entries in specified target post types (such as an article's `author`, a product's `categories`, or a documentation page's self-referencing `parent`).

### Constraints

| Constraint Key | Type | Default | Description |
| --- | --- | --- | --- |
| `targets` | `string[]` | Required (min 1) | Non-empty list of allowed target post-type slugs (polymorphic references are supported by listing multiple slugs). Duplicates fail with `duplicate_reference_target`. |
| `multiple` | `boolean` | `false` | When `false`, value is a single entry ID string. When `true`, value is an array of entry ID strings (`string[]`). |
| `minItems` | `integer` | — | Minimum number of referenced entries when `multiple: true`. |
| `maxItems` | `integer` | — | Maximum number of referenced entries when `multiple: true`. |
| `integrity` | `"strong"` \| `"weak"` | `"strong"` | Referential integrity mode enforced when a target entry is trashed or purged. |

### Referential Integrity (`strong` vs `weak`)

OvertCMS extracts every reference (including those inside nested objects, lists, and `<cms-block>` props) into the `entry_references` table across **both** `draft` and `published` snapshots:

- **Target verification on write:** Every referenced entry ID must exist in the same site (`reference_target_not_found`), must not be `trashed` (`reference_target_trashed`), and must belong to one of `constraints.targets` (`reference_target_type_mismatch`). Every reference validation issue includes `searchEndpoint` so agents can immediately discover valid target IDs.
- **`integrity: "strong"` (default):** Trashing or permanently purging a target entry that has incoming `strong` references from any non-trashed entry is **blocked** with `409 reference_in_use`, returning a `details.referencedBy` list of `{ id, postType, field }`.
  - Human Admin users may override strong references with `force: true`.
  - **Agents can never force-delete** strong references (`input.Force` is unconditionally forced to `false` on the Agent Plane and MCP).
- **`integrity: "weak"`:** Allows the target entry to be trashed or purged even while referenced.

### Self-Referencing Trees & Cycle Guard

A post type can include itself in `constraints.targets` (for example, `docs` with a single-reference `parent` field targeting `["docs"]`) to build hierarchical trees:

- **Write-time cycle guard:** On every update, publish, schedule, or restore, OvertCMS performs a breadth-first traversal of outgoing references starting from the target(s). Direct self-references (`A -> A`) and indirect cycles (`A -> B -> C -> A`) are rejected with `422 reference_cycle_detected`.
- **Traversal safety cap:** Graph cycle walks are bounded at **256 nodes**; deeper graphs fail safely with `422 reference_cycle_depth_exceeded`.
- **Delivery tree queries:** On `GET /delivery/v1/{postType}`, if a post type has a single-value self-referencing field (preferring the key `"parent"` when multiple exist):
  - `?parent=root` returns only top-level published entries (where the self-reference is `null`).
  - `?parent=<entryId>` returns direct published children of `<entryId>`.
  - `?tree=true` attaches nested published `children[]` breadth-first up to **depth 5** and **1,000 total nodes** with cycle protection.

---

## Searchable Reference Options & Empty-Search Rescue

Schemas returned by `/agent/v1/schema` and `/agent/v1/schema/{postType}` automatically populate `searchEndpoint` on every `reference` field:

```text
GET /agent/v1/collections/{postType}/fields/{fieldKey}/options?q=ada&limit=20
```

(Or via MCP using [`cms_search_reference_options`](/agents/mcp-server#cms_search_reference_options).)

### Query Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| `q` | `string` | Accent- and case-folded search string matched against target entries' display labels, slugs, and search keys. |
| `target` | `string` | Optional single post-type slug to narrow a polymorphic reference field. |
| `limit` | `integer` | Page size (default `20`, max `100`). |
| `cursor` | `string` | Opaque keyset pagination cursor returned as `nextCursor`. |

### Empty-Search Rescue (`suggestedOptions`)

If an AI agent searches with a misspelled or slightly off query `q` that matches **0 items**, and the target pool contains **50 or fewer** eligible entries (`totalEligible <= 50`), OvertCMS automatically populates `suggestedOptions` with up to **10 existing target options** so the agent can self-correct in a single turn without guessing:

```json
{
  "field": "author",
  "targets": ["authors"],
  "items": [],
  "hasMore": false,
  "totalEligible": 8,
  "suggestedOptions": [
    {
      "id": "0195c8a2-0001-7000-8000-000000000001",
      "postType": "authors",
      "slug": "ada-lovelace",
      "label": "Ada Lovelace",
      "status": "published"
    }
  ]
}
```

---

## Batched Reference Expansion on Delivery (`?expand=`)

On the Delivery Plane (`GET /delivery/v1/{postType}`, `GET /delivery/v1/{postType}/{idOrSlug}`, and `GET /delivery/v1/singletons/{slug}`), pass a comma-separated list of top-level reference field keys in `expand`:

```http
GET /delivery/v1/posts?expand=author,categories&depth=2
```

- **Zero N+1 queries:** OvertCMS collects all referenced IDs across every entry on the page and resolves each depth level in a single batched `GetByIDs` query.
- **Depth bounds:** `depth` defaults to `1` when `expand` is present and is capped at **`2`** (`maxDeliveryExpandDepth`).
- **Strict publication & scope isolation:** Only `published` targets (with non-null `publishedData` and allowed by the Delivery API key's `allowedPostTypes`, if enabled) are hydrated. Unpublished, missing, or disallowed targets are **never leaked**—single references become `null` and multi-reference arrays omit them.
- **Cycle protection:** Ancestor entry IDs along the expansion path are skipped automatically.
- **Cache invalidation:** Every expanded target's `entry:<id>` is automatically added to the response's `Surrogate-Key` header (on public Delivery responses) so updating an author invalidates cached posts that expanded that author.
