37514da4c1
Document the architecture and dependency graph, module responsibilities, screen state machine, puzzle pipeline, UI and layout rules, persistence keys, assets, ads and audio flows, test map, invariants, change recipes and known gotchas in CODE_MAP.md. Link it from the README source map.
33 KiB
33 KiB
Code map — Lumen
Agent-oriented overview of the Flutter app. Read this before changing code. 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()inlib/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._NotebookStatelistens 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
SharedPreferencesAsyncbehindlib/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
lib/domain/game.dart— screens, modes, puzzle session, awards and persistence keys.lib/domain/puzzle.dart— puzzle model, generation, solver, hints and difficulty.lib/main.dart— screen builders plus gesture/dialog glue.lib/ui/paper.dartandlib/ui/board.dart— page layout, landscape split, grid rendering.lib/services/*— storage, narration and ads.assets/— campaign, narration scripts, audio manifest and artwork.
Repository tree (source only)
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
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"]
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"]
ads["services/ads.dart<br/>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 importsui/or Flutter widgets beyondfoundation/services(it is testable headlessly).ui/may importdomain/puzzle.dartfor the model, but neverGame,Progressormain.dart.services/are platform adapters; onlyprogress.dartis imported bydomain/game.dart.main.dartis 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, loadsBookandProgress, constructsGame, awaitsgame.restore(), then runsLumenApp.LumenAppis aMaterialAppwith seed colourblue(#274956), cream surface (#f3e7cc),fontFamily: 'MaraHand'andNotebookashome._NotebookStatecreates exactly oneNarrator(g.book.tracks)and oneAds(enabled: widget.adsEnabled), subscribes toGamewith_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;disposestops/disposes the narrator, disposes ads and removes listeners. PopScopeintercepts Android back: it pops only onhomewith nobusywork; otherwise it callsback().build()switches ong.screen; a full-screen overlay withCircularProgressIndicatorcovers the app whileg.busy(classic board generation).
Screens and state machine
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-<index> |
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-<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, 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_<pageId>; 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_<i> and open 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; 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 Constraints 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:
0empty,1lit,2crossed out.Game.markcycles through them;givencells are pre-marked and immutable; a solved board locks. - Solver cells:
-1unknown,0dark,1lit (applyHintmaps between encodings).
Content pipelines:
- Campaign:
Book.load()parsesassets/campaign.json→CampaignLevel.puzzle()buildsPuzzle(7, picture)and appliesclues(forced-given indices) andareas(top,left,height,widthrectangles 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 + levelseed), generated on an isolate.
UI, layout and rendering rules
- All visible handwriting uses
hand(size)(MaraHand→ Dancing Script). Colours live inlib/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.InkButtonis the only button style: transparent, underlined ink text, minimum 48 px touch target, optionalprimaryemphasis, wrapped inPageSwipeBlocker.
Paper and leaves
Paperdrawsassets/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); landscapex 10%–83%,y 6%–94%of the viewport. - A page turns when a horizontal drag ends with
|dx| ≥ 48and|dx| > 1.3·|dy|.PageSwipeBlockerinstalls a descendant horizontal recogniser so grid/button drags never reach the page; taps and vertical drags still pass through. Leafis the standard page body: a scrolling column in portrait, andwideBodyin landscape when supplied. The footer stays pinned. Scroll keys areleaf-scroll(portrait) andleaf-side-scroll(landscape side column).Coveris the tappable notebook cover on the home screen.Sketchdraws 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-cellValueKey('cell-<i>').maxWidthdefaults to 350 (portrait). On wide leaves it is passed the available square; the clue unit isu = 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 inPageSwipeBlocker. PixelPictureshows 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
splitPuzzlecolumns with the leaf navigation pinned below. splitPuzzlesizing (content widthw, heighth): usable widthmin(w, 980), side panelmin(min(280, max(200, 0.40·usable)), 0.55·usable), boardmin(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_<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() |
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_<index> |
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 (<key>):
- Campaign and the opening story puzzle:
story_v1_<0..11>— story page 3 and the first campaign entry (index 0) sharestory_v1_0deliberately. - 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 }] }.pictureis 49 characters of0/1(7×7, row-major).cluesis a comma-separated list of forced-given indices.areasistop,left,height,widthrectangles 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 }] } } }.Narratorplaysassets/audio/<file>.- 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.ttfregistered asMaraHand;assets/fonts/OFL.txtis registered withLicenseRegistryinmain(). pubspec.yamllists every bundled asset explicitly (no directory globs), so new assets must be added there.
Audio flow
Narratorwraps oneAudioPlayerplusaudio_session(speech configuration).toggle(id, speed)loads the track, seeks when finished, sets speed and plays;pause/stopare idempotent.label,statusandpassagedrive theaudio()row;passageis highlighted inside the leaf text byreading(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.supportedis false on the web, whenenabled/adsEnabledis false (both test suites passadsEnabled: 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_<key>), later hints require confirmation andads.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 callsnext()if ads are unavailable, stale (≥58 min) or unconsented. privacy()opens the privacy options form only when UMP requires it; otherwisemain.dartshows the local privacy explanation.- Ad unit IDs default to Google test IDs; production overrides come from
ADMOB_APP_ID(Gradle),ADMOB_REWARDED_IDandADMOB_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:
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
- 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) usesetStateafter persisting the preference. - Persist through
Progress. Never callSharedPreferencesfrom widgets or domain code. New keys belong in the table above. - Awards are exactly once.
check()returns early whenwonand writesdone_<key>; never award in UI code. - Reading access ≠ completion.
story_access_levelcontrols what can be read;campaignUnlocked/done_*control awards. - Board identity is the key.
story_v1_0is 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. - 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 inPaperwith a ≥48 px horizontal drag that is 1.3× more horizontal than vertical. - Landscape is additive. Portrait keeps the original scrolling column; landscape supplies
Leaf.wideBodyand, for the game screen, a bottom action bar. Do not fork puzzle logic between layouts — build both fromareaPicker,boardandpuzzleNotes. - Typography and colour. Use
hand()/writing()and the palette inlib/ui/paper.dart; do not hardcode fonts or new colours. - Domain stays headless.
lib/domainmay not import Material widgets orGame; keep it testable with plain Dart. - Offline only. No network calls, analytics, accounts or remote content; all assets must be bundled and listed in
pubspec.yaml. - Ads never block.
Ads.betweenalways calls its continuation; a missing reward ad shows a toast and leaves the board untouched. - Stop audio on navigation and background.
_changedanddidChangeAppLifecycleStatestop the narrator; flush pending preference writes when backgrounding. - Formatting. The repo uses the current tall-style
dart format; run it on changed files.flutter analyzemust stay clean. - 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-<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. pumpAndSettlecan struggle with the full app. Prefer a boundedpump()loop when mountingLumenApp; the audio streams keep notifying and may prevent settling.Game.restore()must be awaited beforerunApp. Otherwise the app opens onhomeand 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()resetsmodeto campaign andcampaignIndexto 0. Daily and classic starts set their own mode afterwards; keep that order.startPracticediscards 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()viahint_<key>, not in the domain. - Read-ahead never bypasses access.
reveal(i, readAhead: true)still redirects wheni > accessible. - Streaks use UTC epoch days. Do not compare local
DateTimevalues directly;visibleStreakdrops to zero when the last completion is older than yesterday. Puzzle.deductionRoundsthrows 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 ROADMAP: keep vertical scrolling as the accessibility fallback).
- Gesture layering is deliberate.
PageSwipeBlockerwins 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: falsein tests,supportedguard in the service, andbetween()always routes even on no-fill. - Narration assets are checksum-locked.
check_narration_assets.pyrequires the scripts, manifests and WAV masters to agree; edit them together. - QA integration test fails without
--dart-define=QA_TEST=trueand should run on theqaflavour (com.lumen.daily.qa). build/,artifacts/,.dart_tool/, IDE state and signing keys are ignored. Do not commit APKs or screenshots;pubspec.lockis tracked.
Grep anchors
# 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
README.md(user-facing overview) andROADMAP.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 testandpython3 scripts/check_narration_assets.pyafter 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.