# MysteryForge Game Definition Format (GDF) — v1

This document is the **contract** between game designers, AI agents, the MysteryForge
runtime, and the MCP server. A MysteryForge game is a Godot 4.7+ project containing the
`addons/mystery_forge/` runtime plus a `game/` directory of declarative JSON and assets.
The runtime interprets the JSON; nothing about a specific game lives in code.

Design goals:

- **Human-writable, AI-writable.** Plain JSON, snake_case ids, normalized coordinates,
  forgiving defaults. An agent can author a whole game without touching a `.tscn` file.
- **Validatable.** Every cross-reference (scene → scene, hotspot → item, choice → node)
  can be checked statically. `tools/validate.gd` and the MCP `validate_project` tool
  report precise, actionable errors.
- **Asset-swappable.** The classic adventure-series model: one engine, twenty years of
  games. Replace the JSON and assets, get a new game.

## Directory layout

```
<project>/                      Godot project root
  project.godot                 engine config (managed by MysteryForge, rarely touched)
  addons/mystery_forge/         the runtime (do not edit per-game)
  game/
    project.json                game metadata, start scene
    variables.json              flags & counters with initial values
    items.json                  inventory items
    characters.json             characters (names, portraits)
    scenes/<scene_id>.json      one file per scene
    dialogues/<dialogue_id>.json one file per dialogue tree
    puzzles/<puzzle_id>.json    one file per puzzle instance
    hints.json                  optional: the Hint button's ordered hint entries
    contacts.json               optional: the in-game phone's contacts
    topics.json                 optional: things characters can be asked about (see "Topics & conversations")
    clues.json  deductions.json optional: the case board — clues to find, conclusions to draw (see "Clues & deductions")
    achievements.json           optional: things the player earns across saves (see "Achievements")
    endings.json                optional: the named, tiered endings (see "Endings")
    mystery.json                optional: who did it, what proves it, and the final accusation (see "Mystery model & accusation")
    links.json                  optional: doors joining two scenes, both ways at once (see "Links")
    regions.json                optional: the location tree — buildings, floors, wings — with a map each (see "Regions & maps")
    walkthroughs/<name>.json    optional: scripted playthroughs replayed by `make walkthrough`
    review/comments.json        optional: review notes pinned to places in the game (see "Review mode"; never ships)
    art/                        optional: the real-art workbook (bible, shots, provenance; never ships)
    scripts/                    optional: game-local GDScript (custom puzzles, steps, checks)
      actions/<name>.gd  conditions/<name>.gd  puzzles/<name>.gd
    assets/
      backgrounds/              scene background images (svg/png/jpg/webp)
      items/                    inventory icons (~256x256)
      portraits/                character portraits (~512x512)
      voice/                    recorded dialogue audio (wav/ogg)
      sfx/                      sound effects (wav/ogg)
      music/                    music & ambient loops (wav/ogg)
```

**Asset paths** in JSON are always relative to the project root, e.g.
`"game/assets/backgrounds/foyer.svg"`. No `res://` prefix.

**Ids** are snake_case: `[a-z][a-z0-9_]*`. Scene/dialogue/puzzle file names must equal
the `id` field inside them (`scenes/foyer.json` → `"id": "foyer"`).

**Coordinates** are normalized 0.0–1.0 relative to the design resolution
(default 1920×1080). `[0.5, 0.5]` is screen center regardless of window size.

## project.json

```jsonc
{
  "id": "cellar_key",                  // snake_case, used for save folder
  "title": "The Case of the Cellar Key",
  "former_titles": ["The Cellar Key"], // optional: the game's earlier titles, so its players keep their saves (see "Renaming a game")
  "version": "0.1.0",
  "format_version": 1,                 // optional: the game-data format these files use (see "Versioning")
  "author": "Studio Name",             // optional
  "start_scene": "foyer",              // scene shown on New Game
  "start_actions": [],                 // Actions run once on New Game, before the scene
  "resolution": { "width": 1920, "height": 1080 },   // optional, this is the default
  "ui": {
    "accent_color": "#d4af6a",         // optional hex, themes buttons/highlights
    "skin": { /* optional: one look for the menus, panels and every puzzle — see "Skin" */ },
    "show_hotspot_labels": true,       // optional, default true: label near cursor on hover
    "dialogue_portraits": "auto",      // optional: "auto" (default) hides the big conversation portrait while the speaker
                                       // is standing in the room as an actor; "always" keeps it up as well
    "title_background": "game/assets/ui/title.webp",   // optional: a picture behind the title screen — see "Title screen & startup cards"
    "title_side": "left"               // optional: where the title and its buttons stand on it: "left", "center" (default) or "right"
  },
  "map": { "background": "game/assets/backgrounds/manor_map.svg", "auto": false },  // optional map screen (the top level; see "Regions & maps")
  "audio": { "duck_db": -9, "crossfade": 1.2 },   // optional mix: how far music ducks under speech (0 = never), seconds to fade between music files
  "budget": {                          // optional: memory and size limits `make budget` holds the game to (see "Budgets"); all optional
    "scene_vram_mb": 512,              // one room's pictures in video memory
    "working_set_vram_mb": 1024,       // a room plus the rooms one door away (they are preloaded)
    "texture_max_px": 8192,            // the longest edge of any picture
    "game_disk_mb": 4096               // everything under game/assets
  },
  "time": { /* optional: the game's clock — days made of named phases; see "Time & schedules" */ },
  "chapters": [ /* optional: acts — a title card and a fresh set of steps; see "Chapters, checkpoints & migrations" */ ],
  "migrations": [ /* optional: bring players' older saves up to date; see "Chapters, checkpoints & migrations" */ ],
  "difficulty": {                      // optional: two or more levels ask the player on New Game
    "levels": [
      { "id": "junior", "name": "Junior Detective", "description": "Hints on tap, gentler puzzles." },
      { "id": "senior", "name": "Senior Detective", "description": "You're on your own.", "hints": false }
    ],
    "default": "senior"                // level used when the player isn't asked (default: the first)
  },
  "credits": "Written by ...",         // optional, shown on the end screen
  "subtitle": "An Inspector Hale Mystery: Episode 2",   // optional: the line under the title on the title screen (else the author)
  "splash": [                          // optional: startup cards, shown once when the game starts — see "Title screen & startup cards"
    { "image": "game/assets/backgrounds/studio_card.webp", "seconds": 3, "text": "Larkspur Games presents" }
  ]
}
```

### Title screen & startup cards

The title screen shows the game's `title`, and under it the `subtitle` when there is one (a series line such as "An Inspector Hale
Mystery: Episode 2"), otherwise the `author`. Both are translatable.

