---
title: "Core Concepts"
description: "The multi-stage turn spine, immutable log tree, unified WorldState, and prompt-cache zones."
---

> Documentation Index
> Fetch the complete documentation index at: https://tavern.piepia.space/llms.txt
> Use this file to discover all available pages before exploring further.

# Core Concepts

Effect Tavern separates **narrative prose**, **mechanical settlement**, and **structured memory** at the protocol level. Every runtime behavior derives from a small set of orthogonal primitives defined in `packages/runtime/src/`.

## 1. The Eight-Stage Turn Spine

A player turn is a fixed execution pipeline rather than a single LLM completion:

Structured stages are **strictly opt-in**: a pure chat card (`banxing.yaml`) executes only `narrate` and `record`. All other stages activate automatically when the card declares their inputs.

| Stage | Runs When | Reads | Responsibility |
| - | - | - | - |
| `lookup` | Unlocked `lore`, pack `entries`, or `recall` rows exist | `<world>`, `<input>`, factual ledger, host `catalog` | Settles via `DecisionModel` on a complete catalog (`p > 0.5`, top 8), else runs the LLM `search_context` / `read_context` loop, freezing `deliveries` |
| `decide` | `rules.actions` non-empty & `act` input | `<world>`, `<input>` (excluding `thought`), available actions | Picks an action ID and estimates `{ judge }` chance if declared (single beat per turn) |
| `settle` | `decide` chose an action | Seeded RNG + `rules` | Pure code: rolls dice, clamps `fields`, emits turn `events`, records `Beat` |
| `gate` | `lore` entries exist | Post-settlement `WorldState` + turn events | Pure code: evaluates monotone `unlock` floors and per-turn `offer` windows |
| `direct` | `card.director: true` & windows opened | `<world>`, factual ledger, open windows, `<input>` | Partitions open lore into `must` vs. `may` and emits a one-line scene `tone` (`Brief`) |
| `narrate` | Every turn | Full `frame`, `<fiction>` bands, `transcript`, `tail` | Streams story prose |
| `check` | `guard` or `must` non-empty | `<world>`, `review.head`, `<draft>` prose | Runs `DecisionModel` fast pass when enabled; falls back to LLM `check` when ambiguous, triggering at most one correction rewrite |
| `polish` | `switches.polish !== false` & `lexicon` hit | `<world>`, `review.head`, `<draft>` matched sentences | Rewrites only narration sentences outside dialogue that match `lexicon` slop patterns |
| `record` | Every turn | `<world>`, `review.head`, `<scene>` final prose | Answers `readouts`, extracts `chronicle`/`theater` products, commits sparse `world` `DomainChange` ops |

### Decision Model Pre-Check (`lookup` & `check`)

Alongside language-model `Connection`s, Effect Tavern supports an optional install-wide **Decision Model** (`/decision`: Google Gemini Decisions, OpenAI Decisions, or TypeSafe Jev), toggled via the **Pre-check** switch on the default-model page:

- **Complete-catalog `lookup`:** Each turn builds a host `catalog` view (`context.ts`). When the catalog fits `≤ 256` units and `≤ 10,000` characters, the Decision Model scores unread entry hooks and unread sections of resident entries (`p > 0.5`, up to 8) and settles `lookup` with zero language-model calls. Larger catalogs or unavailable decision services fall back seamlessly to the LLM tool loop.
- **Fast-pass `check`:** Evaluates `guard` prohibitions and open lore disclosures as boolean probability questions (`LO = 0.25`, `HI = 0.75`). When every answer is clear-cut and clean, `check` settles immediately; the Decision Model **never** triggers a correction rewrite by itself—any borderline score or error hands off to the LLM `check`.

> **Why Not One Completion + Regex Status Bars?**
>
> Legacy tavern setups force a single chat completion to simultaneously write prose, reason inside `<thinking>` tags, format `<status>` or MVU JSON patches, and suggest player choices—then scrape and hide those blocks with client regexes. In Effect Tavern, `narrate` writes prose only and **never** sees raw field numbers (state reaches narration strictly via `when`-gated `fiction` bands). Dice settle in code (`settle`), while state judgements and structured tables run in `record` against strict schemas.

## 2. Two Coordinates, One `Card` Schema (Beyond "Character Cards")

SillyTavern's `chara_card_v2` / `ccv3` format assumes every card is a single NPC (`description`, `personality`, `scenario`, `mes_example`), forcing ensemble casts, tabletop RPGs, and world simulations to abuse character fields as makeshift scripts. Effect Tavern uses a single `Card` schema across all genres, distinguished along two orthogonal coordinates:

1. **Player presence (`persona` frame slot):**
   - **Participant mode** (`persona` filled): the player inhabits a character in the scene. Private diegetic `thought` (marked e.g. with `⦅⦆`) stays in the transcript for *dramatic irony* while `decide` ignores it (*has no agency*).
   - **Author mode** (`persona` empty): the player directs from outside the story while the narrator writes every character.
2. **Default input channel (`input`):**
   - `"act"` enters the `transcript` as in-world speech and action.
   - `"note"` feeds `direct` and `narrate` on the current turn only, never entering the historical transcript—eliminating inline `[OOC: ...]` chat brackets and sticky `Author's Note` hacks at the data-model level.

## 3. Immutable Log Tree vs. Flat Swipes & Checkpoints

