Files
logic-puzzle/docs/CODE_MAP.md
T
2026-11-02 05:35:14 +01:00

492 lines
42 KiB
Markdown
Raw 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.2+11).
- **Stack:** Flutter 3.47.5 / Dart 3.13.4, Material widgets, no backend and no account.
- **Entry point:** `main()` in `lib/main.dart` → `Book.load()` + `Progress.load()` → `Game(...)` → `await game.restore()` → `runApp(LumenApp(game: game))`.
- **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 { home, story, contents, briefing, game, reveal }`, rendered by six builder methods in `_NotebookState`.
- **Puzzle content:** twelve authored 7×7 pictures in `assets/campaign.json`; daily and classic boards are generated 5×5 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
│ ├── book.dart Book, CampaignLevel, StoryPage/StoryPageType — loads authored content
│ └── game.dart Game (ChangeNotifier), Screen/Mode, puzzle session, awards
├── services/
│ ├── 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
│ └── ads.dart Ads — UMP consent, rewarded hints, interstitials
└── ui/
├── paper.dart Paper, Leaf, Cover, Sketch, InkButton, PageSwipeBlocker
└── board.dart Board, PencilMark painter, PixelPicture
assets/
├── 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/>six screen builders · dialogs"]
game["domain/game.dart<br/>Game (ChangeNotifier)<br/>Screen/Mode · session · awards"]
puzzle["domain/puzzle.dart<br/>Puzzle · LogicSolver · JavaRandom · Difficulty"]
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
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, loads `Book` and `Progress`, constructs `Game`, awaits `game.restore()`, 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()` stops narration when the route string (`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` |
| --- | --- | --- | --- | --- |
| `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 |
| --- | --- |
| `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 four entries; 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.seeded(epochDay(date) * 7919)` under `d<YYYY-MM-DD>`; `Screen.game` |
| `startPractice([level])` | Generate 5×5 board off the UI isolate with `compute(generatePractice)`; key `v2_<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:** `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(7, picture)` 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.
## 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.
- `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).
- `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.
## Persistence key map
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` | int 0–2 | `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 |
### 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>` | bool | `hint()` | Tracks hint use; daily/classic later hints need a rewarded ad, campaign hints stay free |
| `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 per fourth campaign step |
| `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: `d<YYYY-MM-DD>` based on the local date.
- Classic: `v2_<DIFFICULTY>_<level>`, e.g. `v2_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. Every new continuation has narrator cues; the original take remains byte-identical as PCM and has its own prefix checksum in the manifest.
- 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.
- Twenty-three narrator tracks use `bm_george`: seven cottage prose leaves and `campaign.<4..11>.before/after`. `scripts.json` records speaker/voice/speed; the renderer accepts `--speaker Narrator` to preserve Mara’s original takes. `--append-continuations` appends only the narrator additions to existing PCM masters and records the original PCM frame count and checksum; use it when adding to existing recordings. The asset checker validates narrator scripts against notebook/campaign text.
- `audio()` follows the current cue speaker, including the switch from Mara to the narrator on the window/match memory pages. Both original and continuation 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` lists every bundled asset explicitly (no directory globs), so new assets must be added there.
### 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: campaign hints are always free and explained. Daily/classic boards keep the first-free policy (`hint_<key>`); later hints require confirmation and `ads.hint(give)`. 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 per fourth campaign step (`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/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/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/widget_test.dart` | Pattern-to-art timing/replay, back-to-solved-grid navigation, repeated free story hints, 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/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 |
| `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 |
| --- | --- | --- |
| 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`.** Otherwise the app opens on `home` and ignores the 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 free/ad gate lives in `_NotebookState.hint()` via `hint_<key>`, 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 5×5 without regions.** Only authored campaign boards are 7×7 with A/B/C areas; don't run region logic against generated puzzles.
- **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 optional by design.** `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 screenshots; `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.2+11._