`ui.title_background` puts a picture behind it — the game's key art, filling the screen (cropped to fill, so paint it at the game's
shape or wider). `ui.title_side` says where the title and its buttons stand on it: `"left"` or `"right"` puts them in that side's
column over a soft shade (so paint the picture's subject on the other side and keep that side quiet), `"center"` (the default) puts
them in the middle over a lighter, even shade. Over a picture the lettering gets a shadow. Without a picture the title screen is the
engine's own dark ground.

`splash` is a list of **startup cards**, shown one after another when the game starts — after Godot's own boot splash, before the
title, never again in that session. Each card is a full-screen picture (`image`, kept to its shape on a black ground: draw it at the
game's resolution, or 1.5× for Retina screens) that fades in, holds for `seconds` (default 3, 0.5 to 15) and fades out. **Any click,
tap or key moves on at once** — a player is never made to sit through them — and Reduce motion drops the fades. `text` is what a
screen reader says for the card (its words, say), and is translatable. Bots, tests and headless runs skip the cards; a screenshot run
shows them only with `--mf-splash`.

### Renaming a game

On a computer, Godot keeps a game's settings, saves and achievements in a folder named after its **title**
(`…/Godot/app_userdata/<title>`), so changing the title alone would greet every player with an empty Continue. List the
earlier titles in `former_titles` (newest first): on the first start under the new title — while its folder holds nothing
of the player's yet — the game **copies** everything MysteryForge kept in the first earlier folder that has some
(settings, every player's saves, autosave, checkpoint, achievements; never the bots' scratch saves). It copies and never
moves, so the old folder stays behind untouched as a backup, and it never writes over a file already there. Headless runs
(tools and tests) never do it; the web build keeps its data per site rather than per title, so it has nothing to carry; and a
game that names its own data folder (`application/config/use_custom_user_dir`) is left alone. The validator warns when a
former title is the current one. Keep the old titles listed for as long as anyone might still have a save from then.

### Living portraits

A 3D character can talk the way the classic pre-rendered adventures' characters did: never frozen, breathing, glancing,
nodding, with a mouth that follows the voice. `portrait_motion` holds pre-rendered loops, each a sheet of frames (`image`,
`columns`, `rows`, `count`, played at `fps`):

- **`idle`** (required) plays while the character listens or between lines: breathing, a drifting head, a blink.
- **`talk`** (a list) plays while their voice line plays, one loop after another in turn, so a long scene doesn't repeat a
  gesture. Talk frames have the mouth **closed**; each loop's optional **`mouths`** sheet holds, for every frame (its
  columns), small patches of the same frame with the mouth more and more open (its rows: `shapes` of them, half-open first,
  widest last), each `size` big and laid at that frame's `at` (both fractions of the frame). While the voice plays, the
  engine listens to it (the same lip-sync as actors, see "Actors") and lays the patch for how open the mouth should be over
  the face — so a moving head lip-syncs any recording with nothing authored per line.
- Every loop starts and ends on the **same neutral pose**: talking starts a talk loop from its first frame (a short
  cross-fade hides the step from the idle loop), a line that ends mid-loop finishes it with the mouth shut, and the idle loop
  then carries on from its own first frame. Reduce motion holds the first frame and keeps only the mouth.
- Frames need not be square: a waist-up shot (say 480×640, so the hands can gesture in frame) is shown as tall as its shape
  needs, growing upward from the bottom of the usual portrait box (at most 640 of 1080 high); `size` and `at` are fractions
  of the frame's width and height. **`still`** (optional, recommended) is that shot's first idle frame — shown while the
  sheets load (the web build fetches them after start, see "Web builds: the late pack") so the picture doesn't change shape
  or framing when they arrive; without it the square `portrait` stands in.
- A mouth sheet may name its rows: **`visemes`** lists each row's mouth shape (see "Mouth shapes" below), e.g.
  `["open", "wide", "press", "teeth", "round", "pucker", "fv"]`. A voice line with a mouth track then shows the row for the
  shape it asks for at each moment; without a track, loudness picks among the rows named `open` and `wide`. A sheet whose
  rows are not named is ordered half-open → widest as above.
- `portrait_motion` wins over `portrait_video`, the static `portrait` and `talk_frames` in conversation; the `portrait`
  stays the character's picture everywhere else (the dossier, the case board). The validator checks the sheets exist, the
  counts fit the grids and there is one `at` per frame.

### Mouth shapes

A voice line may come with a **mouth track**: which mouth shape shows when, worked out from the recording and the line's
text. It lives beside the recording as `<voice>.lips.json` (same folder, same name, `.lips.json` for the extension) and is
made by `tools/lipsync.py` with Rhubarb Lip Sync (an outside program: `MF_RHUBARB` names it, else `rhubarb` on the PATH):

```json5
{ "lips": 1, "made_by": "rhubarb", "source_sha1": "<the recording's SHA-1>", "duration": 9.61,
  "cues": [ [0.0, "rest"], [0.02, "round"], [0.18, "pucker"], [0.25, "teeth"] ] }   // [seconds, shape], each until the next
```

The shapes are `rest` (closed, no patch), `press` (lips pressed: m b p), `teeth` (teeth together: k s t ee), `open` (eh ae),
`wide` (ah), `round` (oh aw), `pucker` (oo w), `fv` (upper teeth on the lower lip: f v) and `tongue` (a long l). A living
portrait shows the row its mouth sheet's `visemes` names for the shape, or the next best one it has (pucker → round →
open, f/v → teeth → open, a missing `press` is the closed frame); anything that only goes from closed to wide (an actor's
talk `frames`, a sheet without `visemes`) opens as far as the shape is open. A line without a track is driven by its
loudness, as before — a track is an improvement, never a requirement. `tools/lipsync.py` makes a track for every recording
under `game/assets/voice/` that lacks a current one (a track remembers its recording's SHA-1, so a re-recorded line gets a
new one; a track whose recording is gone is removed; the engine ignores a track whose `duration` is more than a quarter
second off its recording's length); recordings that are not a line's — a language pack's — use Rhubarb's
language-independent recognizer. `--check` only reports. `make lipsync GAME=<folder>` runs it.

### Web builds: the late pack

A web build downloads the whole game pack before its title can show, and living portraits' sheets are big (a few MB a
character). So `tools/deploy_cloudflare.py` leaves every sheet a character's `portrait_motion` names — and every actor
pose's `sheet` that has an `image` to stand still in meanwhile (a figure's loops in a room) — out of the main pack and
ships them in a second one, `late.pck` (built by `tools/late_pack.gd`: each asset's `.import` and imported files),
with `late.json` beside the page — `{"url": "late.pck", "sha256": "<hex>", "size": <bytes>, "files": [...]}`. Once the
game runs, `core/late_pack.gd` downloads it into memory (never `user://`: on the web that is IndexedDB, which holds a file
of at most ~128 MB, and one bigger made every save fail — the browser's HTTP cache keeps the download for the next
visit), checks its size and SHA-256 and mounts it; until then a conversation shows the still `portrait` and a figure in a
room stands still in its pose's `image` (it picks up its loop when the pack mounts). A build with no
`late.json` (desktop, a plain `make export-web`) has everything in its main pack. Nothing in a game's files changes.

The **voice lines** go late too — all but the opening's (the start scene's own, those of every dialogue it names, and the start
actions'), which stay in the main pack: a line whose recording has not arrived yet is shown as text and waits for a click. They
travel in a pack of their own fetched first, because a player meets them sooner than the portraits: `late.json` then names the
voice pack and chains the next with `"next": "late2.json"` (the sheets in `late2.pck`, `late3.pck`, … — each manifest names the
next). Each pack is a file of its own because hosts cap a file's size (itch.io: 200 MB): the deploy fills a pack to 180 MB and
starts the next, so a group of any size stays under the cap; `core/late_pack.gd` mounts each as it arrives and never deletes a
mounted pack while fetching the next.

### Difficulty levels

With two or more `difficulty.levels`, **New Game** first asks the player to choose one.
The choice is stored in the built-in variable **`difficulty`** (the level's `id`), so any
condition can branch on it: `{ "var": "difficulty", "eq": "junior" }` — show an extra hint
hotspot, start an easier puzzle variant, hide a time limit. A level may set
`"hints": false` to switch the Hint button off. With one level or none, the player isn't
asked and `difficulty` holds the default (or `""`).

Two variables are **built in** and need no declaration in `variables.json`:
`difficulty` (above) and `hints_used` (how many hint levels the player has revealed — handy
for an end-screen rank: `{ "var": "hints_used", "lt": 3 }`).

### Versioning

Two version numbers keep long-lived games upgradable:

- **Engine version** (`ENGINE_VERSION` in `addons/mystery_forge/core/version.gd`, e.g. `0.3.0`) — the addon's
  release. Every game folder carries its own copy of the addon (the classic adventure-series model: an engine per game),
  so a game keeps working exactly as shipped until you choose to upgrade it.
- **Format version** (`FORMAT_VERSION`, and `format_version` in `project.json`) — the game-data format in this
  document. It only changes when existing game files would need *rewriting*; new optional features
  never bump it. A game newer than its engine fails validation; an older one gets a warning.

To move a game to a newer engine, run **`make upgrade-game GAME=/path/to/game`** (or the MCP `upgrade_engine`
tool, or the Studio's "Upgrade engine" button on the Dashboard). It backs up the old addon to
`.mf_backup/<timestamp>/`, replaces `addons/mystery_forge/`, `addons/mystery_forge_studio/` and `tools/`
(deleting files the new engine no longer has), refreshes the engine tests, tops up `project.godot`, runs any
format migrations in order, and stamps `format_version`. The game's own `game/` data and `game/scripts/` are never
touched except by a migration. `--dry-run` shows what would change.

## variables.json

Flags and counters. Booleans, numbers, or strings. All state an author can branch on
must be declared here (the validator rejects references to undeclared variables).

```jsonc
{
  "variables": {
    "met_housekeeper": false,
    "drawer_unlocked": false,
    "snoop_count": 0
  }
}
```

## items.json

```jsonc
{
  "items": [
    {
      "id": "brass_key",
      "name": "Brass Key",
      "icon": "game/assets/items/brass_key.svg",
      "description": "A small brass key. The bow is shaped like an ivy leaf.",
      "voice": "game/assets/voice/items/brass_key.wav",  // optional, played on examine
      "combine": [                      // optional recipes: put this item together with another
        {
          "with": "iron_hook",          // the other item
          "result": "grappling_hook",   // item made (optional)
          "consume": true,              // default true: both inputs are used up; false keeps them
          "text": "You lash the rope to the hook.",   // optional narration
          "voice": "game/assets/voice/items/lash.wav", // optional
          "if": [],                     // optional Conditions: the recipe only works when true
          "actions": []                 // optional Actions, run after the result is given
        }
      ]
    }
  ]
}
```

### Combining items

While holding an inventory item, clicking *another* inventory item tries to
combine them. A recipe is written on either item and works in both directions
(holding the rope and clicking the hook, or vice versa). If a usable recipe
exists, the inputs are consumed (unless `consume` is `false`), the `result` item is
given, `text` is shown, then `actions` run. If there is none, the player hears
"Those don't go together." and the second item becomes the held one.

## characters.json

```jsonc
{
  "characters": [
    {
      "id": "mrs_hartley",
      "name": "Mrs. Hartley",
      "portrait": "game/assets/portraits/mrs_hartley.svg",
      "portraits": {            // optional expression variants; a node's "emotion" picks one
        "concerned": "game/assets/portraits/mrs_hartley_concerned.svg"
      },
      "talk_frames": [          // optional open-mouth frame(s), alternated with the resting
        "game/assets/portraits/mrs_hartley_talk.svg"   // portrait while a voice line plays
      ],
      "portrait_video": "game/assets/video/hartley.webm", // optional looping video portrait (.webm or .ogv; WebM may be transparent)
                                                          // (overrides the static image + lip-flap)
      "portrait_motion": {      // optional: a LIVING portrait — pre-rendered loops of a 3D character (see "Living portraits")
        "fps": 10,
        "still": "game/assets/portraits/hartley_still.webp",   // optional: the first idle frame, shown while the sheets load
        "idle": { "image": "game/assets/portraits/hartley_idle.webp", "columns": 8, "rows": 5, "count": 40 },
        "talk": [
          { "image": "game/assets/portraits/hartley_talk1.webp", "columns": 6, "rows": 5, "count": 30,
            "mouths": { "image": "game/assets/portraits/hartley_talk1_mouths.webp", "shapes": 2,
                        "visemes": ["open", "wide"],                                // optional: each row's mouth shape
                        "size": [0.2, 0.15], "at": [[0.4, 0.55], [0.4, 0.56]] } }   // one [x, y] per frame
        ]
      },
      "color": "#9ecbff",       // optional, name color in dialogue
      "suspect": true,          // optional: listed in the Suspects dossier from the start
      "bio": "The housekeeper of thirty years.",  // optional, shown in the dossier
      "actor": { /* optional: how they look standing in a room — see "Actors" */ },
      "schedule": [ /* optional: where they are, and when — see "Time & schedules" */ ]
    }
  ]
}
```

Two speaker ids are built in and need no entry: `"player"` (the protagonist; no
portrait, lines shown as your own) and `"narrator"` (italic descriptive text). In a game with a **party** (below), `"player"` is whoever
leads — their name and portrait — and two more are built in: `"@lead"` (the same) and `"@partner"` (the first other member in the party).

### Party — playable characters

A game may let the player be **more than one character**: two brothers, a heroine and her friends, or — for a chapter — someone else
entirely. `project.json` names them; one of them **leads** (the cursor, the player's lines and the hints' point of view are theirs), the
others go along, stand in the room and give the hints. Without a `party` the player is the one anonymous protagonist above, exactly as
before.

```jsonc
// project.json
"party": {
  "members": ["dan", "tom"],           // character ids: who the player can be when a new game starts
  "lead": "dan",                       // optional, default the first member
  "switch": "free",                    // optional: free (the player switches — the party bar, the Switch key Q, a controller's L3), story (only steps do), never
  "companions": true,                  // optional, default true: the others stand in a room that has a `companion` (or `companion_<id>`) marker
  "hint_from": "@partner"              // optional: who gives a hint that names no `from` — "@partner", "@lead" or a character id
}
// characters.json — optional, for a member
"playable": { "hud_portrait": "game/assets/portraits/tom_small.png" }   // the party bar's picture (default: the character's `portrait`)
```

```jsonc
{ "lead": "tom" }                      // a condition: Tom leads now
{ "in_party": "bennett" }              // a condition: Bennett is in the party now
{ "present": ["dan", "tom"] }          // a condition: every one of them is in the party
{ "action": "set_lead", "id": "tom" }  // hand the lead over
{ "action": "set_party", "members": ["bennett"], "lead": "bennett" }   // a chapter played as someone else (everyone not listed leaves the party)
{ "action": "lock_switch" }            // / unlock_switch — hold off the player's switching for a moment
{ "action": "play_voice", "text": { "dan": "Father's papers.", "tom": "Boring.", "*": "A desk." } }   // a line per member ("*": anyone else); `voice` may be a table too, and so may show_text's `text`
```

```jsonc
// a hotspot only one member can use — or only all of them together
{ "id": "ladder", "label": "Ladder", "shape": { /* … */ }, "actions": [ /* … */ ],
  "requires": { "lead": "tom" },                                    // and/or "present": ["dan", "tom"]
  "refusal": { "dan": "Tom's the climber.", "*": "Not me." } }      // what the lead says when it is not met (a string, or a line per member)
```

- **The party bar** (top-left) shows a portrait per member in the party, the lead's raised; pressing another (or the Switch key, rebindable in
  Settings → Controls, or L3 on a controller) hands them the lead. A party of one shows no bar.
- **It is plain game state underneath.** At load the party becomes reserved variables — `@lead` (the lead's id), `@party.<id>` (in the party
  now) and `@party_locked` — the conditions and steps above become variable tests and `set_var`s, a line per member becomes one step per
  member guarded by `@lead`, and every scene gets one hotspot per member, `party_<id>` with `ui: "party"`, which the bar presses through the
  ordinary click path. A hotspot with `requires` shows only while it is met; a twin `<id>__refused` in the same place answers with the refusal
  (and refuses held items without using them up) the rest of the time. So the story check, the exact **soft-lock search**, the bot and
  walkthroughs (`{ "lead": "tom" }`, or `{ "click": "party_tom" }`) need nothing new: a game that can only be won by switching is found
  winnable, and one whose lead can never change cannot.
- **Companions**: a member with an `actor` block, in the party and not leading, stands at the room's `companion_<id>` marker, else its
  `companion` marker (rooms without one show nobody), and can be talked to when the character has `talk`.
- `"player"` lines (`play_voice`, refusals, "That doesn't seem to work.") are said by the lead, by name; the conversation log and the recap
  keep who said each. A hint's `from` may be `"@partner"` or `"@lead"`.
- The validator reports: a member that is not a character, a lead outside the party, a condition, step or `requires` naming someone never in
  it, party conditions or steps in a game without a party, a line keyed by someone never in the party, and a member with no line and no `"*"`.

## Scenes — scenes/<scene_id>.json

A scene is one camera position: a wide location view or a close-up (desk, keypad,
poster). Close-ups are just scenes you `goto_scene` into, with a `move_back` hotspot
to return — exactly the classic slideshow navigation model.

```jsonc
{
  "id": "library",
  "name": "Library",                  // shown in saves & journal context
  "group": "Ground floor",            // optional: the Studio lists rooms with the same group together
  "background": "game/assets/backgrounds/library.svg",   // required — unless the scene has a "panorama" instead
  "panorama": { "image": "game/assets/panoramas/conservatory.png" },   // optional: a 360° look-around view —
                                      // see "Panoramas" below
  "music": "game/assets/music/manor_theme.ogg",     // optional, loops; continues across
                                                    // scenes with the same track
  "ambient": "game/assets/sfx/clock_tick.ogg",      // optional second loop layer
  "video": "game/assets/video/fire_loop.webm",      // optional looping video background
                                                    // (.webm or .ogv — see "Video"); drawn over the still image
  "map_pos": [0.22, 0.5],             // optional: show on the Map screen at this
                                      // normalized 0..1 position (travel when visited)
  "map_when": [ { "var": "at_lake", "eq": false } ],   // optional: the map goes here only while these hold
  "map_leave_when": [ { "var": "door_open", "eq": true } ],  // optional: the map can leave this room only while these hold
  "map_lock": true,                   // optional: the map can never leave this room (a locked closet, a chase)
                                      // — see "Map travel rules"
  "compass": { "n": "attic", "e": "hall", "s": "foyer", "w": "garden" },  // optional:
                                      // an in-game compass turns to these rooms (any subset)
  "transition": "dissolve",           // optional: "fade" (default), "dissolve", or a video clip (.webm/.ogv)
                                      // clip path played as a transition when entering
  "on_first_enter": [],               // Actions, run only the first time ever entered
  "on_enter": [],                     // Actions, run every time (after on_first_enter)
  "overlays": [
    // Images composited over the background, toggled by game state. Use these for
    // visual state changes (an opened drawer, a character present, a taken object's
    // absence) instead of duplicating scenes.
    {
      "id": "note_on_desk",
      "image": "game/assets/backgrounds/overlay_note.svg",
      "rect": [0.41, 0.55, 0.10, 0.08],            // x, y, w, h normalized
      "visible_if": [ { "missing_item": "old_note" } ],
      // optional animation / look — see "Animation" below:
      "frames": ["game/assets/anim/fire_1.png", "game/assets/anim/fire_2.png"],  // cycled at `fps`
      "sheet": { "image": "game/assets/anim/fire_sheet.png", "columns": 4, "rows": 2, "count": 8 },
                                                   // or: frames cut from one grid image (left→right, top→bottom);
                                                   // `count` (default columns × rows) when the last row isn't full
      "video": "game/assets/video/fire.webm",      // or: a looping clip in the rectangle (a transparent WebM keeps its alpha);
                                                   // `image` is the still shown when the clip can't play — see "Video"
      "fps": 8,                                    // default 8
      "loop": true,                                // default true; false = play once, hold the last frame
      "opacity": 1.0,                              // starting transparency 0..1 (default 1)
      "fade": 1.5,                                 // optional: when `visible_if` changes, cross-fade over this many seconds
                                                   // instead of switching at once (see "Atmosphere & camera")
      "parallax": 0.5,                             // optional: drifts against the picture when the camera zooms or pans (see "Parallax")
      "arrived_from": ["garage", "drive"]          // optional: shown only when the player came here from one of these rooms (the car
                                                   // parked where it was left). Visual only — saved with the game, never readable by a condition
    }
  ],
  "fx": [ /* ambient effects drawn over the room — see "Atmosphere & camera" */ ],
  "markers": { /* named standing places for actors — see "Actors" */ },
  "floor": [ /* how big people stand at each depth — see "Actors" */ ],
  "actors": [ /* people standing in the room — see "Actors" */ ],
  "hotspots": [ /* see Hotspots */ ]
}
```

### Panoramas (360° look-around scenes)

A scene may be a **panorama** instead of a single picture: one wide image the player turns around in, the
way the classic games let you spin in a room. It is opt-in per scene — the slideshow + compass model stays the
default and the two mix freely (a panorama room can sit between ordinary ones).

```jsonc
"panorama": {
  "image": "game/assets/panoramas/conservatory.png",   // required: an equirectangular image (2:1 for a full circle)
  "h_span": 360,                      // optional, degrees of a circle the image covers horizontally (10–360, default 360)
  "v_span": 180,                      // optional, degrees vertically (10–180); default: worked out from the image's shape
  "yaw": 0,                           // optional start direction in degrees (+ = right); 0 = the middle of the image
  "pitch": 0,                         // optional start tilt in degrees (+ = up)
  "fov": 90                           // optional start field of view in degrees (clamped to 40–110)
}
```

- **Coordinates are on the flat image.** Hotspots in a panorama scene use the usual `rect` / `circle` / `polygon`
  shapes, normalized 0..1 across the *whole panorama image* (not the screen). The engine projects them onto the
  screen as the view turns, so a hotspot sticks to what it covers. A shape that must cross the image's left/right
  seam is split into two hotspots. A circle's `radius` is a fraction of the image's height.
- **The image** is stretched round a sphere: x is yaw (−`h_span`/2 … +`h_span`/2), y is pitch. A full 360° image
  wraps seamlessly (its left and right edges must match); a partial one (`h_span` < 360) stops the camera at its edges.
- **Looking around:** drag with the mouse, push the pointer against the screen edge, use the arrow keys or the right
  stick; the wheel zooms. `Tab` / `Shift+Tab` (or the left stick / D-pad) still step through hotspots and turn the view
  to face the one that's focused. With *Reduce motion* on, the turn is instant. Clicking is on release, so a drag that
  starts on a hotspot pans instead of clicking it.
- **Overlays work in a panorama.** An overlay's `rect` is on the flat panorama image — the same coordinates a hotspot uses — and
  its picture is bent onto the sphere as the view turns, so a lit lamp, an open drawer or a flickering fire stays glued to
  the spot it covers. Frames, sprite sheets, `video`, `opacity`, `visible_if` and the `move_overlay` / `fade_overlay` /
  `play_overlay` actions all work (`move_overlay` slides across the panorama image). A rectangle may straddle the seam of
  a full 360° image. To put an upright person or prop *in* the room, use an actor (see "Actors"), not an overlay: an overlay
  is part of the painted picture and shares its distortion.
- **Not drawn:** a scene-level `video` behind a panorama (the validator warns — give an overlay a `video` instead). `compass`, `on_enter` and the rest work as usual.
- `background` may be omitted when a `panorama` is present.

### Hotspots

```jsonc
{
  "id": "door_to_study",
  "label": "Study",                   // tooltip near cursor, and the name keyboard / screen-reader / read-aloud players get — the validator warns when it's missing
  "cursor": "move_right",             // see cursor list below; default "examine"
  "shape": { "type": "rect", "rect": [0.86, 0.25, 0.14, 0.55] },   // a way out (it goes to another scene) is warned about below 2.5% of the screen either way: too small to find
  "visible_if": [],                   // Conditions; hidden+inactive when false
  "actions": [                        // run on normal click
    { "action": "goto_scene", "scene": "study" }
  ],
  "use_items": [                      // run instead when the player clicks while
    {                                 // holding a selected inventory item
      "item": "brass_key",
      "consume": false,               // true removes the item on success
      "actions": [ { "action": "set_var", "var": "drawer_unlocked", "value": true } ]
    }
  ],
  "wrong_item_text": "That doesn't fit."   // optional; shown when a held item has no
                                           // use_items entry here. Omit for the
                                           // built-in default line.
}
```

A `use_items` entry has only `item`, `consume` and `actions` (the validator rejects any other key). To make what an item does
depend on the story, give the hotspot a twin on the same spot with its own `visible_if`, or put `if` on the steps themselves.

**Shapes** (all coordinates normalized):

| type      | fields                                   |
|-----------|------------------------------------------|
| `rect`    | `"rect": [x, y, w, h]`                   |
| `polygon` | `"points": [[x,y], [x,y], ...]` (≥3)     |
| `circle`  | `"center": [x, y], "radius": r` (r is a fraction of design height) |

**Overlap.** Where hotspots overlap, the one **later in the list** is on top and gets the click. A hotspot whose whole shape lies
under a later hotspot that is always shown (no `visible_if`) can never be clicked, and the validator reports it as an error — give
the cover a `visible_if` that is false while the hotspot underneath is needed, or put that one after it. Covers that depend on
conditions are found in play: the walkthroughs, the autoplay bot and the fuzz bot click only a hotspot the pointer can reach,
and a walkthrough step that clicks a covered one fails, naming what is on top of it. The HUD is on top of every room: the **inventory tray** (bottom centre — always on
screen while playing, labelled *Inventory*, saying *empty* when it is, and only as wide as what it holds, so the bottom corners
stay free) and the top buttons take the clicks over them, and the bots count them as covering too. Keep a hotspot from lying
wholly under the bottom-centre tray or the top-right buttons.

**Cursors** signal the verb, like the classic magnifying glass:
`default`, `examine`, `take`, `talk`, `action`, `move_left`, `move_right`,
`move_up`, `move_back`.

### Verbs

Some adventures play by *picking a verb, then picking the thing*: Examine, Open, Take, Speak, Hit. A game switches that on by naming its verbs in `project.json`; a hotspot then says what each verb does to it.

```jsonc
"ui": {
  "verbs": {
    "list": [                              // required: at least one; the order is the order of the buttons
      { "id": "examine", "name": "Examine", "cursor": "examine", "refusal": "You see nothing special." },
      { "id": "open", "name": "Open", "cursor": "action" }
    ],
    "sticky": false,                       // true: the verb stays armed after it is used (default: it is put away)
    "rect": [0.04, 0.80, 0.92, 0.07]       // where the verb bar sits: fractions of the window (this is the default)
  }
}
```

```jsonc
{
  "id": "desk_drawer",
  "label": "Drawer",
  "shape": { "type": "rect", "rect": [0.3, 0.5, 0.2, 0.15] },
  "actions": [],                           // a plain click (no verb armed) — may be empty
  "verbs": {                               // verb id → the steps that verb runs on this hotspot
    "examine": [ { "action": "show_text", "text": "A drawer with a small brass lock." } ],
    "open": [ { "action": "set_var", "var": "drawer_open", "value": true } ]
  }
}
```

- **Arming.** The verb bar has one button per verb. Pressing one arms it (the cursor takes the verb's `cursor`, default `action`); pressing it again, or holding an item, puts it away — a verb and a held item are never both in hand. With a verb armed, the next click on a hotspot runs that hotspot's steps *for that verb*; the verb is then put away unless `sticky`.
- **A verb the hotspot does not answer to** says the hotspot's `wrong_item_text`, else the verb's `refusal`, else "That doesn't work." — and runs nothing. A plain click on a hotspot with no `actions` but with verbs asks the player to choose a verb first.
- **It is "hold an item and click", underneath.** At load a hotspot's `verbs` table is rewritten into `use_items` entries whose item is the pseudo item `@verb:<id>` (always available, never in an inventory), so the validator, story check, **soft-lock search**, bot and walkthroughs all treat each verb as the move it is. A mistake in a verb's steps is reported at `…hotspots[n].verbs.<id>`.
- **Walkthroughs** say `{ "verb": "open", "on": "desk_drawer" }`. **Typed play** (`make text-play`) takes the game's own verbs as commands — `open drawer`, `examine drawer` — ahead of the built-in synonyms.
- **Translation.** Verb `name` and `refusal` lines are translatable strings like any other text.
- **Verbs on what you carry.** An inventory item may have the same table in `items.json`: `"verbs": { "examine": [steps], "open": [steps] }`. With a verb armed, pressing an inventory item runs its steps for that verb (or the verb's `refusal`); with none armed it is held, combined and examined as before. The soft-lock search takes each of these as a move available while the item is held. Walkthroughs say `{ "verb": "examine", "item": "wallet" }`; typed play, `examine wallet` when nothing in the room has that name.

### Views & close-ups

A scene can have **views**: named camera positions inside the same room — a close look at the desk, a turn toward the window. A
`go_view` step zooms the camera in (a panorama turns and narrows its field of view), the view's own hotspots appear while the room's
step aside, and a **Back** button (also Esc, and a right-click) zooms out again. Use it for anything that is still the same
picture; keep a separate scene for a close-up that is its own painting.

```jsonc
"views": {
  "desk": {
    "name": "The desk",                 // optional: announced to screen readers
    "toward": [0.41, 0.60],             // a flat scene: the point to zoom toward — 0..1 on the picture, or a marker's / actor's name
    "zoom": 3.0,                        // a flat scene: magnification (1 = the whole picture, up to 6)
    "yaw": 40, "pitch": -10, "fov": 40, // a panorama: where to look and how narrowly (degrees)
    "parent": "",                       // optional: the view Back returns to (default: the room as a whole)
    "seconds": 0.8,                     // optional: how long the move takes (default 0.8; instant with Reduce motion)
    "image": "game/assets/closeups/desk.png",   // optional: a picture of this view, drawn over the room's own while the camera is here
    "region": [0.28, 0.45, 0.26, 0.30], // optional: the part of the room's picture `image` covers — [x, y, w, h], 0..1 (default: all of it)
    "on_enter": []                      // optional steps run each time the view is entered
  }
}
```

- A view's **`image`** is the high-detail picture for a zoom: it is drawn over the room's picture, covering `region`, and fades in over the camera move
  (`seconds`) and out again when the view is left (at once with Reduce motion) — so a close look at the desk shows a painting made for it rather than the room's
  picture enlarged. Paint it to line up with that part of the room (`region` is where it sits). A view without an `image` shows the room's own. In a panorama
  `region` is on the flat sheet like an overlay's `rect`. The picture counts in its room's memory budget and is checked like any other asset.

- A **hotspot** says where it lives with `"view": "desk"` (or `"views": ["desk", "drawer"]`); `"view": "*"` shows it in the room and in
  every view; a hotspot with no `view` belongs to the room as a whole and steps aside inside a view.
- `{ "action": "go_view", "view": "desk" }` enters a view of the scene it runs in (also directly from another view);
  `{ "action": "leave_view" }` goes up one level (to the view's `parent`). Both can carry an `"if"`.
- Every scene with views gets a **`view_back` hotspot** written for it (a "Back" the HUD draws as a button); use `{"click": "view_back"}`
  in a walkthrough. Coming into a room always starts on the whole room: its `on_enter` begins by clearing the view, so a `go_view`
  belongs in `on_enter` after that, not in `on_first_enter`.
- The state is one reserved variable per scene (`@view.<scene>`, the id of the view, `""` for the room), so the story check and the
  soft-lock search treat views like any other state: a key found only inside the drawer view is reachable, and Back is always a move.
- The validator reports: an unknown view in `go_view` or a hotspot (with a suggestion), a `parent` that does not exist or loops, `go_view`
  in a scene that has no `views`, a view with no camera, camera fields that suit the other kind of scene, a hotspot already called
  `view_back`.

### Containers

A drawer, a trunk, a wallet-sized safe: a thing in a room that **opens to show what is inside**, from which the player takes items out and into which they put items back — the way the classic verb-driven adventures handle most of what you find. A scene lists its containers; what opens one is up to the game (a verb, a click, a key, a puzzle).

```jsonc
// in scenes/study.json
"containers": [
  {
    "id": "desk_drawer",                      // snake_case, unique across the whole game
    "name": "Desk drawer",                    // shown on the panel
    "items": ["brass_key", "letter"],         // inside at the start
    "accepts": ["pen"],                       // also allowed to be put in (an item that starts inside can always be put back)
    "on_take": { "brass_key": [ { "action": "add_clue", "clue": "the_key" } ] },   // steps run after that item is taken out…
    "on_put": { "pen": [ { "action": "show_text", "text": "The pen rolls into a corner." } ] }   // …or put in
  }
]
```

```jsonc
{ "action": "open_container", "container": "desk_drawer" }     // e.g. under a hotspot's "verbs": { "open": [ … ] }
{ "contains": "desk_drawer", "item": "brass_key" }             // a condition: that item is in there now
```

- **Opening** shows the **container panel**: the contents (press one to take it out), what the player is carrying that fits (press to put it in) and *Close*. One container is open at a time in a room (opening one shuts the others), and a room is always entered with them all shut.
- **It is plain game state underneath.** At load each container becomes two reserved variables — `@open.<id>` and `@in.<id>.<item>` — and, for every item it can ever hold, a hotspot that takes it out (`give_item`, then `@in…` false, then its `on_take` steps) and one that puts it back (`remove_item`, then `@in…` true, then `on_put`), plus one that closes it. Those hotspots have `ui: "container"`: the room never draws or hit-tests them and the panel
  presses them through the ordinary click path. So the story check, the exact **soft-lock search**, the bot and walkthroughs (`{ "click": "ct_desk_drawer_take_brass_key" }`) need nothing new, and an item that can be left in a container for good is a soft-lock the search finds like any other.
- The validator reports: a duplicate or malformed id, an item that is not an item, a `contains` or `open_container` naming a container that does not exist (with the game's containers listed) or an item the container never holds.
- Names the player sees (the container's `name`, "Take %s", "Put %s in the %s") are translatable strings. *Not included:* a capacity, and containers that travel with the player (a wallet) — a container belongs to a room.

### Framed viewport

A room is drawn across the whole window (`full`, the default) or inside a window of its own with a frame around it and the rest of the screen free for the interface (`framed`) — most point-and-click adventures use both: a framed picture pane for exploring, and full-screen pictures for close-ups and set pieces.

```jsonc
"ui": {
  "viewport": {
    "rect": [0.05, 0.06, 0.70, 0.70],      // the window a framed room is drawn in: fractions of the screen (this is the default)
    "frame": "game/assets/ui/viewport_frame.png",   // optional: a picture drawn around the window, cut in nine
    "frame_margin": 24,                    // pixels of the frame's edge kept uncut, 0 to 200; the frame sits outside the window by that much
    "background": "#101010",               // what fills the rest of the screen: a colour, or a picture path
    "default": "full"                      // "full" or "framed": the mode of a room that does not say (default full)
  }
}
```

A scene says `"viewport": "framed"` or `"viewport": "full"`; leaving it out takes the project's `default`. Switching between two rooms of different modes happens behind the usual fade.

- **Nothing in a room changes.** Hotspots, overlays, effects, actors and a panorama's camera are all fractions of the *picture*, so they follow it into the frame. A flat room's picture is **stretched** to the window (paint it at the window's proportions); a panorama simply sees through a window of that shape.
- The rest of the interface (top bar, inventory, verb bar, subtitles, the compass) stays where it is on the screen — put `ui.verbs.rect` and the window so they do not overlap.
- Pictures and the frame are checked like any other asset; a missing frame is an error. A framed room costs the same memory as a full one.

## Links — links.json

A door between two scenes is two hotspots that have to agree: where each stands, what it is called, which way you face on
arrival. `links.json` writes both from one entry, at load, as ordinary `goto_scene` hotspots — so the validator, the story
check, the soft-lock search, walkthroughs (`click: link_<id>_a`) and the Studio's scene editor treat them like any other.

```jsonc
{ "links": [
  {
    "id": "hall_study",                     // optional (default: the two scene ids joined); the hotspots are link_<id>_a / link_<id>_b
    "a": {
      "scene": "hall",
      "at": [0.86, 0.25, 0.10, 0.50],       // required: [x, y, w, h] on the picture, 0..1 (a panorama's picture is the whole 360° image)
      "label": "Study",                     // optional: default is the other scene's name
      "cursor": "move_right",               // optional: default points the way the door lies (left / right / forward)
      "compass": "e"                        // optional: also make the other scene the compass' n / e / s / w answer here
    },
    "b": {
      "scene": "study",
      "at": [0.02, 0.25, 0.10, 0.50],
      "label": "Hall",
      "arrive": { "yaw": 180, "pitch": 0 }  // optional: where the camera points on arriving IN this scene (a panorama)
    },
    "visible_if": [],                       // optional: the door only exists while these hold
    "actions": [],                          // optional steps run each time the door is used, before the move
    "one_way": false                        // true: only the `a` end gets a hotspot (and `b` needs no `at`)
  }
] }
```

- **Arrival.** Going through a door into a panorama, the camera turns to face *away from* the door you came through (`face` the
  return hotspot with `away`), so you look into the room. `arrive` on the destination end overrides that with a fixed yaw / pitch /
  fov. A one-way link has no door back to turn from, so it keeps the scene's own start view unless `arrive` says otherwise.
  Flat scenes have nothing to turn.
- **Errors** the validator reports: an unknown scene (with a suggestion), a missing or out-of-range `at`, an id used twice,
  an id that is not snake_case, a hotspot of that name already in the scene, a compass direction that is not n/e/s/w.
- The Studio's **Doors** tab edits the list; the MCP server has `list_links`, `upsert_link` and `delete_link`; renaming a scene
  rewrites its links.

## Regions & maps — regions.json

A game with a few dozen rooms can show them all on one picture. A game with a few hundred needs *places that contain places*:
a house, its floors, a wing. `regions.json` describes that tree; a scene says which place it is in with `"region": "<id>"`.

```jsonc
{ "regions": [
  { "id": "manor",
    "name": "The Manor",                     // shown on the map and in its path of buttons
    "map": { "background": "game/assets/backgrounds/manor_map.svg", "auto": false },
    "music": "game/assets/music/manor.ogg",  // optional defaults for every room inside (and inside the places inside it)
    "ambient": "game/assets/sfx/rain.ogg",
    "transition": "dissolve",
    "fx": [ { "type": "vignette", "intensity": 0.3 } ]
  },
  { "id": "ground_floor", "name": "Ground floor", "parent": "manor",
    "map_pos": [0.30, 0.62],                 // where this place's marker sits on its parent's map (default: along the top)
    "map": { "auto": true }                  // no picture: lay the rooms out for me
  }
] }
```

- **Defaults are inherited.** A room that sets none of its own takes the nearest place's `music`, `ambient` and `transition`; the
  places' `fx` stack outermost first, with the room's own effects last. Settings the room has always win.
- **The Map screen shows one place at a time.** It opens on the place the player is in, with a marker for each room in it (a room with a
  `map_pos`, or any room when the place's map has `"auto": true`), a marker for each place inside it (`▸ Ground floor`, or `???`
  until the player has been somewhere in it) and a path of buttons back up. The top level shows the rooms that are in no place
  (so a game with no `regions.json` behaves exactly as before) and the top-level places.
- **Automatic layout.** With `"auto": true`, rooms without a `map_pos` are walked from the start room along their doors (every
  `goto_scene`, door link and compass entry) and laid out in a snake across the map, steering round rooms that have a `map_pos`;
  a line is drawn between rooms joined by a door. A 25-room floor needs no authoring at all.
- **Validation:** unknown or looping `parent`, a room in an unknown place (with a suggestion), unknown settings, a bad `map_pos`,
  and a warning for rooms that a place's map would miss (no `map_pos`, no `auto`).
- The Studio's **Places** tab edits the tree and each place's defaults; a scene's inspector picks its place; the MCP server has
  `list_regions`, `upsert_region` and `delete_region`, and `rename_id` handles `kind: "region"`.

## Budgets

A big game fails at the margins: a room whose panorama plus overlays plus the next room's panorama do not fit in video memory, an
8K picture an older GPU cannot hold, a build that no longer fits the web. `make budget` (and the MCP's `check_budgets`) measure it from
the pictures' headers — nothing is decoded, so 250 rooms take about a second — and exit non-zero when a limit is broken, so it is a
gate in `make check`.

- **A room's cost** is the video memory of every picture it draws (background or panorama, overlays and their frames and sheets, the
  poses of the people standing in it) plus what is always resident (item icons, portraits, the map). Godot keeps 2D textures
  uncompressed on the GPU, so a picture costs *width × height × 4 bytes* however small its file is — unless its import is
  *VRAM Compressed* (BC7 / ETC2), when it costs one byte a pixel.
- **The working set** adds the pictures of the rooms one door away (hotspot `goto_scene`s and the compass): the engine streams
  those in the background while the player is in the room, so crossing a door doesn't wait for the disk, and lets the oldest go
  once they add up past `working_set_vram_mb`. It streams a neighbour's *own* pictures (background, overlays, views), not the
  people standing in it — their poses load when the room is entered — and the working set counts exactly that.
- **Limits** are the optional `budget` block of `project.json` (`scene_vram_mb`, `working_set_vram_mb`, `texture_max_px`,
  `game_disk_mb`); the defaults (512, 1024, 8192, 4096) let ordinary games pass until they say otherwise.
- The report lists the heaviest rooms with their heaviest pictures, a line per place (rooms, picture MB, peak working set), the
  game's size on disk, and the megabytes of pictures nothing uses.
- The Studio's Dashboard edits the limits; `tools/budget.gd` is the headless tool (`-- --text` for a table).

## Dialogues — dialogues/<dialogue_id>.json

A dialogue is a graph of nodes. It always begins at node `"start"`. The reserved
target `"end"` exits the dialogue.

```jsonc
{
  "id": "hartley_intro",
  "nodes": {
    "start": {
      "speaker": "mrs_hartley",       // character id, or "player" / "narrator"
      "text": "You must be the investigator. I'm Mrs. Hartley.",
      "voice": "game/assets/voice/hartley/intro.wav",   // optional
      "emotion": "concerned",         // optional: a key in the speaker's "portraits"
      "actions": [ { "action": "set_var", "var": "met_housekeeper", "value": true } ],
      "choices": [
        { "text": "Ask about the cellar.", "goto": "cellar", "if": [], "once": false },
        { "text": "\"I'll look around.\"", "goto": "end" }
      ]
    },
    "cellar": {
      "speaker": "mrs_hartley",
      "text": "Locked since the master passed. The code died with him, I'm afraid.",
      "next": "start"                  // linear hop when there are no choices
    }
  }
}
```

Node fields: `speaker` (required), `text`, `voice`, `emotion`, `actions` (run when the
node is entered), then **either** `choices` **or** `next` (default `"end"`), optionally preceded by a `branch`.
Choice fields: `text`, `goto` (node id or `"end"`), optional `if` (Conditions),
optional `once` (true = selectable a single time per save), optional `actions`
(run before jumping to `goto`).

Two things make big conversations manageable:

- **A node with no `text`** (and no `voice`) shows no line: it goes straight to its `branch`, `choices` or `next` — a *menu* node.
  The speaker's portrait and name stay up and the previous line stays on screen while the player chooses.
- **Nobody comes or goes mid-conversation.** While a conversation is open, the people standing in the room keep their places: a step
  that changes who is there (a `visible_if` on an actor) shows when the conversation ends, never while someone is talking.
- **A line is said once per conversation.** When a conversation comes back to a node with `choices` whose line it has already
  said (the greeting every answer returns to), the line is not said again: its `actions` run and the choices come back under
  the last answer, like a menu node. A player who missed a line replays it from the conversation log. Talking to the character
  again later starts a new conversation, so the greeting is said again.
- **A question asked before reads dimmer.** A choice the player has picked shows in the dim text colour the next time it is offered
  (in this or any later conversation of the same dialogue; a screen reader hears "Asked before") — a quiet reminder, never a lock: it
  can be asked again. Choices are remembered by their dialogue and their text, and one that leaves (`"goto": "end"`) is never marked.
  It is the player's history (the save's `asked`), not game state: no condition can read it. A save from before this marks whatever
  its conversation log shows the player said.
- **`branch`** is a switch: `"branch": [ { "if": [ … ], "goto": "node" }, …, { "goto": "fallback" } ]`. After the node's line it
  jumps to the first entry whose `if` holds (no `if` always matches); if none does, the node's `choices` / `next` apply.
  "If they've met before, go to `welcome_back`" is one node, not a choice the player can see.

## Topics & conversations

Most investigation is *asking*: you learn something, so you can ask about it; you find an object, so you can show it. Writing
that as dialogue trees means a node for every (person × topic) pair. Instead a character carries a **table** of what they say
to each topic and to each thing shown to them, and the engine builds the menu.

`topics.json` declares what can be asked about:

```jsonc
{
  "topics": [
    { "id": "the_will", "name": "The will" },                          // learned by a `learn_topic` step
    { "id": "the_cellar", "name": "The cellar", "known": true },        // known from the start
    { "id": "gossip", "name": "Gossip", "known_if": [ { "has_item": "torn_letter" } ] }   // known when learned OR the condition holds
  ]
}
```

A character's `talk` table (in `characters.json`):

```jsonc
"talk": {
  "greeting": { "text": "Back again?", "once": true },          // optional; said when the conversation opens (a list of replies works too)
  "ask": {
    "the_will": [                                                // the replies for a topic: the FIRST whose `if` holds (and isn't used up) is said
      { "if": [ { "has_item": "torn_letter" } ], "text": "Where did you get that?", "voice": "game/assets/voice/clerk/will.wav",
        "emotion": "worried", "actions": [ { "action": "give_item", "item": "spare_key" } ], "once": true },
      { "text": "I know nothing of any will." }
    ],
    "the_cellar": { "text": "Locked since the master passed." },
    "*": { "text": "No idea, I'm afraid." }                      // optional: the reply for any other topic the player knows
  },
  "show": {                                                      // what they say when shown an item the player holds
    "torn_letter": { "dialogue": "clerk_letter_scene" },
    "*": { "text": "I've never seen that before." }
  },
  "farewell": { "text": "Mind how you go." },                    // optional
  "labels": { "ask": "Ask about…", "show": "Show something…", "bye": "Goodbye" }   // optional: the menu's wording (also: never_mind, ask_about, show_item, dont_know, no_idea)
}
```

A **reply** is `{ "if", "text", "voice", "emotion", "dialogue", "actions", "once" }`: it says `text` (spoken by the character, with
`voice` and a portrait `emotion`), *then* runs `dialogue` (a whole dialogue) and `actions`. A reply with only `actions` is silent.
`once: true` uses a reply up: the next time the same topic is asked, the next matching reply is said.

The player's menu lists *Ask about…* (every topic they know that the character has a reply for, or all of them when there's a
`"*"`), *Show something…* (the items they hold that the character reacts to, or any item with a `"*"`) and *Goodbye*. After a reply
the list comes back; *Never mind* returns to the first menu.

Steps and conditions:

| | |
|---|---|
| `{ "action": "converse", "character": "clerk" }` | opens the conversation (put it on a hotspot, or bind the hotspot to an actor) |
| `{ "action": "learn_topic", "topic": "the_will" }` | the player learns a topic; a "New topic: The will" notice appears the first time |
| `{ "knows_topic": "the_will" }` | true once learned (not for `known_if` — use that condition directly) |
| `{ "asked": "clerk:the_will" }` | true once the character has answered that topic |
| `{ "showed": "clerk:torn_letter" }` | true once the item has been shown to them |

**How it works.** When the game loads, each `talk` table is compiled into an ordinary dialogue named `@talk_<character>`, and the
steps above are rewritten into `set_var` / `start_dialogue` and `var` conditions on reserved variables (`@topic.<id>`,
`@asked.<character>.<topic>`, `@showed.<character>.<item>`, `@once.…` — they need no declaration). So the validator, the story
check and the exact soft-lock search see conversations like any other dialogue, with no special cases: a conversation that
can strand the player is found the same way.

## Clues & deductions

The player keeps what they find on a **case board**: each clue is a card; selecting two or more and pressing *Connect* makes a
**deduction** when they really belong together. It is detective work the player does, not a cutscene the game plays — and it can
gate anything, because a made deduction is just state your conditions and steps can use.

`clues.json` declares what can be found; `deductions.json` what can be concluded:

```jsonc
{ "clues": [
    { "id": "torn_letter", "title": "Torn letter", "text": "Half a letter, addressed to the solicitor.", "icon": "game/assets/items/letter.png" },
    { "id": "stamp", "title": "Odd stamp", "text": "From a post office that closed in 1998." }
] }
```

```jsonc
{ "deductions": [
    { "id": "letter_forged",
      "name": "The letter is forged",
      "requires": [ "torn_letter", "stamp" ],                 // EXACTLY these clues — no more, no fewer
      "text": "The stamp post-dates the date on the letter. Someone forged it.",    // read out when it is made
      "actions": [ { "action": "learn_topic", "topic": "the_will" } ]                 // optional steps: unlock a topic, add a clue, set a variable…
    }
] }
```

| | |
|---|---|
| `{ "action": "add_clue", "clue": "stamp" }` | the clue joins the board (once); a "Clue found" notice appears. Works from any step list. |
| `{ "action": "make_deduction", "deduction": "letter_forged" }` | the player reaches the conclusion *in the story* — said in a conversation, written in a notebook — exactly as if they had connected its clues: its `actions` run (the first time only), a "Deduction" notice appears, and the board lists it. |
| `{ "has_clue": "stamp" }` | true once the clue has been found |
| `{ "deduced": "letter_forged" }` | true once the player has made that deduction |

The board answers a *Connect* with one of: **made** (the deduction's `text` is read, a notice shows, its `actions` run), **already
made**, **close** ("you're on to something… but there's more to it" — a selection that is part of a real deduction, without saying
what's missing), or **not connected**. Selecting every clue never works: a deduction needs exactly its own set, so two deductions
can't connect the same clues (the validator checks). The **Case** button (`C`, rebindable) appears once the first clue is found. The board is the player's notes: each card shows its whole note;
clues that have already led to a conclusion sort last and say what they led to; a line says whether *some* of the clues found so far
belong together (never which), so a player can tell "think" from "keep looking" without a hint; and the open tasks are listed beside it.

Like topics, the state is plain variables with reserved names (`@clue.<id>`, `@deduced.<id>`) and the steps and conditions are
desugared at load, so the story check proves every deduction *can* be made (every clue it needs can be found) and flags clues
nothing can find; the exact soft-lock search treats making a deduction as a move the player can take at any time it is possible.

**The board can be optional.** A game need not make the board the only way forward: put the inference in the story instead — a
conversation that asks the player what the clues add up to, with a `make_deduction` step on the right answer (and plausible wrong
ones that are turned aside) — and the board becomes a place to organise thoughts that can get there first. Gate the story on the
same `deduced` condition either way, and let the conversation accept a deduction already made on the board.

## Mystery model & accusation

A whodunit needs an answer. `mystery.json` names the culprit, says which clues show the *means*, the *motive* and the *opportunity*
against each suspect — and which clues clear them — and describes the finale: the player **accuses** someone, laying a clue against
each part of the case. The right person with enough evidence ends the case; anyone else, or too little proof, runs the consequences you
wrote.

```jsonc
{ "culprit": "vane",                              // or "culprits": ["vane", "ashby"] — one is drawn for each new game
  "suspects": [
    { "id": "vane",   "means": [ "poison_vial" ], "motive": [ "forged_will" ], "opportunity": [ "tea_service_log" ] },
    { "id": "nora",   "clears": [ "nora_alibi" ] },
    { "id": "ashby",  "clears": [ "ledger_receipt" ] }
  ],
  "accusation": {
    "available_if": [ { "has_clue": "poison_vial" } ],       // default: once any clue has been found
    "legs": [ "means", "motive", "opportunity" ],             // what the case is made of (default: all three)
    "need": 3,                                                // how many legs must be backed by a clue (default: all of them)
    "attempts": 2,                                            // wrong accusations allowed before on_failed (0 = unlimited)
    "on_solved": [ { "action": "end_game", "result": "win", "text": "Vane confesses." } ],
    "on_wrong":  [ { "action": "show_text", "text": "That can't be right." } ],      // someone innocent
    "on_weak":   [ { "action": "show_text", "text": "You need more than a hunch." } ],   // the culprit, but too little proof
    "on_failed": [ { "action": "end_game", "result": "lose", "text": "The culprit walks free." } ]   // the mistake that uses up `attempts`
  } }
```

| | |
|---|---|
| `culprit` / `culprits` | the character who did it. With `culprits`, one is drawn when a new game starts (a walkthrough can pin it with its own `"culprit"`); the whole game is checked once for each. |
| `suspects[].id` | a character. `means`, `motive`, `opportunity` list the clues that show that leg against them; `clears` lists clues that rule them out. A clue can't both support a leg and clear the same suspect. |
| `accusation.legs` / `need` | the legs the player must fill in, and how many must be backed by a clue that really supports that leg for the culprit. |
| `on_solved` / `on_wrong` / `on_weak` / `on_failed` | step lists. A failure (wrong or weak) counts toward `attempts`; the one that uses the last attempt runs `on_failed` after its own list. |
| `{ "culprit": "vane" }` | a condition: true when that character is this game's culprit (so rooms, lines and clues can change with who did it). |

The **Accuse** button (`A`, rebindable) appears when `available_if` holds. The player picks a suspect, then a found clue for each leg (or
"no clue"); the panel never says which clue is right. What it amounts to is decided by the game: the culprit named with a supporting clue in
at least `need` legs is **solved**; the culprit with less is **weak**; anyone else is **wrong** — whatever clues were laid. Without
`on_*` steps the game says so plainly. Make the finale fair: every innocent suspect should have a `clears` clue, and every clue a suspect
relies on should be findable (the validator warns when not).

State is plain variables with reserved names — `@culprit` and `@accusations` (failed accusations so far) — so the story check proves the case
**can** be made for each candidate culprit (the game is analysed once per candidate: a game that cannot be won for one of them is an error that
names them), and the exact soft-lock search starts a game for each candidate and treats accusing — with proof, without it, and the innocent —
as moves available whenever `available_if` holds. In a walkthrough: `{ "accuse": "vane", "evidence": { "means": "poison_vial", "motive": "forged_will", "opportunity": "tea_service_log" } }`.
The QA bot accuses at random now and then.

## Achievements

Achievements are things the player earns that outlast any one save — the in-game list, and the platform's store (Steam) when there is one.
`achievements.json`:

```jsonc
{ "achievements": [
    { "id": "sharp_eyed",
      "name": "Sharp Eyed",
      "description": "Find the poison vial.",
      "icon": "game/assets/items/vial.png",
      "hidden": false,                                     // true: the list shows "???" until it is earned
      "when": [ { "has_clue": "poison_vial" } ],           // earned the first time these hold (checked whenever the state changes)
      "steam": "ACH_SHARP_EYED" },                         // the platform's name for it (default: the id in capitals)
    { "id": "collector", "name": "Collector", "description": "Find every clue.",
      "progress": { "var": "clues_found", "goal": 12 } },  // a counter: shown as 3 / 12, earned when the variable reaches the goal
    { "id": "showoff", "name": "Showoff", "description": "Boast to the housekeeper.", "hidden": true }   // earned only by a step
] }
```

| | |
|---|---|
| `when` | conditions (the usual forms, `has_clue` and friends included). Earned the first time they all hold. |
| `progress` | `{ "var", "goal" }`: earned when the variable reaches `goal`; the list and the platform show the count. |
| `{ "action": "unlock_achievement", "id": "showoff" }` | earns it from any step list. |
| `hidden`, `icon`, `steam` | presentation and the platform id. `name` and `description` are translatable. |

What a player has earned is a **profile**, not game state: a file beside the saves (`user://mysteryforge/<game>/achievements.json`), shared by
every save and kept when a game is restarted. So no condition can read it, saves don't carry it, and the story check and the soft-lock search
never see it — `unlock_achievement` changes nothing they model. The story check does prove each one **can** be earned (its condition or
counter can come true, or a step the player can reach names it) and the validator warns about one that is earned the instant a new game starts.
The title screen and the pause menu get an **Achievements** list when the game has any; earning one shows a notice and plays a chime.

**Platforms.** The local profile is always the source of truth. Adapters (objects with `unlock(def)` and `progress(def, value, goal)` in
`MF.platform_adapters`) are told about every unlock and counter step; `core/platform_steam.gd` is one for GodotSteam, added automatically when
the `Steam` singleton exists. It has not yet been verified against a live Steam client (that needs a Steam App ID and a dry-run depot). A
walkthrough can assert `"expect": { "achievement": "sharp_eyed" }` (runs use a private profile, reset at the start of each).

## Endings

By default an `end_game` says "Case Closed" or "The Trail Goes Cold". `endings.json` makes the endings first-class: named, starred, with an epilogue — and countable, so a player can
see how many of a game's endings they have found.

```jsonc
{ "endings": [
    { "id": "whole_truth",
      "name": "The Whole Truth",                 // the big title on the ending screen (instead of "Case Closed")
      "result": "win",                            // "win" or "lose": which kind of end_game can arrive here
      "tier": 3,                                  // optional, 1–5: shown as ★★★☆☆
      "text": "Every thread is pulled; nothing is left unexplained.",   // optional epilogue, after the end_game's own text
      "when": [ { "has_clue": "ledger" } ] },     // optional conditions: this ending fits when they hold
    { "id": "case_closed", "name": "Case Closed", "result": "win", "tier": 1 },
    { "id": "cold_trail", "name": "The Trail Goes Cold", "result": "lose" }
] }
```

An `end_game` step arrives at an ending like this: if it names one (`{ "action": "end_game", "result": "win", "ending": "case_closed" }`) it gets that one; otherwise it gets the **first**
ending listed whose `result` matches and whose `when` holds — so list the best, most demanding ending first and a catch-all (no `when`) last. A game with no endings ends as it always did.

The ending reached is the reserved variable `@ending`; the ending screen shows its name, its stars and its epilogue and — across games, in the player's profile beside the achievements — how many of the
game's endings the player has found ("A new ending! You have found 2 of 4."). The validator checks the shape, that an `end_game` names a real ending of its own kind, and warns about an ending listed
after one that always fits when no `end_game` names it (nothing can then reach it). The exact soft-lock search reports **the endings some play-through reaches** and warns about each one that none does (its `when` can
never hold when the game ends, or nothing ends the game that way). A walkthrough can assert `"expect": { "ending": "whole_truth" }`. Names and epilogues are translatable.

## Puzzles — puzzles/<puzzle_id>.json

```jsonc
{
  "id": "cellar_keypad",
  "type": "keypad",
  "name": "Cellar Door Keypad",
  "config": { "code": "1847", "max_length": 4 },
  "solve_once": true,                 // default true: stays solved, replays skip it
  "on_solve": [ { "action": "set_var", "var": "cellar_open", "value": true } ],
  "on_fail": [],                      // optional, run on each wrong attempt
  "skip_after": 3,                    // optional assist: offer "Skip this puzzle" after 3 wrong attempts
  "skip_after_seconds": 120,          // optional assist: …or after two minutes on a puzzle with no wrong answers
  "difficulty": {                     // optional: per-difficulty-level overrides — tables, not code
    "junior": { "config": { "max_length": 6 }, "skip_after": 1 },
    "senior": { "config": { "code": "18475" } }
  }
}
```

**Walking away.** Closing a puzzle without solving it (Esc, *Walk away*) keeps its board: opening the same puzzle again (same difficulty level, so the same settings) finds it exactly as it was left — pieces where they were, a random board dealt the same way — for as long as
the game lasts. Beginning a new game or loading a save drops every kept board (they belong to a game that is gone), and a solved puzzle is never kept. (Boards are not written into saves; loading a game puts every puzzle back to a fresh board.)

### Puzzle types

A puzzle type is one script that builds the playable board **and describes itself**: its settings (name, kind, default,
limits, hint) and a solver that *proves an instance can be won*. Everything else — the Studio's form, the validator's
checks, the localisation extractor, the `make puzzles` proof — is driven by that description, so a new type needs no Studio
or validator code. The validator checks every puzzle's `config` (and each difficulty level's merged config) against the
description, runs the solver on it and **replays the solution on the live model**, so a win condition that rejects the
solver's own answer is caught too. Types that deal a random board (mazes, sliders, grids) are proven over sample seeds.

Built-in puzzle types and their `config`. Settings left out take their default; most boards that are dealt at random
accept a `seed` to fix the deal (`0`, the default, means a new deal each time).

| type             | config                                                          |
|------------------|------------------------------------------------------------------|
| `keypad`         | `code` (string of digits), `max_length` (int, 0 = the code's length)     |
| `combo_lock`     | `combo` ([int,...]), `min` (default 0), `max` (default 9)               |
| `word_lock`      | `solution` (string, letters A–Z) — one rotating column per letter       |
| `cipher_wheel`   | `solution` (string) — a Caesar-shifted word; rotate the ring to decode it |
| `safe_dial`      | `combination` ([int,…]), `numbers` (dial size 10–100, default 40), `directions` (bool, default true: right, left, right…), `first` (choice, default right), `tolerance` (0–3) — drag, hold or key the dial, press Set on each number |
| `riddle`         | `question` (text), `answers` ([string,…], matching ignores case/punctuation/leading the-a-an), `hint` (text, shown after two wrong answers) |
| `pin_tumbler`    | `pins` (3–8, default 5), `order` ([int,…] binding order, empty = random), `probes` (loose pushes allowed, 0 = unlimited), `seed` — pick a lock by feel |
| `sliding_puzzle` | `columns` (int ≥2, default 3), `rows` (int ≥2, default 3)                |
| `jigsaw`         | `image` (any SVG **or raster photo**, required), `columns` (≥2, default 3), `rows` (≥2, default 3) — sliced into pieces to swap back into place |
| `arrange`        | `items` ([string,…] in the CORRECT order; an image path shows a picture), `prompt` (text), `seed` — click two cards to swap until they read right |
| `hanoi`          | `disks` (3–8, default 4), `max_moves` (0 = unlimited; the minimum is 2^disks − 1) — Tower of Hanoi |
| `water_jugs`     | `capacities` ([int,…] 2–4 jugs), `amount` (the target), `start` ([int,…] levels, empty = first jug full), `tap` (bool: fill/empty allowed) — measure an exact amount |
| `maze`           | `layout` ([string,…] rows of # . S E, empty = a fresh random maze), `width`, `height` (random mazes), `fog` (flashlight radius, 0 = none), `seed` |
| `pipes`          | `width` (3–8), `height` (3–8), `seed` — turn pieces until all connect to the power source; built from a spanning tree so always solvable |
| `lights_out`     | `rows` (≥2, default 3), `columns` (≥2, default 3), `scramble` (int, default 5) |
| `switch_board`   | `lamps` (2–16), `switches` ([[lamp,…],…] — what each switch flips), `start` ([lamp,…] lit at the start, empty = a fresh solvable mix), `reveal` (bool: label each switch with its lamps), `seed` — the solver finds the fewest presses |
| `wiring`         | `count` (2–6, default 4) — connect matching colored terminals          |
| `simon`          | `pads` (2–6, default 4), `length` (int ≥2, default 4) — watch & repeat |
| `memory_match`   | `pairs` (int 2–12, default 6) — concentration grid; flip two cards to find matching pairs |
| `sound_match`    | `sounds` ([path, …], each dealt as a pair) — concentration by ear; tiles play a tone |
| `logic_grid`     | `rows`/`columns` (equal-length label arrays), `solution` ([col index per row]), `clues` (opt strings) — deduction grid |
| `mastermind`     | `length` (2–6 positions), `symbols` (3–8), `repeats` (bool), `secret` ([int,…] fixed code, empty = random), `attempts` (0 = unlimited; running out clears the board), `seed` — each guess reports right-place / wrong-place counts; symbols carry shapes as well as colours |
| `nonogram`       | `picture` ([string,…] rows of # and ., 2–15 wide) — clues are worked out from it, any fill that satisfies them wins; the solver counts solutions and warns when the picture is ambiguous |
| `sudoku`         | `size` (4, 6 or 9), `givens` ([string,…] rows, . for empty; empty = a fresh puzzle with one solution), `symbols` (e.g. ABCDEF), `clues` (generated puzzles), `seed` |
| `word_search`    | `words` ([string,…] letters A–Z), `size` (6–16), `directions` (choice: across/down, plus diagonals, or all and backwards), `seed` — the words are hidden fresh each time |
| `spot_difference`| `image_a`, `image_b`, `differences` ([[x, y, w, h],…] fractions of the picture), `misses` (wrong clicks allowed, 0 = unlimited) |
| `sokoban`        | `layout` ([string,…] rows: `#` wall, space floor, `@` you, `$` crate, `.` goal, `*` crate on a goal, `+` you on a goal) — push every crate onto a goal; Undo and Restart; the solver finds the shortest walk |
| `rush_hour`      | `layout` ([string,…] rows: `.` free, `#` block, `X` your horizontal car, any other capital letter one vehicle of 2–4 cells) — slide the traffic until X leaves by the right edge; the solver finds the fewest slides; drawn on a picture: `background` (image, optional: the place seen from above — a loaded van, a yard), `grid` ([[x, y, width, height]] with a picture: where the grid lies, square cells), `piece_art` ([string,…] `Letter: picture.png`, each piece drawn as its own picture lengthwise along it, turned a quarter for one that stands the other way) — made for a close-up |
| `peg_solitaire`  | `layout` ([string,…] rows: `#` outside, the letter o for a peg, `.` an empty hole), `last_at` (`"column,row"` the final peg must end in, empty = anywhere) — jump pegs until one is left; stuck boards reset |
| `crossword`      | `entries` ([string,…] one per word: `row,column,across|down,ANSWER,clue` — rows and columns from 1; crossing words must agree, and a run of letters no clue accounts for is a warning) — type into the grid, Check marks wrong squares; the clues are translatable |
| `nim`            | `piles` ([int,…] 2–5 piles of 1–9 stones), `misere` (bool: last stone loses), `first` (choice you / house) — beat a perfect house at Nim; the solver proves the start is winnable for you |
| `color_mixing`   | `paints` ([`#rrggbb`,…] 2–6), `names` ([string,…] pot labels), `target` (`#rrggbb` sample), `drops` (most drops, 2–14), `tolerance` (0.01–0.4) — add drops until the mix matches; the solver tries every combination, and the display says in words which way it is off |
| `counterfeit_coin` | `coins` (3–27), `weighings` (1–4), `odd` (choice heavier / lighter), `fake` (1-based coin, 0 = random), `seed` — find the false coin on a balance; the solver runs the three-way-split strategy against every possible coin |
| `cryptogram`     | `message` (the plain message, translatable), `shift_key` (optional: 26 letters, the code letter for A…Z), `seed` (the key when none is given), `reveal` (letters decoded to start with), `page` (image, optional: the paper with the coded message already written on it), `letters` ([[x, y],…] with a page: where each coded letter of the message is written, one per letter A–Z in reading order, fractions of the picture), `cell` (float, default 0.045: a pencilled letter's height as a fraction of the picture), `pencil` (colour, default #3b3a3f) — decode a letter-substitution cipher; the solver checks the key decodes the message; on a page the player pencils letters straight under the written ones (a translated message, whose letters the page does not show, gets the plain board) |
| `river_crossing` | `items` ([string,…] 2–6 who must cross), `rules` ([string,…] lines like “wolf eats goat”), `capacity` (passengers besides you, 1–3), `max_crossings` (0 = unlimited) — the solver finds the fewest crossings; a crossing that leaves a rule broken is a wrong try |
| `radio_tuning`   | `frequency` (the station), `band_min`, `band_max`, `step`, `tolerance` — turn the dial, watch the signal (also written in words), lock it in |
| `logic_circuit`  | `switches` (2–8, named A, B, C…), `bulbs` ([string,…] one expression per bulb: switch letters with AND, OR, XOR, NOT and parentheses), `start` (letters of the switches that begin up) — light every bulb; the solver finds the fewest flips |
| `balance_weights`| `object` (its weight, on the left pan), `weights` ([int,…] each used once, on either pan or off), `show_object` (bool) — make the scale level; the solver searches every placement |
| `ring_lock`      | `rings` ([string,…] concentric rings of equal length, outermost first), `word` (one letter per ring), `linked` (bool: a ring drags its neighbours round the other way) — spell the word in the marked column; the solver finds the fewest turns |
| `mirror_beams`   | `layout` ([string,…] rows: `.` empty, `#` wall, `> < ^ v` the lamp and its direction, `T` target, `*` gem, `/` `\` fixed mirrors, `?` a loose mirror starting as `/`, `!` starting as `\`) — flip the loose mirrors so the beam reaches the target through every gem |
| `music_box`      | `teeth` (the comb: note names low to high, 3–12, each once, `#` for a sharp: `C D E F G A B`), `melody` (2–16 steps, each a tooth or `-` for a rest), `clue` (choice sheet / hear / none: the notes written above the columns, a Hear button that plays the tune, or neither — the story tells it), `tempo` (notes per minute) — pin the cylinder, Play to listen (never a wrong try), Wind it up to check; the solver proves every note is on the comb and replays the pins |
| `tile_twist`     | `columns`, `rows` (2–6), `spread` (choice self / cross / block: a turn moves only the tile, it and its four neighbours, or the block of nine round it), `scramble` (turns the board was mixed with, 3–60), `seed` (0 = a different board each time), `image` (optional picture cut into the tiles; without it each tile is a letter with a corner mark) — click a tile to turn it a quarter clockwise until all are upright; boards are made by turning an upright one, so every board is winnable, and the proof replays the turns that undo the scramble |
| `word_ladder`    | `start`, `goal` (words of 2–8 letters, A–Z, the same length), `words` ([string,…] the words a step may use, one per line; others lengths are ignored), `max_steps` (0 = no limit) — type the next word, one letter changed each time, until the goal; Undo and Start over; a word that is not a legal step is only turned down (never a wrong try); the solver finds the shortest ladder (breadth-first) and proves it fits `max_steps` |
| `magic_square`   | `size` (3–5), `given` (int_rows: the squares already filled in, 0 = blank), `pool` ([int,…] the numbers to place, default 1…size², each once), `sum` (what each line adds up to; 0 = the numbers' total ÷ size), `diagonals` (bool) — pick a square, then a number; a full square that does not add up is a wrong try (the lines that miss turn red); the solver searches for a square that fits (backtracking, with a step limit past which it says "not proven") |
| `mechanism`      | `dials` ([string,…] one per line, 1–6: `Name: position position …`, 2–12 named positions), `levers` ([string,…] one per line: `Label: Dial +1, Dial -2, Dial =position` — each move turns a dial on that many positions, wrapping, or sets it to a position by name or by number from 1; all of a lever's moves happen at once), `start` (position numbers from 1, one per dial; blank = all first), `goal` (position numbers from 1, 0 = that dial does not matter), `max_moves` (0 = no limit) — **a bespoke machine described in data, with a proof**: the solver searches every state it can reach (breadth-first, up to 200 000) and finds the fewest pulls; a wrong pull is never a failure; optional pictures draw it instead of plain cards: `background` (a picture of the machine), `dial_art` ([string,…] one per dial: `Name: a.png, b.png, …`, one picture per position), `lever_art` ([string,…] `Name: resting.png, pulled.png`, the pulled one optional and shown for a moment), `layout` ([string,…] `Name: x, y`, fractions 0–1 of the background) — a picture that does not exist yet is a warning and that dial or lever stays a plain card; `cards` (bool, default true) — off, the pictures are the whole machine: each dial is only its picture (drawn at the background's scale, centred where `layout` puts it), each lever only its picture, pulled by a click on any of its pixels that is not wholly clear (so a nearly clear shape can make a part of the machine the lever) and named when hovered — no labels and no targets on screen, the player reads the machine itself (every dial and lever then needs a picture; made for a close-up) |
| `pick`           | `picture` (image, required), `areas` ([string,…] one per line: `Name: x, y, width, height`, fractions of the picture, 2–24), `answer` (the name of one area), `prompt` (text, optional) — **choose the right thing on a picture** (the lot in a catalogue that fits a description, the key on a board): each area is a choice the player clicks, named when hovered; a wrong choice is a wrong answer (a failed attempt), the right one solves it; made for a close-up |
| `map_route`      | `places` ([string,…] one per line, 2–12: `Name: Neighbour, Neighbour` — roads work both ways, either end may list one, and a place named only as a neighbour needs no line of its own), `start`, `goal`, `must_visit` ([string,…] stops to make, up to 6), `ordered` (bool: in that order), `closed` ([string,…] a place `Church` or a road `Market-Church` the route may not use), `max_steps` (0 = no limit), `positions` ([string,…] optional `Name: x, y`; the rest are laid out left to right by distance from the start) — click the next place along a road (click the last one again to step back); arriving without every stop is a wrong try; the solver finds the shortest route that meets the clue (a route may double back) |
| `sneak`          | `prompt` (what to do), `layout` ([string,…] one row per line: "#" wall or hedge, "." open ground, "b" bush — cover, "g" gravel and "d" dry leaves — noisy, "S" start, "E" the hiding place, "A"–"D" watchers), `watchers` ([string,…] `A: S, W, S, E` — the way each faces on each beat, round and round), `names` ([string,…] optional `A: Vera`), `sight` (squares, default 4), `hearing` (squares, default 2) — creep to the hiding place: each move or wait is a beat, then every head turns; a watcher sees a quarter-circle ahead of her as far as `sight`, not through walls or bushes nor into a bush; a step onto gravel or dry leaves within `hearing` squares is heard. The board tints what is watched now and marks where each will look next. Seen or heard is a wrong try (back to the start); the solver finds the fewest beats and warns when no waiting is needed |
| `seating`        | `guests` ([string,…] 2–8 names, each once — one seat for each), `layout` (choice ring / row: seats numbered clockwise from the top of a table, or left to right along a bench), `clues` ([string,…] one per line, names without regard to case: `Ada at 3`, `Ada not at 3`, `Ada next to Ben`, `Ada not next to Ben`, `Ada opposite Cora` (a ring with an even number of seats), `Ada left of Ben` / `Ada right of Ben` (a bench; anywhere to that side); a reason may follow a spaced dash — `Ida not next to Clara — she still owes her for the black silk` — written under the clue, never read as part of its rule), `show_progress` (bool, default on: each clue is ticked or crossed once the guests it names are seated) — **a seating plan with a proof**: the solver tries every way of seating the guests, and the checker reports how many satisfy the clues (any one of them wins; a ring with no "at" or "not at" clue can be turned, and the checker warns); drawn on a picture: `background` (image, optional: the seats seen from above), `seats_at` ([[x, y],…] with a picture: where each seat's place card lies, in seat-number order), `note_at` ([[x, y, width]]: where the note with the clues is pinned, default the top right), `tray_at` ([[x, y, width]]: where the guests' cards wait, default a row along the foot) — each seat a place card on its chair; made for a close-up |
| `liars`          | `suspects` ([string,…] 2–6 names), `statements` ([string,…] one per suspect, “Name: what they say” — X is lying / is telling the truth; X and Y are both lying / both truthful / the same / different; at least one of X and Y is lying; exactly one of X and Y is lying; exactly / at least / at most N of us are lying) — **truth and lies**: the truthful say only what is true, the liars only what is false; the player marks each suspect Truthful or Liar and checks. The checker tries every marking and requires **exactly one** that fits (none, or several, is an error) |
| `torch_bridge`   | `people` ([string,…] one per line, 2–6: `Name: minutes` from 1 to 60), `capacity` (2–3: how many are on the bridge at once), `time_limit` (minutes) — **everyone across a bridge by torchlight**, the slowest of a group setting its pace and the torch going with every crossing; the solver finds the fastest total time and the checker refuses a limit below it (and warns when the limit is much looser). Running past the limit is a wrong try and the bridge resets |
| `knight_tour`    | `columns`, `rows` (3–8), `start` (a chess square: column letter then row number from the bottom, a1 = bottom-left), `blocked` ([string,…] holes) — **a knight visits every open square once**; the solver (Warnsdorff's rule, run to the end) finds a tour or proves there is none, and a board it cannot decide within its budget is an error ("make it smaller or add a hole"). A knight stuck with squares left is a wrong try |
| `gear_train`     | `pegs` ([string,…] 2–9: `Name: x, y`), `drive` (`Peg: teeth` — the fixed motor gear, turning clockwise), `gears` ([string,…] 1–6 spare gears, teeth 4–40), `target` (the shaft peg), `turn` (choice clockwise / anticlockwise), `speed` (choice any / faster / slower than the motor) — **build a gear chain**: a gear of t teeth is t/2 units in radius and two mesh when their pegs are exactly (t1 + t2)/2 apart; neighbours turn opposite ways, a bigger gear turns slower, a ring of an odd number of gears jams. The solver tries every placement of the spares; the checker counts the arrangements that work |
| `packing`        | `columns`, `rows` (2–8), `pieces` ([string,…] 2–12, one per line: a name — mono domino I3 L3 I4 L4 T4 S4 O4 and the pentominoes F5 I5 L5 N5 P5 T5 U5 V5 W5 X5 Y5 Z5 — or a drawn shape such as ##/#. with # a square, . empty and rows divided by a slash; at most 6 squares each), `blocked` ([string,…] holes, squares written column letter then row number from the TOP: a1 is top-left), `flip` (bool, default on: pieces may be mirrored as well as turned) — **fill the board exactly**: pick a piece, turn or flip it, click where its first square goes; click a placed piece to lift it. The solver packs the board (exact cover) and the checker counts the ways; pieces whose squares do not add up to the open squares, or that cannot fill it, are refused |
| `cages`          | `size` (3–6), `cages` ([string,…] one per line: `6+: a1 a2 b1` — a target, a sign + - x / (or none for one square), a colon and the squares; - and / take exactly two squares; every square in exactly one cage), `givens` ([string,…] numbers filled in, like a1=3), `show_progress` (bool, default on: repeats in a row or column, and complete cages that are wrong, turn red) — **number cages** (KenKen): fill the grid with 1 to N, no repeats in any row or column, each cage making its figure. The solver finds every filling and the checker requires **exactly one** (none or several is an error — add a given) |
| `duel`           | `game` (choice queen / dots), `player_moves` (choice first / second), `ai_skill` (1–4: how often the computer finds its best move), `columns`, `rows` (3–10), `start` (queen: a square like f7, row from the BOTTOM — the goal is a1), `boxes_across`, `boxes_down` (dots: 2–3, at most 17 lines in all), `seed` (0 = the computer slips differently every time) — **a game against the computer**, turn about. *queen*: move the queen west, south or south-west any distance; whoever lands it on a1 wins (Wythoff's game). *dots*: draw one line per turn; closing a box scores it and earns another turn; most boxes wins. Both are solved by the checker, which **requires that the seat chosen can force a win** (a duel nobody can win is an error); a loss resets the game and is a wrong try |

The set is open-ended: a game's own puzzle script under `scripts/puzzles/` is used as `"type": "<name>"`, and if it
defines `static func meta()` and `static func analyze(settings)` (see `addons/mystery_forge/puzzles/puzzle_base.gd`) it gets
the same form, validation and proof as a built-in. `validate_project` reports unknown types.

### Puzzle assists & difficulty

Difficulty is data. `difficulty` (above) maps a game difficulty level id to overrides applied when the player chose that level:
`config` (settings merged over the puzzle's own) and the assist settings. The validator checks each merged config as its own
instance, so "Junior" cannot quietly be unwinnable. Two assists, both off by default:

- `skip_after` — after that many wrong attempts the puzzle offers **Skip this puzzle**; skipping counts as solved (`on_solve` runs).
- `skip_after_seconds` — the same after that long on the puzzle, for boards where nothing counts as a wrong attempt (mazes, sliders).

What counts as a wrong attempt is the board's own call: a keypad's rejected code, a riddle's wrong answer, a mastermind board
running out of attempts. `on_fail` runs on exactly the same events.

### Puzzle close-ups

A puzzle is played on a panel over the dimmed room unless it has a `close_up`: then it fills the screen like a room of its own — a painting of the thing itself, close
to (the clock on the mantel, the notebook open on the desk, the engine under its hatch) — and the board is laid on it, scaled to fit the rectangle `board` gives. Its
name is a caption at the foot with **Step Away** (and the skip assist when it is offered). A board that draws itself on a picture (a `mechanism` with `cards` off)
sizes its picture to that rectangle; any other board is scaled into it.

```jsonc
"close_up": {
  "picture": "game/assets/puzzles/pell_clock.webp",   // optional: fills the screen behind the board (cropped to fill, like a room); without it the screen is black
  "board": [0.0, 0.0, 1.0, 1.0]                       // optional: where the board goes, as fractions of the screen [x, y, width, height]; default the whole screen
}
```

## Custom scripts

For the rare thing the editors can't express, a game can ship its own **GDScript** under
`game/scripts/` and use it from plain game data — no change to the engine addon, and the engine
can be upgraded independently. Three kinds, each one file named in `snake_case`:

| kind | file | used as | the script defines |
|------|------|---------|--------------------|
| step | `scripts/actions/<name>.gd` | `{ "action": "run_script", "script": "<name>", "args": {…} }` | `func run(mf: Node, args: Dictionary) -> void` — may `await` |
| check | `scripts/conditions/<name>.gd` | `{ "script": "<name>", "args": {…} }` in any condition list | `func check(state, args: Dictionary) -> bool` — fast, no side effects |
| puzzle | `scripts/puzzles/<name>.gd` | `"type": "<name>"` in `puzzles/<id>.json` (its `config` is passed through) | `extends "res://addons/mystery_forge/puzzles/puzzle_base.gd"`, `func build(config)`, emits `solved` / `failed` |

`mf` is the game (the `MF` autoload): `mf.state` (variables via `get_var`/`set_var`, `inventory`,
`visited`, `solved`…), `mf.ui` (`show_subtitle`, `run_dialogue`, `change_scene`…), `mf.run_actions([...])`.
Each kind may add a static validation hook that the validator calls — `validate(args)` for steps and checks,
`validate_config(config)` for puzzles — returning a `PackedStringArray` of problems.
The validator also checks that every referenced script exists and compiles. The Studio's **Scripts**
tab creates one from a commented template and edits it in place; the MCP server has
`write_script` for an AI to do the same.

## Animation

Overlays aren't just stills. Three things make a scene move, none of which need video:

- **Frame animation.** Give an overlay `frames` (a list of images) and it cycles through them at
  `fps` (default 8) — a flickering fire, a ticking clock, a waving character. `loop: false` plays
  once and holds the last frame, replaying each time the overlay appears (or when `play_overlay`
  runs). `image` stays as the still fallback and the first frame when `frames` is absent.
- **Sprite sheets.** Art tools export animation as one image holding every frame in a grid; give the
  overlay `sheet: {image, columns, rows, count?}` and the frames are cut from it (left to right, top to
  bottom) — the same `fps` / `loop` / `play_overlay` rules apply. With a sheet, `image` may be omitted
  (the first frame is the still). One file instead of dozens keeps an animated asset easy to replace.
- **Moving and fading.** `move_overlay` slides an overlay's top-left corner to `to` (normalized
  0..1) — add `from` to start somewhere else first, e.g. off-screen for a character who walks in.
  `fade_overlay` eases its transparency to `alpha`. Both are *awaited* by default so the next step
  starts when they finish; set `"wait": false` to run several in parallel (start a walk, then a fade,
  then `wait` for both). Give an overlay `"opacity": 0` to start invisible and `fade_overlay` it in. With the player's
  **Reduce motion** setting on, both happen at once (and wait for nothing), so pace a short animation with the steps' own
  `wait` rather than separate `wait` steps when it should vanish for those players.
- **A group of overlays.** An `overlay` name ending in `*` names every overlay of the scene whose id starts with what comes
  before it — `"map_*"` moves or fades `map_home`, `map_town` and `map_barn` together (the same thing drawn for each place
  an `arrived_from` overlay stands for). The validator wants at least one overlay to match; the Studio offers a group for
  every prefix two or more overlays share.
- **Where they apply.** These actions target an overlay by its `id` in the scene that is running
  them (a hotspot or `on_enter` of that scene); from a dialogue or puzzle they target the
  scene currently on screen. Movement and fades are visual only — a scene reload returns an overlay
  to its authored position, so set a variable when a change should stick and switch overlays with
  `visible_if`.

- **Video regions.** An overlay with `video` plays a clip inside its rectangle — a hearth fire, a flag, rain on a
  window — and with a transparent WebM the room shows through. It loops unless `loop` is `false` (then it holds the last
  frame), pauses while the overlay is hidden, and falls back to the overlay's still `image` when the decoder isn't
  installed or *Reduce motion* is on. Works in panoramas too.

A cutscene is simply a step list: `fade_overlay`, `move_overlay` (with `wait: false`), `wait`, narration,
`play_sfx`, `play_video` — the Studio shows it as one storyboard.

## Actors

An **actor** is a person you can see standing in a room — the housekeeper behind her counter, a suspect pacing the library.
Where a portrait is a face in a dialogue box, an actor is a *body in the scene*: it stands on the floor at the right size for
its depth, walks between places, turns, changes pose, talks (the mouth follows the voice) and — through a hotspot — can be
clicked. It works the same in a flat scene and a 360° panorama (there the sprite stands upright and is projected, so it stays
glued to the spot as the camera turns). A character can be an actor in any number of scenes; a game decides per room.

An actor's art is flat pictures of the character — what an image generator or an illustrator makes: a standing pose, a few
mouth shapes, a walk cycle, a gesture. (Real-time 3D and video actors are other ways to fill the same slot; the stage
directions below don't change.)

### The character's `actor` block

```jsonc
"actor": {
  "height": 0.6,                // standing height at scale 1, as a fraction of the picture's height (default 0.5)
  "feet": [0.5, 1.0],           // where the feet are on each pose picture, 0..1 (default bottom-centre)
  "facing": "right",            // the way the art faces — "right" (default) or "left"; the other way is drawn mirrored
  "poses": {                    // named pictures; "idle" is required
    "idle": { "image": "game/assets/actors/hartley_idle.png" },
    "walk": { "sheet": { "image": "game/assets/actors/hartley_walk.png", "columns": 4, "rows": 1 }, "fps": 8 },
    "talk": { "frames": ["game/assets/actors/hartley_m0.png", "game/assets/actors/hartley_m1.png", "game/assets/actors/hartley_m2.png"] },
    "wave": { "frames": ["game/assets/actors/hartley_w1.png", "game/assets/actors/hartley_w2.png"], "fps": 6,
              "loop": false, "then": "idle" },
    "point": { "image": "game/assets/actors/hartley_point.png", "then": "idle", "seconds": 1.4 },
    "blink": { "image": "game/assets/actors/hartley_blink.png" }
  },
  "life": {                     // optional: what they do while they just stand there (see "Idle life")
    "sway": 1.0,                // degrees they lean either side of upright, about the feet (0–6; default 0)
    "breathe": 0.012,           // how far they swell and settle, as a fraction of their height (0–0.05; default 0)
    "seconds": 4.0,             // one lean-and-breath cycle (1–20; default 4)
    "blink": "blink",           // a pose that is the idle picture with the eyes shut, flashed now and then (default: none)
    "blink_every": [2.5, 6.0],  // shortest and longest seconds between blinks (default [2.5, 6])
    "blink_seconds": 0.12       // how long the eyes stay shut (0.04–1; default 0.12)
  },
  "looks": {                    // optional: the same poses rendered for another room (see "Looks")
    "bank": {
      "height": 0.42,           // optional: replaces the base height in that room
      "feet": [0.5, 1.0],       // optional: replaces the base feet point
      "portrait": "game/assets/portraits/hartley_coat.png",   // optional: a look in other clothes has its own conversation
      "talk_frames": [],        //   portrait — `portrait`, `talk_frames`, `portrait_motion`, as the character's (see "Looks")
      "portrait_motion": {},
      "poses": {                // the poses it replaces, by the base names (usually all of them)
        "idle": { "image": "game/assets/actors/hartley_bank_idle.png" },
        "talk": { "frames": ["game/assets/actors/hartley_bank_idle.png", "game/assets/actors/hartley_bank_m1.png"] }
      }
    }
  }
}
```

- A **pose** is a picture: `image`, or `frames`, or a `sheet` (a grid of frames), or a `video` (a WebM with alpha is a
  filmed actor) — the same fields, `fps` and `loop` as an overlay (see "Animation"). Use transparent PNG/WebP; the asset
  audit warns about a figure with no alpha. Poses live under `game/assets/actors/`.
- **Loops rendered in the room.** A pose may carry both a `sheet` and an `image`: the sheet plays, and the `image` (the sheet's
  first frame on its own) stands in while the sheet is not there yet — on the web it arrives in the late pack (see "Web builds:
  the late pack") — and with Reduce motion the first frame holds. A figure rendered in 3D standing in its room usually has an
  idle loop (breathing, a drift of the head, a blink) and a talk loop (a gesture, the mouth moving — `"lipsync": false`, so the
  frames play rather than follow the voice; the conversation's portrait does the lip-sync). Switching between two looping poses
  (standing → talking and back) **cross-fades** over a fifth of a second instead of jumping between two loops' frames.
- **One-shot poses.** `loop: false` plays once and then holds its last frame; `then` names the pose to settle into
  afterwards, and `seconds` holds a *still* pose for that long before `then`. `actor_play` waits for a one-shot to finish.
- **`walk`** shows while the actor walks, **`talk`** while they speak; both fall back to `idle` when missing.
- **Lip-sync.** A `talk` pose with two or more frames lists mouth shapes from a *closed mouth* (first) to the *widest*
  (last). While a voice line plays the engine listens to the speech itself and picks the frame by how loud it is right now,
  relative to the loudest the line reaches — so any recording, placeholder or final, lip-syncs with nothing authored per
  line. A line with no recording flaps at a steady rhythm. `"lipsync": false` on the pose turns the mouth-following off
  (the frames just animate).

### Looks

A figure rendered in 3D (or photographed) is lit by the room it was made in, so the same person standing in two rooms needs
two sets of pictures. `looks` holds the others: each is named, and replaces the base poses of the same names (and, if it says
so, `height` and `feet`) wherever a scene's actor entry asks for it with `"look"`. Because a look keeps the base pose
names, talking, blinking, walking and the stage directions work in every room unchanged; a pose a look doesn't render falls
back to the base one. A look may only replace poses the actor already has. Only the look a room uses counts toward its
video-memory budget.

**A look in other clothes.** When a look dresses the character differently (a raincoat in from the storm, an apron at
work), its conversation portrait must match: the look may carry its own `portrait`, `talk_frames` and `portrait_motion`
(the same fields as the character's). While the speaker stands in the room in that look, a conversation shows those — all
three are the look's, so the everyday living portrait is never mixed in, and emotion variants (`portraits`) are not
used — and everywhere else (the journal, the suspects, a room they are not in) the character's own portrait stays. A look
with none of them uses the character's. The validator checks a look's portrait like a character's; a look's living
portrait is counted in the budget and travels in the web late pack like any other.

### Idle life

A figure that never moves looks pasted onto the room. A character's `actor.life` gives a standing figure a little life, using only what the art already has:

- **`sway`** leans the figure either side of upright and **`breathe`** swells it from the feet up and lets it settle, both as a slow sine over `seconds`; the breath runs a little faster than, and out of step with,
  the lean so the two do not read as one wobble, and two people in a room do not move in step. Both are about the *feet*, so they stay on the floor.
- **`blink`** names a pose — the idle picture with the eyes shut — that is flashed for `blink_seconds` at a random moment between `blink_every`'s two numbers. It only happens while the figure stands in its `idle` pose and
  is not talking: someone mid-gesture keeps their eyes open, and a speaking mouth is not interrupted. An `idle` that is itself a
  loop (frames or a sheet) blinks in its own frames, so the `blink` pose is never flashed over it.
- It all **stops while the figure walks** (the walk cycle is its own motion) and is **off with Reduce motion** (Settings → Accessibility), like every other idle movement. A character with no `life` stands perfectly still, as before.
- The validator reports a `blink` that is not a pose of the actor (or is `idle` itself), numbers out of range, `blink_every` that is not `[shortest, longest]`, a `life` that does nothing, and `blink_every` / `blink_seconds` with no `blink`.

### The stage: `markers`, `floor`, `actors`

A scene's coordinates are 0..1 across its picture (across the panorama image in a panorama scene) — an actor's position is
where their **feet** are.

```jsonc
"markers": {                         // named standing places
  "door": { "at": [0.9, 0.7], "scale": 0.8, "facing": "left" },   // `scale` multiplies the depth scale; `facing` is how they stand on arrival
  "desk": [0.3, 0.78]                // or just [x, y]
},
"floor": [[0.55, 0.6], [0.95, 1.0]], // [y, scale] pairs: people stand at 0.6 of their height at y 0.55 and full size at y 0.95
                                     // (linear between, held beyond) — they shrink as they walk away from the camera
"actors": [
  {
    "id": "hartley",                 // optional, default the character's id (what stage directions call them)
    "character": "mrs_hartley",
    "at": "desk",                    // a marker name or [x, y]
    "scale": 1.0,                    // optional extra multiplier
    "pose": "idle",                  // optional, default idle
    "look": "foyer",                 // optional: which of the character's `looks` this room shows (see "Looks")
    "facing": "left",                // optional; default the marker's facing, otherwise the art's
    "visible_if": [ { "var": "met_housekeeper", "eq": true } ],   // Conditions — present only while true
    "hotspot": "talk_hartley"        // optional: the id of one of this scene's hotspots, which then follows the actor
  }
]
```

- **Size** = the character's `height` × the floor's scale at the actor's y × the marker's `scale` × the entry's `scale`; a
  scene with no `floor` stands everyone at full size. People lower in the picture are drawn in front.
- **Clickable actors.** `hotspot` binds one of the scene's ordinary hotspots to the actor: it is moved over the actor's
  bounding box each time they move (its own `shape` is only the starting place), keeps its label, cursor, `actions`,
  `use_items` and keyboard / screen-reader behaviour, and is hidden while the actor is. So "talk to her" is a normal hotspot
  that starts a dialogue.
- **Speaking.** When a dialogue node's `speaker` is a character with an actor on stage, that actor talks (and, in a
  panorama, the camera turns to bring them into view) and the big portrait steps aside — set `ui.dialogue_portraits` to
  `"always"` to keep it. `actor_say` speaks a line outside a dialogue. With both on screen, the figure in the room follows its
  living portrait gesture for gesture and frame for frame: talk loop 1 of the portrait is the actor's `talk` pose, loop 2
  its `talk2`, loop 3 `talk3` (looping sheets, as many as the figure has), and the portrait only plays the loops the figure
  has. A player who would rather see only the figures turns **Settings → Game Settings → Portraits in conversations** off
  (`portraits`, shown only when the game keeps portraits `"always"`): then the portrait steps aside as with `"auto"`.
- **Scene changes.** Actors exist for as long as the scene is on screen; stage directions are visual and don't change game
  state — set a variable (and give the actor a `visible_if`) when who's-where must persist.

### Stage directions

The `actor_*` actions (see the table in "Actions") direct an actor by `actor` — the id of one placed in the scene, or a
character id (`actor_enter` brings that character on). Places (`at`, `from`, `to`, `via`) are marker names or `[x, y]`.

```jsonc
{ "action": "actor_enter", "actor": "hartley", "from": "door", "at": "desk" },          // walks in
{ "action": "actor_say", "actor": "hartley", "text": "Mind the dust.", "voice": "game/assets/voice/hartley/dust.wav" },
{ "action": "actor_walk_to", "actor": "hartley", "to": "door", "via": ["desk"], "wait": false },
{ "action": "actor_exit", "actor": "hartley", "to": "door", "walk": "walk_away", "fade": 0.4 }   // walks off, back turned
```

Walks take `seconds`, or work out their length from the distance at `speed` (picture widths per second; default 0.2 in a
flat scene, 0.05 in a panorama, whose picture is a whole circle). Like `move_overlay` they wait for the step to finish
unless `"wait": false`, so several actors can move at once. With *Reduce motion* on, walks and fades are instant.

A walk shows the actor's `walk` pose; `"walk"` on `actor_enter`, `actor_walk_to` or `actor_exit` names another one — a figure
rendered walking away from the camera (`walk_away`) for leaving by a door at the back. As with every pose, the picture is
mirrored when the walk goes the other way from the way the art faces, so draw (or render) each walk going to the right.

## Time & schedules

A game can have a **clock**: days made of named phases (Morning, Afternoon, Evening, Night). Time moves only when a step says so —
there is no real-time clock to race — which keeps the story provable. Characters can keep a **schedule**: where they are, and when.

```jsonc
// project.json
"time": {
  "phases": ["Morning", "Afternoon", "Evening", "Night"],   // the parts of a day, in order
  "days": 3,                                                 // how long the game lasts (default 14)
  "start": { "day": 1, "phase": "Morning" },                 // optional; default day 1, the first phase
  "show": true,                                              // optional: "Day 2 — Evening" on screen (default true)
  "on_end": [ { "action": "end_game", "result": "lose", "text": "You ran out of time." } ]   // optional: steps run once when the last day is over
}
```

| | |
|---|---|
| `{ "action": "advance_time" }` | the next phase (the day rolls over after the last). `"phases": 2` moves two. |
| `{ "action": "advance_time", "to": "Morning" }` | on to the next time that phase comes round (from Evening: tomorrow's Morning) |
| `{ "action": "set_time", "day": 2, "phase": "Morning" }` | jump to a day and phase |
| `{ "day": 2 }` `{ "day_gte": 2 }` `{ "day_lte": 2 }` | conditions on the day (1 = the first) |
| `{ "phase": "Evening" }` `{ "phase_in": ["Evening", "Night"] }` | conditions on the time of day |

The player sees the day and phase at the top left, and a notice whenever it changes. When the clock passes the game's last day, the
`on_end` steps run (once) — typically a losing ending.

**Schedules.** A character's `schedule` puts them in scenes at times:

```jsonc
"schedule": [
  { "scene": "library", "at": "desk", "days": [1, 2], "phases": ["Morning", "Afternoon"] },   // `at`: a marker of that scene, or [x, y]
  { "scene": "kitchen", "at": "stove", "phases": ["Evening"], "if": [ { "has_item": "key" } ] },
  { "away": true, "phases": ["Night"] }                  // nowhere — on purpose (so the checker doesn't warn)
]
```

Omitted `days` / `phases` mean every day / all phases; `if` adds conditions; `pose`, `facing` and `scale` are as on an actor entry. Each
entry becomes an **actor** in that scene (see "Actors"), visible only at those times — and a character with a `talk` table also gets
a talk hotspot that follows them (`"talk": false` on the entry turns that off), so "find Mrs. Hartley, she's in the library in the
morning" needs no other wiring. The validator warns about any day-and-phase with no entry (and no `away` entry) — "Mrs. Hartley is nowhere on
day 3 Evening" — so the person the player needs is never lost between two rows.

**How it works.** The whole clock is one reserved number (`@clock`, phases since the start of day 1); the steps and conditions above are
rewritten into `inc_var` / `set_var` and ordinary conditions when the game loads, so the story check and the exact soft-lock search see
time as a counter — a three-day, four-phase game is a dozen clock values, not a new kind of state.

## Chapters, checkpoints & migrations

Three things that make a long game survivable — for the player and for you.

**Chapters.** `project.json` can list acts. Starting one shows a title card (a click skips it), moves the story on, and runs the
chapter's own steps; conditions know which chapter it is.

```jsonc
"chapters": [
  { "id": "arrival", "title": "Chapter 1 — Arrival" },
  { "id": "the_cellar", "title": "Chapter 2 — The Cellar", "subtitle": "Below the manor",
    "on_start": [ { "action": "add_objective", "id": "find_ledger", "text": "Search the cellar." } ],       // steps run when it starts
    "fresh_map": true, "fresh_objectives": true }                                                          // optional: a clean Map and To-Do list (below)
]
```

**A clean slate for the player.** `"fresh_map": true` makes the Map show only the rooms seen since the chapter began (the room you start it in counts); `"fresh_objectives": true` makes the To-Do
list show only the tasks set in that chapter (a task from before chapters existed counts as chapter 1). Both only change what the player *sees*: rooms and tasks are not forgotten, so `visited`, `objective_done`
and `objective_active` conditions, the story check and the exact soft-lock search behave exactly as without them. (The rooms seen since a chapter began are saved with the game.)

| | |
|---|---|
| `{ "action": "start_chapter", "chapter": "the_cellar" }` | the title card, then the chapter's `on_start` steps |
| `{ "chapter": "the_cellar" }` / `{ "chapter_gte": "the_cellar" }` | in that chapter / in it or any later one |

The first chapter is the starting one. (Like the clock, the chapter is one reserved number, so the story check and soft-lock search read it as a counter.)

**Checkpoints.** `{ "action": "checkpoint", "id": "before_the_vault" }` remembers the game as it is now (the `id` is optional). When the player
loses — an `end_game` with `"result": "lose"` — the ending offers **Try again from the last checkpoint**, or from the last autosave when there
is no checkpoint, so a fatal mistake costs a few minutes, not the game. Put one before anything risky. (The soft-lock search treats a
losing ending as the end of that line; rewinding is the player's choice, not a move in the story.)

**Save migrations.** A save records the game's `version` (project.json). When you patch a released game, add a migration so older saves load:

```jsonc
"version": "1.2",
"migrations": [
  { "from": "1.0", "to": "1.1", "rename_vars": { "found_key": "has_key" }, "set_vars": { "bonus_seen": false }, "remove_vars": ["old_counter"] },
  { "from": "1.1", "to": "1.2", "rename_items": { "rusty_key": "brass_key" }, "rename_scenes": { "cellar_door": "cellar_entry" } }
]
```

On load, the chain runs from the save's version up to the game's `version`. `rename_*` also moves the player if they were standing in a renamed
scene; `set_vars` only adds what a save doesn't have yet; `"from": ""` upgrades saves written before versions were recorded. A variable
declared in `variables.json` that a save lacks starts at its declared default when the save loads (after the migrations), so adding a
variable never strands an older save — a migration is needed only when the default would be wrong for a game already under way. The validator
checks that the chain reaches the current version and that renamed targets exist.

## Atmosphere & camera

### Effects (`fx`)

A scene's `fx` list lays ambient effects over the room — no art needed, drawn by small shaders in flat scenes and panoramas
alike:

```jsonc
"fx": [
  { "type": "fog", "intensity": 0.4, "color": "#a8c0b8" },
  { "type": "dust", "intensity": 0.5 },
  { "type": "rain", "intensity": 0.7, "visible_if": [ { "var": "storm", "eq": true } ], "fade": 2 },
  { "type": "grade", "saturation": -0.3, "brightness": -0.05, "visible_if": [ { "var": "night", "eq": true } ] },
  { "type": "dust", "intensity": 0.8, "area": [0.55, 0.15, 0.25, 0.6], "feather": 0.25 },
  { "type": "rain", "area": [0.39, 0.24, 0.21, 0.39], "mask": "game/assets/backgrounds/barn_rain_mask.png" }
]
```

| `type` | what it draws |
|---|---|
| `rain`, `snow` | falling streaks / flakes in three depths (`intensity` = how heavy) |
| `dust` | drifting, twinkling motes — a sunbeam, an old attic |
| `fog` | slow mist, thicker toward the floor |
| `flicker` | a warm light that wavers like fire or a candle (`color` to change the hue) |
| `caustics` | the shifting net of bright lines light makes through water — a pool, a harbour wall, a ceiling over a lake; add it with an `area` over the water, `speed` for how fast it shimmers (lights up the picture, so it needs a dark enough room to show) |
| `glow` | a soft bloom of light round a point — a lamp, a window, a fire — steady and round, fading to nothing at the edge of its `area` (give it a square `area` centred on the light; without one it blooms from the middle of the picture) |
| `vignette` | dark edges, for mood |
| `grain` | film grain |
| `tint` | a flat colour wash (night blue, an alarm's red) |
| `grade` | colour grading of everything under it: `brightness`, `contrast`, `saturation`, each −1…1 |

Common fields: `area` (`[x, y, w, h]` of the picture, 0..1 — the effect is drawn only there, anchored to that part of the room so it moves and zooms with the camera: dust in a sunbeam, mist in a doorway, a flickering fire in its hearth; default the whole picture. In a panorama `area` is on the flat sheet, like a hotspot's shape, and the effect is placed over the box the area covers on screen as the view turns, hidden while it is behind you)
and `feather` (0..0.5, default 0.2: how softly an `area`'s edge fades out), `mask` (a picture stretched over the effect — its `area`, else the whole picture — white where the effect shows and black or transparent where it doesn't, for a shape a rectangle can't give: rain in a doorway with a car standing in it), `intensity` 0..1 (default 0.5), `color` (hex; each type has a sensible one), `speed` (1 = normal) for the
animated ones, `visible_if` (Conditions) and `fade` (seconds the effect takes to come in or go out when `visible_if` changes,
default 1). Effects are presentation only — they never change game state. With *Reduce motion* on, the moving ones (`rain`,
`snow`, `dust`, `flicker`, `caustics`) are left out and the rest hold still.

### Parallax

A flat room is one painted picture, so a camera move zooms every part of it alike. Giving an **overlay** a `parallax` makes it move against the picture instead, which is what gives a close-up view or a slow cutscene push-in some depth:
a branch across the top of the frame (`"parallax": 0.6`) sweeps past faster than the room, a distant sky (`-0.4`) lags behind it. The layer is magnified as if the camera were at `1 + (zoom − 1)(1 + parallax)` rather than `zoom`, about the point the camera is
looking at — so at zoom 1 nothing moves, and nothing moves for an overlay with no `parallax` (the default, 0). It is for decoration: a hotspot sits on the picture, not on a parallax layer, so do not put anything the player must click under one.
It does nothing in a panorama (overlays there are projected onto the sphere; the validator warns) and is skipped with nothing else to configure — Reduce motion already shortens camera moves to nothing.

### Time of day and other state changes

An overlay with a `fade` cross-fades when its `visible_if` flips instead of snapping. Put a full-frame overlay (`rect`
`[0, 0, 1, 1]`, or the whole panorama image) with the night picture, show it when `night` is true and give it a `fade`;
add a `grade` or `tint` effect with the same condition for the mood, and the room moves from day to dusk to night as the
story's variables change. Entering a room that is already at night shows it at once.

### The camera

Camera moves are for cutscenes. They are visual only — they end when the scene does — and `camera_reset` returns to where the
player was looking before the first one.

| action | what it does |
|---|---|
| `camera_look` | **Panorama:** turns the camera `toward` a marker, an actor or `[x, y]` on the picture (or to `yaw` / `pitch`, degrees) and/or zooms (`zoom` divides the scene's field of view; or give `fov`). **Flat scene:** pans the picture to put `toward` in the middle and pushes in by `zoom` (1 = the whole picture; it never shows past the picture's edge). `seconds` (default 1) and `wait` as for `move_overlay`. |
| `camera_shake` | a jolt that dies away: `strength` 0..1, `seconds`. Doesn't wait unless `"wait": true`. Ignored with *Reduce motion*. |
| `camera_reset` | eases back to the view before the first camera move |
| `letterbox` | cinematic bars slide in (`"on": true`, the default) or out over `seconds`; they sit over the picture but under subtitles and dialogue |

## Music & sound

Music is a file, or an **adaptive track** from `game/score.json` that follows the story. Everything fades: moving to a room with
different music crossfades (`project.audio.crossfade`, default 1.2 s; instant with Reduce motion), and music and ambience **duck** under
voice lines and stingers (`project.audio.duck_db`, default −9 dB) so speech is always on top. Sound runs on its own buses
(music, ambience, effects, voice, one-shots) under the player's volume sliders.

```jsonc
// game/score.json — all three lists optional
{
  "tracks": [
    { "id": "manor",
      "fade": 2.0,                                   // default seconds a stem takes to fade in or out
      "stems": [                                     // played together, in step: give them the same length and tempo
        { "id": "bed",    "file": "game/assets/music/manor_bed.ogg" },                           // no condition: always on
        { "id": "tense",  "file": "game/assets/music/manor_tense.ogg", "db": -3, "fade": 4.0,
          "when": [ { "var": "danger", "gte": 2 } ] }                                           // fades up while the condition holds
      ] }
  ],
  "stingers": [ { "id": "discovery", "file": "game/assets/sfx/discovery.ogg", "db": 0, "duck_db": -6 } ],
  "beds": [                                          // ambience: a loop with one-shots scattered over it
    { "id": "cellar", "loop": "game/assets/sfx/cellar_drone.ogg", "db": -4,
      "oneshots": [ { "file": "game/assets/sfx/drip.ogg", "every": [6, 14], "db": -8 } ] }   // every 6–14 s, somewhere different in the room
  ]
}
```

- A scene's (or place's) `music` may name a **track** instead of a file, and its `ambient` a **bed**; `play_music` too. Stems fade
  toward where their `when` puts them as the game's variables change; a stem with no `when` is always on.
- `play_stinger` plays a stinger over whatever is playing and ducks the music by its `duck_db` for its length.
- **Reverb.** A scene (or place) may have `"reverb": { "room": 0.4, "damp": 0.5, "wet": 0.2 }` (each 0–1): voices and effects
  sound in that space while the player is there.
- **Rooms that sound like their size.** Instead of tuning a reverb by ear, a scene may say how big the room is and what it is made of:
  `"space": { "width": 6, "depth": 8, "height": 3, "surface": "stone" }` (metres, 0.5–500; `surface` is `soft` | `wood` | `plaster` (default) | `stone` | `glass` | `open`). The engine works out
  the reverberation time by Sabine's rule (0.161 × volume ÷ total absorption) and turns it into `room` / `damp` / `wet`: a bare stone cellar rings for seconds, a carpeted study hardly at all, `open`
  (outdoors) is dry. A scene's own `reverb` always wins over its `space`; the validator warns when both are set.
- **Mix presets.** `project.audio.mixes` names balances of the buses that ease in while something is going on:
  `"mixes": { "dialogue": { "music": -4, "ambient": -6, "seconds": 0.6 }, "cutscene": { "music": 3, "sfx": -3 } }`. `dialogue` is on while a conversation is open, `cutscene` while a video cutscene plays;
  each bus (`music`, `ambient`, `sfx`, `voice`) is a dB offset from where the player's slider puts it (−40…+6, on top of the ducking under speech), and `seconds` is how long a 12 dB change takes
  (default 0.6; 0 = at once). Anything not named stays put, and a game with no `mixes` sounds exactly as before.
- **Interface sounds.** The engine signals what happens with short cues. Every game has them with no files at all (built-in
  tones), and `project.audio.cues` gives any cue a sound of the game's own (a file on the effects bus); a cue left out keeps its tone.

```jsonc
"audio": { "cues": { "pickup": "game/assets/sfx/pickup.ogg", "clue": "game/assets/sfx/clue.ogg", "ring": "game/assets/sfx/phone_bell.ogg" } }
```

  | Cue | Plays when | Built-in |
  |---|---|---|
  | `pickup` | something goes into the inventory (`give_item`, a combination) | rising two notes |
  | `clue` | a clue is found (`add_clue`, a `set_var` with `found`) | as `journal` |
  | `journal` | a journal entry, an email, a dossier note | three notes |
  | `objective` | a task is added | as `journal` |
  | `objective_done` | a task is completed | as `journal` |
  | `click` | a button, a choice, a menu item is pressed | a tick |
  | `error` | a wrong answer on the case board | two low notes |
  | `success` | the case board is right; the ending | a rising arpeggio |
  | `achievement` | an achievement is earned | as `success` |
  | `ring` | the telephone rings (again every 2.2 s while it rings) | a two-tone bell |
  | `text` | a text or a voicemail arrives | two high notes |
  | `chapter` | a chapter's title card is shown | silent |

  The validator fails a cue whose file is missing and warns about a name that is not a cue. The Studio's Dashboard picks them under
  *Interface sounds*.
- **Positional sound.** A scene's `sounds` place sounds in the room; in a panorama each one's pan and volume follow where the
  camera points (hard right when 90° to the right of where you look, centred when you face it, 12 dB quieter behind you); in a flat
  scene the pan is the sound's place left to right. At most four play at once.

```jsonc
"sounds": [
  { "id": "clock", "file": "game/assets/sfx/tick.ogg",
    "at": [0.75, 0.5],                // where on the picture (0..1); in a panorama that is a direction in the room
    "db": -6, "loop": true,            // loop defaults to true
    "visible_if": [ { "var": "clock_stopped", "eq": false } ] }
]
```
- The validator checks files, ids, conditions, ranges and fades, that every `play_stinger` names a stinger, and warns about a track,
  stinger or bed nothing uses. The Studio's **Music** tab edits the score, a scene's inspector picks its music / ambience / reverb /
  positional sounds, and the Dashboard sets the mix; the MCP server has `get_score`, `upsert_score_entry` and `delete_score_entry`.

## Timers & chance

`start_timer` runs a list of actions after a number of seconds of play — a countdown for a
chase, a bomb, a visitor who arrives in two minutes. Give it a `label` and the player sees a
live `m:ss` countdown at the top of the screen.

```jsonc
{ "action": "start_timer", "id": "bomb", "seconds": 90, "label": "Defuse it!",
  "actions": [ { "action": "end_game", "result": "lose", "text": "The vault goes up in smoke." } ] }
```

- **Pausing.** By default a timer *pauses* while a dialogue, puzzle, or panel (journal, map…) is
  open and while the pause menu is up, so reading never costs the player time. Set
  `"realtime": true` for pressure that doesn't wait — it keeps counting during dialogues and
  puzzles (only the pause menu stops it), e.g. a puzzle you must solve before time runs out.
- **The Menu pauses the game.** While the pause menu — or a screen opened from it (Settings, Save/Load, Achievements, Report a
  problem) — is up during play, no timer moves (not even a real-time one: a ringing phone waits too) and the music, the ambience,
  the room's positional sounds and its video loop, a playing cutscene and the voice hold where they are; they pick up from there when
  it closes. Menu clicks still sound.
- **When it fires.** Its `actions` run as soon as nothing else is on screen; any `if` / awaitable
  steps work as usual. A timer is then removed.
- **Restarting / stopping.** Starting a timer id that is already running restarts it.
  `cancel_timer` stops it; the `timer_running` condition lets hotspots and dialogue react while it
  runs (to react *after* it was cancelled, set a variable in the same step list).
- Running timers are saved and restored with the game.

`random_var` sets a variable to a random whole number between `min` and `max` (inclusive) — dice
rolls, which suspect is lying this time, which of three hiding spots holds the key. Combine it with
per-step `if` conditions to branch on the result.


## Variables in text

Any text the player is shown may hold `{$name}`, which is replaced by that variable's value at the moment the text is displayed (`core/text.gd`, called by `MF.t()` — so it works in every place text is shown: narration, dialogue lines, journal and clue text, hints, item and
hotspot labels, notices). "You have found {$clues_found} of 5 clues." · "The vault opened with {$vault_code}." A whole number prints without a decimal point, a list joins its items with commas, and a name that is not a variable (or one that has never been set) is left as written so a typo
is visible; the validator names every `{$name}` that is not a declared, built-in or engine-maintained variable (a warning, with a did-you-mean). Translation happens first, so a locale entry keeps its placeholder: `"You have {$coins} coins."` → `"Sie haben {$coins} Münzen."`.
Together with `random_var` this lets a game deal a fresh code or figure each playthrough and print it wherever the clue lives. The text of a conversation-log line is kept as written and filled when the log is shown, so it shows the variable's value *then*, not when the line was first said.

## Phone, inbox & suspects

Three in-game devices, each a button in the HUD that only appears once it has something to show.

**Phone — contacts.json.** The **Phone** button (or `P`) opens a contact list and a dial pad.
Saved contacts can be rung from the list; any contact with a `number` can also be reached by
*dialing* it — so a number found on a note or business card is a real clue. A number nobody owns
says "The number you have dialed is not in service."

```jsonc
{
  "contacts": [
    {
      "id": "mabel",
      "name": "Mabel Hart",
      "number": "555-0142",             // optional; digits and ( ) + - . * # only, unique
      "saved": true,                     // default true: shown in the list. false = dial-only
      "if": [],                          // optional Conditions: reachable (and listed) only when true
      "dialogue": "call_bess",           // optional: a dialogue started when the call connects
      "actions": []                      // optional Actions, run after the dialogue
    },
    {
      "id": "informant", "name": "Informant", "number": "555-0166", "saved": false,
      "if": [ { "var": "found_card", "eq": true } ],
      "dialogue": "call_informant"
    }
  ]
}
```

A contact that isn't `saved` must have a `number` — or be rung by an `incoming_call` step, which is how a
mystery caller reaches the player. A contact with neither `dialogue` nor `actions` does nothing when
called (the validator warns).

**Incoming calls, voicemail and texts.** The phone has four tabs — *Dial* (the list and pad above), *Calls*
(a log of answered, called and missed calls, each with *Call back*), *Voicemail* and *Messages* (a thread per
contact) — and its button shows `●n` for what has not been looked at, `☎` while it rings. Three steps drive them:

```jsonc
{ "action": "incoming_call", "contact": "informant", "ring": 20,         // seconds it rings (default 20)
  "voicemail": "Meet me at the pier. Come alone.",                       // optional: left if nobody picks up
  "on_missed": [ { "action": "set_var", "var": "informant_missed", "value": true } ] }   // optional: runs when it rings out or is declined
{ "action": "add_text", "contact": "mabel", "text": "Did you find the key?",
  "from": "contact",                                                     // "contact" (default) or "player" — a message the player sent
  "id": "bess_key", "reply": "text_bess_key" }                           // optional: a Reply… button that starts this conversation, once; `id` is required with it
{ "action": "leave_voicemail", "contact": "mabel", "text": "It's me. Call me back." }
```

The phone rings with a chime, a notice and an **Answer / Decline** bar on screen. *Answer* runs the contact's
`dialogue` and `actions` exactly like calling them (a ringing contact can be answered whatever its `if`, `saved` or
`number`); *Decline*, or letting it ring out, logs a missed call, leaves the `voicemail` and runs `on_missed`.
The ringing is a real-time timer (it keeps counting while the phone is open), so it is saved with the game. A
message with a `reply` keeps `@textpending.<id>` true until the player answers it, and `@replied.<id>` afterwards
(readable as `{ "var": "@replied.bess_key" }`). The story check treats an `incoming_call` as making that contact
reachable and its `on_missed` possible; the exact search takes *answer*, *let it ring out* and *reply to a text* as moves
(an unanswered call that changes the story switches the search reduction off; one that cannot — no `on_missed`, or one that only loses the game — keeps it, so a phone that rings
the moment a case opens costs the search nothing). A walkthrough drives it with
`{ "answer": "informant" }`, `{ "decline": "informant" }` and `{ "reply": "bess_key" }`, and `expect` accepts `ringing`
(a contact id), `texts` and `voicemail` (text that must appear).

**Inbox.** `add_email` delivers a message (once per `id`); the **Inbox** button (or `E`) appears
with an unread badge. Opening a message marks it read. Conditions `email_received` / `email_read`
let the story react ("only after the player has read the invitation").

**Suspects.** Characters with `"suspect": true`, and any character that `add_dossier` has noted a
clue about, appear in the **Suspects** screen (button or `S`) with their `portrait`, `bio`, and every
clue learned so far.

## Hints — hints.json

The player's **Hint** button (top bar, or `H`) is the classic "call a friend" moment. It
shows the hint that fits where they're stuck, starting with a nudge and revealing a
clearer level each time they ask for another. The button only appears when the game
defines hints and the current difficulty level doesn't turn them off.

```jsonc
{
  "hints": [
    {
      "id": "cellar_code",
      "from": "mrs_hartley",              // optional character: portrait + name shown with the hint
      "if": [ { "unsolved": "cellar_keypad" }, { "visited": "library" } ],   // when this entry applies
      "levels": [                          // gentlest first; the player reveals them one at a time
        { "text": "Maybe someone in the house knows about the cellar." },
        { "text": "Mrs. Hartley said the code died with the master.", "voice": "game/assets/voice/hints/cellar_2.wav" },
        { "text": "The old note in the writing desk lists the year." }
      ]
    },
    { "id": "keep_looking", "levels": [ { "text": "Try talking to everyone again." } ] }
  ]
}
```

Entries are tried **in file order** and the **first** whose `if` conditions all hold (and that
has at least one level) is the active one — so list the most specific situations first and a
catch-all (no `if`) last. (The validator warns when an unconditional entry shadows later ones.)
A level may be a plain string as shorthand for `{ "text": "..." }`. Revealed levels are kept
per hint (and saved), so re-opening the Hint screen shows what you already learned plus a button
for the next level. With no applicable hint the player is told to keep exploring.

## Conditions

A condition list is implicitly **AND**. Omitted or empty lists are true.

```jsonc
{ "var": "snoop_count", "eq": 3 }      // also: ne, lt, lte, gt, gte
{ "has_item": "brass_key" }            // / { "missing_item": "brass_key" }
{ "solved": "cellar_keypad" }          // / { "unsolved": "cellar_keypad" }
{ "visited": "library" }               // / { "not_visited": "library" }
{ "objective_done": "find_ledger" }    // / { "objective_active": "find_ledger" }
{ "email_received": "invite" }         // / { "email_read": "invite" }  (see "Phone, inbox & suspects")
{ "timer_running": "bomb" }            // true while that timer is counting down (see "Timers")
{ "script": "is_night", "args": {} }   // a custom check you wrote in GDScript (see "Custom scripts")
{ "chapter": "the_cellar" }            // / { "chapter_gte": "the_cellar" } — the story is in that chapter / has reached it (see "Chapters, checkpoints & migrations")
{ "day": 2 }                           // / { "day_gte": 2 }, { "day_lte": 2 }, { "phase": "Evening" }, { "phase_in": ["Evening", "Night"] } — the clock (see "Time & schedules")
{ "has_clue": "stamp" }                // / { "deduced": "letter_forged" } — found that clue / made that deduction (see "Clues & deductions")
{ "culprit": "vane" }                  // this game's culprit is that character (see "Mystery model & accusation")
{ "knows_topic": "the_will" }          // the player has learned that topic (see "Topics & conversations")
{ "asked": "clerk:the_will" }          // / { "showed": "clerk:torn_letter" } — the character has answered it / been shown it
{ "contains": "desk_drawer", "item": "brass_key" }   // that container has that item inside (see "Containers")
{ "lead": "tom" }                      // / { "in_party": "tom" }, { "present": ["dan", "tom"] } — playable characters (see "Party")
{ "any": [ ...conditions... ] }        // OR group
{ "all": [ ...conditions... ] }        // AND group (for nesting inside "any")
```

## Actions

Actions run in order; each may carry an optional `"if": [Conditions]` making it
conditional. Awaitable actions (dialogue, text, puzzles) block the rest of the list
until done.

| action            | fields                                            | notes |
|-------------------|---------------------------------------------------|-------|
| `goto_scene`      | `scene`, `yaw`, `pitch`, `fov`, `face`, `away`    | fade transition; in a panorama the camera arrives at `yaw` / `pitch` / `fov` (degrees), or turned toward the destination hotspot `face` (and, with `away`, the opposite way — how you look into a room after coming through its door) |
| `go_view`         | `view`                                            | zoom into a view of this scene (see "Views & close-ups") |
| `open_container`  | `container`                                       | open a container of this room, showing what is inside (the others in the room shut; see "Containers") |
| `close_container` | `container`                                       | shut a container |
| `set_lead`        | `id`                                              | hand the lead to a member of the party (see "Party") |
| `set_party`       | `members`, `lead`                                 | change who is in the party (everyone else leaves it); `lead` defaults to the first member |
| `lock_switch`     | —                                                 | the player cannot switch the lead until `unlock_switch` |
| `unlock_switch`   | —                                                 | the player may switch again |
| `leave_view`      | —                                                 | back out one level |
| `set_var`         | `var`, `value`                                    | |
| `inc_var`         | `var`, `by` (default 1)                           | numeric vars |
| `give_item`       | `item`                                            | with pickup chime |
| `remove_item`     | `item`                                            | |
| `start_dialogue`  | `dialogue`                                        | awaits completion |
| `show_text`       | `text`, `voice` (opt)                             | narrator subtitle, awaits |
| `play_voice`      | `voice`, `text`                                   | awaits; a line the player (in a party, the lead) says: the recording and/or its subtitle — `text` alone is a line not recorded yet |
| `play_sfx`        | `sfx`                                             | fire and forget |
| `play_music`      | `music`                                           | switches track — a file, or the id of an adaptive track (see "Music & sound"); the old one fades out |
| `play_stinger`    | `stinger`                                         | a short cue from `score.json` over the music; the music ducks under it |
| `stop_music`      | —                                                 | |
| `start_puzzle`    | `puzzle`                                          | awaits close/solve |
| `show_item`       | `item`                                            | examine close-up |
| `play_video`      | `video`, `skippable` (default true)               | fullscreen cutscene (.webm / .ogv — see "Video"), awaits |
| `add_journal`     | `title`, `text`                                   | one entry per title |
| `add_objective`   | `id` (snake_case), `text`                         | adds a To-Do task (once per id) |
| `complete_objective` | `id`                                           | checks the task off |
| `run_script`      | `script`, `args` (opt object)                     | runs `game/scripts/actions/<script>.gd`; see "Custom scripts" |
| `move_overlay`    | `overlay`, `to` ([x,y]), `from` (opt [x,y]), `seconds` (default 1), `wait` (default true) | slides an overlay to a new position; see "Animation" |
| `fade_overlay`    | `overlay`, `alpha` (0..1), `seconds` (default 0.5), `wait` (default true) | fades an overlay in or out |
| `play_overlay`    | `overlay`                                         | restarts an overlay's frame animation from the first frame |
| `converse`        | `character` | opens that character's conversation (their `talk` table): ask about topics, show items; see "Topics & conversations" |
| `start_chapter`   | `chapter` | the chapter's title card, then its `on_start` steps; see "Chapters, checkpoints & migrations" |
| `checkpoint`      | `id` (opt) | remembers the game: losing then offers "Try again from the last checkpoint" |
| `advance_time`    | `phases` (default 1) or `to` (a phase name) | moves the clock on; see "Time & schedules" |
| `set_time`        | `day`, `phase` | sets the clock |
| `add_clue`        | `clue` | adds a clue to the player's case board (once); see "Clues & deductions" |
| `make_deduction`  | `deduction` | the player makes that deduction (once) without the board — its steps run, a notice shows; see "Clues & deductions" |
| `learn_topic`     | `topic` | the player learns a conversation topic (once); a notice tells them |
| `incoming_call` | `contact`, `ring`, `voicemail`, `on_missed` | the phone rings; answer, decline or let it ring out; see "Phone, inbox & suspects" |
| `add_text` | `contact`, `text`, `from`, `id`, `reply` | a message in a contact's thread; `reply` offers a conversation to answer it with |
| `leave_voicemail` | `contact`, `text` | a voicemail appears without a call |
| `unlock_achievement` | `id` | the player earns that achievement (once ever); a notice tells them; see "Achievements" |
| `actor_enter`     | `actor`, `at`, `from` (opt), `pose` (opt), `walk` (opt), `facing` (opt), `fade` (default 0.4), `seconds` / `speed` (for a walk-in), `wait` (default true) | brings an actor on stage — fading in at `at`, or walking in from `from`; see "Actors" |
| `actor_walk_to`   | `actor`, `to`, `via` (opt list), `walk` (opt), `seconds` / `speed` (opt), `wait` (default true) | walks to a marker or position, turning as they go and showing their `walk` pose (or the pose `walk` names) |
| `actor_face`      | `actor`, `facing` (`left` / `right`) or `toward` (a marker or another actor) | turns an actor |
| `actor_play`      | `actor`, `pose`, `wait` (default true) | takes up a pose; a one-shot is waited for, then they settle into its `then` |
| `actor_say`       | `actor`, `text`, `voice` (opt), `pose` (opt) | the actor speaks a line (name in their colour); their mouth follows the voice. Awaits like `show_text` |
| `actor_exit`      | `actor`, `to` (opt), `walk` (opt), `fade` (default 0.4), `seconds` / `speed` (opt), `wait` (default true) | walks off to `to` (if given), fades out and leaves the scene |
| `camera_look`     | `toward` (opt), `yaw` / `pitch` (opt), `zoom` (opt), `fov` (opt), `seconds` (default 1), `wait` (default true) | turns / pans / zooms the camera; see "Atmosphere & camera" |
| `camera_shake`    | `strength` (0..1, default 0.5), `seconds` (default 0.6), `wait` (default false) | a jolt that dies away |
| `camera_reset`    | `seconds` (default 0.8), `wait` (default true) | back to the view before the first camera move |
| `letterbox`       | `on` (default true), `seconds` (default 0.6) | cinematic bars in or out |
| `start_timer`     | `id` (snake_case), `seconds`, `actions`, `label` (opt), `realtime` (opt, default false) | runs `actions` after `seconds` of play; see "Timers" |
| `cancel_timer`    | `id`                                              | stops a running timer |
| `random_var`      | `var`, `min` (default 0), `max` (default 1)       | sets the variable to a random whole number, `min`..`max` inclusive |
| `add_email`       | `id` (snake_case), `from`, `subject`, `text`      | a message arrives in the Inbox (once per id) |
| `add_dossier`     | `character`, `text`                               | notes a clue on a suspect's dossier page (deduplicated) |
| `end_game`        | `result` (`win`/`lose`), `text` (opt)             | shows end screen |
| `wait`            | `seconds`                                         | |

The **To-Do list** (the player's `T` key / "Tasks" button) shows objectives added
by `add_objective`, with completed ones checked off. `objective_done` /
`objective_active` conditions gate on them. The validator warns if an objective is
completed or checked but never introduced by an `add_objective`.

The **Map screen** (`M` key / "Map" button, shown only when some scene has a
`map_pos`) lets the player fast-travel between *visited* locations; undiscovered
ones read as `???`. An optional `project.map.background` image sits behind the
location markers. The map area is 2:1 and nearly the whole screen (1760×880 of 1920×1080) and keeps the picture's
shape, so a 2:1 picture fills it and a marker's `map_pos` lands on its drawing (draw it 2640×1320 for Retina screens).

A scene's **`compass`** ( `{n,e,s,w: scene_id}`, any subset) shows an in-game
compass widget that walks to the linked rooms — classic second-person "turn to
face a wall" navigation. Directions not listed are greyed out; the widget hides
on scenes with no compass. The validator checks each target scene exists.

### Map travel rules

By default the Map screen takes the player from anywhere to any visited room with a `map_pos`. A game whose story only lets
the player go somewhere at certain times — the car only drives to the lake after camp, a locked closet must be escaped, not
left — says so on its rooms:

- **`map_when`** (conditions): the room is a destination only while they hold. Otherwise its marker is shown greyed (the
  player has been there, so its name is known) and can't be pressed.
- **`map_leave_when`** (conditions): the map can take the player away from this room only while they hold — usually exactly
  when the room's own way out is open. Otherwise every marker is greyed and the screen says "You can't leave from here just
  now."
- **`map_lock`** (`true`): the map can never leave this room.

The same rules hold everywhere a trip by map happens: the Map screen, the typed `travel` command, a walkthrough's `goto` step
(a `goto` along the room's `compass` is a walk, not a trip by map, and is not checked) and the exact soft-lock search, which
only takes the trips the rules allow — so its verdict is about the game the player actually has.
The rules live in `core/map_travel.gd`; a game that uses none of them travels exactly as before.

## Patching & updates

Ship a fix without re-shipping the game. A **patch** is a small zip of only what changed since a shipped build — the game's data and its re-imported assets (Godot's own `--export-patch`, so imported textures and audio are right) — plus a `patch.json`: the game, the version it is
for (`base_version`), the version it leads to (`version`), and the SHA-256 of every file. Patches are the game's **content**: a change to the engine or to the game's own scripts needs a full release, and the builder refuses it.

**Building** — `make patch ARGS="--release-zip build/release/<game>-1.0.0-linux.zip --from v1.0.0"` (`python3 tools/patch.py`): the shipped build's pack comes from the release zip (or `--base-pck` with `--base-version`); the game's `project.json` version must be newer; only `game/**`, re-imported
assets and the uid cache may go in; and, given the old game's data (`--from <git ref>` or `--from-dir`), **a scene, item or variable that existed in the shipped version and no longer does is refused unless a migration from that version renames or removes it** (`rename_scenes`, `rename_items`,
`rename_vars` / `remove_vars`) — saves made before the patch must keep working (`--allow-breaking` builds anyway). A patch cannot *delete* files: ones removed since the shipped build stay in the game, unreachable, and the builder says which. Patches are per platform (`--platform`).

**Applying** (`core/patches.gd`, at start, before any game data is read): the engine looks in `patches/` beside the executable and the player's `user://patches/` (`MF_PATCH_DIR` overrides both, for testers and CI; a run from the editor looks nowhere), reads each zip's `patch.json`, refuses any that is not a patch, is for another game or format, goes
backwards, whose version is not the one the game is at, or **whose files do not match their checksums** (a damaged download is refused before it is mounted), and mounts the rest as a chain from the version that shipped. A **cumulative** patch (1.0.0 → 1.0.3) wins over the small ones it contains; an **incremental** chain
(1.0.0 → 1.0.1 → 1.0.2) is followed step by step. The game then reads its patched `project.json`: the title screen's version, new saves' `game_version` and the migrations all see the new version. What was applied and what was refused, and why, is in the log, in `MF.patch_report` and in the support bundle's manifest.
On macOS use `user://patches/` (a file inside the signed `.app` would break its signature); the web build has no folder to read — redeploy it. Steam and other stores update by replacing files: patches are for direct distribution and testers.

`make patch-proof` (in `make check`) proves it on a fresh game: a probe running *from the base pack* sees v1.0.0 alone and v1.0.1 with the patch (the dialogue **and the re-imported picture**), a damaged patch and one for the wrong version are refused, a change to the engine cannot be a patch, and a removed scene is refused naming it
unless a migration covers it.

## Release packaging

`make release` / `python3 tools/package.py` (every game carries it) takes a finished game to artifacts you can hand to a store or a tester, in one command:

1. **The gate.** `tools/release.sh <level>` (default `beta`) must pass, or nothing is built — unless `--force`, which builds anyway and records `gate.passed: false` in the manifest. `--gate none` skips it.
2. **Exports** for each platform (`web`, `windows`, `linux`, `macos`; `--platforms` picks) whose export template is installed and that has a preset; the rest are *skipped with the reason*. A platform that was ready and failed to export fails the run.
3. **Staging.** Each build is packed with `README.txt`, `VERSION.txt` (game, version, engine, Godot, git revision, build time), `CHANGELOG.txt` (git log since the last tag), the game's **licence** (`LICENSE*` / `EULA*` / `COPYING*`, with a warning if there is none) and
   `THIRD_PARTY.md` — generated by `tools/notices.gd` from the licence data compiled into Godot (its licence and every component's), the video extension's FFmpeg (LGPL, `--disable-gpl`) when it is bundled, and the game's own credits. The macOS app gets the game's **version** in its
   `Info.plist` (the preset's own is a fixed 1.0) before it is signed.
4. **Signing, from the environment only** — never from a file in the repository, and nothing secret is printed: `MF_CODESIGN_IDENTITY` (macOS "Developer ID Application: …"; unset gives an **ad-hoc** signature that verifies but is not for distribution), `MF_NOTARY_PROFILE` (a keychain profile
   from `xcrun notarytool store-credentials`: the app is submitted, waited for and stapled), `MF_WINDOWS_SIGN_CMD` (the command that signs an exe, the path appended, e.g. `signtool sign /fd SHA256 /a /tr <url> /td SHA256`), `MF_GPG_KEY` (a detached `.asc` beside each zip). A macOS app is **verified**
   (`codesign --verify --deep --strict`) whatever the identity; GDExtensions get the library-validation entitlement.
5. **`SHA256SUMS`** (`shasum -c` format) and **`manifest.json`**: game, version, engine, Godot, git revision (and whether the tree was dirty), the gate's level and verdict, how each platform was signed, what was skipped or failed, and every artifact's size and SHA-256.

`--dry-run` exports nothing: it says, per platform, whether the template and preset are there and what signing would be used, and checks that the identities and tools the environment names exist — everything that can be proved without the identity. Zips keep symlinks and permissions (an `.app` needs both).
The gate has two rows that exist for shipping: **the macOS bundle identifier is the game's own** (the template's `org.mysteryforge.*` warns at beta and blocks gold — and Apple's rules apply: letters, digits, `-` and `.`) and **a licence or EULA ships with the game**
(a file of real substance; one still saying REPLACE THIS does not count). `make package-proof` (in `make check`) proves it on a fresh game: the gate stops one with no licence, a good one packages with every SHA-256 matching and notices, licence, version and README inside, the macOS app carries the game's version and
bundle id and verifies under codesign, and `--force` is recorded. Not done here, because it needs accounts: a real Developer ID, notarisation, a Windows certificate, store submission.

## Diagnostics & support

When something goes wrong a player can hand the people who made the game what they need, and read every part of it first. **Report a problem** is on the pause menu and a quiet link at the bottom left of the title; it
opens a screen that says what it is, lets the player type **what happened**, and lists the file's contents *with sizes* before anything is made (`core/support.gd`, `ui/support_panel.gd`). **Create the file** writes one zip to the player's own
`user://support/` folder and offers to show it in the file manager. **Nothing is ever sent from here** — the player sends it.

The zip holds only this fixed list: `manifest.json` (game id, title and version; engine and Godot versions; OS, CPU, memory, GPU and renderer; screen and window mode; language and the accessibility settings; whether this is the first or another player — never a name;
where the player is and for how long; the state — ok, empty, recovered, unreadable, newer — of each save slot, whether the settings were reset, and the last few save problems), `log.txt` (the last 400 lines of the engine's log), `settings.json`, `save.json` (the game as it is now,
only while a game is open), `slots.txt` (each slot's state, not its contents), `playtest.jsonl` (only in a playtest build) and `note.txt` (only if the player typed something). Folders on the player's computer are replaced by `~`, `<user data>` and `<game>`. No save slot's
contents, no player or profile name, goes in.

Desktop builds write a rotating log (`user://logs/godot.log`, the newest ten kept; set explicitly in `project.godot`), which starts with one line saying what game, version, engine and system it came from. Web builds keep none, and the bundle says so.

## Display settings

Player-level, in **Settings → Display** (`core/display.gd`, saved in `settings.json`): **Window** (windowed / fullscreen / borderless window), **Window size** (automatic — the project's own 1440×810 — or the sizes that fit this screen with room for the
title bar and the dock; greyed out unless windowed), **Vertical sync**, and a **Frame rate limit** (none, 30, 60, 120, 144, 240). A size saved on a larger monitor is cut down to fit the one in use, in proportion — a monitor unplugged between
runs never leaves a window off the screen. Sizes are the screen's own **points**, not its pixels: on a Retina Mac (2× scale) the automatic window is 1440×810 to the eye
(2880×1620 pixels), never a half-size 720×405, and the sizes offered are those that fit the screen's points. An old settings file that only said `fullscreen` becomes `fullscreen` (the key is kept in step with the mode). On the **first run** — no settings file yet — the language is the operating system's
if the game ships a locale for it (`pt_BR` before `pt`), else the game's own; a headless run (a tool or a test) is never switched. There is deliberately no separate "UI scale": the picture stretches to the window in proportion, and text size is its own
accessibility setting.

## Menus always fit

The title screen's column (the title and its buttons) and the pause menu are scaled down about their centre whenever what they hold would not fit the window
(`ui/fit_to_screen.gd`): a larger text size, a playtest or player notice, a long translation or one more button never puts **Quit** — or anything else — below
the bottom of the screen. At their natural size when they fit.

## The menu during a conversation

The player can always reach the menu — the **Menu** button (it stays usable above a conversation, a puzzle, a close-up or a cutscene, which cover the HUD), **Esc** or
the gamepad's **Start**. While the menu (or a screen opened from it) is up, the story waits: the voice pauses, so a line can't finish and move on behind it, and
**Resume** goes back to exactly where it was. In the middle of something, **Save Game** and **Load Game** wait until it is over (the menu says so) — half a
conversation is never saved — and **Main Menu** warns first that what is going on won't be kept, then leaves on a second click: the conversation stops where it
stands, nothing after it runs (`MF.abort_sequences`), and the last autosave (made on entering the room) stands.

## Conversation log & recap

Every line the player is shown or told is kept in the game's state as `spoken` (`state.gd`, saved with the game, newest 300 kept): narration and plain lines (`say` / `show_text`), what a character says (an actor's line, a dialogue node's `speaker`), and the option the
player chose (as speaker `player`, shown as "You"). Each entry is `{who, text, voice}` with `who` a character id, `narrator`, `player` or empty and `text` the game's own words — **translated when shown**, so changing language changes the log too. The same line from the same speaker twice in a row is one entry; a
blank line is none; a save from before the log has an empty one. Lines are recorded by the screens that show them (`MF.log_line`, from the subtitle bar and the dialogue overlay), never by game data, so the soft-lock search — which shows nothing — logs nothing, and no condition can read the log.

- **The conversation log** — `L` (a rebindable hotkey, Settings → Controls), or *Conversation log* in the pause menu: everything said so far, oldest first, in a scrolling panel — the speaker's name in their character `color`, narration in italics, and a ▶ beside every line that has
  a recording to replay it. Empty, it says so. It is also the answer to "what did she say again?" for a player who read a line too fast or relies on a screen reader (the panel's rows are real labels and buttons with accessibility names).
- **"Previously…"** — choosing a saved game (Continue, or Load from the title or pause menu) shows a card on black *before* the room opens (`core/recap.gd`): the chapter and room the player is in, the last five things said, and up to four open tasks (more are counted); Continue, Enter or Esc goes on.
  Nothing is shown when there is nothing to recall (nothing said, nothing to do), and **Settings → Recap when continuing** (`recap`, on by default) turns it off. It is shown by the title's Continue/Load flow only — a checkpoint rewind, a walkthrough or a bot loading a game does not wait for it.

## Touch

Player-level, in **Settings → Controls → Touch controls** (`core/touch.gd`, `MF.touch_mode()`, saved in `settings.json` as `touch`): **Automatic** (the default), **On**, **Off**. In Automatic, touch mode is on once a finger has
touched the screen and off again when a real mouse is used (Godot also turns the first finger into mouse events, marked `InputEvent.DEVICE_ID_EMULATION`, and those do not count as a mouse); a phone or tablet build starts out with a finger
seen. It is a setting of the *player*, never game data — no condition can read it, so it cannot change what the story check or the soft-lock search find.

What touch mode changes:

- **Tap targets.** A hotspot whose smaller side is below the finger size (`MFTouch.MIN_TARGET` = 96 px at the 1080-line design size, scaled with the view) catches a tap that lands within half the shortfall of its outline — a rectangle grows
  on every side, a circle's radius and a polygon's edge by that much. A hotspot that is big enough does not change, and where two grown hotspots overlap the one drawn later wins, as it does for the pointer. Only *where a tap lands* changes;
  nothing is drawn differently, so the pictures and the Studio's outlines stay true to the authored shapes.
- **Pinch to zoom.** On a panorama, two fingers moving apart or together narrow or widen the field of view by the ratio of the gaps (within the same limits as the mouse wheel and the picture); while a second finger is down the first
  one's drag does not also pan.
- **Held items** still use the long press (about 0.6 s) as the right-click, and a tap on a hotspot is still a click.

The engine's own screens use buttons large enough for fingers already; whether *this* tap size and pinch speed feel right is for real devices (docs/HUMAN_TASKS.md).

## Controllers

A game plays from the couch with a game controller — Xbox, PlayStation, Nintendo, a Steam Deck or anything Steam Input or SDL knows — with nothing in the game's data
(`core/pad.gd` pure, `ui/pad_controller.gd` the input, `ui/pad_pointer.gd`, `ui/pad_prompts.gd`, `ui/pad_glyph.gd`, `ui/pad_keyboard.gd`). Using a controller makes it the
active device; moving the mouse, touching the screen or pressing a key hands control back. Buttons are known by POSITION (the bottom one confirms on every pad), and the
screen names them as they are printed on the pad in the player's hands (A / Cross / B, Menu / Options / +…). What each button does depends on what is on screen:

| on screen | left stick | D-pad | A | B | X | Y | LB / RB | LT / RT | right stick | Start / View |
|---|---|---|---|---|---|---|---|---|---|---|
| a room | moves a pointer (the game's own cursor, slower over anything clickable, a soft rumble on finding it) | jumps the pointer to the next hotspot that way | clicks where it points (with an item held: uses it there) | puts the held item / armed verb down, else backs out of a view | shows every spot | opens the items | next / previous hotspot | hold the next / previous item | looks around a panorama | the Menu / the Journal |
| the items (after Y) | — | picks an item | holds it (or uses the held one on it) | back | examines it | back | — | — | — | — |
| any screen with buttons | moves the focus (held: repeats) | moves the focus (held: repeats) | presses; on a text field, opens the on-screen keyboard | what Esc does there | — | — | step through the controls; flip Journal → Tasks → Map; turn Settings pages | — | scrolls a long page | the Menu / the Journal |
| a puzzle board with focus | as the arrow keys | as the arrow keys | as Enter | what Esc does | as the X key | — | to the board's other controls | — | — | — |
| a line, a cutscene, the recap | — | — | moves on | moves on | — | — | — | — | — | the Menu |
| the on-screen keyboard | moves between keys | moves between keys | types the key | closes it | deletes | a space | Shift | — | — | Start = Enter (Done) |

Every screen with buttons ALWAYS has one focused while a controller is in use (its default: the title's Continue when there is a game to continue, else the first),
so a controller can never face a screen that ignores it; a screen with nothing to focus gets the pointer. Everything the pointer does is an ordinary mouse event at the
pointer, so a room, the HUD, a drag or a drawn puzzle needs no controller code; and every puzzle a keyboard can play (`tools/puzzle_a11y.gd`), a controller can.
The on-screen keyboard types into the field as a real keyboard would (`text_changed`, and Done is Enter — `text_submitted`), follows the focus when the field hands it on
(a crossword square moves to the next) and has a page of accented letters.

Player settings, never game data (no condition reads them), in **Settings → Controls → Controller**: `pad_speed` (0 slow / 1 normal / 2 fast), `pad_vibration` (the
rumble), `pad_prompts` (the button prompts along the bottom), with a chart of what each button does drawn for the pad in use. The layout lint scans the prompts in every
situation and both keyboard pages, and on every screen it visits reports a screen with buttons a controller cannot focus, or a button it cannot reach.

## Release gate

Is this game fit to ship? `make release-check LEVEL=alpha|beta|gold` (`bash tools/release.sh <level>`, which every game carries; the MCP `release_check`) gives one verdict from two parts: the **proof suite** (`tools/check.sh` — the
data validates, every room and puzzle is reachable, the exact soft-lock search is complete, finds no soft-lock and reaches **every ending**, every puzzle is proved winnable, the memory budget holds, the walkthroughs replay, a bot wins the game,
the UI holds up pseudo-localised) and the **data gates** (`tools/release.gd`, `core/release.gd`). Nothing in it calls a provider or needs a key.

| gate | alpha | beta | gold |
|---|---|---|---|
| identity | a title and a version like `1.0.0` | + an author and credits | same |
| validation | no error | + no warning | same |
| pictures | none missing | at most 50% placeholder | none placeholder, none missing |
| voice (only if the game is voiced) | — | at most 50% of lines missing, none edited since recorded | none missing, none stale, none synthesized |
| translations (every locale file is a shipped language) | — | each at least 80% | each 100% |
| review comments | — | warns if any open | none open |
| builds | every export preset keeps the Studio, `tools/` and `tests/` out | same | same |
| playtests | — | warns if no playtest notes in `game/playtests` | same |

A **fail** blocks the release; a **warn** is worth reading; a **skip** means the game has nothing of that kind (no voice, no other language). `alpha` runs the proof suite with warnings tolerated (`LENIENT=1`). The
gate is told in plain words what failed and how to fix it. `make release-proof` (in `make check`) proves it on a real game: a fresh scaffold with an author, credits and a 1.0.0 version passes gold; one placeholder picture
makes gold refuse by name while alpha still passes.

## Render hand-off

For an artist who will paint or render the rooms without opening the game. `make handoff [OUT=<folder>]` (the MCP `export_handoff`, `tools/handoff.gd`, `core/handoff.gd`) writes a pack, by default to
`build/handoff`:

| file | what it is |
|---|---|
| `guides/<room>.svg` | the **layout guide**, at the size to deliver: every hotspot drawn where it will be clicked (blue = a way to another room, pink = a person, yellow = something to pick up, orange = a puzzle, green = something to look at; dashed = appears later in the story), and — for an ordinary room — the parts of the screen the interface covers (the buttons at the top right, the compass, the subtitle bar). A panorama's guide is the flat sheet. It carries text, so it is for people and never part of the game's assets. |
| `shotlist.csv` | one row per room: id, name, group, room or panorama, **deliver size** (the game's picture size, or a 2:1 sheet — 4096 × 2048 for a full circle, narrower for `h_span` < 360), **deliver as** `<room>.png`, the file it replaces, what the game has now (`final` / `placeholder` per the asset manifest / `missing`) and its size, hotspots, doors, items to find, people, and a note when the current picture is the wrong shape. |
| `guides/<room>__<view>.svg` | the guide for a **close-up**: a view with its own `image` (see "Views & close-ups") is a row of its own — kind `closeup`, delivered at the part of the room it covers (`region`) at the room's delivery size times the view's zoom (a panorama's from its field of view), at most 4096 px on the long edge — drawn with the hotspots that live in that view remapped into it and the interface zones. A room's own guide no longer shows what lives in a close-up, and a hotspot that only has a view condition does not count as "appears later". |
| `current/<room>.*` | a copy of the picture the game shows now (close-ups likewise, as `current/<room>__<view>.*`). |
| `index.html` | a contact sheet: guide and current picture side by side for every room, with its status. |
| `README.md` | the rules: no text, interface or hotspot outlines in the picture; leave what is under a hotspot readable; panoramas wrap; one `<room>.png` per room; how the producer drops the pictures in. |

## Scene diffs

What changed in the rooms between two versions of a game, drawn rather than listed — for a producer reviewing a week of edits, an artist who has repainted a room, or anyone asking "who moved the door?". `make scene-diff BEFORE=<version> [AFTER=<version>] [OUT=<folder>]`
(`tools/scene_diff.py`, which every game carries and which needs only Python and Godot; the MCP `scene_diff`; `tools/scene_diff.gd`, `core/scene_diff.gd`) writes one page, by default `build/scene_diff/index.html`. A *version* is a git revision (`HEAD~3`, a tag, a commit),
`working` (the folder as it is now — the default for `AFTER`) or a folder that holds a `game/`. A revision is unpacked into a temporary folder — only `game/project.json`, the scenes and the pictures they name, never the audio or video — and removed again; nothing is checked out and nothing in the game changes.

It compares the authored `game/scenes/*.json` — not the loaded game, where a door link is already a hotspot — room by room, matching hotspots by `id`:

| a room is | when |
|---|---|
| **added** / **removed** | its file is only in one version |
| **changed** | any hotspot was added, removed, moved (its `shape` differs) or edited (any other key — `label`, `actions`, `visible_if`…, named in the report), any other field differs (`music`, `overlays`, `on_enter`… listed leaf by leaf, up to 40), its picture is a different file, **or the picture file under the same name has different contents** (a repaint) — and the same for a view's close-up picture (`close-up picture repainted: desk`) |
| unchanged | none of the above — it is counted but not drawn |

For each room that differs the page shows the picture and the hotspots on it: **before** (what is about to go in red), **after** (what is new in green), and **changes** on the new picture (gone: red, dashed; new: green; moved: amber, dashed where it was and solid
where it is, with an arrow; edited: blue), plus the changes in words. Pictures of the rooms that differ are copied next to the page (`before/<room>.<ext>`, `after/<room>.<ext>`) so it can be sent as a folder. A panorama is drawn as its flat sheet, hotspots included.
The tool prints a summary between `===MF_SCENEDIFF_BEGIN===` and `===MF_SCENEDIFF_END===` (counts, and per room its status and the changes in words), which the MCP returns.

Not shown: door links (`links.json`) and region settings, which only become hotspots when the game loads, and changes to anything but rooms (dialogue, items, puzzles — `git diff` reads those well).

## Room templates & bulk edits

For a game with many alike rooms — a hotel's floors, a street of shopfronts — an AI agent (or a script) can stamp rooms out of a **template** and change many rooms in one go. This is authoring only: the engine,
the validator and the Studio never read it, templates are kept out of exports and out of the asset scan, and what comes out are **ordinary scenes** (nothing in a game refers to a template, so there is nothing to keep in step).
The MCP tools do it (`list_templates`, `upsert_template`, `template_from_scene`, `delete_template`, `create_scenes_from_template`, `duplicate_scene`, `bulk_update_scenes`); the logic is `mcp/src/templates.ts`.
The Studio does it too — **Scenes → Templates & bulk edit** — with the same operations in GDScript (`core/room_tools.gd`), and `make templates-parity` (in `make check`) runs both on one set of cases (`mcp/test/templates_cases.json`) and fails if they ever disagree.
In the Studio a template is made from the open room (a box of `parameter = text as it is in this room` lines), rooms are made from one-per-line `id | parameter = value, …` entries, and a bulk edit is chosen by room ids / an id pattern / a group / a place / a hotspot, written as `field = value`, `hotspot: field = value` and `old => new` lines, previewed line by line, and applied as **one undo step** (the MCP's `apply` flag is the Studio's Apply button).

A **template** is `game/templates/<id>.json` (not game format — the example is `json5` so the Studio parity guard, which reads the `jsonc` blocks that *are* format, leaves it alone):

```json5
{
  "id": "hotel_room",
  "name": "A hotel room",                         // optional
  "params": { "number": null, "style": "plain" }, // each parameter's default; null = every room must give a value
  "scene": {                                      // a full scene document; any string may hold {{name}} placeholders
    "id": "hotel_{{number}}", "name": "Room {{number}}",
    "background": "game/assets/backgrounds/{{style}}.png",
    "hotspots": [ { "id": "door", "label": "Corridor", "shape": { "type": "rect", "rect": [0.8, 0.2, 0.15, 0.6] },
                    "actions": [ { "action": "goto_scene", "scene": "corridor" } ] } ]
  }
}
```

- `create_scenes_from_template` takes `rooms: [{id?, params?}]` — a room's parameters are the defaults with its own on top. A string that is *only* a placeholder takes the value's own type (`"{{zoom}}"` with `2.5` is the number 2.5); inside longer text it is
  written as text (a list as JSON). The new scene's id is the room's `id`, else the filled scene `id` (`hotel_204`). A parameter with no value, a scene that already exists (without `overwrite`) and two rooms with one id are refused, naming the room. `dry_run` writes nothing.
- `template_from_scene` goes the other way: `params` maps each parameter to the text it stands for in a room that already works (`{"number": "101", "name": "Room 101"}`); every occurrence in any string becomes a placeholder, longest text first, and the texts become the defaults.
- `duplicate_scene` copies a room, swapping text (`replace`) in everything but its id; door links (`links.json`) belong to rooms by id and are not copied.
- `bulk_update_scenes` selects scenes by `ids`, `group`, `region`, a glob over ids (`match: "hotel_*"`) and/or `has_hotspot` — all that are given must hold, and giving none is refused — then applies `set` (scene fields; `null` removes one; the id never changes), `hotspots`
  (`[{id, set?, remove?}]` by hotspot id wherever a scene has it), `add_hotspots` (only to scenes with none of that id) and `replace` (text, id excepted). **Nothing is written unless `apply` is true**: without it the answer is the plan, scene by scene, one line per change; scenes where nothing
  would change are counted, not listed, so applying twice changes nothing the second time.

## Playtest telemetry

How a producer finds out where testers get stuck, with nothing sent anywhere. A playtest build — the game run with `--mf-telemetry[=<file>]`, with the
`MF_TELEMETRY` environment variable (a file, or `1`), or exported from a preset carrying the custom feature `mfplaytest` — writes one JSON line per event to a local
file (default: `playtest.jsonl` in the player's save folder). The title screen says so while it records ("what you do is written to … Nothing is sent anywhere"). The
tester hands the file over; the producer drops the files in `game/playtests/` (kept out of exports) or any folder.

```json
{"s":"b322e845","t":12.5,"e":"puzzle_solved","id":"tide_pump","secs":8.2,"fails":1,"skipped":false}
```

`s` is a random session id, `t` the seconds since the session began, `e` the event; the rest are ids from the game itself — nothing personal. Events:
`session_start` (game, version, difficulty, scene, loaded), `scene`, `dialogue`, `puzzle_open`, `puzzle_fail`, `puzzle_solved` (secs, fails, skipped — true when the skip
button was used), `puzzle_abandon` (secs, fails), `hint` (id, level reached), `item`, `clue`, `objective` (finished), `ending` (result), `perf` (scene, fps, worst_ms, vram_mb, mem_mb, draw_calls — the
frames of the last five seconds, not written by a headless run) and `session_end` (reason: menu, quit, new_session).

**Profiling HUD.** **F3**, on any screen of any build, shows frame rate, the worst frame of the last half second, texture and static memory, draw calls and the room — for a tester
asked "what does it say?" and for whoever is tuning a room. A second line says what is playing — the score's track with its stems' levels or the music file, the ambience, whether a voice line is speaking — how far the music is ducked, and each bus's level in dB (the audio debug view). Hidden by default; it never takes a click. The static budgets (`make budget`) say what a room *should* cost; the HUD and the
`perf` events say what it did, and the report's **Performance** table lists the slowest rooms first and flags one that averaged under 30 fps or dipped under 20.

`make playtest-report [NOTES=<file or folder>]` (the MCP `playtest_report`, `tools/playtest.gd`) turns any number of sessions into a report: sessions won / lost / unfinished,
typical and longest play time, every puzzle (testers, solved by, walked away, skipped, fails each, average solving time — a skip is not a solve), every room (visits, testers,
time per tester), the hints asked for, where the unfinished sessions stopped, and **where to look first** — a ranked list with the reason in plain words (a puzzle a third of its
testers walked away from, one that needed the skip button, one failed five times each or taking three minutes, a room testers lingered in, a hint most of them needed, a room
where several stopped). `make playtest` proves it end to end: the autoplay bot plays the bundled game recording notes, and the report must agree with what it did.

## Saves & players

Player-level, not game data: nothing here is in the game's files and the Studio has nothing to edit.

- **Slots.** Eight slots plus an autosave (on every scene change), in `user://mysteryforge/<game id>/`. Each save records the scene, the time, the play time, the
  difficulty and what the player was working on (the first objective not yet done), and — in a windowed run — a picture of the room (`slot_N.png`, 320×180, taken
  when the pause menu steps aside). The Save and Load screens show them. Saving over a full slot and deleting a save each ask twice; a save made without a picture
  never keeps the previous one's. A headless run draws nothing, so its saves have no picture.
- **Nothing the player owns can be lost** (`core/safe_io.gd`). Slots, the autosave, the checkpoint, the achievements-and-endings profile, the settings and the players list are written to
  `<file>.tmp`, read back and compared, and only then swapped in by a rename — so a crash, a full disk or a pulled plug leaves the old file whole; the version it replaces is kept as `<file>.bak`.
  A file that exists but cannot be read is never shown as an empty slot: a damaged save with a backup opens from the backup and says so ("the previous version of it was opened instead"); one with no
  backup is shown as *could not be read* (it cannot be loaded; it can be saved over or deleted); a damaged `settings.json` is set aside as `settings.json.corrupt-<time>` (the newest three are kept for
  support) and the defaults are used, with a notice. A save written by a **newer version of the game** (`game_version`) or in a newer layout (`save_format`) is refused with a message that names both versions, rather than half-loaded —
  migrations only go forward. A save that cannot be written says so and leaves the slot as it was. **Continue** opens the newest save it *can* open and, if it can open none, says why.
- **Players.** The title screen's **Players** button lists everyone who plays this game on this computer, each with their own saves, checkpoint and achievements:
  pick one to hand the computer over, add one by name (up to 12, names up to 24 characters), or remove one (asked twice; it throws their saves away). The first
  player ("Player 1") is the folder saves have always lived in, so no existing save moves; the others are `profiles/<id>/` beneath it. The title screen says who is
  playing once there is more than one. Who played last is remembered in `profiles.json` and a new game starts with them. `MF.save_dir()` is always the current
  player's folder — never build a save path by hand.

## Cloud sync hooks

The engine never talks to a cloud. A platform adapter (an object in `MF.platform_adapters`; Steam's activates by itself) is the bridge, and the engine gives it three things (`core/cloud.gd`):

- **To be told.** Each time a save slot, the autosave, the checkpoint or the achievements profile reaches the disk the engine calls `file_written(kind, rel)` on every adapter that has that method
  (`kind` is `slot` | `autosave` | `checkpoint` | `achievements`; `rel` is relative to the game's save folder, e.g. `slot_3.json` or `profiles/ann/autosave.json`), and emits `MF.player_file_written(kind, rel)`.
  A failed write calls nothing.
- **To know what to carry.** `MF.cloud_info()` returns `{root, files}`: the real folder on this computer (what a store's auto-cloud setting must point at) and `[{path, size, modified}]` for the files the cloud
  should carry — saves, autosave, checkpoint, achievements and the players list. Never the device's own settings, the slot pictures (they are made again), the `.bak` / `.tmp` / `.corrupt-*` files or support bundles.
- **To hand a file back.** `MF.cloud_apply(rel, text)` takes a file the cloud has and returns `{action, why}` — `take` (theirs was newer and replaced ours, through SafeIO so ours is kept as `.bak`), `keep` (ours is the same or
  newer), `merge` (achievements and endings: the union, the earlier time kept — an earned achievement is never lost to a sync), `tie` (saved at the same moment with the same play time but different content: ours stays,
  nothing is overwritten) or `refuse` (a half-downloaded file, a save from a newer game or engine, or a path outside the folder). Newer means a later `saved_at`; with the same `saved_at` more `playtime` wins.

A store's folder-based cloud (Steam Auto-Cloud) needs none of this beyond `cloud_info().root`; an API-based one uses all three. It has not been exercised against a live store yet (docs/HUMAN_TASKS.md).

## Runtime behaviors authors can rely on

- **State**: variables, inventory, visited scenes, solved puzzles, used `once` choices,
  and journal entries are all persisted in saves (8 slots + autosave on scene change; see "Saves & players").
- **Missing voice files** degrade gracefully: the subtitle waits for a click instead.
  Ship text first, record audio later — the classic production pipeline.
- **Hot reload**: in a debug run, F5 reloads all game JSON and re-renders the current
  scene. An agent can edit JSON while a designer has the game open.
- **CLI**: `godot --path <project> -- --mf-record=<file>` records the playthrough as a walkthrough (see
  "Walkthroughs"). `godot --path <project> -- --mf-scene=<id>` boots a fresh game directly
  into a scene (skipping the menu) — used by the MCP `run_preview` tool for fast
  iteration. `--mf-strict` makes validation errors fatal at boot. A screenshot run is silent (the master bus is muted), and `--mf-mute` silences any windowed run. A run that jumps in (`--mf-scene`, `--mf-dialogue`, `--mf-set`, `--mf-screenshot`, `--mf-puzzle`, `--mf-give`) — and every tool that plays the game (walkthroughs, the autoplay and fuzz bots, the layout lint, text play) — saves into a scratch folder of its own, emptied at the start of the run (`MF.use_scratch_saves`), never into a player's saves, checkpoint, achievements or settings. With `--mf-scene` and `--mf-screenshot=<png>` (the MCP `screenshot_scene` tool) the picture can be taken of a *state*:
  `--mf-container=<id>` opens that container, `--mf-verb=<id>` arms that verb, `--mf-give=<item,item>` holds those items, `--mf-set=<var>=<value>` starts with a variable set, `--mf-asked=<dialogue>|<choice text>` shows that choice as already asked, and `--mf-hotspots` outlines every hotspot.
- **Keyboard & gamepad play** (always on, no setup): `Tab` / `Shift+Tab` step through the clickable hotspots
  in reading order; the arrow keys (or D-pad / left stick) jump to the nearest hotspot in that direction;
  `Enter` (gamepad **A**) activates the focused hotspot exactly like a click, and its label is shown; `Space`
  (gamepad **X**) outlines every clickable hotspot for a moment; `1`–`9` hold an inventory item (gamepad
  shoulders cycle hotspots, **B** puts the item down). Moving the mouse returns control to the pointer.
- **Accessibility settings** (Settings panel, saved per player in `user://mysteryforge/settings.json`,
  never part of the game data): **Text size** — Normal / Large (125%) / Extra large (150%) scales every
  piece of UI text, repeatably (each control remembers its original size) and including text created later;
  **High-contrast highlights** — a thicker, black-edged outline on the keyboard-focused hotspot and the
  `Space` reveal; **Controls** — the panel hotkeys (journal `J`, tasks `T`, map `M`, hint `H`, phone `P`,
  inbox `E`, suspects `S`, conversation log `L`) can be rebound (click one, press the new key; a key already in use is refused, `Esc`
  cancels, *Reset keys* restores the defaults) and the top-bar hints follow. On touch screens a long press
  (about 0.6 s) puts a held item down, the equivalent of right-click. **Colour filter** — Protanopia /
  Deuteranopia / Tritanopia "daltonization" over the whole screen (colours only; nothing moves).
  **Reduce motion** — scene changes are instant (no fades, dissolves or transition clips) and animated
  overlays hold their first frame. **Read text aloud** — narration, dialogue lines (unless they have recorded
  voice), the focused hotspot, the room you enter and the focused menu item are spoken with the system
  text-to-speech voice. On a first run, High-contrast and Reduce motion follow the operating system's
  preferences.
- **Screen readers** (Godot's AccessKit support — VoiceOver, NVDA, Orca): hotspots, inventory items and the
  compass carry accessible names, and everything the game announces (the lines above) is also written to a
  live region the screen reader speaks. When a screen reader is active, the built-in text-to-speech stays quiet.
- **Gamepad everywhere**: when a menu or panel opens from the keyboard or a gamepad, focus lands on its first
  control (D-pad / stick / Tab move, **A** / Enter press). **B** or `Esc` closes the open panel; **Start** opens
  the pause menu (or closes what's open); **Back** opens the journal; **Y** holds the next inventory item;
  the **shoulder buttons** flip between open panels (Journal → Tasks → Map → Hint → Phone → Inbox → Suspects).
- **Subtitles are always on** in v1; voice is an enhancement, never required.

## Localization

Display text is authored inline (the "base" language). Translations live in
`game/locales/<code>.json` — a flat map from the **source string** to its
translation (gettext-style), e.g. `game/locales/es.json`:

```json
{
  "Library": "Biblioteca",
  "The Case of the Cellar Key": "El Caso de la Llave del Sótano"
}
```

At runtime every player-visible string passes through `MF.t()`, which returns the
translation for the current language or the original if absent — so a partial
translation is fine. The player picks a language on **Settings → Language** (the title and pause menus open Settings on one of its
three pages — **Game Settings**, **Controls**, **Language** — with tabs between them); the choice persists, and a first start picks the
operating system's language when the game has it. The page has two lists, each language named in its own tongue (`core/languages.gd`;
the authored text is listed as English): **Text and subtitles** (the authored text plus each `game/locales/<code>.json`) and **Spoken
language** (the authored voices plus each text language that has a voice pack, `game/assets/voice/<code>/`; saved as `voice_language`,
`"auto"` by default = the text's language when it has a pack, else the authored voices). Switching the text language changes what is
already on screen at once: each shown text is traced back to its source through the old language's map and translated again.

A locale may set a reserved `"@@rtl": true` entry (any `@@`-prefixed key is meta,
never a translatable string) to mark a right-to-left script (Arabic, Hebrew, …);
`MF.is_rtl()` then mirrors the in-game HUD, menus, and dialogue while the scene
world stays put. The Studio's **Languages** panel toggles this with a checkbox.

Generate a starter `game/locales/template.json` of every translatable string
with `godot --headless --path <project> -s res://tools/extract_strings.gd`
(or `make extract-strings`), or edit translations visually in the Studio's
**Languages** panel. Translatable fields: project `title`/`credits`, item
`name`/`description`, character `name`, scene hotspot `label`/`wrong_item_text`,
dialogue node `text` and choice `text`, puzzle `name`, and the text of
`show_text`/`play_voice`/`actor_say`/`add_journal`/`add_objective`/`add_email`/`add_dossier`/`end_game` actions, `start_timer` `label` (and its steps), contact `name`,
character `bio`, item `combine`
`text`, hint level `text`, and difficulty level `name`/`description`, achievement `name`/`description`, the project `author`, and the
steps of the accusation's outcomes. Inside a puzzle, the parts a type marks as text are offered — for example a seating plan's
clues and their reasons, a machine's dial names, its positions in words (not numerals) and its lever labels, and a pick's area names —
while the rules, layouts and answers are still read in the author's words. The engine's own menus, panels, hints and notices ("Close", "Case board", "%d moves") are offered too
(`core/ui_strings.gd`; a test fails when the UI source sends a text through `MF.t()` that the list lacks).

### Pseudo-localisation and the UI lint

`godot --path <project> -- --mf-pseudo` turns every `MF.t()` text into an accented, 40% longer, bracketed look-alike — `‹Ĵôûŕñàļ ····›` — with
`%d`/`%s` placeholders and `[bbcode]` tags left alone. Text that stays plain was never sent through `MF.t()`, so no translator can reach it; text
that no longer fits shows what German or French will do to it. `make lint-ui` (`tools/walkthrough.gd -- --lint[=<text scale>]`, MCP `lint_ui`)
does the looking for you: it runs the real UI pseudo-localised at 150% text, visits every room, panel, dialogue line and set of choices,
puzzle (the game's, plus every built-in type on its starter settings) and close-up, and reports **offscreen** (text past the edge of the screen or
out of its scrolling area), **cutoff** (a fixed-size box too small for its text), **split** (a wrapping box narrower than one of its words, so the word breaks in the middle) and **untranslated** (visible text that did not go through `MF.t()`;
one or two characters, language pickers and controls marked `mf_data` — puzzle data such as a coded message — are exempt). It fails on any
finding, and `make check` and the sample checks run it.

## Voice-over

Every spoken line — dialogue node, item description, hint level, `show_text` / `actor_say` step — can carry a `voice` path. Production
tooling (the MCP server's tools, usable from any assistant; `tools/voices.gd` lists the lines) turns a game of thousands of lines into
recording sessions:

- **Line ids.** A line's id is where its recording goes by convention, minus the folder and extension: `finch_intro/n3` (a dialogue
  node), `items/rusty_key`, `hints/cellar_1`, `<scene>/<hotspot>_2` (narration). It is stable as long as the line stays where it is.
- **Recording scripts** — `export_vo_script`: one CSV per speaker, `game/vo/<speaker>.csv` (`game/vo/<language>/<speaker>.csv` for a
  language pack): `id, speaker, kind, where, text, emotion, file, status, seconds, notes`. The node's `emotion` is the actor's direction.
  `only: unrecorded | missing | stale` makes pick-up and re-record sessions.
- **Takes** — `import_vo_takes`: audio files named after the line id (`finch_intro/n3.wav`, or `finch_intro__n3.wav`; `_t2` / `-take3`
  marks a later take) are matched to lines, the highest take (then the newest file) is copied to `game/assets/voice/<id>.<ext>`, the
  line's `voice` is pointed at it, it stops being a placeholder, and the text it was recorded from is logged. `convert` compresses
  WAV/MP3 takes to OGG; `dry_run` shows the plan; files that match no line are listed.
- **Coverage and pick-ups** — `vo_status`: per speaker, lines recorded / placeholder / missing / **stale**, the minutes of recorded audio
  (WAV is measured), and the pick-up list. A line whose text was edited after it was recorded is *stale*: `game/vo/log.json` keeps a hash
  of the text each recording was made from.
- **Language packs.** A recording in `game/assets/voice/<language>/<same path as the line's voice, any audio format>` plays instead of
  the authored one when the player's language is `<language>` (and the authored recording plays when the pack has none), so a French
  voice cast is a folder of files — no change to the game's data. `import_vo_takes language: "fr"` and `vo_status language: "fr"` work
  on a pack; the line's own `voice` is left alone.
- Placeholders from `generate_missing_voices` are logged too, so `vo_status` tells how much is still synthesized.

## Voice casting

Between the placeholder voices (macOS `say` / espeak) and recorded actors sits an AI read: `game/vo/casting.json` gives each speaker a
voice and a direction for a speech model, and the tools record every line that has no real recording yet. **Authoring-only** — nothing in
the game reads the casting (export presets drop it), and what it makes are ordinary voice files at the lines' usual paths, so replacing
them with actors later changes nothing else.

```json5
{
  "provider": "openai",                       // the only provider so far; the key is OPENAI_API_KEY in the environment, never in a file
  "model": "gpt-4o-mini-tts",                 // any speech model the provider's /v1/audio/speech takes; gpt-4o-mini-tts reads the directions
  "style": "A small-town mystery of 1930, acted like a good radio drama.",   // said before every line's own direction
  "voices": {                                 // speaker id → a voice and how to read
    "narrator": { "voice": "marin", "instructions": "Nora's own narration: close, conversational, lively." },
    "walter":   { "voice": "cedar", "instructions": "Warm and dry, gently teasing." }
  },
  "default": { "voice": "alloy" },            // for a speaker not named (else every speaker must be cast)
  "usd_per_minute": 0.015,                    // the price the estimate uses (check the provider's own page)
  "chars_per_second": 14,                     // how fast speech goes, for the estimate
  "loudness": -20                             // each take is levelled to this (LUFS, true peak under -1 dBFS) before it is encoded
}
```

Voices: alloy, ash, coral, echo, fable, nova, onyx, sage, shimmer, ballad, verse, marin, cedar. A line's `emotion` is added to its direction.

- **Estimate first, free.** `make voices-estimate GAME=<folder>` / MCP `estimate_voices` checks the casting and prices every line without
  a real recording: lines, characters, minutes, dollars, per speaker. No call is made.
- **Record under a cap.** `make voices-record GAME=<folder> MAX_USD=<dollars>` / MCP `record_voices` (`apply: true`, `max_usd`) records
  until the next line would cross the cap. `SPEAKERS=` / `LINES=` / `LIMIT=` record a sample first, and `AUDITION=<folder>` (MCP `output_path`) makes it an audition: the takes go to that folder and the game is not touched. Each take is saved as it is made (a stopped run loses nothing), mono Ogg through libvorbis when `MF_WAV2OGG` or `oggenc` is there, and logged in `game/vo/log.json`
  with a key of its text, model, voice and direction: a second run skips what is done (an interrupted or capped run resumes, never pays twice),
  and changing a speaker's direction records only that speaker again. A line marked `final` (a real recording) is never replaced.
- An AI take stays a **placeholder** in the asset list, so the release gate's `voice` row still counts it as synthesized until actors replace it.
  After recording: `make lipsync GAME=<folder>` (mouth tracks) and the loudness normaliser.
- Tests use the local mock (`scripts/mock_art_server.mjs`, `MF_OPENAI_BASE_URL`) — `make voicecast-test`, in `make check`.

## Production report

`make production` (`tools/production.gd`; the Studio's **Production** tab; MCP `production_report`) answers a producer's question — *how
finished is this game, and where is the work?* — for every room:

| part | what is counted | weight |
|---|---|---|
| pictures | the room's pictures that are final (not listed as `placeholder` in `game/assets/manifest.json`, and present on disk) | 35% |
| voice | the room's spoken lines that are *recorded*: a dialogue's lines belong to the room that starts it, a `show_text` step to its scene; item and hint lines are counted globally. *Synthesized* (placeholder), *missing* and *stale* lines (text edited since the recording was logged) are outstanding | 35% |
| clean | no validation errors in the room's file, and every puzzle it starts provably winnable | 20% |
| memory | the room is within its budget (see "Budgets") | 10% |

The report lists rooms least finished first, an average per place, the game's totals (pictures, lines recorded / synthesized / to pick up,
errors and warnings) and, per language file in `game/locales/`, how many of the game's translatable strings it translates.

## Loudness

`node mcp/dist/cli.js loudness <game>` (`make loudness`, in `make check`; MCP `check_loudness`) measures every audio file under
`game/assets` with ITU-R BS.1770-4 — integrated loudness in LUFS (K-weighted, 400 ms blocks, gated) and the sample peak — and groups
them by kind (the folder: `voice`, `music`, `sfx`, `ambient`…). WAV is decoded directly, OGG/MP3 through ffmpeg when installed. A peak at
full scale (clipping) or near silence is an **error**; a file more than `--tolerance` LU (default 6) from its kind's median is a
**warning** — a voice line recorded hot, a music bed far louder than the rest.

**Normalising.** `node mcp/dist/cli.js normalize <game> [--apply] [--revert]` (`make loudness-normalize`, `APPLY=1` / `REVERT=1`; MCP `normalize_loudness`) brings each WAV to a target per kind —
voice −20, music −24, ambient −26, sfx −20 LUFS (override with `--voice`, `--music`, `--ambient`, `--sfx`) — with the gain that moves its integrated loudness there, never more than ±12 dB and never so much
that the peak passes −1 dBFS (a file that cannot reach its target without clipping stops short and is flagged `limited`). Kinds with no target are left alone; OGG/MP3 are never rewritten (normalise the
source recording and import again). It is a **dry run** unless asked to apply; when it rewrites a file it first keeps the original under `game/art/loudness_originals/` (authoring-only: never shipped),
and `--revert` puts them back. Samples are scaled in place at their own bit depth, so nothing else about the file changes. `make loudness-test` (in `make check`) proves it on generated WAVs.

## Asset pipeline

Assets live under `game/assets/<kind>/` (`backgrounds`, `panoramas`, `items`, `portraits`, `actors`, `voice`, `sfx`, `music`,
`video`; any other folder is allowed). A project starts on SVG stand-ins and moves to real art/audio without
touching the game data:

- **Formats.** Images: SVG, PNG, JPG, WebP (BMP). Audio: WAV, OGG, MP3 (prefer OGG — about a tenth the size of WAV).
  Video: `.webm`/`.mkv` (VP9, via the video extension) or `.ogv` (Theora) — see "Video". A reference is the project-relative path (`game/assets/backgrounds/library.png`), so a swap that
  changes the extension rewrites the references (below).
- **Placeholders** are tracked in an optional `game/assets/manifest.json`. Art and voices the Studio's *Generate*
  makes, `write_asset_text` and `generate_voice` write are stand-ins and are listed there; importing or replacing an
  asset marks it final. An asset not listed is final.

```jsonc
{
  "assets": {
    "game/assets/backgrounds/library.svg": { "status": "placeholder", "note": "needs a painted version" },
    "game/assets/voice/hartley/hello.wav": { "status": "placeholder" }   // "final" entries are only kept for a note
  }
}
```

  The engine ignores the manifest (it never ships a decision about art); the validator checks it (unknown status =
  error; an entry for a missing file = warning).
- **Audit** (`make assets`, `tools/assets.gd`, the MCP `check_assets` tool, the Studio's Assets panel): every file's
  size and format, image dimensions, whether anything uses it, its status, and production problems — a background
  that isn't the game's aspect (it would be cropped to fill the screen) or is narrower than ~90% of it (soft); a
  full-circle panorama that isn't 2:1; an uncompressed WAV over ~1.5 MB (convert to OGG); an SVG with `<text>`
  (Godot can't draw it); oversized icons/portraits/backgrounds.
- **Replacing** (Studio *Replace…*, MCP `replace_asset`): the new file goes where the old one is. The same extension
  overwrites in place; a new extension of the same kind (PNG for SVG, OGG for WAV) is saved beside it, every
  reference in the game is rewritten, the old file is removed, and the asset becomes final. *→ OGG* (Studio) and
  `convert_audio` (MCP) do the WAV→OGG step with `ffmpeg` (or `oggenc`) when installed.
- **Batch voices.** Every spoken line — dialogue nodes, item descriptions, hint levels, `show_text` steps — can have a
  `voice` file. The Studio's *Voices* card and MCP `generate_missing_voices` record a placeholder for each line without
  one (macOS `say` / espeak-ng; a stable voice per speaker), at `game/assets/voice/<dialogue>/<node>.wav`,
  `voice/items/<id>.wav`, `voice/hints/<hint>_<n>.wav` and `voice/<scene>/<thing>_<n>.wav`, set the line's `voice`, and
  list them as placeholders. `list_voice_lines` / `tools/voices.gd` report what is recorded. Recordings from a studio
  replace them at the same paths.

## Video

Video appears in four places: a scene's `video` (a looping clip over the still background), a character's `portrait_video`
(a looping talking-head clip), the `play_video` step (a fullscreen cutscene) and a scene's `transition` (a clip that
bridges the swap). Every one takes the project-relative path of a clip under `game/assets/video/`.

| Format | Plays | Notes |
|--------|-------|-------|
| **Ogg Theora** `.ogv` | always — Godot's own decoder | old and large; no transparency; **imported** by Godot (run `make import` after adding one) |
| **WebM / Matroska** `.webm`, `.mkv` | with the **`mf_video` extension** (`addons/mf_video/`) | VP9 video (optionally **with an alpha channel**) and Opus or Vorbis audio; smaller and sharper than Theora; used straight from the file, nothing to import |

**The extension.** `addons/mf_video/` is built from `extensions/mf_video` (a minimal LGPL FFmpeg with only royalty-free
decoders — see that folder's README) and copied into a game like the rest of the engine: the scaffold includes it and
`upgrade_engine` / *Upgrade engine* keeps it current. It carries one library per platform (macOS, Windows, Linux); an upgrade
only ever **adds to or updates** a game's own `addons/mf_video/bin/`, never deletes from it. **Without it a `.webm` is
simply skipped**: the engine logs one warning per clip and shows the still picture, the cutscene is a no-op, and a clip used as
a transition falls back to the fade — the game never breaks. Web builds can't load the extension, so WebM clips fall back the
same way (the Web export preset leaves it out); use Theora for Web.

**Behaviour.** Looping clips loop; a talking-head clip is stretched into the portrait frame, a scene video and a cutscene
into the screen (so a clip should be the game's shape: 16:9 for 1920×1080). A WebM with an alpha plane draws with real
transparency (a character walking in front of the room). The picture and sound are locked together by a single clock;
seeking jumps to the nearest earlier keyframe.

**Making a clip.** Any video becomes a WebM with ffmpeg. The Studio does it when you import an `.mp4`/`.mov`/`.avi`/… (it
asks what the clip is) and in *Assets → Video → → WebM* for an `.ogv`; the MCP `convert_video` tool does the same as a
background job. The three presets (identical in Studio and MCP; `make video-parity` checks) are:

| Preset | For | ffmpeg (besides `-vf scale=-2:'min(1080,ih)'`, `-deadline good -cpu-used 2 -row-mt 1`) |
|--------|-----|-------|
| `cutscene` | an intro, a cutscene, a transition | VP9 `-crf 32 -b:v 6M -maxrate 8M`, keyframe every 150 frames, Opus 96 k |
| `loop` | a silent looping background (rain, fire, water) | VP9 `-crf 35 -b:v 4M -maxrate 6M`, keyframe every 90, `-an` |
| `actor` | a character or effect on transparency | VP9 `yuva420p` (keeps the source's alpha), `-auto-alt-ref 0`, Opus 96 k |

A keyframe every ~5 s keeps seeking and skipping quick; 2–8 Mbps looks the same as more at 1080p.

**Checks.** The validator warns when a video file is missing, isn't a kind the engine plays, or is a `.webm`/`.mkv` in a game
that doesn't carry the extension. The asset audit (`check_assets`, the Assets panel) reads each clip's size, frame rate,
duration, bitrate, alpha and keyframe spacing through the extension and flags: a shape that isn't the game's (it will look
squashed — transparent clips and portrait clips are exempt), a clip much smaller than the screen (soft), keyframes more than
10 s apart (slow seeking), more than 60 fps, an extreme bitrate, a huge file, and an Ogg Theora clip (WebM is smaller and can
be transparent). Without the extension it can only report sizes.

**Shipping.** Godot packs `.webm` files and the extension's `.gdextension` like any other resource, and copies the matching
platform library next to (or into) the built game; the desktop export presets also include `addons/mf_video/*.txt` so the notice
and licence travel with it (they skip `*.md`). **FFmpeg is LGPL 2.1+**: credit it in the game (Studio → Publish → Video adds
the line) and keep `addons/mf_video/NOTICE.txt` and the licence text. Sign macOS/Windows builds as usual; the library is inside
the app. Existing games' `export_presets.cfg` aren't rewritten by an upgrade: add `addons/mf_video/*.txt` to a preset's
*include filter* (and `addons/mf_video/*` to the Web preset's exclude filter) by hand, or copy the new ones.

## Art workbook — game/art/

The real-art pipeline's working files: the look every picture must share, the list of pictures to make, and where
each finished one came from. They are authoring-time only — never read by the engine, and the export presets drop
`game/art/*`. The work goes through `tools/art.gd`, the Studio's *Art* panel and the MCP `art_*` tools; all
three share one implementation (`addons/mystery_forge_studio/core/art/`). API keys are read **only** from the
environment (`OPENAI_API_KEY`, `BLOCKADE_API_KEY`) and are never written to any game file or log.

```
game/art/
  bible.json          the style bible
  shots.json          the shot list
  provenance.json     what made each accepted picture
  .cache/<key>/       generated candidates, content-addressed (gitignored)
```

**`bible.json`** — everything is optional; a project without one gets the defaults shown.

```jsonc
{
  "style": "Painterly gouache, moody lamplight, 1930s English country house",   // prepended to every prompt
  "negative": "text, captions, watermarks, modern objects",                        // appended as "Avoid: …"
  "camera": "eye-level point-and-click adventure view",                           // rooms only
  "lighting": "warm tungsten lamps against cool window light",                    // rooms only
  "palette": ["#1f3b4d", "#d9a441"],
  "providers": { "flat": "openai", "panorama": "skybox", "edit": "openai" },       // or "mock" (offline stand-in)
  "models": {
    "openai": { "generate": "gpt-image-2.5-flare", "edit": "gpt-image-2.5-sunburst", "quality": "high" },
    "skybox": { "style_id": 0 }
  },
  "seam_repair": true,                                                            // cross-fade a panorama's wrap-around seam
  "delivery": { "background": "webp", "panorama": "webp", "lossy_quality": 0.9 },   // file type per kind (png default; webp/jpg keep a game small)
  "pricing": { "openai": { "per_image": 0.19, "output_per_million": 30, "text_input_per_million": 5, "image_input_per_million": 8 } },   // USD; estimates + the real cost of each call
  "characters": [
    { "id": "nora", "description": "A stout woman in her sixties, lace collar", "references": ["game/assets/portraits/nora_ref.png"] }
  ]
}
```

**`shots.json`** — one entry per picture to make. Planning (`tools/art.gd plan`, the Studio's *Plan shots*) adds a
shot for every scene background / panorama, item icon and character portrait that is missing or still a placeholder. A room's first-draft prompt says where its always-present hotspots are — each with what it is for (a way through, someone to talk to, something to
pick up…) and roughly where it sits, left to right (in a panorama, how many degrees round from straight ahead), and for a flat room the parts of the screen the interface covers — so the painted room puts the door where the door is and keeps its corners quiet.
Hotspots that only appear later, the Back button and shapeless hotspots are left out; the prompt is a draft the producer edits, and shots already planned keep their prompts.
Planning also adds a shot for every view whose own picture (`image`, see "Views & close-ups") is missing or still a placeholder: kind `image` at the view's path, sized to the part of the room it covers times the zoom (at most 3840 on a side, multiples of 16),
its prompt describing that view's hotspots, and — once the room itself has a painted raster picture — that picture as a reference, so the close-up matches the room's style and light.
For a character whose portrait is a real picture but who has no `talk_frames`, planning adds two `expression` shots with a `mouth` (`open`, `wide`) that take the portrait as their reference — the same face with the mouth open — and accepting one writes
it into the character's `talk_frames` at its place, so the portrait lip-flaps in dialogue.

**Actor poses.** An actor (see "Actors") needs full-length pictures, which the pipeline paints as `pose` shots (`core/art/art_poses.gd`): `kind: "pose"` with a `character` and a `pose` name (`idle`, `blink`, `wave`, … — it becomes `actor.poses.<name>`), asked for tall (`1024x1536`) on a
transparent background and delivered 768 px tall **without trimming**, so every pose of one figure keeps one frame and the feet stay where `actor.feet` says. Planning adds an `idle` shot for each character who is an actor in some scene (or has an `actor` block) whose standing picture is
missing or a placeholder — taking the portrait as its reference when that is a real picture, so it is the same person — and, once the idle is a real picture, a `blink` shot taking *the idle* as its reference (the same figure, eyes closed); any other pose is added by hand the same way. Accepting one writes
`actor.poses.<name>: {image}` (making the `actor` block if there is none; a `blink` with no `actor.life` also sets `life: {blink: "blink"}` — the picture does nothing otherwise), in the CLI and the Studio alike. Preflight refuses a pose with no character or name, and any pose but the idle with no finished idle as a reference.
Walk cycles, gestures and mouth shapes for a full-length figure are authored the same way (a hand-made `pose` shot) but not planned: image models do not draw a consistent sheet reliably.

**Preflight.** Before a shot is run (and in `estimate`, `art_estimate` and the Studio's cost line) it is checked offline for what would make it fail, so nothing is paid for a doomed request: a missing prompt or target, a `size` OpenAI will refuse (not `WxH` in multiples of 16 within 256–3840),
and for a `variant` a base that is missing or only a placeholder SVG, a `mask` that is not a rectangle inside the picture (a warning for a patch under 1% of the picture, over 60%, or under 64 px at the edit size), and an `overlay` with no scene; for a `mouth` shot a missing portrait reference.
`run_shot` refuses a shot with an error (`skip_preflight` overrides); warnings are only reported.

**Hotspot calibration.** Hotspots are placed against the picture a room was *planned* with; once the real picture exists they may sit beside what they name. `tools/art.gd calibrate --scene=ID | --all [--provider=openai|mock] [--min-iou=0.5] [--apply]`
(the Studio's Scenes → *Check hotspots against the picture…*, the MCP `art_calibrate`; `core/art/art_calibrate.gd` is the pure comparison, `art_runner.calibrate` does the call) shows a vision model the room's picture (a panorama image, else
the background; downscaled to at most 1024 px on its longest side; a placeholder SVG is skipped with a reason) and asks, for each **labelled** hotspot (not a `ui` back button), for its object's box as `[x, y, w, h]` fractions of the picture, or null if it is not
visible. The question names each object by id and label and says *roughly* where it is in words ("upper left", "the middle of the picture"), never in numbers a model would only echo. Each reply is judged against the hotspot's own box (a circle's radius is a fraction of the
**height**, so a circle is judged against the best circle that fits what was found, and a panorama is read on its own picture's aspect): **ok** (overlap at least `min_iou`), **nudge** (a rectangle or circle, with the `shape` that would replace it), **review** (a polygon
that is off: reported, never rewritten — a box cannot stand in for an outline), **missing** (the model said it is not visible) or **no_answer**. Nothing is written without `--apply` / the dialog's *Move the checked hotspots*; applying replaces only the chosen nudges' `shape`
(the Studio does it on the live model as one undo step, so unsaved edits survive; the CLI rewrites the scene file), is idempotent (a second pass finds them in place), and uses four decimals. The vision model is `bible.models.openai.vision` (default `gpt-4.1-mini`), its price
`bible.pricing.openai_vision` (`text_input_per_million`, `output_per_million`) so the report can say what a call cost; the provider needs `OPENAI_API_KEY` from the environment, like every provider (`mock` is offline: it "finds" each object in the grid cell its position names).
A real call costs a few cents a room and is never cached; a model's boxes are a *proposal* to look at, not a measurement.

```jsonc
{
  "shots": [
    {
      "id": "bg_hall",                                      // unique; free-form snake_case
      "kind": "background",                                 // background | panorama | portrait | item | variant | expression | image | pose
      "target": "game/assets/backgrounds/hall.png",         // where the accepted picture is saved
      "replaces": "game/assets/backgrounds/hall.svg",       // optional: the placeholder it retires (references follow)
      "scene": "hall",                                      // optional owner: scene | item | character (+ expression)
      "prompt": "A grand hall: an oak door, a grandfather clock",
      "n": 2,                                               // candidates to ask for (default 1)
      "status": "todo",                                     // todo | generated | accepted | rejected
      "characters": ["nora"],                               // bible characters in the picture
      "references": ["game/assets/portraits/nora.png"],     // pictures to match (sent as image inputs)
      "provider": "openai",                                 // override the bible's pick
      "size": "2560x1440"                                   // override the provider size (OpenAI: WxH, multiples of 16)
    },
    {
      "id": "pano_quay", "kind": "panorama", "target": "game/assets/panoramas/quay.webp", "scene": "quay",
      "h_span": 110,                                        // degrees of a circle the picture covers (default 360 = a full wrap-around)
      "size": "2560x1280", "prompt": "a stone quay at night in a storm"
    },
    {
      "id": "var_hall_lit", "kind": "variant", "target": "game/assets/overlays/hall_lit.png",
      "base": "bg_hall",                                    // a shot id or an asset path: the picture to edit
      "mask": [0.4, 0.3, 0.2, 0.3],                         // the region to repaint, [x, y, w, h] of the picture
      "scene": "hall", "overlay": "lamp_lit",               // accepting adds this overlay to the scene…
      "visible_if": [{ "var": "lamp_lit", "eq": true }],    // …shown under these conditions
      "prompt": "the chandelier is lit"
    },
    {
      "id": "face_nora_angry", "kind": "expression", "target": "game/assets/portraits/nora_angry.png",
      "character": "nora", "expression": "angry", "prompt": "Nora, furious"
    },
    {
      "id": "mouth_nora_open", "kind": "expression", "target": "game/assets/portraits/nora_talk_open.png",
      "character": "nora", "mouth": "open",                  // a talk frame instead of an expression: accepting adds it to her `talk_frames` (open, then wide)
      "references": ["game/assets/portraits/nora.png"], "prompt": "Nora, the mouth slightly open, as if in the middle of a word"
    },
    {
      "id": "item_key", "kind": "item", "target": "game/assets/items/key.png", "item": "key", "prompt": "a brass key",
      "key": "9f2c7a41d0b83e55", "candidates": 2, "accepted": 1                    // written by the pipeline
    }
  ]
}
```

`key`, `candidates` and `accepted` are written by the pipeline (the cache entry holding the candidates, how many there are,
which one is in the game); everything else is authored.

**`provenance.json`** — written when a candidate is accepted, keyed by the picture's path, so a studio always knows which
model and prompt produced a picture (and what to ask for to redo it).

```jsonc
{
  "assets": {
    "game/assets/backgrounds/hall.png": {
      "shot": "bg_hall", "kind": "background", "provider": "openai", "model": "gpt-image-2.5-flare",
      "prompt": "Art style: …", "references": [], "date": "2026-10-23T18:02:11", "usage": {}, "candidate": 1, "cost": 0.18                  // usage: the provider's token counts; cost: USD actually billed (needs pricing.<provider>.output_per_million)
    }
  }
}
```

**What a run does.** Each shot becomes a prompt (`style` + a per-kind brief + the subject + the characters' bible
descriptions + `camera`/`lighting` for rooms + `Avoid: negative`). With no references it is a *generation*; with
references, or for a `variant` (base picture + a transparent-where-to-edit mask), an *edit* — OpenAI's `images/generations`
and `images/edits`. Panoramas go to Blockade Labs Skybox (create → poll → download, keeping its depth map as
`<target>_depth.png`). The provider's picture is then conformed to the game: backgrounds → the project resolution
(cover-fit); panoramas → 2:1 at the provider's own resolution (up to 4096 wide) with the wrap-around seam repaired —
or, when the shot has `h_span` below 360, left exactly as made, since OpenAI's models paint wide vistas rather than true
360° wraps (accepting sets the scene's `panorama.h_span` to match, so the camera stops at the picture's edges); `image`
shots (puzzle art, handouts) → exactly as made; portraits/expressions → 512×512 and items → 256×256 on transparency
(trimmed); variants → just the edited region as a feathered patch. Backgrounds and panoramas are delivered as PNG, or as
lossy WebP/JPG when the bible's `delivery` says so (roughly a tenth the size). Godot would re-encode those losslessly on import (a 0.6 MB room ships as 2.6 MB), so delivering lossy art also adds `importer_defaults` → `texture` → lossy to `project.godot`, unless the project already sets its own. `tools/art.gd prune` deletes cache entries no shot points at (each candidate's raw image is ~6 MB). Requests are cached by a hash of
everything that affects the result (including the bytes of each reference), so repeating one costs nothing. *Accepting* a
candidate writes it to `target`, repoints every reference to the placeholder (or binds a brand-new picture to its owner),
removes the stand-in, marks the picture final in the asset manifest, adds the overlay for a variant, and records
provenance. `provider: "mock"` paints a deterministic offline picture, for trying the workflow free.

## Skin

A game's art direction is written once and worn everywhere: `project.json` → `ui.skin` recolours the menus and panels *and* every puzzle board (the Kit's palette is a set of variables the
skin sets before any board is built — `puzzles/kit.gd`, `core/skin.gd`). Every key is optional; a game without a skin looks exactly as it always did, and a key left out keeps the engine's own value.

```jsonc
"ui": {
  "accent_color": "#d4af6a",             // buttons and highlights in menus (as before)
  "skin": {
    "highlight": "#e8c66a",              // the picked piece, focus rings and "switched on" on every puzzle
    "text": "#ebe3d1",                   // body text in menus and panels
    "text_dim": "#a8a08a",               // quiet text: captions, hints, puzzle captions
    "panel": "#15130f",                  // the background of panels and menus
    "panel_border": "#594d38",           // its outline
    "ink": "#1f1c1a",                    // the dark of a puzzle's wells and backs
    "edge": "#4d4533",                   // lines and borders on puzzles
    "good": "#80d180",                   // right
    "bad": "#e66b61",                    // wrong
    "radius": 10,                        // corner radius of panels and buttons, 0 to 40
    "font": "game/assets/fonts/serif.ttf",   // a .ttf or .otf, project-relative (the Studio draws every text with it)
    "title_font": "game/assets/fonts/display.ttf", // headings: the title screen, panel and puzzle titles, a speaker's name, the end card (default: font)
    "frame": "game/assets/ui/frame.png",     // a picture drawn as the panel background, cut in nine
    "frame_margin": 24,                  // pixels of the frame's border kept uncut, 0 to 200
    "notebook": "game/assets/ui/notebook.png", // paper the journal and the task list are written on, cut in nine
    "notebook_margin": 32,               // pixels of the paper's border kept uncut, 0 to 200
    "notebook_ink": "#29243a",           // the writing on it (default a dark blue-black)
    "tray": "game/assets/ui/tray.png",   // the inventory tray's picture (a satchel strap, a drawer), cut in nine; its pockets darken it
    "tray_margin": 24,                   // pixels of the tray picture's border kept uncut, 0 to 200
    "icons": {                           // a small picture beside a HUD button's name: hint, phone, inbox, suspects, case, accuse, journal, tasks, map, menu
      "journal": "game/assets/ui/icons/journal.svg"
    }
  }
}
```

The validator checks every colour, the ranges, that the files exist, and the **contrast** of `text` on `panel` (WCAG: at least 4.5 : 1, and 3 : 1 for `text_dim`) — a skin that is lovely and unreadable is a warning, not a surprise
at the weekend test. The Studio draws one editor for it (Dashboard → Game settings → Skin) with a "use" box per colour: unticked erases the key. The MCP's `update_project_info` merges `ui` and `ui.skin` key by key.
With `panel` set, buttons are shades of it (lighter at rest, lighter still under the pointer, darker pressed). Headings — the title screen, panel
and puzzle titles, a speaker's name, the end card — use `title_font` (theme type `MFTitle`), else `font`.
A font's licence file shipped beside it (any `*LICENSE*`, `*LICENCE*` or `*OFL*` .txt / .md under `game/assets/`) is repeated in the release's third-party notices (`tools/notices.gd`).
Colours a puzzle takes from its *meaning* (the four pads of a Simon, the wires of a wiring puzzle) are not part of the skin.

## Walkthroughs

A walkthrough is a scripted playthrough — the regression test for a whole game. `make walkthrough`
(`tools/walkthrough.gd`, the MCP `run_walkthroughs` tool) replays every `game/walkthroughs/*.json` headless
through the **real game UI**: it clicks real hotspots, picks real dialogue options and holds real items, so it
fails the moment a later edit breaks the route — and says which step, why, and where the player was.

```jsonc
{
  "name": "Main route to the ending",
  "difficulty": "junior",                       // optional: the level to pick on New Game
  "culprit": "vane",                            // optional: who did it, for a mystery that draws its culprit
  "steps": [
    { "expect": { "scene": "foyer", "visible": ["talk_hartley_first"], "hidden": ["door_open"] } },
    { "click": "talk_hartley_first" },           // click a hotspot (by id) in the current scene
    { "choose": "Ask about the locked cellar" }, // pick a dialogue option: text (substring) or a 1-based number
    { "use": "brass_key", "on": "locked_drawer" },   // hold an item and click a hotspot
    { "verb": "open", "on": "locked_drawer" },       // arm a verb and click a hotspot (see "Verbs")
    { "combine": ["rope", "hook"] },            // put two inventory items together
    { "lead": "tom" },                          // hand the lead to that playable character — the click on their portrait (see "Party")
    { "call": "mrs_hartley" },                  // ring a phone contact (by id) — runs their dialogue and steps
    { "accuse": "vane", "evidence": { "means": "poison_vial" } },   // make an accusation (see "Mystery model & accusation")
    { "deduce": "letter_forged" },              // open the case board, select that deduction's clues and press Connect (or a list of clue ids)
    { "read": "will_scan" },                    // open an inbox message (marks it read)
    { "solve": "cellar_keypad" },               // the open puzzle is solved (the player's skill isn't tested)
    { "abandon": true },                        // walk away from the open puzzle
    { "goto": "cellar" },                       // teleport (a shortcut, not a player action)
    { "wait": 1.5 },                            // let timers run
    { "expect": { "has_item": ["brass_key"], "missing_item": "rope", "solved": "cellar_keypad",
                  "conditions": [ { "var": "met_housekeeper", "eq": true } ],
                  "said": "The cellar door drifts open", "game_over": "win" } }
  ]
}
```

Narration, dialogue lines and close-ups advance automatically, so a walkthrough only spells out the
*decisions*; if a dialogue is waiting on a choice (or a puzzle is open) and the next step isn't a `choose` /
`solve`, the run fails and lists the options. `expect` accepts: `lead` (who leads, in a game with a party), `scene`, `has_item` / `missing_item` (one id or a
list), `solved`, `achievement` (one id or a list: earned), `visible` / `hidden` (hotspot ids in the current scene), `conditions` (a condition list: the forms the engine evaluates as written — `var`, `has_item`, `solved`, `visited`, `any` / `all`… — and `has_clue`, `deduced` and `contains`; any other friendly form is *refused*, because the loader rewrites those only inside the game's own files and here the check could never fail),
`game_over` (`"win"`/`"lose"`) and `said` (text shown during the previous step). A failed step stops that
walkthrough. Write one per route worth protecting — the main route, each difficulty, each alternative ending.

**Recording instead of writing.** Play the game with `--mf-record=<file>` (the Studio's *Playtests* panel does this
for you: *Record a playthrough*) and every real action — hotspot clicks, held items used on hotspots, dialogue
choices, item combinations, phone calls, opened emails, solved/abandoned puzzles, compass and map moves (recorded
as `goto`) — is written out as a walkthrough, with `expect` checks added for you (the scene after each change of
scene; at the end the scene, the items held, the puzzles solved and how the game ended). The file is rewritten after
every step, so quitting any way loses nothing. A run that used the debug panel or loaded a save gets a `"warning"`
(it may not replay). `--mf-record-name=<text>` sets the walkthrough's `name`. A recording starts at New Game.

### The goal-driven bot

`make autoplay` (`tools/walkthrough.gd -- --auto[=<steps>] [--culprit=<id>] [--write=<file>]`, the MCP `autoplay_game`) plays the game to its
**ending** with nobody at the keyboard, through the same real UI. In every situation it tries what it has not yet tried *in that situation*
— each visible hotspot, each held item on the hotspots that take it, each recipe, a ringing phone (answered), a text (replied to), a letter
(read), every dialogue option (going round a menu, exit first, when all have been tried), every puzzle (solved) and, once the player holds a clue
for enough parts of the case, the accusation — and when a room has nothing left to try it walks back through the doors it has seen to the nearest room
that has not been gone over since the world last changed. "The same situation" is the soft-lock search's own state key (`Explorer.state_key`): only what
some condition can observe counts, so a counter nothing reads cannot keep the bot busy forever. A mystery with several candidate culprits is played once
for each. Rooms swap instantly (the player setting `reduce_motion`) so a long game takes seconds.

It passes when the game ends in a win. It fails — naming the room, how many rooms and puzzles it reached and what it held — when it runs out of things to try,
the game ends in a loss, or the UI stops responding. `--write=<file>` saves what it did as a walkthrough (`expect`s included), so a game that has none gets a
regression test for free (the file is rewritten per culprit with a `_<culprit>` suffix). It makes a deduction (opens the case board, selects its clues,
presses Connect — the `deduce` step) as soon as the clues for one have been found. `make check` runs it on the bundled game, and `tools/check.sh` (every game's own suite) on yours.

### The QA bot

`make fuzz` (`tools/walkthrough.gd -- --fuzz=<steps> --seed=<n>`) plays the game at random through the real UI: it clicks what is
on screen, answers dialogues, solves or walks away from puzzles, uses and combines what it holds and teleports now and then, over as
many new games as the steps take. It fails if the game ever stops responding (something is waiting for input nothing can give) or the
engine prints a script error, and writes the steps that led there to `user://fuzz_failure_seed<n>.json` — a walkthrough that
`--file=` replays exactly. Different seeds are different games; `make check` runs one.

### The text front end

`tools/text_play.gd` plays the real game UI as typed commands on standard input/output: a room is the list of what can be clicked (`[id] label — a way
through | someone to talk to | look closer`), a conversation is its numbered replies, a puzzle is its own on-screen controls numbered (`press <n>`, `type <n> <text>`).
Every answer is printed between `<<BEGIN>>` and `<<END>>`, then a `<<STATE>>{json}` line (turn, room, clues, hints used, puzzles solved, game over, ending); the game's
clock stops while it waits for a command. `core/text_view.gd` does the describing and only reads. A puzzle type describes a board that is *drawn* (not made of labelled
buttons) through two optional methods on its script — `text_state() -> String` (what the eye would see) and `text_act(words) -> String` — see `puzzles/puzzle_base.gd`.
`tools/llm_session.py` wraps it for an AI tester (a background session, a transcript and a summary per session, `report` over many) — `docs/LLM_PLAYTEST.md`.

**The commands** (the in-game `help` prints the same list; a word is matched against ids and displayed names, and `choose` takes words rather than numbers because numbers change as replies are used up):

| Command | What it does |
|---|---|
| `look` | the room again, and what can be done in it |
| `click <thing>` | the obvious thing: go through a door, look closer, pick it up, talk to them. The thing is an id (`[brackets]` in the room list) or what it is called. A thing that changes is several hotspots with ids `desk`, `desk_2`… — type the one that is showing |
| `choose <words or n>` · `use <item> on <thing>` · `combine <item> with <item>` | a reply; an item on a hotspot; two items |
| `<verb> <thing>` (a game with `ui.verbs`) | the game's own verb on a hotspot — `open drawer`; the verb's id or its button text |
| `inventory` `journal` `tasks` `clues` `suspects` `mail` `phone` `map` | the panels as text |
| `read <mail>` · `call <contact>` · `dial <number>` · `answer` · `decline` · `reply <text id>` · `travel <place>` | inbox, phone and map. `dial` reaches a contact who is only a number on a card (and says "not in service" for any other) |
| `hint` · `hint more` · `deduce <clue> <clue>…` · `accuse <suspect> means=<clue> motive=<clue> opportunity=<clue>` | hints (they count), the case board, the finale |
| `puzzle` · `press <n> [x<times>]` · `type <n> <text>` · `act <words>` · `skip` · `leave` | inside a puzzle: the numbered controls (`press 3 x5` turns a wheel five places), a text field, a puzzle's own verbs, walking away |
| `wait <seconds>` · `note <words>` · `help` · `quit` | time, a remark for the report |
| `debug solve` · `debug goto <room>` | only with `--dev`, for the automated replays |

A **typed route** is a text file in `game/walkthroughs/*.txt`: one command per line, `#` comments, and an optional `  ## words` the answer to that line must contain. `tools/check.sh`
(step `text`) runs every typed route (it must end in a win) and replays every recorded walkthrough as typed commands (`llm_session.py replay`; a puzzle step becomes `debug solve`,
which only exists with `--dev`).

## Review mode

Two things for the people who read the game rather than play it: the **script**, and **pinned comments**.

**The script.** `make script` (`tools/script.gd`, the MCP `export_script` tool, the Studio's Review tab) writes every line the game shows or says
in reading order, as a document: the cast; each room (in its place) with what happens when you arrive and what each hotspot does or says, with the
conversations it starts printed as branching scripts right below; each character's answers by topic and by item shown; puzzles, items, the case
board and the accusation, hints, the phone, achievements. Every spoken line is labelled with who says it and carries a stable reference
(`hartley_intro/n3`, `cellar/take_ledger/1`) for discussion; conditions are in plain words ("only when holding Key"); what happens (an item gained,
a clue found, a move to another room, the ending) is listed in italics, and plain variable changes quietly. The top gives spoken-line and word
counts per speaker. `FORMAT=csv` (or `format: "csv"`) gives one row per line — section, kind, speaker, text, reference, condition — for a
spreadsheet. The script is built from the loaded game, so it matches what the player meets.

**Comments.** `game/review/comments.json` holds notes a writer, editor or tester pinned to a place:

```jsonc
{ "comments": [
    { "id": "comment_1",
      "target": "scene:foyer#stair_portrait",     // global · scene:<id> · scene:<id>#<hotspot> · dialogue:<id> · dialogue:<id>#<node> · character:<id> · item:<id> · puzzle:<id> · clue:<id> · hint:<id>
      "text": "Describe the portrait's eyes.",
      "author": "ed",
      "date": "2026-10-24",
      "status": "open" }                           // "open" or "resolved"
] }
```

The file is shared through version control and left out of builds (`game/review/*` is in the export filters and skipped by the asset and voice
scans). The script export pins each comment under the thing it is about (`--comments=open|all|none`) and lists the open ones again at the end.
Renaming a room, conversation, character, item, puzzle or clue carries its comments with it; a comment whose target has been deleted is reported
as **orphaned** (a warning) rather than lost, and the production report counts a room's open comments.

## Game-flow analysis

`validate_project` checks that the data is well-formed; the **story check** (`make analyze`,
`tools/analyze.gd`, the MCP `analyze_game` tool, and the Studio's *Check for problems* screen) asks
whether the *story* works. It plays the game optimistically from a new game — every puzzle solved, every
dialogue branch taken, everything done in the best possible order — accumulating what becomes possible
(rooms reached, items obtained, the values each variable can take, dialogues started…), and reports what
**still** can't happen:

- the game can't be won (no reachable winning `end_game`) — an **error**;
- a scene nobody can enter; a hotspot whose `visible_if` can never hold; a dialogue, node or choice that
  can never be reached or offered; a puzzle or contact nothing can start or reach;
- a variable checked against a value nothing ever sets (the classic typo'd flag), and a counter compared to a
  number nothing can add up to;
- an item the story requires (`has_item`, `use_items`) that the player can never obtain.

Numbers are tracked as ranges (`inc_var` makes "at least N" possible; `random_var` covers every face). It
deliberately ignores things that only restrict the player (`remove_item`, `once` choices, `missing_item` /
`unsolved` / `not_visited` conditions) so it never reports a problem that isn't one — which also means it does
**not** find soft-locks that depend on an exact order of play. Custom scripts are opaque: assumed to change
nothing, and called out in the report.

## Soft-lock search

The story check is optimistic, so it can't see mistakes that depend on the *order* of play. The soft-lock
search (`make softlocks`, `tools/softlocks.gd`, MCP `find_softlocks`, the Studio's *Search for soft-locks*
button) is exact: it simulates the game's real rules and walks **every sequence of player moves** — each
hotspot click, item use, item combination, compass/map step, phone call, dialogue answer, puzzle (solved or
walked away from), face of a `random_var`, and timer firing — building the graph of every state the player
can be in, then asks of each state "can the player still win from here?"

It reports, as **errors**:

- **Points of no return** — a move after which the game keeps running but can no longer be won (discarding the
  only key, spending a one-time `once` choice that forfeits the clue, a one-way door), with the shortest route to it
  and what the player chose along the way;
- **Dead ends** — a state with nothing left to do and no way to win;
- and, when nothing wins at all, that the game can't be won.

A deliberate `end_game` with `"result": "lose"` is an ending, not a soft-lock. The search models what changes the
story (variables, inventory, scene, visited rooms, solved puzzles, one-time choices, tasks, emails, running
timers), and ignores state nothing else can observe, which keeps big games tractable (the 121-room stress game is
explored in full in under a minute). With several difficulty levels each is searched. Numbers are clamped to ±1000.
**It never guesses:** if it hits the state or time limit (`--max-states`, `--max-seconds`) it says the search
stopped early and reports no soft-locks. Custom scripts are opaque (assumed to change nothing).

**Reduction (so real games finish).** Taken in every order, harmless parallel steps — pick up the key, pick up the
note, ask the innkeeper everything — multiply the states without ever deciding whether the game can be won (a
30-room mystery with a dozen independent pickups has millions). The search therefore takes **provably harmless
moves at the first opportunity** instead of branching on them. A move is harmless when it only *adds* (give an
item, set a flag, add a task or email, solve a puzzle whose rewards only add), no condition anywhere would be
switched off by it other than its own "not taken yet" gate, and it stays available until taken (nothing else can
switch off the condition that shows it). That covers pickups, safe puzzle solves, `consume: false` item uses and
whole conversations. They are taken everywhere the player can walk *to and back from* through plain doors, so the
order of independent errands stops mattering — while a pickup in a room you can't return to, one another move
can shut off, or anything consumed, is still explored in every order (those are the real soft-locks). It is not
used at all when a timer can do more than end the game. The Map screen is skipped when the doors alone already
connect every room (it then only shortcuts them). The verdict is the same as the full search (`--no-reduce` /
`exhaustive` runs that one, slower); the report says `reduced` and how many harmless moves were taken early. A
path in a report may note "took every harmless pickup and answer within reach".

## Validation severity

- **error** — will break at runtime (missing scene ref, unknown action, bad shape).
  The MCP server refuses `run_preview` while errors exist unless `force` is set.
- **warning** — suspicious but playable (missing voice file, unreachable scene,
  unused item, undeclared-but-unused variable).
