Files

578 lines
54 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Code map — Lumen
> Agent-oriented overview of the Flutter app. Read this before changing code.
> Location: `docs/CODE_MAP.md`. Update it when you move files, add screens, or change persistence keys or invariants.
> Symbol names and paths are stable; line numbers are deliberately omitted because they drift.
## 30-second summary
- **What it is:** an offline illustrated logic-puzzle notebook ("Lumen", version 2.0.3+12).
- **Stack:** Flutter 3.47.5 / Dart 3.13.4, Material widgets, no backend and no account.
- **Entry point:** `main()` in `lib/main.dart` → `StoryLibrary.load()` + `Progress.load()` → open selected story/language → `Game(...)` → `await game.restore()` → `game.showLibrary()` → `runApp(LumenApp(game: game))`. The shelf is the first window; `restore()` has already positioned each book's saved leaf so choosing a book resumes it. `Book.load()` remains an English Mara compatibility loader for existing tests/tools.
- **State:** one `Game extends ChangeNotifier` (`lib/domain/game.dart`) owns the current screen, puzzle session, marks, undo history and progress. `_NotebookState` listens to it and rebuilds the active screen.
- **Screens:** `Screen { library, home, story, contents, briefing, game, reveal }`, rendered by seven builder methods in `_NotebookState`.
- **Story content:** an offline catalogue in `assets/library.json`; Mara has twelve authored 7×7 pictures; Paper Boat demonstrates English/German packages; The Midnight Invitation is a complete English Halloween special (38 leaves, twelve puzzles, thirteen illustrations, 26 recorded passages). Daily and classic boards are generated 7×7 puzzles.
- **Persistence:** local `SharedPreferencesAsync` behind `lib/services/progress.dart`; legacy Java saves are never imported.
- **Platform:** Android is the tested target; iOS scaffolding exists but is unvalidated. `legacy/` is archived Java 1.7 and is excluded from builds and analysis.
## Suggested reading order
1. `lib/domain/game.dart` — screens, modes, puzzle session, awards and persistence keys.
2. `lib/domain/puzzle.dart` — puzzle model, generation, solver, hints and difficulty.
3. `lib/main.dart` — screen builders plus gesture/dialog glue.
4. `lib/ui/paper.dart` and `lib/ui/board.dart` — page layout, landscape split, grid rendering.
5. `lib/services/*` — storage, narration and ads.
6. `assets/` — campaign, narration scripts, audio manifest and artwork.
## Repository tree (source only)
```text
lib/
├── main.dart LumenApp, Notebook, all screen builders, dialogs, routing
├── domain/
│ ├── puzzle.dart Puzzle, JavaRandom, LogicSolver, Difficulty, Region, Hint
│ ├── thinking.dart ThinkingAnalyzer, ThinkingReport — snapshot deduction waves and bounded hypothetical proofs
│ ├── book.dart Book, CampaignLevel, StoryPage/StoryPageType — validated content and locale overlays
│ ├── library.dart StoryDefinition, StoryLibrary — catalogue, locale resolution and cached books
│ └── game.dart Game (ChangeNotifier), Screen/Mode, puzzle session, awards
├── services/
│ ├── translation.dart TranslationCatalog, MessageTranslator — separate UI catalogues and placeholders
│ ├── progress.dart Progress — typed façade over SharedPreferencesAsync
│ ├── ambience.dart Ambience, Soundscape — location loops, fades and narration ducking
│ ├── narrator.dart Narrator — just_audio playback and passage cues
│ ├── ad_audience.dart AdAudience — local age group and ad treatment
│ └── ads.dart Ads — age-gated UMP consent, rewarded hints, interstitials
└── ui/
├── paper.dart Paper, Leaf, Cover, Sketch, InkButton, PageSwipeBlocker
├── board.dart Board, PencilMark painter, PixelPicture, PatternStamp
├── discovery.dart Discovery — pattern-to-art transition and replay
├── ad_age_group.dart Age-group choice shown before advertising starts
├── translation.dart CopyScope, CopyText — translated controls, locale parsing and font fallback
└── mara_story.dart Original-story presenter (part of main.dart); standard packages use standardStory
assets/
├── library.json Story catalogue, IDs, asset paths and language metadata
├── locales/ App UI catalogue index and English/German messages
├── stories/paper-boat/ Small standard story with a German overlay
├── campaign.json premise + 12 authored levels (chapter/title/object/before/after/picture/clues/areas; optional illustrationAsset)
├── notebook.json sixteen stable cottage leaf records (type, speaker, campaignIndex, text source)
├── narration/scripts.json canonical diary text, one record per recorded page
├── narration/manifest.json source masters and checksums for narration
├── audio/narration_manifest.json runtime tracks: file, duration, cue timings
├── audio/*.wav 28 bundled PCM16 recordings (APK runtime assets)
├── audio/*.flac archival lossless exports (not declared in pubspec)
├── artwork/*.png watercolours, vignettes and the notebook page
└── fonts/DancingScript.ttf bundled as family MaraHand; OFL.txt ships with licences
test/puzzle_test.dart domain tests (Java parity, generation, solver, awards, restore)
test/widget_test.dart widget tests (page gestures, scrolling, landscape layout)
test/fixtures/java_boards.json 40 reference boards from the Java 1.7 version
integration_test/notebook_test.dart one on-device end-to-end test (QA flavour only)
scripts/ narration verification, install smoke check, narration rendering
```
## Architecture
```mermaid
flowchart TD
subgraph UI["lib/ui — reusable page widgets"]
paper["paper.dart<br/>Paper · Leaf · Cover · Sketch<br/>InkButton · PageSwipeBlocker"]
board["board.dart<br/>Board · PencilMark · PixelPicture · PatternStamp"]
discovery["discovery.dart<br/>Discovery · transition · replay"]
end
main["main.dart<br/>LumenApp · Notebook<br/>seven screen builders · dialogs"]
game["domain/game.dart<br/>Game (ChangeNotifier)<br/>Screen/Mode · session · awards"]
puzzle["domain/puzzle.dart<br/>Puzzle · LogicSolver · JavaRandom · Difficulty"]
thinking["domain/thinking.dart<br/>ThinkingAnalyzer · ThinkingReport"]
cli["tool/analyze_puzzles.dart<br/>Authoring report CLI"]
book["domain/book.dart<br/>Book · CampaignLevel · StoryPage"]
progress["services/progress.dart<br/>Progress — local key/value store"]
narrator["services/narrator.dart<br/>Narrator — just_audio"]
ambience["services/ambience.dart<br/>Ambience · Soundscape — just_audio"]
ads["services/ads.dart<br/>Ads — UMP consent + AdMob"]
main --> paper
main --> board
main --> discovery
discovery --> board
discovery --> paper
main --> game
main --> narrator
main --> ambience
main --> ads
board --> puzzle
board --> paper
game --> puzzle
cli --> thinking
cli --> puzzle
thinking --> puzzle
game --> book
game --> progress
book --> puzzle
book --> campaign[("assets/campaign.json")]
book --> notebook[("assets/notebook.json")]
book --> scripts[("assets/narration/scripts.json")]
narrator --> manifest[("assets/audio/narration_manifest.json")]
narrator --> wav[("assets/audio/*.wav")]
ambience --> wav
```
Dependency rules:
- `domain/` never imports `ui/` or Flutter widgets beyond `foundation`/`services` (it is testable headlessly).
- `ui/` may import `domain/puzzle.dart` for the model, but never `Game`, `Progress` or `main.dart`.
- `services/` are platform adapters; only `progress.dart` is imported by `domain/game.dart`.
- `main.dart` is the only place that wires everything together.
## Module responsibilities
| Path | Lines | Role | Key symbols | Depends on |
| --- | ---: | --- | --- | --- |
| `lib/main.dart` | ~1110 | App shell, routing glue, all screen builders, dialogs, story extras and hint flow | `main`, `LumenApp`, `Notebook`, `_NotebookState` | `domain/*`, `services/*`, `ui/*`, `intl` |
| `lib/domain/game.dart` | 305 | Single source of truth for navigation, puzzle session and awards | `Game`, `Screen`, `Mode`, `generatePractice`, `visibleStreak`, `completedStreak` | `puzzle`, `book`, `Progress` |
| `lib/domain/puzzle.dart` | 375 | Deterministic generation, constraints, solver, hints, difficulty grading | `Puzzle`, `JavaRandom`, `LogicSolver`, `Constraint`, `Region`, `Hint`, `Analysis`, `Difficulty`, `epochDay` | `dart:math` only |
| `lib/domain/book.dart` | 98 | Loads authored campaign and story records from assets | `Book`, `CampaignLevel`, `StoryPage` | `puzzle`, `dart:convert`, `rootBundle` |
| `lib/services/progress.dart` | 47 | Typed key/value store; memory mode for tests; serialised disk writes | `Progress`, `Progress.memory`, `snapshot`, `flushed` | `shared_preferences` |
| `lib/services/narrator.dart` | 118 | One audio player, pause/resume, speed, cue-based passage highlighting | `Narrator` (`toggle`, `pause`, `stop`, `label`, `status`, `passage`) | `just_audio`, `audio_session` |
| `lib/services/ads.dart` | 181 | Consent-gated ads; never blocks gameplay | `Ads` (`supported`, `start`, `hint`, `between`, `privacy`, `dispose`) | `google_mobile_ads` |
| `lib/ui/paper.dart` | 325 | Paper background, page-turn gesture, leaf layout, nav buttons, sketches | `Paper`, `Leaf`, `Cover`, `Sketch`, `InkButton`, `PageSwipeBlocker`, `hand`, colour constants | `material`, `gestures` |
| `lib/ui/board.dart` | 311 | Square clue/grid board with pencil marks, semantics, pixel-art reveal | `Board`, `PencilMark`, `PixelPicture` | `puzzle`, `paper` |
## Runtime wiring
- `main()` sets the system overlay style, registers the Dancing Script OFL licence, initializes date symbols, loads the catalogue and progress, resolves the saved story and requested language, constructs `Game`, awaits `game.restore()`, opens the shelf with `game.showLibrary()`, then runs `LumenApp`.
- `LumenApp` is a `MaterialApp` with seed colour `blue` (`#274956`), cream surface (`#f3e7cc`), `fontFamily: 'MaraHand'` and `Notebook` as `home`.
- `_NotebookState` creates exactly one `Narrator(g.book.tracks)` and one `Ads(enabled: widget.adsEnabled)`, subscribes to `Game` with `_changed`, and starts ads after the first frame.
- `_changed()` replaces narration tracks when the active book/language changes, stops narration when the route string (`storyId:language:screen:storyIndex|campaignIndex`) changes, then rebuilds.
- Lifecycle: backgrounding stops narration and awaits `prefs.flushed`; `dispose` stops/disposes the narrator, disposes ads and removes listeners.
- `PopScope` intercepts Android back: it pops only on `home` with no `busy` work; otherwise it calls `back()`.
- `build()` switches on `g.screen`; a full-screen overlay with `CircularProgressIndicator` covers the app while `g.busy` (classic board generation).
## Screens and state machine
```mermaid
stateDiagram-v2
[*] --> home
home --> story: openNotebook / showStory
home --> game: startDaily or startPractice
story --> story: turn within sixteen cottage leaves
story --> contents: Contents
story --> home: Close book
story --> briefing: leaf 6 lantern link
contents --> story: cottage entry, memory or bookmark
contents --> briefing: accessible campaign entry
contents --> reveal: recovered campaign entry
contents --> home: Close the notebook
briefing --> game: startCampaign
briefing --> reveal: read-ahead back
briefing --> contents: Back to notebook
game --> reveal: solved campaign
game --> briefing: swipe back
game --> contents: Back to notebook
game --> home: daily or classic back
reveal --> briefing: next leaf
reveal --> game: previous leaf / Android back / inspect solved pattern
reveal --> contents: last page or Back
reveal --> game: Today's puzzle
game --> game: daily or classic solve
```
| Screen | Builder in `_NotebookState` | Leaf key | Content | `onTurn` |
| --- | --- | --- | --- | --- |
| `library` | `libraryScreen()` | `library` | Bookshelf: every catalogue entry as a card with cover, languages, restored patterns and settings | none (cards call `selectStory`) |
| `home` | `home()` | none (own `Scaffold` body) | Harbour art, notebook cover, daily ritual, difficulty, rules, privacy, licences | none |
| `story` | `story()` | `story-<index>` | Sixteen cottage leaves: dedication, four entry/puzzle/memory beats, note, inspection, closing | `turn()` |
| `contents` | `contents()` | `contents-<chapter>` | Four chapter entries, ribbon bookmark, reading resume and optional cottage scraps; chapter navigation | none |
| `briefing` | `briefing()` | `briefing-<i>` | Chapter, title, `before` passage, "Restore the pattern →" | `turnCampaign()` |
| `game` | `game()` | `game-<key>` | Puzzle heading, area totals, square board, hint/undo, actions | `turnCampaign()` in campaign mode only |
| `reveal` | `reveal()` | `reveal-<i>` | Object name, pattern-to-watercolour transition and permanent symbol (or `PixelPicture` fallback), `after` passage plus continuation, ending text on level 12 | `turnCampaign()` |
### Navigation methods (`Game`)
| Method | Effect |
| --- | --- |
| `showLibrary()` | `Screen.library`; cancels pending board generation. Never written to `flutter_screen`, so each book's saved route survives and the app opens on the shelf |
| `home()` | `Screen.home`; cancels pending board generation |
| `openNotebook()` | `showStory(index of notebook_last_page, else 0)` |
| `showStory(i)` | Clamp `i` to available pages; set campaign mode and the record’s campaign index; on a puzzle leaf load its `story_v1_<index>` unless already loaded; persist last page and `viewed_<pageId>`; `Screen.story` |
| `contents([chapter])` | One chapter’s entries (derived from stable `chapterId`); persist `notebook_contents_chapter`; default to current campaign chapter |
| `leaveCottage()` | Open Chapter II for reading without awarding unfinished cottage puzzles |
| `briefing(i)` | Clamp to `accessible`; cottage entry leaf or later `Screen.briefing` |
| `reveal(i, {readAhead})` | Redirect to `briefing(i)` unless recovered, or read-ahead is allowed for an accessible level; otherwise the cottage memory leaf or later `Screen.reveal` |
| `startCampaign(i)` | No-op if `i > accessible`; including recovered levels, load `book.levels[i]` under `story_v1_<i>` and open the cottage puzzle leaf or later `Screen.game` |
| `startDaily(day)` | Load `Puzzle.generateSeven(epochDay(date) * 7919, Difficulty.medium)` under `d7_<YYYY-MM-DD>`; `Screen.game` |
| `startPractice([level])` | Generate a 7×7 board off the UI isolate with `compute(generatePractice)`; key `v3_<DIFFICULTY>_<level>`; `Screen.game` |
| `mark(i)` / `undo()` / `area(i)` | Cycle a cell 0→1→2→0, restore the previous snapshot, select an A/B/C area |
| `applyHint()` | Return one explained `Hint` and apply it (prefers detecting a conflicting earlier mark) |
| `check()` | Award completion exactly once; cottage solves advance to the matching memory record; later solves advance to the reveal; classic levels advance; daily updates the streak |
| `restore()` | Re-open the saved screen (`flutter_screen`), including read-ahead reveals and unfinished campaign/classic boards |
### `main.dart` internal map
- **Boot/app:** `main`, `LumenApp`, `Notebook`, `_NotebookState`.
- **Lifecycle/router:** `initState`, `_changed`, `didChangeAppLifecycleState`, `dispose`, `build`, `back`.
- **Screens:** `libraryScreen`, `home`, `story`, `contents`, `briefing`, `game`, `reveal`.
- **Puzzle UI:** `puzzleBody`, `areaPicker`, `board`, `puzzleNotes`, `splitPuzzle`, `hint`, `nextPractice`.
- **Story extras:** `reading` (narrator cue highlight), `audio` (play/pause, stop, speed), `illustration`, `navigation`, `bookmark`, `openLetter`, `inspect`, `speed`.
- **Leaf turning:** `turn`, `turnCampaign`, `nextCampaign`.
- **Dialogs/feedback:** `toast`, `confirm`, `message`, `chooseDifficulty`, `rules`, `privacy`.
- **Layout helpers:** `column`, `action`, `gap`, `divider`, `folio`.
## Puzzle domain
| Type | Shape |
| --- | --- |
| `Puzzle(size, picture)` | `size` (5 or 7), `solution` (0/1 per cell), `given` flags, mutable `regions` |
| `Puzzle.seeded(seed)` | Factory: 5×5 random picture plus givens until the answer is unique |
| `Puzzle.generate(seed, difficulty)` | Factory: retries up to 256 seeded boards, strips redundant givens unless Easy, keeps the board whose `deductionRounds` matches the requested grade |
| `Puzzle.rows` / `cols` | Authored totals per row/column |
| `Puzzle.constraints` | Row, column and area `Constraint`s used by the solver and UI |
| `Puzzle.initial` | Solver input: `-1` unknown, `0` dark, `1` lit |
| `Puzzle.regionTotal(r)` | Lit cells inside a region |
| `Puzzle.solved(cells)` | Every cell matches the solution (lit → `1`, dark → `2`) |
| `Puzzle.countSolutions()` | Unique-solution check (fast row/column search for plain 5×5, general solver otherwise) |
| `LogicSolver` | `nextHint(known)` (explained single deduction), `analyze(initial)` (area deductions, solvable flag), `countSolutions(initial)` |
| `Difficulty` | `easy`/`medium`/`hard`, stored as `EASY`/`MEDIUM`/`HARD`; graded by deduction rounds ≤2, ≤4, else hard |
| `JavaRandom` | 48-bit Java-compatible LCG so generated boards stay stable across platforms and match the old Java reference |
| `epochDay`, `visibleStreak`, `completedStreak` | Local-calendar streak helpers (UTC day numbers) |
Cell encoding across the app:
- Session/UI cells: `0` empty, `1` lit, `2` crossed out. `Game.mark` cycles through them; `given` cells are pre-marked and immutable; a solved board locks.
- Solver cells: `-1` unknown, `0` dark, `1` lit (`applyHint` maps between encodings).
Content pipelines:
- **Campaign:** `Book.load()` parses `assets/campaign.json` → `CampaignLevel.puzzle()` builds `Puzzle(size, picture)` (default size 7) and applies `clues` (forced-given indices) and `areas` (`top,left,height,width` rectangles labelled A, B, C…).
- **Daily:** fixed board per local calendar day (`Puzzle.seeded(epochDay * 7919)`), progress keyed by date.
- **Classic:** deterministic practice board per difficulty and level (`1000000 + level` seed), generated on an isolate.
## Thinking-depth authoring tool
- `lib/domain/thinking.dart` is pure Dart and is not wired into gameplay, hint pricing, generation or saved progress. `ThinkingAnalyzer(cellCount, constraints).analyze(initial)` receives visible constraints and solver-encoded marks, never an answer picture.
- All direct deductions in a wave use the same snapshot. Only after direct waves stall are two-clue overlap comparisons used; comparisons are exhausted before bounded contradiction lookahead. The trace distinguishes long write-down chains from simultaneous hypothetical assumptions.
- On an ordinary-rule stall a bounded solution counter classifies inconsistent or non-unique boards; its answer search never supplies deduction marks. `lookaheadDepth` is null unless the complete model path succeeds. Depth and node limits produce explicit unresolved statuses rather than claiming a human must guess.
- `tool/analyze_puzzles.dart` loads campaign records without Flutter assets/Book, or uses the existing daily/practice generator. It writes a compact table, Markdown reports and full JSON proofs. `--input` accepts generic constraints/partial marks. See [THINKING_DEPTH.md](THINKING_DEPTH.md) for encodings, strategy, limits and interpretation.
- `test/thinking_test.dart` covers clue-order invariance, one- and two-level lookahead, exact small-system enumeration, partial/invalid boards, budget handling and all campaign traces. Answer-bearing test fixtures are never passed into the analyzer itself.
## UI, layout and rendering rules
- All visible handwriting uses `hand(size)` (`MaraHand` → Dancing Script). Colours live in `lib/ui/paper.dart`: `ink` `#36413c`, `blue` `#274956`, `muted` `#796b55`, `cream` `#f3e7cc`, `amber` `#e0b568`.
- `writing()` adds paper spacing; `folio()` is the small blue label above a leaf's content.
- The home folio stays above the scroll viewport so its lettering remains fully visible during scrolling; the title, illustrations and actions scroll below it. Home is keyed by story ID, so selecting a different story opens at its cover instead of retaining the preceding book’s home scroll offset.
- `InkButton` is the only button style: transparent, underlined ink text, minimum 48 px touch target, optional `primary` emphasis, wrapped in `PageSwipeBlocker`.
### Paper and leaves
- `Paper` draws `assets/artwork/mara-single-page-v2.png` (1024×1536). Portrait scales to fit both dimensions; landscape scales to width, so the sheet is cropped vertically.
- Content area: portrait `x 11%–83%`, `y 12%–91%` of the sheet (8%–91% when narrower than 480 px); landscape `x 10%–83%`, `y 6%–94%` of the viewport.
- A page turns when a horizontal drag ends with `|dx| ≥ 48` and `|dx| > 1.3·|dy|`. `PageSwipeBlocker` installs a descendant horizontal recogniser so grid/button drags never reach the page; taps and vertical drags still pass through.
- `Leaf` is the standard page body: a scrolling column in portrait, and `wideBody` in landscape when supplied. The footer stays pinned. Scroll keys are `leaf-scroll` (portrait) and `leaf-side-scroll` (landscape side column). These are ordinary value keys: opening or revisiting a leaf always starts at the top, without restoring a saved scroll offset. Both panes include top padding for handwriting ascenders.
- `Cover` is the tappable notebook cover on the home screen. `Sketch` draws pencil props (`match`, `envelope`).
### Puzzle board
- `Board(puzzle, cells, onMark, selectedArea, won, maxWidth)` renders a square grid with row/column clues, fixed-clue dots, region highlight and per-cell `ValueKey('cell-<i>')`.
- `maxWidth` defaults to 350 (portrait). On wide leaves it is passed the available square; the clue unit is `u = boardWidth / (size + 1.3)` and clue text is clamped to 16–23 px.
- Each cell has a semantic label such as `Row 3, column 5, lit, fixed clue`; the whole board is wrapped in `PageSwipeBlocker`.
- `PixelPicture` shows the recovered 7×7 object when artwork is unavailable. `PatternStamp` draws the exact same 49 solution cells without a frame.
- `Discovery` (`ui/discovery.dart`) holds the solution briefly, then crossfades into the watercolour over 2.8 seconds. A small permanent stamp links the art to the solved symbol; an ink button replays the transition. Reduced-motion settings show the finished illustration and stamp immediately. Recovered grids are read-only and reconstructed from the solution if an old completed save lacks marks.
### Portrait versus landscape composition
- Portrait `game()`: a single scrolling column — heading, `puzzleBody()` (area totals, board, caption, undo/hint), win text, and actions.
- Landscape `game()`: `splitPuzzle()` puts the board in its own column and the heading, area totals, notes, hint/undo in a side column; a compact action bar (`How to play`, `Back to notebook`, plus the primary win action) sits below both.
- Landscape puzzle leaf (story page 3): same `splitPuzzle` columns with the leaf navigation pinned below.
- `splitPuzzle` sizing (content width `w`, height `h`): usable width `min(w, 980)`, side panel `min(min(280, max(200, 0.40·usable)), 0.55·usable)`, board `min(min(h, usable − panel − 18), 520)`. The board is always square and is centred; the side column scrolls when text is large.
- `navigation()` uses one row of five buttons in landscape and two rows in portrait.
## Story library and localization
See [Story packages and translations](STORY_PACKAGES.md) for the authoring schema and a complete recipe.
- `StoryLibrary` reads `assets/library.json` and caches books by stable story ID and resolved language. `Book.loadDefinition()` merges only display fields from locale overlays, validates IDs/references/grid shapes, and derives chapters from stable `chapterId` values.
- `Game.selectStory()` cancels old puzzle work and restores that story's route/marks; `selectLanguage()` replaces localized content without replacing the live grid or undo stack. `Game.showLibrary()` opens the bookshelf, which is the app's first window; `bookCard`/`shelfBooks` load every book once per requested language, and a broken package is skipped so the rest of the shelf stays usable. The shelf is responsive: dense single-column cards below 480 logical pixels, a two-column grid from 720 px, and a centred column capped at 860 px; Settings scrolls with the books. The language picker is reachable from the shelf's Settings and from a book's home; language is also available while reading.
- `LumenApp` rebuilds its locale/theme and `CopyScope` from `Game`. Flutter localization delegates handle standard controls and RTL direction. `CopyText` translates UI messages separately from authored passages, which `reading()` displays directly. The board explicitly remains LTR so its spatial solution does not change with language.
- Mara's special note/inspection pages live in `lib/ui/mara_story.dart`; `standardStory()` supports new packages without Mara-specific assumptions. Existing ambience scenes apply only to Mara.
- Languages resolve exact tag → base language → original story language; individual missing fields also use original text. Translated books only use explicitly supplied locale narration manifests, so English recordings do not automatically play over translated text.
- The shipped Paper Boat package demonstrates English/German content; Mara's story text is still English. `assets/stories/midnight-invitation/` adds the complete Halloween story with its own narrated English content and original generated artwork. Both English and German app UI catalogues are bundled.
## Persistence key map
`selected_story` and `language` (`system` or a locale tag) are global device preferences. New story-local keys below are stored under `story/<story-id>/`; Mara retains the original unprefixed keys for compatibility. Puzzle identity uses `Book.puzzleKey()` (legacy `story_v1_<index>` for Mara; `story_<story-id>_<puzzle-id>` for other stories). Language is never part of a save key. Daily/practice records, device settings and the total solved counter remain global.
All writes go through `Progress.set` (memory is updated synchronously, disk is written in order; `flushed` awaits the queue). There is no migration from the legacy Java `lumen.xml`.
### Routing and session restore
| Key | Type | Written by | Purpose |
| --- | --- | --- | --- |
| `flutter_screen` | String | `Game._route` | Screen name restored by `Game.restore()` |
| `flutter_campaign` | int | `_route` | Current campaign index |
| `flutter_mode` | String | `_route` | `daily` / `classic` / `campaign` |
| `flutter_date` | ISO String | `_route` | Daily board date |
| `flutter_level` | int | `_route` | Classic level |
| `flutter_read_ahead` | bool | `_route` | Marks a reveal opened before solving; restored as read-ahead |
### Notebook leaves
| Key | Type | Written by | Purpose |
| --- | --- | --- | --- |
| `notebook_last_page` | page id | `Game.showStory` | Resume the last cottage leaf |
| `notebook_contents_chapter` | chapter index | `Game.contents` | Restored chapter contents leaf |
| `notebook_manual_bookmark` | page id | `bookmark()` | "Return to my ribbon bookmark" in Contents |
| `notebook_note_open` | bool | folded-note leaf | Note unfolded/folded state |
| `notebook_handle_seen` | bool | `inspect()` | Repair margin note read; never reveals pre-puzzle artwork |
| `notebook_read_ahead` | bool | `turn()` | Written when leaving the unsolved story puzzle; currently no reader |
| `viewed_<pageId>` | bool | `Game.showStory` | Written per visited leaf; currently no reader |
### Advertising
| Key | Type | Written by | Purpose |
| --- | --- | --- | --- |
| `ad_age_group_v1` | String | age-group dialog | `under13` / `teen` / `adult` / `unknown`; Under 13 and unknown never initialize the ad SDK, teens use child-directed treatment and adults standard treatment |
### Puzzle progress and awards
| Key | Type | Written by | Purpose |
| --- | --- | --- | --- |
| `difficulty` | String | `selectDifficulty` | `EASY` / `MEDIUM` / `HARD` |
| `level_<DIFFICULTY>` | int | classic completion | Next practice level per difficulty |
| `practiceCompleted` | int | classic completion | Drives an interstitial every fourth completion |
| `grid_<key>` | digit string | `Game._save` | Marks per board (`0` empty, `1` lit, `2` crossed) |
| `done_<key>` | bool | `Game.check` | Exactly-once completion and win lock |
| `solved` | int | `Game.check` | Lifetime completions |
| `hint_<key>` | legacy bool | no longer written | Old free-hint tracking is ignored; every hint now requires a separate earned ad reward |
| `lastDaily` | int (epoch day) | daily completion | Streak bookkeeping |
| `streak` | int | daily completion | Consecutive daily completions |
| `campaignUnlocked` | int 0–11 | campaign completion | Furthest solved campaign level |
| `story_access_level` | int 0–11 | `nextCampaign`, `leaveCottage` | Furthest readable campaign level; effective access is at least 3 for cottage exploration, independent of awards |
| `storyAd_<index>` | bool | `nextCampaign` | At most one interstitial at each completed chapter boundary |
| `ambience_enabled` | bool (default true) | Sound & atmosphere | Independent environmental audio switch, applies only within story pages |
| `ambience_volume` | double 0–1 (default 0.7) | Sound & atmosphere | Saved environmental volume, independent of narration speed |
| `recording_speed` | double | speed dialog | `0.85`, `1.0` or `1.15` |
Board key formats (`<key>`):
- Campaign and the opening story puzzle: `story_v1_<0..11>` — story page 3 and the first campaign entry (index 0) share `story_v1_0` deliberately.
- Daily: `d7_<YYYY-MM-DD>` based on the local date.
- Classic: `v3_<DIFFICULTY>_<level>`, e.g. `v3_MEDIUM_7`.
## Content and assets
- `assets/campaign.json`: `{ premise, levels: [{ chapter, title, object, before, after, picture, clues, areas, illustrationAsset?, beforeContinuation?, afterContinuation? }] }`. `picture` is 49 characters of `0`/`1` (7×7, row-major). `clues` is a comma-separated list of forced-given indices. `areas` is `top,left,height,width` rectangles separated by `;` (labels A, B, C… in order).
- `assets/notebook.json`: sixteen ordered records with stable `id`, `type`, `title`, optional `campaignIndex`, `speaker`, `illustrationAsset` and `textSource` (`recording`, `before`, `after`) or inline `text`, plus optional `continuation`. `Book.pageFor()` finds a campaign entry/puzzle/memory. Preserve the first six IDs when extending the chapter.
- Campaign `beforeContinuation`/`afterContinuation` add narrative after the original passage, with one audio control after the full text. Cottage entries/memories inherit these by text source; custom recording leaves can supply their own `continuation`. Recorded scripts include both parts. Recording-source leaves read `baseText` for the original displayed passage. The lighthouse rewrite uses continuations only to separate Mara’s letter from the present-day narrator on two leaves; its audio is regenerated in full, with no preserved PCM prefixes.
- Campaign balance: all area puzzles have at least seven initial single-clue deductions; solver comparison counts are capped at 3 for the key, 5 for the crossing chapter and 6 for the final chapter. These are regression bounds, not a substitute for player feedback. Every area puzzle still needs comparison and has a unique, no-guess solution.
- Cottage `briefing`, `startCampaign` and `reveal` route to the entry, puzzle or memory leaf for levels 0–3. This migrates older saved routes while retaining marks, hint keys and completion awards. Chapters II/III use the existing screens.
- `assets/narration/scripts.json`: canonical complete diary text, one record per recorded page (`pageId`, `text`, optional `baseText`, `continuation`, `continuationSpeaker`). `Book.load()` resolves `recording` base text by stable page ID; a missing script yields empty text.
- `assets/narration/manifest.json`: source masters, text hashes, WAV/FLAC hashes and cues — the provenance record.
- `assets/audio/narration_manifest.json`: runtime `{ tracks: { pageId: { file, durationMs, cues: [{ startMs, endMs, text }] } } }`. `Narrator` plays `assets/audio/<file>`.
- Five Mara recordings exist: `cottage.dedication`, `cottage.window`, `cottage.match.memory`, `cottage.folded.note`, `cottage.lantern.sketch`. The match-puzzle leaf has no recording.
- `tool/compile_mara_story.py` compiles `assets/narration/STORY.md` into all 28 scripts and displayed prose. `cast.json` defines Mara and the narrator; `performance.json` pins Qwen VoiceDesign and its scene directions. `scripts/render_qwen_narration.py --story-root assets --flac-dir assets/audio` stages or publishes complete recordings. Twenty-three readings lead with the narrator, switching to Mara for her dialogue. The asset checker validates displayed text, cast, actual model instructions, cue coverage and lossless archives.
- `audio()` follows the current cue speaker, including the switch from Mara to the narrator on the window/match memory pages. Both letter and present-day paragraphs use cue highlighting.
- `audio()` uses the story ID or `campaign.<index>.before/after`, with a visible speaker label. Never show a recording control for an ID without a bundled track.
- `discoveryArt()` returns only a text placeholder until `Game.recovered(index)` is true. This gates both watercolours and pixel fallbacks; entry, inspection and closing leaves never call it, regardless of completed progress. The helper also rejects calls outside a memory/reveal screen. The repair note uses a text action rather than a picture hotspot; completed saves must not re-enable artwork on earlier leaves. Contextual cottage/background art is separate from the discovery images.
- The `check` Android flavor (`com.lumen.daily.check`) isolates device automation from the user’s installed QA app and progress.
- WAV is the runtime format because FLAC advanced its clock without an audio track on the API 26 Huawei tablet used for testing. FLAC files remain as archives but are not listed in `pubspec.yaml`, so they are not bundled.
- Artwork: `mara-single-page-v2.png` (page), `home-harbour-v2.png`, `home-notebook-cover-v2.png`, `cottage-vignette-v1.png`, `lantern-vignette-v1.png`, `harbour-bell-vignette-v1.png`, plus `match`, `brass-key`, `compass`, `little-boat`, `anchor`, `stone-bridge`, `missing-gear`, `beacon-lens`, `lighthouse` and `home` (each `<name>-vignette-v1.png`); prompts and provenance live beside each file.
- Campaign reveals use optional `CampaignLevel.illustrationAsset` paths from campaign JSON. All twelve discoveries have watercolours; absent or unloadable image assets fall back to `PixelPicture`. The opening match memory shares the first campaign illustration through `discoveryArt()`. No puzzle identity or progress keys change.
- Font: `assets/fonts/DancingScript.ttf` registered as `MaraHand`; `assets/fonts/OFL.txt` is registered with `LicenseRegistry` in `main()`.
- `android/app/src/qa/AndroidManifest.xml` opts the isolated QA package into external installation (`preferExternal`); the production manifest keeps its existing installation policy. Android/OEM support still determines whether an SD-card install is accepted. The review Huawei reports `sm has-adoptable=false` and rejects new ASEC installs; use a compact release build installed internally there.
- `pubspec.yaml` registers individual legacy assets and story/UI directories. Directory declarations are not recursive: add each new subdirectory explicitly.
### Audio flow
- `Narrator.scheduleAutoplay(id, speed)` owns one 3-second timer. `_scheduleAutoplay()` in the notebook calls it on initial entry, page changes and unfolding a note. Only story/briefing/reveal screens with a bundled track qualify; folded notes and puzzles are silent. Manual play/pause/stop, leaving the page, backgrounding and disposal cancel the timer. Returning from the background does not restart a paused/stopped reading. Sound settings cancel a pending start too.
- `Narrator` wraps one `AudioPlayer` plus `audio_session` (speech configuration). `toggle(id, speed)` loads the track, seeks when finished, sets speed and plays; `pause`/`stop` are idempotent.
- `label`, `status` and `passage` drive the `audio()` row; `passage` is highlighted inside the leaf text by `reading(text)` using cue timings.
- Narration stops on route change and when the app backgrounds; the player is disposed with `Notebook`.
- Playback failures surface as reader-friendly text and never block reading.
### Environmental audio
- `Ambience` owns a separate looping player. `soundscapeFor(index)` maps cottage/home to cottage air, boat/anchor/bell to harbour water, bridge to flowing water and tower discoveries to wind. Home, contents, daily and practice screens are silent.
- `_syncAtmosphere()` follows navigation, narration and app lifecycle. Story ambience defaults on and resumes on foregrounding; narration starts 3 seconds after opening a narrated page. Muting/backgrounding stops it; scene transitions and volume changes fade over 240 ms.
- Environmental gain is `0.4 × saved volume`, reduced to one quarter while narration plays or loads. Both players share the speech audio session; the environmental player disables automatic session activation to avoid competing with narration. Audio interruptions/headphone removal use just_audio interruption handling.
- A serial queue and revision guard discard stale requests while loading/fading. Missing soundscapes never block narration or puzzles. `AmbienceOutput` allows race, fade, failure and lifecycle tests without a device backend.
- `scripts/render_ambience.py` deterministically renders four original 24-second PCM16/24 kHz loops offline. `assets/audio/ambience_manifest.json` records seeds/checksums. `scripts/check_soundscape_assets.py` checks bundling, PCM format, levels and loop boundaries.
### Ads and consent flow
- `Ads.supported` is false on the web, when `enabled`/`adsEnabled` is false (both test suites pass `adsEnabled: false`) and on platforms other than Android/iOS.
- `start()` requests UMP consent, shows the form if required, then initialises the SDK and preloads one rewarded and one interstitial ad.
- Hint flow: every hint in campaign, daily and classic requires explicit confirmation and `ads.hint(give)`, including the first hint. The grid changes only in the reward callback; a local guard permits at most one hint per rewarded ad. Late callbacks check the active puzzle key and route. `Notebook.ads` permits deterministic reward/cancel/no-fill tests without bypassing the production gate. If no ad is available the user sees "No ad available. Please try again later." and no hint is consumed.
- Interstitials: `nextPractice()` after every fourth classic completion; `nextCampaign()` at most once at a completed chapter boundary (`storyAd_<index>`). `between(next)` always calls `next()` if ads are unavailable, stale (≥58 min) or unconsented.
- `privacy()` opens the privacy options form only when UMP requires it; otherwise `main.dart` shows the local privacy explanation.
- Ad unit IDs default to Google test IDs; production overrides come from `ADMOB_APP_ID` (Gradle), `ADMOB_REWARDED_ID` and `ADMOB_INTERSTITIAL_ID` (Dart defines).
## Tests and verification
| File | Covers |
| --- | --- |
| `test/thinking_test.dart` | Snapshot-wave invariance, 1/2-level contradiction proofs, exhaustive checks of 200 small systems, partial/invalid boards, search limits and all campaign traces |
| `test/narration_autoplay_test.dart` | Exact 3-second delay, one start per visit, cancellation/replacement, recorded-page eligibility, unfolding notes and backgrounding |
| `integration_test/autoplay_test.dart` | Real-device delayed playback of bundled WAVs, cancellation when entering a puzzle and Stop preventing restart |
| `test/ambience_test.dart` | Scene mapping, voice ducking, mute/background stop, stale loading requests, backend failure/recovery and disposal |
| `integration_test/soundscape_test.dart` | Real-device decoding of all 24 new continuations, bridge/narration mixing, saved mute and automatic Mara-to-narrator handoff |
| `test/halloween_test.dart` | Complete Halloween structure, twelve unique/no-assumption puzzles, all prose/audio/image assets, read-ahead, independent saves and exactly-once completion |
| `test/halloween_widget_test.dart` | All 38 Halloween leaves at 1.5× text in both orientations, gated discovery artwork and bookmarks from later chapters |
| `integration_test/halloween_test.dart` | Complete on-device Halloween flow, all 26 native WAV decodes, play/pause/resume, twelve discoveries, read-ahead, bookmarks and ending |
| `test/library_test.dart` | All registered packages/locales, unique puzzles, identity-safe overlays, fallback/audio, independent story saves, live language switching, variable chapters, UI placeholders and invalid content |
| `test/library_widget_test.dart` | Bookshelf as the app's first window (all books listed and one opened), actual library/language controls, translated metadata, German at larger text in both orientations, Arabic RTL/font behavior |
| `test/puzzle_test.dart` | 40 Java reference boards (signed 64-bit seeds), 300 graded boards, solver counts vs. exhaustive search, campaign uniqueness/no-guess, streaks, fresh progress, read-ahead, daily awards and practice levels |
| `test/ad_audience_test.dart` | Age-group mapping, fail-closed stored values, no ad requests for Under 13/unknown, every dialog option and first-launch persistence |
| `test/widget_test.dart` | Pattern-to-art timing/replay, back-to-solved-grid navigation, rewarded hints in all modes, declined/unavailable ads and duplicate/stale callbacks, page swipes vs. grid drags, swipes over text/blank paper, vertical scrolling and cancelled drags, small/landscape/1.5× text, landscape two-column puzzle leaf, illustrated campaign reveals and pixel fallback at 1.5× text |
| `integration_test/library_test.dart` | Isolated on-device bookshelf start, English/German switching, shared marks/bookmark/undo, story isolation, read-ahead and exactly-once completion; five screenshots |
| `integration_test/notebook_test.dart` | On-device QA flow: six leaves, real WAV playback and pause/resume, bookmarks/discoveries, match and lantern solves, exactly-once awards, QA disk round-trip, screenshots |
| `integration_test/cottage_test.dart` | All sixteen leaves, larger-text portrait/landscape, bookmarks, legacy-key marks, all four awards, all 23 narrator tracks and isolated test persistence; eight screenshots |
| `integration_test/discovery_art_test.dart` | QA tablet screenshots of all twelve discoveries and the opening match memory, portrait/landscape at 1.5× text; checks reachable controls and unchanged awards |
| `tool/shelf_screenshots_test.dart` | Renders the bookshelf at phone (360×640, 390×844, 1.5× text) and tablet (800×1280, 1280×800) metrics, asserts every card and Settings stay reachable without overflow, and writes `artifacts/library/shelf-*.png` |
| `tool/capture_play_store_test.dart` | Renders five 1080×1920 Play Store phone screenshots from the real app at a 360×640 viewport and 3× output |
| `scripts/build_android_release.sh` | Guarded production AAB build; requires real AdMob IDs and upload signing and refuses Google sample IDs |
| `scripts/check_story_package.py` | Independent story script/cue/audio/master/archive and illustration validation |
| `scripts/check_narration_assets.py` | Script text ↔ manifest ↔ WAV masters checksums |
| `scripts/check_flutter_install.py` | Read-only installed-app smoke check and screenshots |
| `scripts/render_narration.py` | Renders the fixed WAV masters and FLAC archives; the app never synthesises speech |
Commands:
```sh
flutter pub get
flutter analyze
flutter test
python3 scripts/check_narration_assets.py
python3 scripts/check_soundscape_assets.py
# QA APK for isolated on-device checks (package com.lumen.daily.qa)
flutter build apk --debug --flavor qa
# Real-device integration test (requires the QA flavour and the define)
flutter drive --driver test_driver/integration_test.dart \
--target integration_test/notebook_test.dart --flavor qa \
--dart-define=QA_TEST=true -d YOUR_ANDROID_DEVICE
```
Artwork QA uses one chapter per run to keep full-resolution screenshot exports within tablet memory limits. Run the following with `ART_CHAPTER=0`, `1` and `2` (zero-based chapters):
```sh
flutter drive --driver test_driver/integration_test.dart \
--target integration_test/discovery_art_test.dart --flavor qa \
--dart-define=QA_TEST=true --dart-define=ART_CHAPTER=0 -d YOUR_ANDROID_DEVICE
```
Each run checks four discoveries in both orientations at 1.5× text, including navigation after scrolling. Chapter 0 also captures the opening match memory. Screenshots go to `artifacts/flutter-check/`.
## Conventions and invariants
1. **One state owner.** Navigation, the active puzzle and awards live in `Game`. Screens are pure builders in `_NotebookState`; UI-only toggles (e.g. folding the note) use `setState` after persisting the preference.
2. **Persist through `Progress`.** Never call `SharedPreferences` from widgets or domain code. New keys belong in the table above.
3. **Awards are exactly once.** `check()` returns early when `won` and writes `done_<key>`; never award in UI code.
4. **Reading access ≠ completion.** `story_access_level` controls what can be read; `campaignUnlocked`/`done_*` control awards.
5. **Board identity is the key.** `story_v1_0` is shared by story page 3 and campaign level 1; the daily key contains the date; classic keys contain difficulty and level. Changing key formats invalidates saved boards.
6. **Gesture isolation.** Anything interactive that must not turn a page is wrapped in `PageSwipeBlocker` (`Board`, `InkButton`). Vertical drags must still reach scroll views. Page turns happen only in `Paper` with a ≥48 px horizontal drag that is 1.3× more horizontal than vertical.
7. **Landscape is additive.** Portrait keeps the original scrolling column; landscape supplies `Leaf.wideBody` and, for the game screen, a bottom action bar. Do not fork puzzle logic between layouts — build both from `areaPicker`, `board` and `puzzleNotes`.
8. **Typography and colour.** Use `hand()`/`writing()` and the palette in `lib/ui/paper.dart`; do not hardcode fonts or new colours.
9. **Domain stays headless.** `lib/domain` may not import Material widgets or `Game`; keep it testable with plain Dart.
10. **Offline only.** No network calls, analytics, accounts or remote content; all assets must be bundled and listed in `pubspec.yaml`.
11. **Ads never block.** `Ads.between` always calls its continuation; a missing reward ad shows a toast and leaves the board untouched.
12. **Stop audio on navigation and background.** `_changed` and `didChangeAppLifecycleState` stop the narrator; flush pending preference writes when backgrounding.
13. **Formatting.** The repo uses the current tall-style `dart format`; run it on changed files. `flutter analyze` must stay clean.
14. **Never edit `legacy/`.** It is archived Java, excluded from analysis and builds.
## Where to change what
| Goal | Touch | Also |
| --- | --- | --- |
| Add a story or translation | `assets/library.json`, new package/locale files, `pubspec.yaml` | Follow `docs/STORY_PACKAGES.md`; run library/domain/widget tests |
| Edit campaign content or pictures | `assets/campaign.json` | Re-run `flutter test` (uniqueness/no-guess campaign tests) and `scripts/check_narration_assets.py` only if text changes |
| Add or reorder cottage leaves | `assets/notebook.json`, `StoryPageType` builders, `Book.pageFor()`, narration scripts if recorded | Add a WAV + manifests + `pubspec.yaml` if narrated; update integration test |
| Add a screen | `Screen` enum, `Game._route`/navigation method, `_NotebookState.build` switch, new builder | Back-button behaviour in `back()` and `PopScope` |
| Change puzzle rules, hints or grading | `lib/domain/puzzle.dart` (`Constraint`, `LogicSolver`, `Puzzle`) | `test/puzzle_test.dart`, `Game.applyHint`, board semantics |
| Change marks, undo, hints or awards | `lib/domain/game.dart` (`mark`, `undo`, `applyHint`, `check`) | `_NotebookState.hint()`, `puzzleNotes()`, widget tests |
| Change persistence or resume | `Progress` usage in `game.dart`/`main.dart` | This map's key table; `Game.restore()` |
| Adjust ads or consent | `lib/services/ads.dart`, `_NotebookState.hint/nextPractice/nextCampaign` | Gradle property `ADMOB_APP_ID`, Dart defines for unit IDs |
| Restyle paper, buttons or typography | `lib/ui/paper.dart` | Screen builders use `writing`/`action`/`folio` |
| Change grid rendering | `lib/ui/board.dart` | Cell keys `cell-<i>` and semantics are used by tests |
| Rework landscape layout | `Leaf.wideBody`, `splitPuzzle`, `game()` wide body | `test/widget_test.dart` landscape test; verify on a device |
| Add narration | `scripts/render_narration.py`, `assets/narration/*`, `assets/audio/*.wav`, `pubspec.yaml` | `scripts/check_narration_assets.py` must pass |
## Gotchas and fragile areas
- **Widget tests use a test font.** Glyphs render as squares, so text wraps far more than Dancing Script. Use geometry assertions and, for visual work, load the real font with `FontLoader('MaraHand')` or check on the device before trusting a layout.
- **`pumpAndSettle` can struggle with the full app.** Prefer a bounded `pump()` loop when mounting `LumenApp`; the audio streams keep notifying and may prevent settling.
- **`Game.restore()` must be awaited before `runApp`.** The shelf is shown first, but selecting a book calls `restore()`; without that route data the book opens on `home` and ignores its saved screen.
- **Story page 3 is index 2.** Solving the opening match puzzle awards the first campaign entry (`story_v1_0`) and jumps to story page 4 (`showStory(3)`), skipping the campaign reveal.
- **`showStory()` sets campaign mode and the page record’s campaign index (0 if absent).** Daily and classic starts set their own mode afterwards; keep that order.
- **`startPractice` discards stale results** with `_request`. Do not remove that guard when refactoring.
- **Hints are applied immediately.** `Game.applyHint()` writes a mark and pushes an undo snapshot; the rewarded-ad gate lives in `_NotebookState.hint()`, not in the domain.
- **Read-ahead never bypasses access.** `reveal(i, readAhead: true)` still redirects when `i > accessible`.
- **Streaks use UTC epoch days.** Do not compare local `DateTime` values directly; `visibleStreak` drops to zero when the last completion is older than yesterday.
- **`Puzzle.deductionRounds` throws** if a board cannot be solved by singles (plus area comparisons). Generation and tests assume no guessing.
- **Generated boards are 7×7 without regions.** Authored campaign boards can have A/B/C areas. Legacy 5×5 save keys are retained but their marks are not mapped onto new grids.
- **Landscape side columns scroll.** With very large text, notes or hint/undo can need scrolling; never shrink text to force a fit (see the root `ROADMAP.md`: keep vertical scrolling as the accessibility fallback).
- **Gesture layering is deliberate.** `PageSwipeBlocker` wins horizontal drags inside boards/buttons while letting vertical drags scroll. Adding another horizontal recogniser around a board can break page turns or mark gestures.
- **Ads are age-gated.** `AdAudience` stores only a broad local group; Under 13 and unknown-age players never initialize the ad SDK. Teens use child-directed treatment and adults standard treatment. `adsEnabled: false` in tests, `supported` guard in the service, and `between()` always routes even on no-fill.
- **Narration assets are checksum-locked.** `check_narration_assets.py` requires the scripts, manifests and WAV masters to agree; edit them together.
- **QA integration test fails without `--dart-define=QA_TEST=true`** and should run on the `qa` flavour (`com.lumen.daily.qa`).
- **`build/`, `artifacts/`, `.dart_tool/`, IDE state and signing keys are ignored.** Do not commit APKs or generated screenshots; upload-ready Play assets in `store/` are intentionally tracked, and `pubspec.lock` is tracked.
## Grep anchors
```sh
# Symbols and public surface
grep -rnE '^(class|enum|abstract|typedef) ' lib
# Module graph (verify the Mermaid diagram)
grep -rn '^import ' lib
# Screen routing
grep -n 'case Screen\.' lib/main.dart lib/domain/game.dart
# Persistence usage
grep -rnE "progress\.(set|number|text|flag|decimal)" lib
# Page-turn gesture and gesture isolation
grep -n 'onHorizontalDrag\|PageSwipeBlocker' lib/ui/paper.dart lib/ui/board.dart
# Widget-test hooks
grep -rn "ValueKey('cell-\|leaf-scroll\|leaf-side-scroll" lib test
```
## Maintaining this map
- Keep it in step with the root `README.md` (user-facing overview) and `ROADMAP.md` (product direction). This file is the only architecture/dependency map.
- Update the Mermaid graph when imports between layers change, when a screen is added, or when persistence keys or invariants change.
- Re-run `flutter analyze`, `flutter test` and `python3 scripts/check_narration_assets.py
python3 scripts/check_soundscape_assets.py` after structural edits.
- The map is hand-maintained; no generator or CI check keeps it current, so treat drift as a bug.
_Last reviewed against version 2.0.3+12._
The cast diary audio system adds `lib/domain/soundscape.dart` (package-defined loops),
`narration/cast.json` and segmented scripts in the Halloween package, plus
`scripts/audio_drama.py` for offline cast validation/Foley. `Book.atmosphere`
binds stable page IDs to nonverbal loops independently of language. Native
cast/mixing coverage is in `integration_test/drama_test.dart`.
Halloween now uses `Book.paperAsset` through `PaperSkin` on all notebook pages.
`tool/compile_midnight_diary.py` compiles the first-person `STORY.md` manuscript
into stable content and cast scripts. `RegionButton` provides a filled selected
state; `Board` overlays a pointer-transparent frame around the selected region.
`test/region_selection_test.dart` verifies frame geometry, marking and book skins.
## Island postcard collection (November 2026)
`lib/domain/postcards.dart` contains fourteen original written scenes;
`postcard_patterns.dart` freezes their 42 independently validated boards.
`Game` exposes `Screen.postcards` and `Mode.postcard`, with global save keys
and exactly-once completion/break claims. `ui/postcards.dart` adds the shelf
activities and collection; `main.dart` uses the existing accessible puzzle
layout and a scrollable postcard reader. Global puzzle starts preserve book
reading routes. `services/ad_pacing.dart` persists full-screen spacing and a
six-per-day automatic cap. `services/play_metrics.dart` keeps local daily
activity and SDK revenue receipts, with currencies and test units separated.
QA/debug Settings can copy its JSON. There is no analytics upload or campaign
attribution. See [the operating guide](RETENTION_MONETIZATION.md).