tilezz 0.2.0

Utilities to work with perfect-precision polygonal tiles built on top of cyclotomic integer rings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! `classify_tiles` -- filter a `tilezz-ratdb` DAFSA dataset into a certified verdict store.
//!
//! One store path (`--store`), three modes selected by flag:
//!
//! - default (`--fast`) -- the fast, staged, resumable classification of one `--perim` block
//!   into the store (Conway, then the cheap Heesch reject bulk, the periodic accepts, then
//!   deep rejects). Each verdict is a verified, provenance-tagged certificate.
//! - `--deep` -- the "crunch the rest hard" deep pass: re-classify only the
//!   store's Undecided residue with a high budget (deep Heesch, high torus kmax,
//!   seeded anisohedral restarts). Results append to the `<store>.deep.jsonl`
//!   overlay as they land (RESUMABLE: a killed run loses only in-flight tiles);
//!   the store itself is untouched until `--merge`.
//! - `--merge <OVERLAY>` -- apply a deep overlay onto the store: a Decided
//!   overlay verdict replaces the store's Undecided line (a cert overrides
//!   unknown, never the reverse).
//! - `--verify` -- re-verify a finished store from disk (replay every cert) and
//!   check that every present perimeter block is COMPLETE against the dataset's
//!   tile counts. Exit code 1 if the store is dirty.
//! - `--pack` -- sort the store by dafsa index (atomic rewrite), enabling
//!   `--lookup`'s byte bisection. Safe at any time; nothing else cares about
//!   line order.
//! - `--lookup <IDX|WORD>` -- O(log n) point query of one tile's verdict in a
//!   packed store. Takes a dafsa index or a turn word like
//!   `-3,2,0,2,3,-2,3,-2,3,2,-3,2,3,2` in ANY presentation (any rotation,
//!   either chirality, either traversal orientation -- it is free-canonicalized
//!   before the dataset lookup).
//!
//! `--periodic-only` / `--heesch-only` (orthogonal to fast/deep) restrict either
//! classification to the accept / reject half when you already know what to expect -- the
//! other half's tiles land Undecided. Most useful on `--deep`, where it stops the
//! hard residue from grinding the whole other half.
//!
//! Example (build the ZZ12 store up to perimeter 13, then deep + verify):
//!
//! ```text
//! for n in $(seq 3 13); do \
//!   ./target/release/classify_tiles --asset web/ratdb/data/zz12_n16_free --perim $n --store certs.jsonl; \
//! done
//! ./target/release/classify_tiles --asset web/ratdb/data/zz12_n16_free --deep   --store certs.jsonl
//! ./target/release/classify_tiles --asset web/ratdb/data/zz12_n16_free --verify --store certs.jsonl
//! ```

use std::path::PathBuf;
use std::process::ExitCode;

use clap::{Parser, ValueEnum};
use tilezz::classify::cert::{Classified, Verdict};
use tilezz::classify::classify_tiles::{
    DeepConfig, FastConfig, StageMode, asset_free_counts, asset_ring, open_ratdb, run_deep,
    run_fast, run_fast_range, run_reptile_screen, run_verify,
};
use tilezz::classify::heesch::{enumerate_coronas, heesch_number_witnessed};
use tilezz::classify::render::{TileColoring, witness_svg};
use tilezz::classify::reptile::reptile_cert;
use tilezz::classify::store::{run_merge, run_pack, store_lookup};
use tilezz::enumerate::canonical::ccw_free_canonical;
use tilezz::geom::rat::Rat;
use tilezz::geom::tileset::TileSet;

/// Coloring for `--render` (see [`Cli::render_mode`]).
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum RenderView {
    /// Color tiles by concentric corona ring.
    Corona,
    /// Color tiles by placement rotation (orientation).
    Rotation,
    /// Render both colorings (one SVG each).
    Both,
}

#[derive(Parser)]
#[command(
    name = "classify_tiles",
    // Embeds the source commit (via TILEZZ_GIT_COMMIT), matching rat_enum,
    // so a cert store's verify harness can provenance-guard the binary it
    // built before trusting its --verify verdict.
    version = tilezz::VERSION,
    about = "Classify a ratdb DAFSA dataset into a certified verdict store (default fast \
             classification; --deep crunches the Undecided residue; --verify checks a store)."
)]
struct Cli {
    /// Path to the ratdb asset directory (`block_index.json` + `blocks/<sha>.bin`).
    #[arg(long, default_value = "web/ratdb/data/zz12_n16_free")]
    asset: String,

