# MysteryForge Architecture

## The lineage

The classic mystery-adventure series shipped ~30 games over two decades on essentially one
engine: a slideshow of pre-rendered scenes, hotspots, an inventory, recorded
dialogue, puzzles, and a flag table. New game = new assets + new data. That
separation — *engine code never changes, game data always does* — is the entire
design center of MysteryForge, updated with one modern addition: the data layer
is designed to be read and written by AI agents as a first-class authoring path.

## The three layers

```
┌──────────────────────────────────────────────────────────────────┐
│  Authoring clients (three peers, one file format)                 │
│  MysteryForge Studio   ──   Claude / GPT / any MCP client   ──    │
│  (visual desktop app)       (the MCP server)                      │
│                              plain text editor                     │
└─────────┬────────────────────────────┬───────────────────┬────────┘
          │ canonical JSON writes        │ MCP (stdio)        │ direct edits
          │                              ▼                    │
          │                ┌──────────────────────────────┐  │
          │                │ mcp/ — mysteryforge-mcp (TS)  │  │
          │                │ CRUD · canonical atomic writes│  │
          │                │ validate/preview/screenshot   │  │
          │                └───────────────┬───────────────┘  │
          ▼                                ▼                   ▼
┌──────────────────────────────────────────────────────────────────┐
│  A game project (one per game; create_game stamps them out)       │
│  ├─ game/                       ← THE GAME: JSON + assets (data)   │
│  ├─ addons/mystery_forge/       ← the engine (GDScript)            │
│  ├─ addons/mystery_forge_studio/← the visual Studio (GDScript)     │
│  ├─ tools/validate.gd           ← headless validator entrypoint    │
│  ├─ tests/run_tests.gd          ← headless engine self-tests       │
│  └─ project.godot                                                  │
└──────────────────────────────────────────────────────────────────┘
```

The Studio and the MCP server are deliberate peers: both are thin authoring
layers over the same `game/*.json`, both delegate deep validation to the engine's
`tools/validate.gd`, and both emit **byte-identical canonical JSON** (verified in
CI) so a human and an AI can edit the same project turn by turn.

`runtime/` in this repo is simultaneously (a) the engine source of truth,
(b) the template that `create_game` copies, and (c) a complete example game
(*The Case of the Cellar Key*).

## Key decisions

**Game-as-data, JSON not scenes.** Godot `.tscn` files are hostile to
programmatic editing and merge conflicts. The Game Definition Format
(docs/SPEC.md) is plain JSON with normalized coordinates, snake_case ids, and
a small declarative action/condition language. An agent can write a whole game
without generating a single line of GDScript — and a designer can read the
diff. The runtime interprets the data; there is no compile step.

**One validator, owned by the engine.** `core/validator.gd` is the single
source of truth for "is this game well-formed." The same code runs at debug
boot, in `tools/validate.gd` (headless CLI), in the test suite, and behind the
MCP `validate_project` tool (the MCP server shells out to Godot and parses the
marker-delimited JSON report). The MCP layer adds only cheap inline warnings at
write time, so the deep rules never fork between TS and GDScript.

**Code-built UI, data-built scenes.** The engine constructs all UI in GDScript
(one trivial `main.tscn`); scenes/hotspots/overlays are instantiated from JSON
at runtime. Stretch mode `canvas_items` + fixed 1920×1080 design space means
normalized hotspot coordinates are resolution-independent for free.

**The Studio is an app, not a Godot plugin.** A standalone Godot scene
(`addons/mystery_forge_studio/`, launched via `--mf-studio` or the `mfstudio`
export feature) rather than an `EditorPlugin`, so a non-developer never opens the
Godot editor — and a game ships as a normal Godot project, exportable to
desktop/web. It owns its own editable model (`editor_project.gd`) distinct from
the runtime's play-time `MFData`/`MFState`, resolves assets against a configurable
project directory (`use_project_dir` + `texture()`) so it can edit its own
`res://game` *or any external folder* (Open… / `--mf-project`), and shells out for
the things the engine already does well (validate, play). `make export-studio`
packages it standalone; `create_game` includes it; the game export presets drop it.

**Agent feedback loops.** Three primitives make AI iteration effective:
`validate_project` (machine-readable errors with "did you mean"),
`screenshot_scene` (boot → render scene → return PNG, so the agent *sees* its
work), and `run_preview --scene X` plus in-game F5 hot-reload (human plays
while the agent edits underneath).

**Voice-first pipeline, audio-optional runtime.** Everything voiced degrades
gracefully to subtitles when the file is missing, so production order is
text → placeholder TTS (`generate_voice`) → real recordings, swapping files at
fixed paths — exactly how the classic studio worked.

**GL Compatibility renderer.** 2D-only content; the compatibility renderer
maximizes deployment reach (old machines + web export later).

## Engine internals (addons/mystery_forge/)

- `game.gd` — the `MF` autoload: owns `MFData` (parsed game), `MFState`
  (playthrough), audio, settings, saves (8 slots + autosave per scene change, with a
  picture and a summary each, per player: `user://mysteryforge/<game_id>/` for the first player, `profiles/<id>/` beneath it for the rest).
- `core/actions.gd` — sequential awaitable interpreter; every story beat
  (dialogue, narration, puzzles, scene changes) is an action list.
