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
+5 -1
View File
@@ -76,10 +76,14 @@ flutter drive --driver test_driver/integration_test.dart \
--dart-define=QA_TEST=true -d YOUR_ANDROID_DEVICE
```
The thirty-eight unit/widget tests cover 40 Java reference boards (including signed 64-bit seeds), 300 graded generated boards, solver counts against 300 exhaustive small systems, all twelve campaign solutions, bounded campaign comparison chains, solved-grid inspection after restart, discovery animation/replay, reward-gated hints in every mode, declined/unavailable ads and duplicate/stale reward callbacks, streaks, fresh progress, read-ahead, completion awards, campaign read-ahead restoration, gesture isolation, swipes over text and blank paper, cancelled drags, vertical scrolling, landscape and larger text; it also checks every cottage leaf with the real font at 1.5× text, all four hint controls, legacy route migration and exactly-once completion after restart. Reference parity protects the port’s rules; it is not used to migrate saves.
The forty-nine unit/widget tests cover 40 Java reference boards (including signed 64-bit seeds), 300 graded generated boards, solver counts against 300 exhaustive small systems, all twelve campaign solutions, bounded campaign comparison chains, solved-grid inspection after restart, discovery animation/replay, reward-gated hints in every mode, declined/unavailable ads and duplicate/stale reward callbacks, streaks, fresh progress, read-ahead, completion awards, campaign read-ahead restoration, gesture isolation, swipes over text and blank paper, cancelled drags, vertical scrolling, landscape and larger text; it also checks every cottage leaf with the real font at 1.5× text, all four hint controls, legacy route migration and exactly-once completion after restart. Reference parity protects the port’s rules; it is not used to migrate saves.
The physical-device integration test uses a disposable in-memory game plus an isolated QA disk round-trip. It plays all five real WAV files, checks pause/resume, explores the six leaves, verifies bookmarks/discoveries, solves match and lantern puzzles and checks exactly-once awards. Screenshots are saved in `artifacts/flutter-check/`. The release smoke script requires an active, unmuted 24 kHz media track in the tablet’s audio mixer as well as exercising the actual play/pause/resume UI and restores the last page after process restart, without injecting puzzle fixtures. The release build includes a targeted R8 keep rule for the database constructor used reflectively by AdMob’s WorkManager dependency. Advertising is disabled for the automated story tests; real UMP startup is checked separately in the normal build. Reward delivery, cancellation and ad no-fill still need manual release testing with your final AdMob configuration.
## Puzzle thinking-depth tool
`dart tool/analyze_puzzles.dart` reports hypothetical lookahead, successive deduction rounds, comparison steps and thin progress for every story puzzle. It also accepts daily/practice boards and custom visible constraints. Export Markdown and JSON traces with `--markdown PATH --json PATH --trace`. This is a defined reasoning-model estimate, not a validated human difficulty score. See [the tool guide](docs/THINKING_DEPTH.md).
## Source map
| Location | Responsibility |
+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.
+453
View File
@@ -0,0 +1,453 @@
import 'puzzle.dart';
enum ThinkingRule { direct, comparison, assumption }
enum ThinkingStatus { solved, inconsistent, nonUnique, depthLimit, nodeLimit }
/// A checkable reason for rejecting a hypothetical mark. A split rejects both
/// values of [cell]; a leaf names the clue contradiction after propagation.
class ContradictionProof {
const ContradictionProof(this.reason, {this.cell, this.branches = const []});
final String reason;
final int? cell;
final List<ContradictionProof> branches;
Map<String, Object?> toJson() => {
'reason': reason,
if (cell != null) 'splitCell': cell,
if (branches.isNotEmpty)
'branches': branches.map((p) => p.toJson()).toList(),
};
}
class ThinkingStep {
const ThinkingStep({
required this.rule,
required this.clues,
required this.marks,
required this.explanation,
required this.cellsCompared,
this.assumptionDepth = 0,
this.rejectedValue,
this.proof,
});
final ThinkingRule rule;
final List<String> clues;
// Solver encoding: 0 = dark, 1 = lit. Indices are zero-based.
final Map<int, int> marks;
final String explanation;
final int cellsCompared, assumptionDepth;
final int? rejectedValue;
final ContradictionProof? proof;
Map<String, Object?> toJson() => {
'rule': rule.name,
'clues': clues,
'marks': [
for (final entry in marks.entries)
{'cell': entry.key, 'value': entry.value},
],
'explanation': explanation,
'cellsCompared': cellsCompared,
'assumptionDepth': assumptionDepth,
if (rejectedValue != null) 'rejectedValue': rejectedValue,
if (proof != null) 'contradictionProof': proof!.toJson(),
};
}
class ThinkingRound {
const ThinkingRound(this.steps);
final List<ThinkingStep> steps;
int get newCells => steps.fold(0, (sum, step) => sum + step.marks.length);
Map<String, Object> toJson() => {
'newCells': newCells,
'steps': steps.map((s) => s.toJson()).toList(),
};
}
class ThinkingReport {
const ThinkingReport({
required this.status,
required this.cells,
required this.rounds,
required this.givens,
required this.solutionCount,
required this.searchNodes,
required this.maxLookahead,
required this.message,
});
final ThinkingStatus status;
final List<int> cells;
final List<ThinkingRound> rounds;
final int givens, searchNodes, maxLookahead;
// null means the bounded solution check did not finish; 2 means at least two.
final int? solutionCount;
final String message;
Iterable<ThinkingStep> get steps => rounds.expand((r) => r.steps);
int get resolvedCells => cells.where((v) => v >= 0).length - givens;
int get initialDirectMoves => rounds.isEmpty
? 0
: rounds.first.steps
.where((s) => s.rule == ThinkingRule.direct)
.fold(0, (sum, s) => sum + s.marks.length);
int get comparisonSteps =>
steps.where((s) => s.rule == ThinkingRule.comparison).length;
int get assumptionSteps =>
steps.where((s) => s.rule == ThinkingRule.assumption).length;
int get maxAssumptionDepthUsed => steps.fold(
0,
(depth, s) => s.assumptionDepth > depth ? s.assumptionDepth : depth,
);
int? get lookaheadDepth =>
status == ThinkingStatus.solved ? maxAssumptionDepthUsed : null;
int get maxCellsCompared => steps.fold(
0,
(count, s) => s.cellsCompared > count ? s.cellsCompared : count,
);
int get narrowestRound => rounds.isEmpty
? 0
: rounds.map((r) => r.newCells).reduce((a, b) => a < b ? a : b);
Map<String, Object?> toJson() => {
'status': status.name,
'message': message,
'solutionCountCappedAtTwo': solutionCount,
'cellCount': cells.length,
'givens': givens,
'resolvedCells': resolvedCells,
'initialDirectMoves': initialDirectMoves,
'deductionRounds': rounds.length,
'comparisonSteps': comparisonSteps,
'assumptionSteps': assumptionSteps,
'maxAssumptionDepthUsed': maxAssumptionDepthUsed,
'lookaheadDepth': lookaheadDepth,
'lookaheadLimit': maxLookahead,
'maxCellsCompared': maxCellsCompared,
'narrowestRound': narrowestRound,
'searchNodes': searchNodes,
'remainingCells': [
for (var i = 0; i < cells.length; i++)
if (cells[i] < 0) i,
],
'rounds': rounds.map((r) => r.toJson()).toList(),
};
}
class _Scan {
const _Scan(this.steps, [this.error]);
final List<ThinkingStep> steps;
final String? error;
}
class _Closure {
const _Closure(this.cells, this.error);
final List<int> cells;
final String? error;
bool get solved => error == null && !cells.contains(-1);
}
class _NodeLimit implements Exception {}
/// A reproducible reasoning model, not a psychometric measure. Ordinary rules
/// are applied in parallel from an unchanged snapshot. When stalled, the model
/// tries contradiction proofs of increasing assumption depth, never consulting
/// the authored picture/answer. All cells can be written down between rounds.
class ThinkingAnalyzer {
ThinkingAnalyzer(this.cellCount, List<Constraint> constraints)
: constraints = List.unmodifiable(constraints) {
if (cellCount < 1 || cellCount > 100) {
throw ArgumentError('Expected 1–100 cells');
}
for (final c in constraints) {
if (c.cells.toSet().length != c.cells.length ||
c.cells.any((i) => i < 0 || i >= cellCount)) {
throw ArgumentError('Invalid cells in ${c.name}');
}
}
}
final int cellCount;
final List<Constraint> constraints;
int _nodes = 0, _limit = 0;
void _visit() {
if (_nodes >= _limit) throw _NodeLimit();
_nodes++;
}
_Scan _scan(List<int> known) {
final unknown = <Set<int>>[], need = <int>[];
final candidates = <int, ThinkingStep>{};
String? conflict;
void propose(ThinkingStep step) {
for (final mark in step.marks.entries) {
final old = candidates[mark.key];
if (old != null && old.marks[mark.key] != mark.value) {
conflict = 'Clues force both lit and dark at cell ${mark.key}.';
} else if (old == null ||
step.clues.length < old.clues.length ||
step.clues.length == old.clues.length &&
step.cellsCompared < old.cellsCompared) {
candidates[mark.key] = step;
}
}
}
for (final c in constraints) {
final empty = c.cells.where((i) => known[i] < 0).toSet();
final remaining = c.total - c.cells.where((i) => known[i] == 1).length;
unknown.add(empty);
need.add(remaining);
if (remaining < 0 || remaining > empty.length) {
return _Scan(
[],
'${c.name} needs $remaining lights in ${empty.length} unmarked cells.',
);
}
if (empty.isNotEmpty && (remaining == 0 || remaining == empty.length)) {
propose(
ThinkingStep(
rule: ThinkingRule.direct,
clues: [c.name],
marks: {for (final i in empty) i: remaining == 0 ? 0 : 1},
explanation:
'${c.name} needs $remaining more lights in ${empty.length} unmarked cells.',
cellsCompared: empty.length,
),
);
}
}
// Prefer writing down every available simple deduction before asking the
// player to compare two clues. Comparisons are used only at a simple-rule stall.
if (candidates.isEmpty) {
for (var a = 0; a < constraints.length; a++) {
for (var b = a + 1; b < constraints.length; b++) {
if (unknown[a].intersection(unknown[b]).isEmpty) continue;
final onlyA = unknown[a].difference(unknown[b]);
final onlyB = unknown[b].difference(unknown[a]);
final diff = need[a] - need[b];
if (diff > onlyA.length || diff < -onlyB.length) {
return _Scan(
[],
'Comparing ${constraints[a].name} and ${constraints[b].name} leaves an impossible difference of $diff lights.',
);
}
if (onlyA.isEmpty && onlyB.isEmpty ||
diff != onlyA.length && diff != -onlyB.length) {
continue;
}
final valueA = diff == onlyA.length ? 1 : 0;
propose(
ThinkingStep(
rule: ThinkingRule.comparison,
clues: [constraints[a].name, constraints[b].name],
marks: {
for (final i in onlyA) i: valueA,
for (final i in onlyB) i: 1 - valueA,
},
explanation:
'Cancel shared unmarked cells in ${constraints[a].name} (${need[a]} lights left) and ${constraints[b].name} (${need[b]} left). Difference: $diff.',
cellsCompared: unknown[a].union(unknown[b]).length,
),
);
}
}
}
if (conflict != null) return _Scan([], conflict);
// Keep each cell's simplest reason, and merge cells with the same reason.
final selected = <ThinkingStep, Map<int, int>>{};
for (final entry in candidates.entries) {
(selected[entry.value] ??= {})[entry.key] = entry.value.marks[entry.key]!;
}
return _Scan([
for (final entry in selected.entries)
ThinkingStep(
rule: entry.key.rule,
clues: entry.key.clues,
marks: entry.value,
explanation: entry.key.explanation,
cellsCompared: entry.key.cellsCompared,
),
]);
}
_Closure _close(List<int> initial, [List<ThinkingRound>? rounds]) {
final known = List<int>.of(initial);
while (true) {
final scan = _scan(known);
if (scan.error != null || scan.steps.isEmpty) {
return _Closure(known, scan.error);
}
rounds?.add(ThinkingRound(scan.steps));
for (final step in scan.steps) {
for (final mark in step.marks.entries) {
known[mark.key] = mark.value;
}
}
}
}
List<int> _choices(List<int> known) {
final unknown = [
for (var i = 0; i < cellCount; i++)
if (known[i] < 0) i,
];
final degree = [
for (var i = 0; i < cellCount; i++)
constraints.where((c) => c.cells.contains(i)).length,
];
unknown.sort((a, b) {
final order = degree[b].compareTo(degree[a]);
return order == 0 ? a.compareTo(b) : order;
});
return unknown;
}
int _count(List<int> initial) {
_visit();
final state = _close(initial);
if (state.error != null) return 0;
if (state.solved) return 1;
final cell = _choices(state.cells).first;
final dark = List<int>.of(state.cells)..[cell] = 0;
final count = _count(dark);
if (count >= 2) return 2;
final light = List<int>.of(state.cells)..[cell] = 1;
final total = count + _count(light);
return total > 2 ? 2 : total;
}
ContradictionProof? _refute(List<int> initial, int extraDepth) {
_visit();
final state = _close(initial);
if (state.error != null) return ContradictionProof(state.error!);
if (state.solved || extraDepth == 0) return null;
// Try every split variable. A refutation requires BOTH branches to fail;
// finding one satisfying or unresolved branch is never a contradiction.
for (final cell in _choices(state.cells)) {
final dark = _refute(
List<int>.of(state.cells)..[cell] = 0,
extraDepth - 1,
);
if (dark == null) continue;
final light = _refute(
List<int>.of(state.cells)..[cell] = 1,
extraDepth - 1,
);
if (light != null) {
return ContradictionProof(
'Both values of cell $cell contradict the clues.',
cell: cell,
branches: [dark, light],
);
}
}
return null;
}
ThinkingStep? _lookAhead(List<int> known, int maxDepth) {
for (var depth = 1; depth <= maxDepth; depth++) {
for (final cell in _choices(known)) {
for (final value in [0, 1]) {
final proof = _refute(List<int>.of(known)..[cell] = value, depth - 1);
if (proof != null) {
return ThinkingStep(
rule: ThinkingRule.assumption,
clues: const [],
marks: {cell: 1 - value},
explanation:
'Assume cell $cell is ${value == 1 ? 'lit' : 'dark'}. Propagation and at most ${depth - 1} additional nested assumptions prove a contradiction, so it must be ${value == 1 ? 'dark' : 'lit'}.',
cellsCompared: 0,
assumptionDepth: depth,
rejectedValue: value,
proof: proof,
);
}
}
}
}
return null;
}
ThinkingReport analyze(
List<int> initial, {
int maxLookahead = 2,
int nodeLimit = 50000,
}) {
if (initial.length != cellCount || initial.any((v) => v < -1 || v > 1)) {
throw ArgumentError(
'Use -1 (unmarked), 0 (dark), 1 (lit), one value per cell',
);
}
if (maxLookahead < 0 || maxLookahead > 3 || nodeLimit < 1) {
throw ArgumentError('Lookahead must be 0–3; node limit must be positive');
}
_nodes = 0;
_limit = nodeLimit;
final rounds = <ThinkingRound>[];
var state = _close(initial, rounds);
int? solutions;
ThinkingReport report(ThinkingStatus status, String message) =>
ThinkingReport(
status: status,
cells: List.unmodifiable(state.cells),
rounds: List.unmodifiable(rounds),
givens: initial.where((v) => v >= 0).length,
solutionCount: solutions,
searchNodes: _nodes,
maxLookahead: maxLookahead,
message: message,
);
if (state.error != null) {
solutions = 0;
return report(ThinkingStatus.inconsistent, state.error!);
}
if (state.solved) {
solutions = 1;
return report(
ThinkingStatus.solved,
'Solved by visible deductions; no hypothetical lookahead needed.',
);
}
try {
// The solution counter validates uniqueness only. It never feeds any
// answer cells back into the human-style deduction or lookahead path.
solutions = _count(state.cells);
if (solutions == 0) {
return report(
ThinkingStatus.inconsistent,
'No completion satisfies all clues.',
);
}
if (solutions > 1) {
return report(
ThinkingStatus.nonUnique,
'Multiple completions satisfy the clues; there is no single answer to deduce.',
);
}
while (!state.solved) {
final step = _lookAhead(state.cells, maxLookahead);
if (step == null) {
return report(
ThinkingStatus.depthLimit,
'The model stalls after testing lookahead through depth $maxLookahead. This is not proof that a human must guess.',
);
}
rounds.add(ThinkingRound([step]));
final next = List<int>.of(state.cells);
for (final mark in step.marks.entries) {
next[mark.key] = mark.value;
}
state = _close(next, rounds);
if (state.error != null) {
return report(ThinkingStatus.inconsistent, state.error!);
}
}
return report(
ThinkingStatus.solved,
'Solved with contradiction-based hypothetical lookahead on this deterministic reasoning path.',
);
} on _NodeLimit {
return report(
ThinkingStatus.nodeLimit,
'Stopped at the $nodeLimit-node search budget; unresolved depth is unknown, not zero.',
);
}
}
}
+409
View File
@@ -0,0 +1,409 @@
[
{
"depth": 1,
"cellCount": 9,
"constraints": [
{
"name": "C0",
"cells": [
0,
1,
2,
3,
7
],
"total": 2
},
{
"name": "C1",
"cells": [
2,
6,
7,
8
],
"total": 2
},
{
"name": "C2",
"cells": [
1,
2,
3,
4,
5,
8
],
"total": 3
},
{
"name": "C3",
"cells": [
1,
3,
4,
5,
7
],
"total": 2
},
{
"name": "C4",
"cells": [
2,
5,
7
],
"total": 1
},
{
"name": "C5",
"cells": [
4,
6,
8
],
"total": 2
},
{
"name": "C6",
"cells": [
0,
1,
2,
3,
4,
5
],
"total": 3
},
{
"name": "C7",
"cells": [
1,
2,
7
],
"total": 1
},
{
"name": "C8",
"cells": [
1,
2,
4,
5,
6,
8
],
"total": 3
}
],
"initial": [
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1
],
"solution": [
0,
0,
1,
1,
1,
0,
1,
0,
0
],
"title": "One hypothetical assumption"
},
{
"cellCount": 16,
"initial": [
0,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1
],
"constraints": [
{
"name": "C0",
"cells": [
2,
4,
6,
9,
10,
13
],
"total": 3
},
{
"name": "C1",
"cells": [
1,
5,
6,
9,
12,
15
],
"total": 3
},
{
"name": "C2",
"cells": [
2,
4,
5,
9,
14,
15
],
"total": 3
},
{
"name": "C3",
"cells": [
0,
4,
5,
8,
11,
12
],
"total": 3
},
{
"name": "C4",
"cells": [
1,
3,
5,
12,
13,
14
],
"total": 3
},
{
"name": "C5",
"cells": [
0,
3,
6,
9,
11,
12
],
"total": 3
},
{
"name": "C6",
"cells": [
4,
6,
7,
8,
9,
15
],
"total": 3
},
{
"name": "C7",
"cells": [
0,
5,
6,
8,
10,
15
],
"total": 3
},
{
"name": "C8",
"cells": [
1,
3,
4,
8,
9,
13
],
"total": 3
},
{
"name": "C9",
"cells": [
5,
6,
7,
8,
11,
13
],
"total": 3
},
{
"name": "C10",
"cells": [
0,
4,
7,
8,
13,
14
],
"total": 3
},
{
"name": "C11",
"cells": [
1,
2,
6,
10,
14,
15
],
"total": 3
},
{
"name": "C12",
"cells": [
0,
2,
7,
12,
13,
15
],
"total": 3
},
{
"name": "C13",
"cells": [
3,
5,
6,
11,
14,
15
],
"total": 3
},
{
"name": "C14",
"cells": [
1,
5,
7,
10,
11,
12
],
"total": 3
},
{
"name": "C15",
"cells": [
3,
4,
7,
10,
12,
14
],
"total": 3
},
{
"name": "C16",
"cells": [
1,
2,
7,
9,
12,
14
],
"total": 3
},
{
"name": "C17",
"cells": [
2,
3,
5,
9,
10,
12
],
"total": 3
},
{
"name": "C18",
"cells": [
0,
1,
7,
8,
9,
11
],
"total": 3
},
{
"name": "C19",
"cells": [
2,
3,
4,
11,
12,
13
],
"total": 3
}
],
"solution": [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1
],
"depth": 2,
"title": "Two nested hypothetical assumptions"
}
]
+271
View File
@@ -0,0 +1,271 @@
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter_test/flutter_test.dart';
import 'package:lumen/domain/book.dart';
import 'package:lumen/domain/puzzle.dart';
import 'package:lumen/domain/thinking.dart';
bool _satisfies(List<int> cells, List<Constraint> constraints) => constraints
.every((c) => c.cells.fold<int>(0, (sum, i) => sum + cells[i]) == c.total);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test(
'successive deductions are snapshot waves, independent of clue order',
() {
final constraints = [
Constraint([0], 1, 'A'),
Constraint([0, 1], 1, 'B'),
Constraint([1, 2], 1, 'C'),
Constraint([2, 3], 1, 'D'),
];
final initial = List.filled(4, -1);
for (final ordered in [constraints, constraints.reversed.toList()]) {
final report = ThinkingAnalyzer(4, ordered).analyze(initial);
expect(report.status, ThinkingStatus.solved);
expect(report.rounds.length, 4);
expect(report.rounds.map((r) => r.newCells), [1, 1, 1, 1]);
expect(report.maxAssumptionDepthUsed, 0);
expect(report.comparisonSteps, 0);
expect(report.cells, [1, 0, 1, 0]);
expect(initial, [-1, -1, -1, -1]);
}
},
);
test('overlap cancellation is a deduction, not hypothetical lookahead', () {
final constraints = [
Constraint([0, 1], 1, 'A'),
Constraint([0, 1, 2], 1, 'B'),
Constraint([2, 3], 1, 'C'),
Constraint([0, 3], 1, 'D'),
];
final report = ThinkingAnalyzer(4, constraints).analyze(List.filled(4, -1));
expect(report.status, ThinkingStatus.solved);
expect(report.initialDirectMoves, 0);
expect(report.comparisonSteps, greaterThan(0));
expect(report.maxAssumptionDepthUsed, 0);
expect(report.cells, [0, 1, 0, 1]);
});
final fixtures = jsonDecode(
File('test/fixtures/thinking_depth.json').readAsStringSync(),
) as List;
for (final fixture in fixtures) {
test('recognises ${fixture['depth']} levels of hypothetical reasoning', () {
final n = fixture['cellCount'] as int;
final initial = (fixture['initial'] as List).cast<int>();
final constraints = [
for (final c in fixture['constraints'])
Constraint((c['cells'] as List).cast<int>(), c['total'], c['name']),
];
final analyzer = ThinkingAnalyzer(n, constraints);
final depth = fixture['depth'] as int;
final limited = analyzer.analyze(initial, maxLookahead: depth - 1);
expect(limited.status, ThinkingStatus.depthLimit);
expect(limited.lookaheadDepth, isNull);
expect(limited.solutionCount, 1);
expect(limited.cells, contains(-1));
final solved = analyzer.analyze(initial, maxLookahead: depth);
expect(solved.status, ThinkingStatus.solved);
expect(solved.maxAssumptionDepthUsed, depth);
expect(solved.lookaheadDepth, depth);
expect(solved.cells, fixture['solution']);
expect(solved.assumptionSteps, greaterThan(0));
expect(
solved.steps
.where((s) => s.rule == ThinkingRule.assumption)
.every((s) => s.proof != null),
true,
);
// Independently enumerate completions to validate each rejection. The
// analyzer itself receives no answer and must not copy the fixture solution.
final known = List<int>.of(initial);
for (final round in solved.rounds) {
for (final step in round.steps) {
if (step.rule == ThinkingRule.assumption) {
final mark = step.marks.entries.single;
var alternatives = 0;
for (var mask = 0; mask < (1 << n); mask++) {
final cells = List.generate(n, (i) => mask >> i & 1);
if (cells[mark.key] != step.rejectedValue) continue;
if (List.generate(
n,
(i) => i,
).any((i) => known[i] >= 0 && known[i] != cells[i])) {
continue;
}
if (_satisfies(cells, constraints)) alternatives++;
}
expect(
alternatives,
0,
reason: 'Rejected branch must be impossible',
);
}
for (final mark in step.marks.entries) {
known[mark.key] = mark.value;
}
}
}
});
}
test(
'multiple answers are not reported as a need to think or guess deeper',
() {
final report = ThinkingAnalyzer(2, [
Constraint([0, 1], 1, 'A'),
]).analyze([-1, -1]);
expect(report.status, ThinkingStatus.nonUnique);
expect(report.solutionCount, 2);
expect(report.assumptionSteps, 0);
},
);
test('contradicting and impossible clues are reported explicitly', () {
for (final constraints in [
[
Constraint([0], 0, 'A'),
Constraint([0], 1, 'B'),
],
[
Constraint([0], 2, 'Impossible'),
],
]) {
final report = ThinkingAnalyzer(1, constraints).analyze([-1]);
expect(report.status, ThinkingStatus.inconsistent);
expect(report.solutionCount, 0);
expect(report.message, isNotEmpty);
}
});
test('a search-budget exit leaves depth and uniqueness unresolved', () {
final fixture = fixtures.last;
final constraints = [
for (final c in fixture['constraints'])
Constraint((c['cells'] as List).cast<int>(), c['total'], c['name']),
];
final report = ThinkingAnalyzer(
fixture['cellCount'],
constraints,
).analyze((fixture['initial'] as List).cast<int>(), nodeLimit: 1);
expect(report.status, ThinkingStatus.nodeLimit);
expect(report.searchNodes, 1);
expect(report.solutionCount, isNull);
expect(report.lookaheadDepth, isNull);
expect(report.cells, contains(-1));
expect(report.toJson()['status'], 'nodeLimit');
});
test('fully marked boards are validated, including incorrect marks', () {
final analyzer = ThinkingAnalyzer(2, [
Constraint([0, 1], 1, 'A'),
]);
final valid = analyzer.analyze([0, 1]);
expect(valid.status, ThinkingStatus.solved);
expect(valid.rounds, isEmpty);
expect(valid.resolvedCells, 0);
expect(analyzer.analyze([1, 1]).status, ThinkingStatus.inconsistent);
});
test('invalid input encodings and constraint indices fail clearly', () {
expect(
() => ThinkingAnalyzer(2, [
Constraint([0, 0], 1, 'Duplicate'),
]),
throwsArgumentError,
);
expect(
() => ThinkingAnalyzer(2, [
Constraint([2], 1, 'Outside'),
]),
throwsArgumentError,
);
final analyzer = ThinkingAnalyzer(2, []);
expect(() => analyzer.analyze([0]), throwsArgumentError);
expect(() => analyzer.analyze([2, -1]), throwsArgumentError);
expect(
() => analyzer.analyze([-1, -1], maxLookahead: 4),
throwsArgumentError,
);
expect(() => analyzer.analyze([-1, -1], nodeLimit: 0), throwsArgumentError);
});
test(
'classification and forced marks agree with exhaustive small systems',
() {
final rng = Random(38);
for (var trial = 0; trial < 200; trial++) {
const n = 6;
final constraints = List.generate(1 + rng.nextInt(8), (c) {
final cells = [
for (var i = 0; i < n; i++)
if (rng.nextBool()) i,
];
return Constraint(cells, rng.nextInt(cells.length + 1), 'C$c');
});
final initial = List.generate(
n,
(_) => rng.nextInt(5) == 0 ? rng.nextInt(2) : -1,
);
final completions = <List<int>>[];
for (var mask = 0; mask < 1 << n; mask++) {
final cells = List.generate(n, (i) => mask >> i & 1);
if (List.generate(
n,
(i) => i,
).any((i) => initial[i] >= 0 && initial[i] != cells[i])) {
continue;
}
if (_satisfies(cells, constraints)) completions.add(cells);
}
final report = ThinkingAnalyzer(n, constraints).analyze(initial);
expect(
report.solutionCount,
min(2, completions.length),
reason: 'Trial $trial',
);
if (completions.isEmpty) {
expect(report.status, ThinkingStatus.inconsistent);
}
if (completions.length > 1) {
expect(report.status, ThinkingStatus.nonUnique);
}
for (final step in report.steps) {
for (final mark in step.marks.entries) {
expect(
completions.every((s) => s[mark.key] == mark.value),
true,
reason: 'Unsound deduction in trial $trial',
);
}
}
}
},
);
test(
'all campaign traces solve the picture without hypothetical assumptions',
() async {
final book = await Book.load();
for (var index = 0; index < book.levels.length; index++) {
final p = book.levels[index].puzzle();
final report = ThinkingAnalyzer(49, p.constraints).analyze(p.initial);
expect(report.status, ThinkingStatus.solved, reason: 'Campaign $index');
expect(report.cells, p.solution);
expect(report.solutionCount, 1);
expect(report.maxAssumptionDepthUsed, 0);
expect(
report.rounds.fold<int>(report.givens, (sum, r) => sum + r.newCells),
49,
);
if (index < 2) expect(report.comparisonSteps, 0);
if (index >= 2) expect(report.comparisonSteps, greaterThan(0));
expect(report.toJson()['remainingCells'], isEmpty);
}
},
);
}
+364
View File
@@ -0,0 +1,364 @@
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'package:lumen/domain/puzzle.dart';
import 'package:lumen/domain/thinking.dart';
const _help = '''Estimate puzzle reasoning depth using the game's visible clues.
Usage: dart tool/analyze_puzzles.dart [options]
Default: analyse all levels in assets/campaign.json.
--campaign PATH Use another campaign file
--level N Analyse one campaign level (1-based)
--practice DIFFICULTY Generate easy, medium or hard practice
--seed INTEGER Practice seed (default: 1000001)
--daily YYYY-MM-DD Analyse the actual daily puzzle for this date
--input PATH Analyse one picture record or generic constraint JSON
--max-lookahead N Maximum nested assumptions, 0–3 (default: 2)
--node-limit N Per-puzzle search budget (default: 50000)
--json PATH Write machine-readable results; - prints JSON only
--markdown PATH Write a readable report; - prints Markdown
--trace Include explained, spoiler-containing solution rounds
--help Show this help
This measures a defined reasoning model, not a universal human minimum or time.
A deduction chain is not the same as keeping hypothetical moves in your head.
''';
typedef _Board = ({
String id,
String title,
int size,
int cells,
List<Constraint> constraints,
List<int> initial,
});
_Board _picture(Map<String, dynamic> data, String id) {
final picture = (data['picture'] as String).split('').map(int.parse).toList();
final size = math.sqrt(picture.length).toInt();
final puzzle = Puzzle(size, picture);
final clues = data['clues'] as String? ?? '';
for (final c in clues.split(',').where((c) => c.isNotEmpty)) {
puzzle.given[int.parse(c)] = true;
}
final areas = data['areas'] as String? ?? '';
var index = 0;
for (final area in areas.split(';').where((a) => a.isNotEmpty)) {
final v = area.split(',').map(int.parse).toList();
if (v.length != 4) {
throw const FormatException('Areas need top,left,height,width');
}
puzzle.regions.add(
Region(String.fromCharCode(65 + index++), v[0], v[1], v[2], v[3]),
);
}
return _fromPuzzle(puzzle, id, data['title'] as String? ?? id);
}
_Board _fromPuzzle(Puzzle p, String id, String title) => (
id: id,
title: title,
size: p.size,
cells: p.solution.length,
constraints: p.constraints,
initial: p.initial,
);
_Board _input(Map<String, dynamic> data) {
if (data.containsKey('picture')) return _picture(data, 'input');
final count = data['cellCount'] as int;
final size = data['size'] as int? ?? 0;
if (size < 0 || size > 0 && size * size != count) {
throw const FormatException(
'Optional size must describe a square cellCount',
);
}
return (
id: 'input',
title: data['title'] as String? ?? 'Custom constraints',
size: size,
cells: count,
initial: data['initial'] == null
? List.filled(count, -1)
: (data['initial'] as List).cast<int>(),
constraints: [
for (final c in data['constraints'] as List)
Constraint(
(c['cells'] as List).cast<int>(),
c['total'] as int,
c['name'] as String,
),
],
);
}
String _coordinate(int cell, int size) =>
size > 0 ? 'r${cell ~/ size + 1}c${cell % size + 1}' : 'cell $cell';
String _ahead(ThinkingReport report) =>
report.lookaheadDepth?.toString() ?? '?';
String _markdown(
List<({_Board board, ThinkingReport report})> results,
bool trace,
) {
final out = StringBuffer('''# Puzzle thinking-depth report
Model: direct clue totals, cancellation of shared cells in two clues, then bounded contradiction proofs. Every deduction wave reads an unchanged snapshot before writing its marks.
**Lookahead** counts the maximum simultaneous hypothetical assumptions used on this solver's path. **Rounds** count successive waves of deductions that can be written down. Neither is a measured human difficulty score, a time estimate, or a universal minimum. A question mark means the analysis did not establish a complete solution. Comparison steps can involve rows, columns or areas.
| Puzzle | Status | Lookahead | Rounds | Direct cells at start | Comparison steps | Smallest wave | Largest clue span |
| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |
''');
for (final item in results) {
final r = item.report;
out.writeln(
'| ${item.board.id}: ${item.board.title.replaceAll('|', '/')} | ${r.status.name} | ${_ahead(r)} | ${r.rounds.length} | ${r.initialDirectMoves} | ${r.comparisonSteps} | ${r.narrowestRound} | ${r.maxCellsCompared} |',
);
}
out.writeln(
'\nLargest clue span = unmarked cells in the clue(s) used for one deduction. Smallest wave includes the final cleanup; a value of one alone does not prove a hard bottleneck. Search budgets apply separately to each puzzle.\n',
);
for (final item in results) {
final r = item.report;
out.writeln('## ${item.board.id}: ${item.board.title}\n');
out.writeln('${r.message}\n');
out.writeln(
'Resolved ${r.resolvedCells}/${item.board.cells - r.givens} initially unmarked cells. Search nodes: ${r.searchNodes}. Assumption limit: ${r.maxLookahead}.\n',
);
if (!trace) continue;
for (var i = 0; i < r.rounds.length; i++) {
out.writeln('**Round ${i + 1} · ${r.rounds[i].newCells} new cells**\n');
for (final step in r.rounds[i].steps) {
final marks = step.marks.entries
.map(
(m) =>
'${_coordinate(m.key, item.board.size)}=${m.value == 1 ? 'lit' : 'dark'}',
)
.join(', ');
out.writeln('- ${step.rule.name}: ${step.explanation} → $marks');
if (step.proof != null) {
out.writeln(
' Contradiction evidence: `${jsonEncode(step.proof!.toJson())}`',
);
}
}
out.writeln();
}
}
return out.toString();
}
void _write(String path, String contents) {
final file = File(path);
file.parent.createSync(recursive: true);
file.writeAsStringSync(contents);
}
void main(List<String> args) {
try {
final options = <String, String>{};
var trace = false;
const names = {
'--campaign',
'--level',
'--practice',
'--seed',
'--daily',
'--input',
'--max-lookahead',
'--node-limit',
'--json',
'--markdown',
};
for (var i = 0; i < args.length; i++) {
if (args[i] == '--help') {
stdout.write(_help);
return;
}
if (args[i] == '--trace') {
trace = true;
continue;
}
if (!names.contains(args[i]) ||
i + 1 == args.length ||
args[i + 1].startsWith('--')) {
throw FormatException('Unknown option or missing value: ${args[i]}');
}
final name = args[i];
if (options.containsKey(name)) {
throw FormatException('Repeated option: $name');
}
options[name] = args[++i];
}
final sources = [
'--campaign',
'--practice',
'--daily',
'--input',
].where(options.containsKey).length;
if (sources > 1 ||
options.containsKey('--level') &&
(options.containsKey('--practice') ||
options.containsKey('--daily') ||
options.containsKey('--input'))) {
throw const FormatException(
'Choose one input source; --level applies only to a campaign',
);
}
if (options.containsKey('--seed') && !options.containsKey('--practice')) {
throw const FormatException('--seed requires --practice');
}
if (options['--json'] == '-' && options['--markdown'] == '-') {
throw const FormatException('Only one output format can use stdout');
}
final maxDepth = int.parse(options['--max-lookahead'] ?? '2');
final nodeLimit = int.parse(options['--node-limit'] ?? '50000');
if (maxDepth < 0 || maxDepth > 3 || nodeLimit < 1) {
throw const FormatException(
'Lookahead must be 0–3 and node limit positive',
);
}
if (options['--json'] != null &&
options['--markdown'] != null &&
File(options['--json']!).absolute.path ==
File(options['--markdown']!).absolute.path) {
throw const FormatException(
'JSON and Markdown need different output paths',
);
}
final boards = <_Board>[];
if (options['--input'] case final path?) {
boards.add(
_input(
jsonDecode(File(path).readAsStringSync()) as Map<String, dynamic>,
),
);
} else if (options['--practice'] case final value?) {
final difficulty = Difficulty.values
.where((d) => d.name == value.toLowerCase())
.firstOrNull;
if (difficulty == null) {
throw const FormatException(
'Practice difficulty must be easy, medium or hard',
);
}
final seed = BigInt.parse(options['--seed'] ?? '1000001');
boards.add(
_fromPuzzle(
Puzzle.generate(seed, difficulty),
'practice',
'${difficulty.label}, seed $seed',
),
);
} else if (options['--daily'] case final value?) {
final date = DateTime.parse(value);
if (!RegExp(r'^\d{4}-\d{2}-\d{2}$').hasMatch(value) ||
date.toIso8601String().substring(0, 10) != value) {
throw const FormatException('Use a valid YYYY-MM-DD date');
}
boards.add(
_fromPuzzle(
Puzzle.seeded(BigInt.from(epochDay(date)) * BigInt.from(7919)),
'daily',
value,
),
);
} else {
final data = jsonDecode(
File(options['--campaign'] ?? 'assets/campaign.json')
.readAsStringSync(),
) as Map;
final levels = data['levels'] as List;
if (levels.isEmpty) {
throw const FormatException('Campaign contains no puzzles');
}
final selected = options['--level'] == null
? null
: int.parse(options['--level']!);
if (selected != null && (selected < 1 || selected > levels.length)) {
throw FormatException('Level must be 1–${levels.length}');
}
for (var i = 0; i < levels.length; i++) {
if (selected == null || selected == i + 1) {
boards.add(_picture(levels[i] as Map<String, dynamic>, '${i + 1}'));
}
}
}
final results = [
for (final board in boards)
(
board: board,
report: ThinkingAnalyzer(board.cells, board.constraints).analyze(
board.initial,
maxLookahead: maxDepth,
nodeLimit: nodeLimit,
),
),
];
final json = const JsonEncoder.withIndent(' ').convert({
'model': 'visible-clue-reasoning-v1',
'interpretation': 'A reproducible solver-path estimate, not a validated human minimum or time. Deduction waves are not hypothetical lookahead. Indices are zero-based; marks use 0=dark and 1=lit.',
'maxLookahead': maxDepth,
'nodeLimitPerPuzzle': nodeLimit,
'puzzles': [
for (final item in results)
{
'id': item.board.id,
'title': item.board.title,
'size': item.board.size,
'constraints': [
for (final c in item.board.constraints)
{'name': c.name, 'cells': c.cells, 'total': c.total},
],
'initial': item.board.initial,
...item.report.toJson(),
},
],
});
final markdown = _markdown(results, trace);
if (options['--json'] case final path?) {
if (path != '-') _write(path, '$json\n');
}
if (options['--markdown'] case final path?) {
if (path != '-') _write(path, markdown);
}
if (options['--json'] == '-') {
stdout.writeln(json);
} else if (options['--markdown'] == '-') {
stdout.write(markdown);
} else {
stdout.writeln(
'Puzzle thinking depth · model estimate, not a human minimum\n',
);
stdout.writeln(
'ID Lookahead Rounds Start Compare Min wave Clue span Status / title',
);
for (final item in results) {
final r = item.report;
stdout.writeln(
'${item.board.id.padRight(3)} ${_ahead(r).padLeft(9)} ${r.rounds.length.toString().padLeft(7)} ${r.initialDirectMoves.toString().padLeft(6)} ${r.comparisonSteps.toString().padLeft(8)} ${r.narrowestRound.toString().padLeft(9)} ${r.maxCellsCompared.toString().padLeft(10)} ${r.status.name}: ${item.board.title}',
);
}
stdout.writeln(
'\nLookahead 0 = deductions can be written down; no hypothetical branching.',
);
stdout.writeln(
'? = no complete depth established; inspect status/message.',
);
if (trace) stdout.write('\n$markdown');
}
if (results.any((r) => r.report.status != ThinkingStatus.solved)) {
exitCode = 1;
}
} on Object catch (error) {
stderr.writeln(
'Cannot analyse puzzles: $error\nUse --help for input options.',
);
exitCode = 2;
}
}