    /// Worker threads for the parallel stages (default: all available cores).
    #[arg(long)]
    workers: Option<usize>,

    /// The cert store (JSONL of `<index>\t<Classified>`). The fast classification appends to
    /// it (resumable: already-done tiles are skipped, so one store accumulates many
    /// perimeter blocks); `--deep` writes the `<store>.deep.jsonl` overlay which
    /// `--merge` applies; `--verify` reads it.
    #[arg(long, required_unless_present_any = ["render", "coronas", "reptile"])]
    store: Option<PathBuf>,

    // --- mode selectors (mutually exclusive; default = the fast classification) ---
    /// Fast staged classification of one `--perim` block (the default; the flag is explicit).
    #[arg(long, conflicts_with_all = ["deep", "verify"])]
    fast: bool,

    /// --deep: re-classify the store's Undecided residue with a high budget,
    /// appending results to the `<store>.deep.jsonl` overlay (resumable;
    /// apply onto the store with `--merge`).
    #[arg(long, conflicts_with_all = ["fast", "verify"])]
    deep: bool,

    /// Apply a deep overlay onto the store: Decided overlay verdicts replace
    /// the store's Undecided lines (never the reverse); entries absent from
    /// the store are appended.
    #[arg(long, value_name = "OVERLAY", conflicts_with_all = ["fast", "deep", "verify", "pack", "lookup"])]
    merge: Option<PathBuf>,

    /// Re-verify a finished store and check per-perimeter completeness.
    #[arg(long, conflicts_with_all = ["fast", "deep"])]
    verify: bool,

    /// Sort the store by dafsa index (atomic rewrite) so `--lookup` can
    /// bisect it. Safe at any time; every other mode ignores line order.
    #[arg(long, conflicts_with_all = ["fast", "deep", "verify", "lookup"])]
    pack: bool,

    /// Point query of one tile's verdict in a PACKED store: a dafsa index, or
    /// a turn word (comma/space-separated, brackets optional) in any rotation,
    /// chirality, or traversal orientation.
    #[arg(long, conflicts_with_all = ["fast", "deep", "verify", "pack"])]
    lookup: Option<String>,

    /// Render a tile's maximal corona patch to SVG (no `--store` needed): a
    /// dafsa index or a turn word (same forms as `--lookup`). Writes one SVG
    /// per selected `--render-mode`, drawing the deepest corona a bounded
    /// Heesch search (bound 3) reaches around the tile.
    #[arg(long, conflicts_with_all = ["fast", "deep", "verify", "pack", "lookup", "merge"])]
    render: Option<String>,

    /// `--render` coloring: `corona` (by concentric ring), `rotation` (by tile
    /// orientation), or `both` (default -- writes one SVG each).
    #[arg(long, value_enum, default_value_t = RenderView::Both, requires = "render")]
    render_mode: RenderView,

    /// `--render` output path. Single mode: the SVG file. `both`: a stem, with
    /// `_corona.svg` / `_rotation.svg` appended. Default: `corona_<index>` in
    /// the working directory. Also the output DIRECTORY stem for `--coronas`.
    #[arg(long)]
    render_out: Option<PathBuf>,

    /// Enumerate ALL distinct k-coronas of a tile (a dafsa index or turn word)
    /// and render each to its own SVG (corona-ring colored). No `--store`
    /// needed. Pair with `--coronas-k` and `--coronas-edge`. Files are written
    /// as `<--render-out stem>_NN.svg`.
    #[arg(long, conflicts_with_all = ["fast", "deep", "verify", "pack", "lookup", "merge", "render"])]
    coronas: Option<String>,

    /// `--coronas`: number of surrounding rings to enumerate (default 2).
    #[arg(long, default_value_t = 2, requires = "coronas")]
    coronas_k: usize,

    /// `--coronas`: enumerate EDGE coronas (rings whose edges are buried)
    /// instead of TRUE coronas (edges buried AND every wedge sealed).
    #[arg(long, requires = "coronas")]
    coronas_edge: bool,

    /// `--coronas`: cap on the number of distinct coronas enumerated/rendered
    /// (guards the combinatorial blow-up at larger k / edge mode).
    #[arg(long, default_value_t = 64, requires = "coronas")]
    coronas_cap: usize,