Legacy clients store a flat message array with per-message `swipes[]`, duplicating entire chat files to branch mid-story and frequently desynchronizing external variable plugins on rewind. Runtime, server, and client in Effect Tavern share a single zero-dependency immutable tree (`packages/runtime/src/log.ts`):

- **Nodes store only ground-truth inputs and outputs:** player `input`, RNG seeds (`beats`), frozen `deliveries`, model `reply` parts, `readout` `answers`, `products`, `DomainChange` ops, and manual `adjust` edits. Snapshots of derived state are never stored on nodes.
- **`head` is the single cursor:** a leaf node ID (or `null` on an empty thread). `checkout` moves `head` to any branch's newest leaf; `drop` removes a subtree.
- **Sibling actions restart at exact stage boundaries** instead of a single undifferentiated "reroll":
  - `swipe` re-runs from `lookup` (fresh retrieval, fresh dice, fresh prose).
  - `reword` re-runs from `narrate` (keeping `deliveries` and settled `beats`), optionally appending a one-turn `note`.
  - `edit` replaces prose, revises `input` while keeping prose, or both—re-running only `check` and `record` so state re-settles cleanly.
- **Everything else is `Derived` (`derived.ts`):** `WorldState`, transcripts, per-turn `Ledger` pills, `TimelineNode` / `TurnDetail` projections, and prefix compression folds are pure functions of the root-to-node path.
- **Post-record `passages` & terminal leaves:** After a player turn's `record` commits, the harness evaluates `Card.passages` (`when` first-match-wins, non-reentrant) to append chapter or macro-loop transition nodes (`passage: true`). A passage declaring `digest` runs an interval `record` pass over the ending epoch and sets `boundary: true`—slicing `narratorHistory`, `ledger`, `Known:`, prefix folds, and `window` lore residency cleanly at the new epoch while keeping scalar `fields`, `lore` unlock floors, and `world`/`chronicle` state folded across the entire path. Nodes ending with `end: "over"` (`end: true` on a passage or `rules.over`) reject further child turns.

## 4. Unified `WorldState` & Three Product Roles

Condition trees (`Cond`) evaluate against a single unified `WorldState`: `{ fields, world, lore }`. Products extracted per turn declare one of three explicit roles (`Product.role`):

| Role | State & Accumulation | Model Feedback | Client Surface |
| --- | --- | --- | --- |
| `world` | Mutable records/tables (`scene`, `people`, `bag`) updated via two-phase `DomainChange` transactions (`insert_entity`, `patch_entity`, `remove_entity`, `patch_record`, `replace`) | `feed: true` → `Current:` line; `recall` → `lookup` index; readable in `Cond` as `world.<id>.<key>` | Status / Readings sheet & per-turn `Ledger` |
| `chronicle` | Path-folded memory (`fold`: `append`, `latest`, or `{ key }`), e.g. default `notes` | `feed: true` → `Known:` line & prefix compression fold; `recall` → `lookup` | Inspector |
| `theater` | Player-only output (`inner`, `options`, commentary) written in `record` | Never fed back or recalled (`feed` / `recall` forbidden); supports on-node `demand` | Inline beneath turn prose (or composer chips for `options`) |

## 5. Two-Zone Prompt Assembly (Why Chat `Depth` Does Not Exist)

Legacy tavern cards and presets rely heavily on numeric **depth injection** (`at_depth` / `@D0`–`@D4`, `Author's Note`, `post_history_instructions`), splicing system instructions `N` messages above the bottom of the chat log. Every new turn shifts which historical message sits at depth `N`, mutating the middle of the message array and **invalidating the LLM provider's KV prefix cache on every single turn** while breaking up chronological dialogue.

Effect Tavern enforces **strictly two prompt zones** (`head` and `tail`):

- **`head` & shared off-stage `<standing_context>` prefix:** `narrate` assembles `<standing_context>` (active system head fragments and standing pack entries), `<writing_switches>` (compiled narrator switches), and active `<fiction>` bands into a stable prefix before the `transcript`. Off-stage passes (`lookup`, `decide`, `direct`, `check`, `polish`, `record`) read the harness read-only stage fence plus `<standing_context>` as reference—`lookup`, `decide`, and `direct` share the `frame` prefix breakpoint, while `check`, `polish`, and `record` share the `reviewed` prefix breakpoint (including `review.head`)—with task material enclosed in `<input>`, `<draft>`, or `<scene>` tags before the stage's task prompt. The independent `DecisionModel` checker receives a compact `<world>` projection (`checkBackground`: `persona`, `setting`, and card-declared background slots).
- **`tail`** sits immediately *after* the `transcript` and current player input in `narrate`, holding `<recalled_context>` (delivered entries), `<turn_state>` (beat outcomes, `Current:`), `<stage_directions>` (`MUST`/`MAY reveal`, `Brief` tone, `note`), `<correction>`, and `<writing_tail>` (player tail fragments)—giving turn-level context maximum recency attention (`@D0`-equivalent position) without ever mutating historical turns.
- **Interval `Fold` vs. rolling summaries:** Instead of rolling chat-summarizer plugins that rewrite a depth-injected summary every few turns, prefix compression folds older turns' `notes` and disclosed lore by code over fixed node intervals into `<story_summary>`. Because each folded block depends only on nodes inside its closed interval, prompt-cache breakpoints (`head` end, folded prefix, and last prior turn) stay byte-identical across turns and across branches.

Source: https://tavern.piepia.space/concepts/index.mdx