- `core/conditions.gd` — pure predicate evaluation over state (`var` ops,
  items, solved, visited, `any`/`all` nesting).
- `ui/main.gd` — orchestrator and the awaitable UI surface the interpreter
  calls (`change_scene`, `show_subtitle`, `run_dialogue`, `run_puzzle`, …).
- `ui/scene_view.gd` — background, conditional overlays, hotspot nodes with
  polygon/circle hit-testing, verb cursors, hover labels. Re-evaluates
  visibility on every state change.
- `puzzles/` — `puzzle_base.gd` + `registry.gd` + `kit.gd`; a puzzle type is one script that builds the board
  and describes itself (`static meta()` settings, `static analyze()` solver that proves an instance winnable and
  replays the answer on the model). The registry, validator, localisation extractor, `tools/puzzles.gd` proof
  and the Studio's settings form all read that description, so a new type is one script + one registry line.
- `core/stage.gd`, `ui/actor_node.gd` — people standing in rooms: stage geometry, poses, auto lip-sync and *idle life* (a lean, a breath, a blink; stops while walking, off with Reduce motion).
- `core/audio.gd`, `core/mix.gd`, `core/acoustics.gd` — buses and their one level function (mix preset offset + duck), and the reverb a room's size and surface imply (Sabine's rule).
- `core/scene_diff.gd` + `tools/scene_diff.py` — what changed in the rooms between two versions of a game, drawn; `mcp/src/templates.ts` — room templates and bulk edits (authoring-only: they output ordinary scenes).

## Video

Godot plays Ogg Theora natively; **WebM (VP9, with alpha, Opus/Vorbis)** comes from the `mf_video` GDExtension
(`extensions/mf_video` → packaged into `addons/mf_video/`, copied into every game). It subclasses `VideoStream`/`VideoStreamPlayback`
and registers a resource loader for `.webm`/`.mkv`, so the engine's `VideoStreamPlayer` code is unchanged. The engine treats the
extension as optional: `MFUtil.load_video` returns null (one warning) and every caller degrades to the still picture. The validator,
asset audit (through `MFVideoStream.probe`), Studio (import/convert, Publish card) and MCP (`convert_video`) all know about it;
see SPEC "Video" and docs/SPIKE_S1_VIDEO.md.

## Extension points

| To add | Touch |
|--------|-------|
| New action type | `core/actions.gd` (interpret), `core/validator.gd` `ACTIONS` + checks, `core/analyzer.gd` `_effect` (story check), `core/strings.gd` if it shows text, SPEC.md, Studio `action_list_editor.gd` `VERBS` + fields, `test_parity.gd` |
| New condition form | `core/conditions.gd`, validator `_check_condition`, `core/analyzer.gd` `_possibly_one`, SPEC.md, Studio `condition_model.gd` KINDS + `condition_editor.gd` |
| New top-level document (like `hints.json`, `contacts.json`) | `core/data.gd` (load), `core/validator.gd` (`_check_*`), `core/strings.gd`, SPEC.md, Studio `editor_project.gd` (load/snapshot/save/`changed_docs`) + a panel + `studio.gd` `PANELS`, MCP `store.ts` + CRUD tools, `test_parity.gd`, `tests/fixtures/game` |
| New door/link feature | `core/links.gd` (runs first in `MFData.load_all`), validator `_check_links`, SPEC "Links", Studio `links_panel.gd`, MCP link tools |
| New puzzle type | `puzzles/<type>.gd` (build + `meta()` + `analyze()`, `_autoplay()` for tests), `puzzles/registry.gd` `TYPE_IDS`, a SPEC.md "Puzzle types" row (the parity test checks it against `meta()`), a play-through case in `tests/run_tests.gd` — nothing in the validator or Studio |
| New MCP tool | `mcp/src/tools.ts` |
| New video format/codec | build it into `extensions/mf_video` (`scripts/build_ffmpeg.sh` decoder list), `core/util.gd` `VIDEO_EXTS`/`EXTENSION_VIDEO_EXTS`, `core/asset_audit.gd`, `mcp/src/assets.ts`, Studio `studio.gd` + `asset_convert.gd`, SPEC "Video" |
| New Studio panel | `addons/mystery_forge_studio/panels/<id>.gd`, register in `studio.gd` `PANELS`/`NAV_ORDER` |
| Change JSON formatting | keep `studio/core/json_writer.gd` and `mcp/src/store.ts serialize()` identical |

## Roadmap

The live roadmap — what is done, what is next, and why — is **docs/ROADMAP.md**. In brief, the
engine now covers the classic mystery-adventure toolkit (item combining, hints & difficulty, phone/inbox/suspects,
timers & chance, frame animation & tweens, keyboard/gamepad play); the Studio can author everything the
format expresses (enforced by a SPEC parity test) with undo, safe renames, a story check, a debug panel
and a Publish tab; games can ship their own GDScript for the rare one-off and are upgradable
(`ENGINE_VERSION` / `FORMAT_VERSION`, `make upgrade-game`); and `make check` also replays a scripted
walkthrough, smoke-tests every Studio panel and cross-checks the two JSON writers. Remaining big rocks:
a cutscene timeline editor, 360° panoramas, a soft-lock explorer, and a real art-complete vertical slice.