    /// Rep-tile check of ONE tile (a dafsa index or turn word, same forms as
    /// `--lookup`): does it tile a `k`-scaled copy of itself with `k*k` copies?
    /// Prints the verdict and, if it is a rep-tile, a serialized `RepTileCert`
    /// (JSON) whose `build` replays the tiling. With `--reptile-out`, also writes
    /// the witness patch to SVG. No `--store` needed.
    #[arg(long, conflicts_with_all = ["fast", "deep", "verify", "pack", "lookup", "merge", "render", "coronas"])]
    reptile: Option<String>,

    /// Max linear scale `k` tried by `--reptile` / `--reptile-screen`
    /// (rep-order up to `k*k`). Default 6.
    #[arg(long, default_value_t = 6)]
    reptile_kmax: usize,

    /// `--reptile` output: SVG path for the witness patch (orientation-colored).
    /// Also the hits store for `--reptile-screen`.
    #[arg(long)]
    reptile_out: Option<PathBuf>,

    /// Screen the cert `--store`'s PERIODIC tiles for rep-tiles, writing one
    /// `<index>\t<RepTileCert>` line per hit to `--reptile-out` (up to scale
    /// `--reptile-kmax`).
    #[arg(long, requires = "reptile_out", conflicts_with_all = ["fast", "deep", "verify", "pack", "lookup", "merge", "render", "coronas", "reptile"])]
    reptile_screen: bool,

    /// `--reptile-screen`: per-scale node budget for the fill. A tile that
    /// exhausts it at some scale is recorded inconclusive (in
    /// `<reptile-out>.inconclusive`) instead of hanging the screen -- a real
    /// rep-tile is found long before this. Default 300000.
    #[arg(long, default_value_t = 300_000)]
    reptile_budget: usize,

    // --- fast-mode args ---
    /// Perimeter (tile boundary length) to classify. Required for the fast classification
    /// unless `--from/--to` give an explicit index range; an optional single-block
    /// filter for `--verify`.
    #[arg(long)]
    perim: Option<usize>,

    /// Fast: classify the explicit dafsa index range [FROM, TO) instead of a
    /// whole perimeter. Progress is recorded in the `<store>.ranges` coverage
    /// sidecar per completed window, so scans can continue from where a
    /// previous launch stopped (and boring certs can be filtered away without
    /// losing the scanned-range record -- see tools/filter_store.py).
    #[arg(long, requires = "to", conflicts_with_all = ["perim", "deep", "verify", "pack", "lookup", "merge"])]
    from: Option<u64>,

    /// Fast: exclusive end of the `--from` index range.
    #[arg(long, requires = "from")]
    to: Option<u64>,

    /// Fast: index-window size -- classify the perimeter in windows of this many
    /// tiles so only one window's rats are resident (needed from n=15 up;
    /// default 0 = whole perimeter at once).
    #[arg(long, conflicts_with_all = ["deep", "verify"], default_value_t = 0)]
    chunk: usize,

    /// Run only the periodic-accept stages (Conway / torus / aniso / iso). Applies
    /// to the fast classification AND `--deep`; leaves everything non-periodic Undecided.
    #[arg(long, conflicts_with_all = ["heesch_only", "verify"])]
    periodic_only: bool,

    /// Run only the Heesch-reject stages. Applies to the fast classification AND `--deep`;
    /// leaves everything not rejected Undecided.
    #[arg(long, conflicts_with_all = ["periodic_only", "verify"])]
    heesch_only: bool,

    // --- bounds (defaults are the calibrated production values) ---
    /// Fast: deep-Heesch node budget for the reject tail (default: the calibrated
    /// `FastConfig` value; the budget-limited family is deferred to `--deep`).
    #[arg(long, conflicts_with_all = ["deep", "verify"])]
    deep_budget: Option<usize>,

    /// Deep: Heesch node budget for the residue (default: the calibrated
    /// `DeepConfig` value -- sized to the measured worst case, see its docs).
    #[arg(long, conflicts_with_all = ["fast", "verify"])]
    res_budget: Option<usize>,

    /// Deep: seeded anisohedral restarts (default 12); the search is heavy-tailed, so
    /// more small restarts beat one large deterministic budget on hard tiles.
    #[arg(long, conflicts_with_all = ["fast", "verify"])]
    aniso_restarts: Option<usize>,
}

