Add a bounded puzzle thinking-depth analysis tool

This commit is contained in:
Hadrian Burkhardt
2026-11-02 10:06:32 +01:00
parent 010b90bef5
commit c6168f46ac
8 changed files with 1617 additions and 2 deletions
+17 -1
View File
@@ -31,6 +31,7 @@ lib/
├── main.dart LumenApp, Notebook, all screen builders, dialogs, routing
├── domain/
│ ├── puzzle.dart Puzzle, JavaRandom, LogicSolver, Difficulty, Region, Hint
│ ├── thinking.dart ThinkingAnalyzer, ThinkingReport — snapshot deduction waves and bounded hypothetical proofs
│ ├── book.dart Book, CampaignLevel, StoryPage/StoryPageType — loads authored content
│ └── game.dart Game (ChangeNotifier), Screen/Mode, puzzle session, awards
├── services/
@@ -40,7 +41,8 @@ lib/
│ └── ads.dart Ads — UMP consent, rewarded hints, interstitials
└── ui/
├── paper.dart Paper, Leaf, Cover, Sketch, InkButton, PageSwipeBlocker
└── board.dart Board, PencilMark painter, PixelPicture
├── board.dart Board, PencilMark painter, PixelPicture, PatternStamp
└── discovery.dart Discovery — pattern-to-art transition and replay
assets/
├── campaign.json premise + 12 authored levels (chapter/title/object/before/after/picture/clues/areas; optional illustrationAsset)
@@ -72,6 +74,8 @@ flowchart TD
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"]
thinking["domain/thinking.dart<br/>ThinkingAnalyzer · ThinkingReport"]
cli["tool/analyze_puzzles.dart<br/>Authoring report CLI"]
book["domain/book.dart<br/>Book · CampaignLevel · StoryPage"]
progress["services/progress.dart<br/>Progress — local key/value store"]
narrator["services/narrator.dart<br/>Narrator — just_audio"]
@@ -90,6 +94,9 @@ flowchart TD
board --> puzzle
board --> paper
game --> puzzle
cli --> thinking
cli --> puzzle
thinking --> puzzle
game --> book
game --> progress
book --> puzzle
@@ -229,6 +236,14 @@ Content pipelines:
- **Daily:** fixed board per local calendar day (`Puzzle.seeded(epochDay * 7919)`), progress keyed by date.
- **Classic:** deterministic practice board per difficulty and level (`1000000 + level` seed), generated on an isolate.
## Thinking-depth authoring tool
- `lib/domain/thinking.dart` is pure Dart and is not wired into gameplay, hint pricing, generation or saved progress. `ThinkingAnalyzer(cellCount, constraints).analyze(initial)` receives visible constraints and solver-encoded marks, never an answer picture.
- All direct deductions in a wave use the same snapshot. Only after direct waves stall are two-clue overlap comparisons used; comparisons are exhausted before bounded contradiction lookahead. The trace distinguishes long write-down chains from simultaneous hypothetical assumptions.
- On an ordinary-rule stall a bounded solution counter classifies inconsistent or non-unique boards; its answer search never supplies deduction marks. `lookaheadDepth` is null unless the complete model path succeeds. Depth and node limits produce explicit unresolved statuses rather than claiming a human must guess.
- `tool/analyze_puzzles.dart` loads campaign records without Flutter assets/Book, or uses the existing daily/practice generator. It writes a compact table, Markdown reports and full JSON proofs. `--input` accepts generic constraints/partial marks. See [THINKING_DEPTH.md](THINKING_DEPTH.md) for encodings, strategy, limits and interpretation.
- `test/thinking_test.dart` covers clue-order invariance, one- and two-level lookahead, exact small-system enumeration, partial/invalid boards, budget handling and all campaign traces. Answer-bearing test fixtures are never passed into the analyzer itself.
## UI, layout and rendering rules
- All visible handwriting uses `hand(size)` (`MaraHand` → Dancing Script). Colours live in `lib/ui/paper.dart`: `ink` `#36413c`, `blue` `#274956`, `muted` `#796b55`, `cream` `#f3e7cc`, `amber` `#e0b568`.
@@ -364,6 +379,7 @@ Board key formats (`<key>`):
| File | Covers |
| --- | --- |
| `test/thinking_test.dart` | Snapshot-wave invariance, 1/2-level contradiction proofs, exhaustive checks of 200 small systems, partial/invalid boards, search limits and all campaign traces |
| `test/narration_autoplay_test.dart` | Exact 3-second delay, one start per visit, cancellation/replacement, recorded-page eligibility, unfolding notes and backgrounding |
| `integration_test/autoplay_test.dart` | Real-device delayed playback of bundled WAVs, cancellation when entering a puzzle and Stop preventing restart |
| `test/ambience_test.dart` | Scene mapping, voice ducking, mute/background stop, stale loading requests, backend failure/recovery and disposal |
+1
View File
@@ -3,6 +3,7 @@
| Document | Purpose |
| --- | --- |
| [Code map](CODE_MAP.md) | Agent-oriented architecture, dependency graph, screen state machine, puzzle pipeline, UI/layout rules, persistence keys, asset and service flows, test map, invariants, change recipes and gotchas |
| [Thinking-depth tool](THINKING_DEPTH.md) | CLI usage, reasoning model, depth limits, reports and human-difficulty interpretation |
| [Project README](../README.md) | Features, artwork, narration, build and verification commands, publishing notes |
| [Roadmap](../ROADMAP.md) | Product direction and the proposed 30–40-leaf campaign |
| [Task list](../TODO.md) | Actionable artwork and asset follow-ups not yet scheduled |
+97
View File
@@ -0,0 +1,97 @@
# Estimating puzzle thinking depth
Run the authoring tool from the repository root, after the normal `flutter pub get` setup:
```sh
# Current campaign, compact table
dart tool/analyze_puzzles.dart
# Export a report and a complete machine-readable trace
dart tool/analyze_puzzles.dart --trace \
--markdown artifacts/thinking-depth/campaign.md \
--json artifacts/thinking-depth/campaign.json
# Inspect a specific story puzzle
dart tool/analyze_puzzles.dart --level 8 --trace
# Use the real daily seed or generated practice rules
dart tool/analyze_puzzles.dart --daily 2026-11-02
dart tool/analyze_puzzles.dart --practice hard --seed 1000001
# Check another campaign without editing the current assets
dart tool/analyze_puzzles.dart --campaign /tmp/alternative-campaign.json
```
The analyzer reads the authored givens and visible clue totals. The reasoning engine receives no solution picture. Exported traces contain the deduced answers, so they are intended for authors reviewing puzzle balance.
## Two different meanings of thinking ahead
**Deduction rounds** count successive waves of visible deductions. Suppose a row determines a cell, which completes a column, which determines another row. That is a chain of deductions. A player can write each result down; the chain does not have to be held in working memory. All deductions in one round are calculated from the same unchanged board snapshot. Swapping the order of clues cannot shorten a chain by silently using marks from the same round.
**Hypothetical lookahead** counts simultaneous assumptions in a contradiction proof. At depth 1 the model tries a mark, propagates ordinary deductions, and rejects the mark if it produces a contradiction. Depth 2 permits one further nested assumption; a nested split is rejected only if both its light and dark branches fail. Sequential assumptions whose conclusions have already been proved and written down do not accumulate as simultaneous depth.
A depth of **0** means the model completes the puzzle without hypothetical branching. It does not mean the puzzle is effortless. A question mark means the tool did not establish a complete depth estimate; it never substitutes zero for an unfinished search.
These numbers describe a reproducible solving model. They are not a validated psychological difficulty score, a solve-time prediction, or proof of the minimum a human must think ahead. A player may notice a better proof or use a technique outside this model. The solver's first successful contradiction at a stall uses the shallowest depth it has exhaustively tested there, but its sequence of choices is not globally optimized to minimize the difficulty of the entire puzzle.
## Rules and deterministic strategy
1. Apply direct row, column and area totals: zero lights remaining crosses the unknown cells; exactly enough remaining lights fills them.
2. Exhaust direct deduction waves before using comparisons.
3. At a direct-rule stall, compare pairs of overlapping clues. Cancel shared unknown cells and use extreme differences to force cells outside the overlap. This can compare rows, columns or areas, not just two named areas.
4. If ordinary deductions stall, check whether there is exactly one completion. Multiple solutions and contradictory clues are reported separately from difficulty. This bounded answer-counting search does not feed any answer marks to the reasoning engine.
5. For a unique unresolved board, try contradiction proofs of increasing assumption depth. Cells with the most clue memberships are tried first; ties use cell index, and dark is tried before light. Ordinary rules run after each assumption. Only proved contradictions produce a mark on the real board.
The default search limit is 50,000 nodes per puzzle and depth 2. You can change them with `--node-limit` and `--max-lookahead` (0–3). A higher limit can be substantially slower. Both the uniqueness check and hypothetical proofs consume the node budget. Ordinary deductions do not consume search nodes. Each puzzle gets its own budget.
## Reading the report
| Field | Meaning |
| --- | --- |
| Lookahead | Maximum simultaneous hypothetical depth used on the completed reasoning path. `?` if incomplete/invalid/non-unique. |
| Rounds | Number of successive waves, including comparison and proved-assumption waves. |
| Direct cells at start | Cells immediately resolved by a single clue before any new marks are made. This counts cells, not independent insights. |
| Comparison steps | Distinct two-clue explanations used in the trace; one explanation may resolve several cells. This is not the old solver's one-cell hint count. |
| Smallest wave | Fewest newly marked cells in any round, including final cleanup. A value of 1 alone is not evidence of a difficult bottleneck. |
| Largest clue span | Number of unmarked cells across the clue(s) considered in one direct/comparison step. A rough scope-of-comparison measure, not a count of facts a human must memorize. |
The detailed trace identifies each round's clues and new cells. Use it to inspect thin progress, late comparisons or long chains rather than compressing everything into an arbitrary 0–100 score.
JSON includes the initial board, visible constraints, final status, metrics, per-round marks, explanations and contradiction proof trees. Cell indices are zero-based; printed coordinates such as `r3c5` are one-based. In a proof tree the first split branch is dark and the second is lit. `lookaheadDepth` is null unless solved; `maxAssumptionDepthUsed` is a record of completed work, not an estimate for unresolved cells. `lookaheadLimit` is the configured cap, not a claim that every depth was tested.
Statuses:
- `solved`: all marks were established using the model.
- `inconsistent`: no completion satisfies all clues.
- `nonUnique`: at least two completions satisfy all clues.
- `depthLimit`: unique, but no next move was proved within the configured depth.
- `nodeLimit`: the search budget ran out; uniqueness may also be unknown.
Exit code 0 means every selected puzzle was solved by the model, 1 means at least one puzzle was unresolved/invalid/non-unique, and 2 means bad input or a command error. `--json -` writes JSON to stdout; `--markdown -` writes the report there.
## Custom constraints and partial boards
`--input PATH` accepts a single authored picture record (the same `picture`, `clues` and `areas` fields as a campaign level), or generic constraints without any answer picture:
```json
{
"title": "A short dependency chain",
"cellCount": 4,
"size": 2,
"initial": [-1, -1, -1, -1],
"constraints": [
{"name": "A", "cells": [0], "total": 1},
{"name": "B", "cells": [0, 1], "total": 1},
{"name": "C", "cells": [1, 2], "total": 1},
{"name": "D", "cells": [2, 3], "total": 1}
]
}
```
`initial` is optional and uses the solver encoding: **-1 = unmarked, 0 = dark, 1 = lit**. This differs from saved game marks (`0 = unmarked, 1 = lit, 2 = dark`); convert saved marks before supplying a partial board. `size` is optional and affects printed coordinates only; when supplied it must square to `cellCount`. Boards are limited to 100 cells. Constraint indices must be unique within each clue and inside the board.
## Current campaign findings
In the current campaign all twelve pictures have hypothetical depth 0. The direct/comparison strategy uses 3–11 deduction waves. The opening match takes 3 waves and no comparison, while the harbour bell takes 11 waves, with thin single-cell progress in some rounds. That makes the bell worth checking in player tests, even though no speculative lookahead is needed.
Regenerate the report after editing clues; these findings are not a replacement for device playtesting. The dedicated tests include exact one- and two-assumption examples, clue-order invariance, incomplete-search handling, exhaustive enumeration of 200 small constraint systems and all twelve campaign pictures.