# 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 — loads authored content
│ └── game.dart Game (ChangeNotifier), Screen/Mode, puzzle session, awards
├── services/
│ ├── progress.dart Progress — typed façade over SharedPreferencesAsync
│ ├── 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)
├── 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 five bundled PCM16 readings (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 8 domain tests (Java parity, generation, solver, awards, restore)
test/widget_test.dart 4 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
Paper · Leaf · Cover · Sketch
InkButton · PageSwipeBlocker"]
board["board.dart
Board · PencilMark · PixelPicture"]
end
main["main.dart
LumenApp · Notebook
six screen builders · dialogs"]
game["domain/game.dart
Game (ChangeNotifier)
Screen/Mode · session · awards"]
puzzle["domain/puzzle.dart
Puzzle · LogicSolver · JavaRandom · Difficulty"]
book["domain/book.dart
Book · CampaignLevel · StoryPage"]
progress["services/progress.dart
Progress — local key/value store"]
narrator["services/narrator.dart
Narrator — just_audio"]
ads["services/ads.dart
Ads — UMP consent + AdMob"]
main --> paper
main --> board
main --> game
main --> narrator
main --> ads
board --> puzzle
board --> paper
game --> puzzle
game --> book
game --> progress
book --> puzzle
book --> campaign[("assets/campaign.json")]
book --> scripts[("assets/narration/scripts.json")]
narrator --> manifest[("assets/audio/narration_manifest.json")]
narrator --> wav[("assets/audio/*.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 0..5
story --> contents: Contents
story --> home: Close book
story --> briefing: leaf 6 lantern link
contents --> story: opening leaf 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 or previous leaf
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-` | Six opening leaves: dedication, cottage, match puzzle, memory, folded note, lantern | `turn()` |
| `contents` | `contents()` | `contents` | Dedication, opening-leaf links, ribbon bookmark, twelve campaign entries with access state, premise | none |
| `briefing` | `briefing()` | `briefing-` | Chapter, title, `before` passage, "Restore the pattern →" | `turnCampaign()` |
| `game` | `game()` | `game-` | Puzzle heading, area totals, square board, hint/undo, actions | `turnCampaign()` in campaign mode only |
| `reveal` | `reveal()` | `reveal-` | Object name, `PixelPicture`, `after` passage, 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 0–5, `mode = campaign`, `campaignIndex = 0`; on `i == 2` load `book.levels[0]` under key `story_v1_0` unless already loaded; persist last page and `viewed_`; `Screen.story` |
| `contents()` | `Screen.contents` |
| `briefing(i)` | Clamp to `accessible`, `Screen.briefing` |
| `reveal(i, {readAhead})` | Redirect to `briefing(i)` unless recovered, or read-ahead is allowed for an accessible level; otherwise `Screen.reveal` |
| `startCampaign(i)` | No-op if `i > accessible`; recovered levels go to `reveal`; else load `book.levels[i]` under `story_v1_` and open `Screen.game` |
| `startDaily(day)` | Load `Puzzle.seeded(epochDay(date) * 7919)` under `d`; `Screen.game` |
| `startPractice([level])` | Generate 5×5 board off the UI isolate with `compute(generatePractice)`; key `v2__`; `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; campaign solve advances to story leaf 3 or 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-')`.
- `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 after a campaign solve.
### 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 opening 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()` | Lantern handle discovered |
| `notebook_read_ahead` | bool | `turn()` | Written when leaving the unsolved story puzzle; currently no reader |
| `viewed_` | 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_` | int | classic completion | Next practice level per difficulty |
| `practiceCompleted` | int | classic completion | Drives an interstitial every fourth completion |
| `grid_` | digit string | `Game._save` | Marks per board (`0` empty, `1` lit, `2` crossed) |
| `done_` | bool | `Game.check` | Exactly-once completion and win lock |
| `solved` | int | `Game.check` | Lifetime completions |
| `hint_` | bool | `hint()` | First explained hint is free; later ones need a rewarded ad |
| `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`, leaf 6 link | Furthest readable campaign level (independent of awards) |
| `storyAd_` | bool | `nextCampaign` | At most one interstitial per fourth campaign step |
| `recording_speed` | double | speed dialog | `0.85`, `1.0` or `1.15` |
Board key formats (``):
- 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` based on the local date.
- Classic: `v2__`, e.g. `v2_MEDIUM_7`.
## Content and assets
- `assets/campaign.json`: `{ premise, levels: [{ chapter, title, object, before, after, picture, clues, areas }] }`. `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/narration/scripts.json`: canonical diary text, one record per recorded page (`pageId`, `text`). `Book.load()` matches the six fixed page ids and titles; 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/`.
- Five recordings exist: `cottage.dedication`, `cottage.window`, `cottage.match.memory`, `cottage.folded.note`, `cottage.lantern.sketch`. The match-puzzle leaf has no recording.
- 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`; prompts and provenance live beside each file.
- Font: `assets/fonts/DancingScript.ttf` registered as `MaraHand`; `assets/fonts/OFL.txt` is registered with `LicenseRegistry` in `main()`.
- `pubspec.yaml` lists every bundled asset explicitly (no directory globs), so new assets must be added there.
### Audio flow
- `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.
### 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: the first hint per board is free (`hint_`), 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_`). `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/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` | 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 |
| `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 |
| `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
# 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
```
## 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_`; 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 opening leaves | `_NotebookState.story()` switch, `Book` page ids/titles, `assets/narration/scripts.json` | 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-` 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()` resets `mode` to campaign and `campaignIndex` to 0.** 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_`, 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` 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._