/// Parse a `--lookup` argument: a plain dafsa index, or a turn word
/// (comma/space-separated i8 turns, surrounding brackets tolerated).
fn parse_lookup(s: &str) -> Result<Result<u64, Vec<i8>>, String> {
    if let Ok(idx) = s.trim().parse::<u64>() {
        return Ok(Ok(idx));
    }
    let cleaned = s.replace(['[', ']'], " ");
    let word: Result<Vec<i8>, _> = cleaned
        .split([',', ' '])
        .filter(|t| !t.is_empty())
        .map(|t| t.parse::<i8>())
        .collect();
    match word {
        Ok(w) if !w.is_empty() => Ok(Err(w)),
        _ => Err(format!("--lookup: neither an index nor a turn word: {s}")),
    }
}

/// One-line human summary of a verdict.
fn verdict_summary(c: &Classified) -> String {
    match c {
        Classified::Decided(Verdict::Periodic(pc)) => format!(
            "PERIODIC via {:?}: meta-tile of {} base copies, {} glue pairs (fundamental domain replayable from `build`)",
            pc.via,
            pc.build.len() + 1,
            pc.glue.len()
        ),
        Classified::Decided(Verdict::CannotTile(hc)) => format!(
            "CANNOT TILE: Heesch {} ({:?}, bound {}, budget {}), corona witness {} glues",
            hc.heesch,
            hc.status,
            hc.bound,
            hc.budget,
            hc.build.len()
        ),
        Classified::Undecided { depth, corona } => format!(
            "UNDECIDED (aperiodic candidate): witnessed corona depth {depth}, witness {} glues",
            corona.len()
        ),
    }
}

impl Cli {
    /// The store path, required by every mode except `--render`, `--coronas`,
    /// and single-tile `--reptile` (clap enforces this via
    /// `required_unless_present`, so the unwrap cannot fire).
    fn store(&self) -> &PathBuf {
        self.store
            .as_ref()
            .expect("--store is required for this mode")
    }
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    let d = open_ratdb(&cli.asset);

    // Ring-AGNOSTIC store maintenance runs before ring detection: it only
    // rewrites store lines (keyed on the dafsa index), never touches geometry.
    if cli.pack {
        let n = run_pack(cli.store());
        eprintln!(
            "pack: {n} lines sorted by index in {}",
            cli.store().display()
        );
        return ExitCode::SUCCESS;
    }

    if let Some(overlay) = &cli.merge {
        run_merge(cli.store(), overlay);
        return ExitCode::SUCCESS;
    }

    // Everything past here is ring-DEPENDENT: detect the asset's effective ring
    // and run the whole pipeline monomorphized for it. `counts` (per-perimeter
    // free tally, index == perimeter) drives the perimeter ranges + completeness.
    let counts = asset_free_counts(&cli.asset);
    let ring = asset_ring(&cli.asset);
    // Reuse the crate-wide ring dispatcher (`ZZ` is the shadowed ring type):
    // every supported ring is picked up automatically, no per-ring arm here.
    tilezz::dispatch_ring!(
        ring,
        run_ring::<ZZ, _>(&cli, &d, &counts),
        else {
            eprintln!("unsupported ring: {ring} (asset effectiveRing not in the dispatch table)");
            ExitCode::FAILURE
        }
    )
}

/// The ring-dependent classifier front end, monomorphized for the asset's ring
/// `T`: every mode whose work touches tile geometry -- `--lookup`, `--render`,
/// `--coronas`, `--verify`, `--deep`, and the default fast classification --
/// runs here. `counts` is the asset's per-perimeter free tally (index ==
/// perimeter), threaded to the perimeter-range and completeness logic.
fn run_ring<T: tilezz::cyclotomic::IsRing, F: Fn(u32) -> std::io::Result<Vec<u8>>>(
    cli: &Cli,
    d: &tilezz::dataset::LazyRatDafsa<F>,
    counts: &[u64],
) -> ExitCode {
    let workers = cli.workers.unwrap_or(0);

    // Resolve a --render / --coronas query to (angle sequence, optional dataset
    // index). A turn word is used directly (with its dataset index if present);
    // a plain index is looked up in the asset.
    let resolve = |q: &str| -> Result<(Vec<i8>, Option<u64>), String> {
        match parse_lookup(q)? {
            Ok(idx) => match d.get(idx) {
                Some(s) => Ok((s, Some(idx))),
                None => Err(format!("index {idx} is outside the dataset range")),
            },
            Err(word) => {
                let canon = ccw_free_canonical(&word);
                let idx = d.index_of(&canon);
                Ok((canon, idx))
            }
        }
    };

    if let Some(q) = &cli.lookup {
        let idx = match parse_lookup(q) {
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::FAILURE;
            }
            Ok(Ok(idx)) => idx,
            Ok(Err(word)) => {
                let canon = ccw_free_canonical(&word);
                match d.index_of(&canon) {
                    Some(idx) => {
                        eprintln!("word canonicalized to {canon:?} = dataset index {idx}");
                        idx
                    }
                    None => {
                        eprintln!("word {word:?} (canonical {canon:?}) is not in the dataset");
                        return ExitCode::FAILURE;
                    }
                }
            }
        };
        return match store_lookup(cli.store(), idx) {
            Err(e) => {
                eprintln!("lookup failed: {e} (is the store packed? run --pack)");
                ExitCode::FAILURE
            }
            Ok(None) => {
                eprintln!(
                    "idx {idx}: no verdict in this store (not yet classified, or store not packed -- run --pack)"
                );
                ExitCode::FAILURE
            }
            Ok(Some(c)) => {
                let seq = d.get(idx).expect("index in dataset range");
                println!("idx {idx}  seq {seq:?}");
                println!("{}", verdict_summary(&c));
                println!("{}", serde_json::to_string(&c).unwrap());
                ExitCode::SUCCESS
            }
        };
    }

    if let Some(q) = &cli.render {
        let (seq, idx) = match resolve(q) {
            Ok(x) => x,
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::FAILURE;
            }
        };

        // Deepest corona a bounded Heesch search reaches around the tile.
        let base = Rat::<T>::from_slice_trusted(&seq);
        let (h, build) = heesch_number_witnessed(TileSet::single(base.clone()), 0, 3, 20_000_000);
        eprintln!(
            "render {seq:?}: {h:?}, {} tiles (center + {} glues)",
            build.len() + 1,
            build.len()
        );

        let label = idx.map_or_else(|| "tile".to_string(), |i| i.to_string());
        let stem = cli
            .render_out
            .clone()
            .unwrap_or_else(|| std::path::PathBuf::from(format!("corona_{label}")));
        let stem = stem.to_string_lossy();
        let stem = stem.strip_suffix(".svg").unwrap_or(&stem);

        let both = cli.render_mode == RenderView::Both;
        let modes: &[(TileColoring, &str)] = match cli.render_mode {
            RenderView::Corona => &[(TileColoring::Corona, "corona")],
            RenderView::Rotation => &[(TileColoring::Rotation, "rotation")],
            RenderView::Both => &[
                (TileColoring::Corona, "corona"),
                (TileColoring::Rotation, "rotation"),
            ],
        };
        for &(mode, tag) in modes {
            let Some(svg) = witness_svg(&base, &build, mode, 720) else {
                eprintln!("render failed: could not replay the corona witness");
                return ExitCode::FAILURE;
            };
            let path = if both {
                PathBuf::from(format!("{stem}_{tag}.svg"))
            } else {
                PathBuf::from(format!("{stem}.svg"))
            };
            if let Err(e) = std::fs::write(&path, svg) {
                eprintln!("write {}: {e}", path.display());
                return ExitCode::FAILURE;
            }
            eprintln!("wrote {} ({tag})", path.display());
        }
        return ExitCode::SUCCESS;
    }

    if let Some(q) = &cli.coronas {
        let (seq, idx) = match resolve(q) {
            Ok(x) => x,
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::FAILURE;
            }
        };
        let base = Rat::<T>::from_slice_trusted(&seq);
        let ts = TileSet::single(base.clone());
        let (builds, capped) = enumerate_coronas(
            &ts,
            0,
            cli.coronas_k,
            cli.coronas_edge,
            20_000_000,
            cli.coronas_cap,
        );
        let kind = if cli.coronas_edge { "edge" } else { "true" };
        eprintln!(
            "{} distinct {kind} {}-coronas{}",
            builds.len(),
            cli.coronas_k,
            if capped { " (cap/budget hit)" } else { "" }
        );
        let label = idx.map_or_else(|| "tile".to_string(), |i| i.to_string());
        let stem = cli.render_out.clone().unwrap_or_else(|| {
            std::path::PathBuf::from(format!("coronas_{label}_{kind}{}", cli.coronas_k))
        });
        let stem = stem.to_string_lossy();
        let stem = stem.strip_suffix(".svg").unwrap_or(&stem);
        for (n, build) in builds.iter().enumerate() {
            let Some(svg) = witness_svg(&base, build, TileColoring::Corona, 480) else {
                continue;
            };
            let path = PathBuf::from(format!("{stem}_{n:02}.svg"));
            if let Err(e) = std::fs::write(&path, svg) {
                eprintln!("write {}: {e}", path.display());
                return ExitCode::FAILURE;
            }
        }
        eprintln!("wrote {} svgs as {stem}_NN.svg", builds.len());
        return ExitCode::SUCCESS;
    }

    if let Some(q) = &cli.reptile {
        let (seq, idx) = match resolve(q) {
            Ok(x) => x,
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::FAILURE;
            }
        };
        let base = Rat::<T>::from_slice_trusted(&seq);
        let label = idx.map_or_else(|| "tile".to_string(), |i| i.to_string());
        match reptile_cert(&base, cli.reptile_kmax) {
            None => eprintln!(
                "{label} {seq:?}: NOT a rep-tile through scale k={} (a proof -- exhaustive over \
                 orientation-preserving copies)",
                cli.reptile_kmax
            ),
            Some(cert) => {
                let order = cert.k * cert.k;
                debug_assert!(cert.verify(&base), "minted cert must self-verify");
                eprintln!(
                    "{label} {seq:?}: REP-TILE of order {order} -- {order} copies tile the \
                     {}x-scaled tile ({} glues in `build`)",
                    cert.k,
                    cert.build.len()
                );
                println!("{}", serde_json::to_string(&cert).unwrap());
                if let Some(out) = &cli.reptile_out {
                    match witness_svg(&base, &cert.build, TileColoring::Rotation, 720) {
                        Some(svg) => {
                            let stem = out.to_string_lossy();
                            let path = PathBuf::from(format!(
                                "{}.svg",
                                stem.strip_suffix(".svg").unwrap_or(&stem)
                            ));
                            if let Err(e) = std::fs::write(&path, svg) {
                                eprintln!("write {}: {e}", path.display());
                                return ExitCode::FAILURE;
                            }
                            eprintln!("wrote {}", path.display());
                        }
                        None => eprintln!("render failed: could not replay the witness"),
                    }
                }
            }
        }
        return ExitCode::SUCCESS;
    }

    if cli.reptile_screen {
        let out = cli
            .reptile_out
            .as_ref()
            .expect("--reptile-out (clap requires it)");
        run_reptile_screen::<T, _>(d, cli.store(), out, cli.reptile_kmax, cli.reptile_budget);
        return ExitCode::SUCCESS;
    }

    if cli.verify {
        let report = run_verify::<T, _>(d, counts, cli.store(), cli.perim);
        return if report.is_clean() {
            eprintln!("verify: store is clean.");
            ExitCode::SUCCESS
        } else {
            eprintln!("verify: store is DIRTY: {report:?}");
            ExitCode::FAILURE
        };
    }

    // Verdict restriction (orthogonal to fast/deep): --periodic-only / --heesch-only.
    let mode = if cli.periodic_only {
        StageMode::PeriodicOnly
    } else if cli.heesch_only {
        StageMode::HeeschOnly
    } else {
        StageMode::Full
    };

    if cli.deep {
        let mut cfg = DeepConfig {
            mode,
            workers,
            ..DeepConfig::default()
        };
        if let Some(b) = cli.res_budget {
            cfg.res_budget = b;
        }
        if let Some(r) = cli.aniso_restarts {
            cfg.bounds.aniso_restarts = r;
        }
        run_deep::<T, _>(d, cli.store(), &cfg);
        return ExitCode::SUCCESS;
    }

    // Default mode: the fast staged classification (whole perimeter, or an
    // explicit --from/--to index range).
    let mut cfg = FastConfig {
        mode,
        workers,
        chunk: cli.chunk,
        ..FastConfig::default()
    };
    if let Some(b) = cli.deep_budget {
        cfg.deep_budget = b;
    }
    match (cli.from, cli.to, cli.perim) {
        (Some(from), Some(to), _) => {
            run_fast_range::<T, _>(d, from, to, cli.store(), &cfg);
        }
        (_, _, Some(perim)) => {
            run_fast::<T, _>(d, counts, perim, cli.store(), &cfg);
        }
        _ => {
            eprintln!("error: the fast classification needs --perim <N> or --from/--to");
            return ExitCode::FAILURE;
        }
    }
    ExitCode::SUCCESS
}