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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
//! Certificate minters: turn a detector's positive into a replayable,
//! verify-gated [`PeriodicCert`] / [`HeeschCert`].
//!
//! Every minter here ends in the same gate -- [`PeriodicCert::verify`] (or a
//! `verify_lower_bound` debug-check for Heesch) -- so a mis-read corona, a
//! mis-carve, or a frame mismatch yields `None` (the tile stays a candidate
//! for the next detector), never a wrong cert. The cert TYPES and their
//! replay/verify live in [`cert`](crate::classify::cert); the
//! decision CASCADES that call these minters live in
//! [`cascade`](crate::classify::cascade).

use crate::classify::cascade::PeriodicVia;
use crate::classify::cert::{HeeschCert, HeeschStatus, PeriodicCert, base_verts, meta_of};
use crate::classify::grow::grow_coronas_build;
use crate::classify::heesch::{Heesch, count_coronas, heesch_number_witnessed};
use crate::classify::lattice::{basis_inverse, in_lattice, lay_lattice_block};
use crate::classify::tiling::{AREA_EPS, Tiling};
use crate::classify::torus::{TorusCover, torus_cover_from_patch};
use crate::cyclotomic::IsRing;
use crate::cyclotomic::geometry::float::area_f;
use crate::geom::iso::{Iso, gluing_iso};
use crate::geom::matches::{EdgeRange, PatchMatch, Segment, TileMatch};
use crate::geom::patch::BasicPatch;
use crate::geom::patch::graph::{WithAdjacency, assemble};
use crate::geom::rat::Rat;
use crate::geom::tileset::TileSet;
use crate::stringmatch::lex_min_rot;
use std::collections::VecDeque;

/// Grow the corona patch ONCE at `coronas` depth (recording its glue recipe),
/// read a `<= kmax`-tile torus cover off it, and mint from that SAME patch --
/// detection and the carve share the one growth, in the one frame:
///
/// - `k == 1`: the base is the meta-tile, a compact p1/p2 self-glue
///   ([`cert_from_placements`]).
/// - `k > 1`: carve a connected `k`-tile fundamental domain out of the patch via
///   [`carve_domain`], reading the adjacency the grower built INLINE (in the
///   [`WithAdjacency`] patch) DURING the search -- no second growth, no
///   re-search, no recipe replay.
///
/// [`PeriodicCert::verify`] gates the result, so a mis-carve just yields `None`,
/// never a wrong cert. `None` also if the depth-`coronas` patch exposes no cover;
/// a SINGLE depth on purpose (the grower is super-linear in depth -- a deep
/// escalation cost a tail tile ~400s once), so the cascade escalates by
/// calling again at deeper coronas rather than this looping internally.
pub(crate) fn torus_cert<T: IsRing>(
    base: &Rat<T>,
    kmax: usize,
    coronas: usize,
) -> Option<PeriodicCert> {
    let (pls, ig) = grow_coronas_build::<T>(base.seq(), coronas)?;
    mint_cover(base, &ig, &pls, kmax)
}

/// Shared cover-mint tail of [`torus_cert`] and [`witness_torus_cert`]: given a
/// graph-carrying patch `ig` and its placements `pls` (node `i` == `pls[i]`),
/// detect a torus cover and mint the cheapest cert for it. Cheapest first, for
/// ANY cover k: the compact base self-glue ([`cert_from_placements`]), which
/// succeeds exactly when the base is itself a p1/p2 monotile in the laid tiling
/// (cert meta-tile k = 1 regardless of the cover's k); else carve a connected
/// k-tile fundamental domain from `ig`'s inline adjacency ([`carve_domain`]).
/// `None` if the patch exposes no cover; [`PeriodicCert::verify`] gates the
/// result, so a mis-carve yields `None`, never a wrong cert.
fn mint_cover<T: IsRing>(
    base: &Rat<T>,
    ig: &WithAdjacency<BasicPatch<T>>,
    pls: &[Iso<T>],
    kmax: usize,
) -> Option<PeriodicCert> {
    let verts = base_verts(base);
    let tile_area = area_f(&verts);
    if tile_area < AREA_EPS {
        return None;
    }
    let cover = torus_cover_from_patch(&verts, base.seq(), pls, tile_area, kmax)?;
    if let Some(pc) = cert_from_placements(
        base,
        &lay_cover(cover.lattice, &cover.domain),
        PeriodicVia::Torus(1),
    ) {
        return Some(pc);
    }
    carve_domain(base, ig, pls, &cover)
}

/// Mint a meta-tile [`PeriodicCert`] by carving a connected `k`-tile fundamental
/// domain out of the periodic tiling a cover describes -- entirely through the
/// patch's inline adjacency, no lattice orbit and no re-tiling search.
///
/// The `ig` patch's adjacency is the lattice-exposing patch's true adjacency,
/// built DURING the corona search by
/// [`WithAdjacency`](crate::geom::patch::WithAdjacency)
/// (node `i` == `pls[i]`) -- so there is nothing to rebuild here.
///
///   1. Coset-label each tile by the lattice.
///   2. [`connected_transversal`] picks one tile per coset, edge-connected;
///      [`assemble`]'s greedy peel replays that domain into a fresh patch, whose
///      glue recipe is the meta-tile `build`.
///   3. Read the meta-tile self-`glue` geometrically: each meta boundary edge
///      is mapped to its patch-frame endpoints (via the placement of the tile
///      that owns it) and paired with the boundary edge that is its exact
///      lattice translate -- same physical edge one cell over, traversed
///      anti-parallel. [`PeriodicCert::verify`] gates the result.
fn carve_domain<T: IsRing>(
    base: &Rat<T>,
    ig: &WithAdjacency<BasicPatch<T>>,
    pls: &[Iso<T>],
    cover: &TorusCover<T>,
) -> Option<PeriodicCert> {
    let trace = crate::classify::trace::cover();
    let verts = base_verts(base);
    let k = cover.k;
    let (w1, w2) = cover.lattice;
    let winv = basis_inverse(&w1, &w2)?;
    // Coset of a placement: which cover domain rep it matches modulo the lattice
    // (`k` = none). The patch and the cover share the tile-0 = identity frame
    // (same grown patch), so this labels correctly.
    let coset = |iso: &Iso<T>| -> usize {
        cover
            .domain
            .iter()
            .position(|r| r.rot == iso.rot && in_lattice(iso.shift - r.shift, w1, w2, &winv))
            .unwrap_or(k)
    };

    // The adjacency is the true adjacency of the grown patch (built during the
    // search), so its node count must match the placement count.
    if pls.len() != ig.num_tiles() {
        return None;
    }
    let cls: Vec<usize> = pls.iter().map(coset).collect();
    if cls[0] >= k {
        return None; // frame mismatch (seed not recognised)
    }
    // Stage 2: one tile per coset, edge-connected (spanning-tree lift, no search);
    // assemble replays its glues into the meta-tile build.
    let dom = connected_transversal(ig.adj(), &cls, k, 0)?;
    if trace {
        eprintln!("CARVE: {} tiles, k={k}, dom={dom:?}", pls.len());
    }
    let (build, gpm, order) = assemble(ig.shape(), ig.adj(), &dom, base)?;

    // Stage 3: pair each meta boundary edge with its lattice-translate partner --
    // directed edge e (A -> B) pairs with f (C -> D) iff A = D + L and B = C + L
    // for a lattice vector L (same physical edge, anti-parallel, one cell over).
    // Endpoints are read in the patch frame (where `pls` and the lattice live).
    let m = verts.len();
    let bn = gpm.len();
    let mut ep: Vec<(T, T)> = Vec::with_capacity(bn);
    for i in 0..bn {
        let t = order[gpm.patch_tile_ids()[i]]; // patch tile of this gpm tile
        let off = gpm.edges()[i].canon_offset;
        let poly = pls[t].tile(&verts);
        ep.push((poly[off], poly[(off + 1) % m]));
    }
    let mut glue: Vec<TileMatch> = Vec::with_capacity(bn);
    for i in 0..bn {
        let (a, b) = ep[i];
        let partner = (0..bn).find(|&j| {
            if j == i {
                return false;
            }
            let (c, d) = ep[j];
            a - d == b - c && in_lattice(a - d, w1, w2, &winv)
        });
        let Some(j) = partner else {
            if trace {
                eprintln!("CARVE: meta boundary edge {i} has no lattice-translate partner");
            }
            return None;
        };
        glue.push(TileMatch::new(
            Segment::new(0, EdgeRange::new(i, 1)),
            Segment::new(0, EdgeRange::new(j, 1)),
        ));
    }
    // k>1 carve: the meta-tile is `build.len()+1` base copies, minted via torus.
    let via = PeriodicVia::Torus(build.len() + 1);
    let cert = PeriodicCert { build, glue, via };
    cert.verify(base).then_some(cert)
}

/// Carve a **connected fundamental domain** out of a patch's adjacency `adj`
/// (per-node incidence lists; `adj[i]` = node `i`'s edges): a set of nodes, one
/// per class (class id given by `class`), that is edge-connected. `k` is the
/// class count. Built by the quotient spanning-tree lift -- contract the graph by
/// class, take a spanning tree of the (connected) quotient rooted at
/// `class[root]`, and lift it: keep a chosen node per class, and for each
/// quotient tree edge attach a class-`b` neighbour of the already-chosen
/// class-`a` node. Nodes whose class is `>= k` (a sentinel for "not a class
/// of interest", e.g. a non-tiling tile) are ignored, so connectivity flows
/// only through real classes. Returns the `k` node ids (root's class first),
/// or `None` if fewer than `k` classes are reachable within this graph.
///
/// Graph-pure: it reads only the adjacency slices the [`WithAdjacency`] patch
/// carries inline, no geometry.
pub(crate) fn connected_transversal(
    adj: &[Vec<TileMatch>],
    class: &[usize],
    k: usize,
    root: usize,
) -> Option<Vec<usize>> {
    debug_assert_eq!(class.len(), adj.len());
    if class[root] >= k {
        return None;
    }
    let mut chosen: Vec<Option<usize>> = vec![None; k]; // class -> node
    chosen[class[root]] = Some(root);
    let mut queue = VecDeque::from([class[root]]);
    let mut placed = 1;
    while let Some(ca) = queue.pop_front() {
        let na = chosen[ca].expect("class in queue is placed");
        // Every class-b neighbour of THIS node; a new class gets placed here.
        for e in &adj[na] {
            let cb = class[e.b.tile_id];
            if cb < k && chosen[cb].is_none() {
                chosen[cb] = Some(e.b.tile_id);
                placed += 1;
                queue.push_back(cb);
            }
        }
    }
    if placed != k {
        return None;
    }
    // Root's class first, then the rest in class order (deterministic).
    let mut out = Vec::with_capacity(k);
    out.push(root);
    for (c, node) in chosen.iter().enumerate() {
        if c != class[root] {
            out.push(node.expect("all classes placed"));
        }
    }
    Some(out)
}

/// Assemble a connected subset of nodes (from a patch's inline adjacency
/// `adj`/`shape`) into a fresh [`BasicPatch`], returning the glue recipe (a
/// `build` for a [`PeriodicCert`]), the patch, and the placement order
/// (`order[j]` is the node placed as tile `j`; `order[0] == nodes[0]`, the seed).
///
/// Lay the periodic tiling a torus cover describes: each domain rep across a
/// block of `+-reach` lattice translates. The reps come off a seed-frame patch
/// grown from the base, so they sit near the origin and a reach of 4 surrounds
/// the base (which is one of the laid tiles). Periodic by construction, so the
/// base's corona neighbours read off it ARE tiling symmetries.
fn lay_cover<T: IsRing>(lattice: (T, T), domain: &[Iso<T>]) -> Vec<Iso<T>> {
    let (v1, v2) = lattice;
    // +-4 lattice cells: the reps sit near the origin (seed-frame patch), so
    // this block surrounds the base with margin for any kmax-bounded domain.
    const LAY_REACH: i64 = 4;
    lay_lattice_block(domain, v1, v2, LAY_REACH, LAY_REACH)
}

/// Like [`torus_cert`], but read the cover off an ALREADY-STORED patch recipe
/// -- a banked corona witness -- instead of growing one: replay the recipe
/// with placement capture, detect the lattice in that patch, and mint (the
/// compact k=1 self-glue, else the carve through the SAME recipe). A stored
/// witness is routinely DEEPER than anything the funnel grows (bound-6
/// Heesch patches vs coronas-5 grows) and replaying it is nearly free -- so
/// the deep pass runs every surviving tile's witness through this before
/// paying for any fresh growth or search. `None` if the witness patch does
/// not expose a lattice (e.g. a rosette-grain patch) -- the tile then falls
/// through to the growing detectors as before.
pub(crate) fn witness_torus_cert<T: IsRing>(
    base: &Rat<T>,
    witness: &[PatchMatch],
    kmax: usize,
) -> Option<PeriodicCert> {
    if witness.is_empty() {
        return None;
    }
    // Replay through a graph-carrying patch: placements + the inline adjacency in
    // one pass (node i == pls[i]), the same adjacency the old carve rebuilt from
    // the recipe -- now built natively so the carve reads it directly.
    let (pls, ig) = crate::classify::grow::replay_placements_graph(base, witness)?;
    mint_cover(base, &ig, &pls, kmax)
}

/// Mint a pure-translation (p1) cert from a Beauquier-Nivat lattice proposal:
/// lay the base across the `(v1, v2)` block and read the k=1 self-glue off
/// its corona. Verify-gated like every minter -- a wrong or degenerate
/// proposal yields `None`, never a wrong cert.
pub(crate) fn translation_cert<T: IsRing>(base: &Rat<T>, v1: T, v2: T) -> Option<PeriodicCert> {
    cert_from_placements(
        base,
        &lay_cover((v1, v2), &[Iso::id()]),
        PeriodicVia::Translation,
    )
}

/// Mint a k=1 corona cert (stamped with `via`) from seed-frame placements that
/// contain the base at the identity somewhere in the list (order irrelevant --
/// the corona read-off skips the identity and searches the rest). Shared by the
/// torus path (via `Torus(1)`) and [`cert_from_tiling`] (Conway / Isohedral).
fn cert_from_placements<T: IsRing>(
    base: &Rat<T>,
    placements: &[Iso<T>],
    via: PeriodicVia,
) -> Option<PeriodicCert> {
    let glue = glue_from_corona(&base_verts(base), placements)?;
    let cert = PeriodicCert {
        build: vec![],
        glue,
        via,
    };
    cert.verify(base).then_some(cert)
}

/// Mint a META-TILE [`PeriodicCert`] from a connected k-copy cluster recipe (the
/// anisohedral cluster witness) and the cluster's OWN verified tiling, which
/// the search already built ([`crate::classify::aniso::tiles_anisohedral_restart`] hands it back -- no
/// re-search, no rebuild). This certifies the genuinely k>1 and rotational
/// (p3/p4/p6) tilings that a k=1 base self-glue cannot represent.
///
/// The search's tiling lives on the lex-min CANONICAL rotation of the cluster
/// boundary, while `verify` replays `build` into the deterministic REPLAY
/// frame; the two boundaries are the same word rotated by
/// `lex_min_rot(meta_seq)`, so the glue's edge indices translate by that fixed
/// offset (`canon[i] == meta[(i + r) % n]`, hence edge `i` canonical == edge
/// `(i + r) % n` replay). [`PeriodicCert::verify`] gates the result, so an
/// offset bug yields `None` (a lost accept, caught by the provenance tests),
/// never a wrong cert. `None` also if the tiling's corona does not read as a
/// clean self-gluing rule.
pub fn cert_from_cluster<T: IsRing>(
    base: &Rat<T>,
    build: &[PatchMatch],
    cluster_tiling: &Tiling<T>,
    via: PeriodicVia,
) -> Option<PeriodicCert> {
    let trace = crate::classify::trace::cover();
    let Some((_meta_verts, meta_seq, _k)) = meta_of(build, base) else {
        if trace {
            eprintln!("CLUSTER: meta_of None");
        }
        return None;
    };
    let Some(glue_canon) = glue_from_corona(&cluster_tiling.verts, &cluster_tiling.placements)
    else {
        if trace {
            eprintln!("CLUSTER: glue_from_corona None");
        }
        return None;
    };
    // Canonical frame -> replay frame: shift every edge index by the rotation.
    let (n, r) = (meta_seq.len(), lex_min_rot(&meta_seq));
    let glue = glue_canon
        .iter()
        .map(|tm| {
            TileMatch::new(
                Segment::new(0, EdgeRange::new((tm.a.range.start_offset + r) % n, 1)),
                Segment::new(0, EdgeRange::new((tm.b.range.start_offset + r) % n, 1)),
            )
        })
        .collect();
    let cert = PeriodicCert {
        build: build.to_vec(),
        glue,
        via,
    };
    let ok = cert.verify(base);
    if trace && !ok {
        eprintln!("CLUSTER: verify failed");
    }
    ok.then_some(cert)
}

/// Mint a [`PeriodicCert`] from a constructed [`Tiling`] (Conway or isohedral)
/// as a k=1 self-gluing rule read straight off the base tile's corona.
///
/// The detector already grew a periodic orbit cheaply (`build_orbit`, no
/// backtracking). For each boundary edge of the base we find the neighbour copy
/// abutting it in that orbit and record which of its edges meets ours; that
/// pairing IS the glue, and `gluing_iso` recovers the placing isometry --
/// translation or half-turn. So the meta-tile is just the base (k=1) and a p2
/// half-turn tiling needs no 2-copy cell. This sidesteps both the bad-lattice
/// misfires of factoring a guessed lattice and `grow_coronas`'s super-linear
/// explosion (158s seen at depth 3). [`PeriodicCert::verify`] gates the result,
/// so a mis-read corona just yields `None` (the tile falls through to the next
/// detector, and failing all, to Heesch/Undecided), never a
/// wrong cert. `None` if the base is not fully surrounded in the orbit.
pub fn cert_from_tiling<T: IsRing>(
    base: &Rat<T>,
    tiling: &Tiling<T>,
    via: PeriodicVia,
) -> Option<PeriodicCert> {
    cert_from_placements(base, &tiling.placements, via)
}

/// Read a k=1 self-gluing rule off the base tile's corona: pair each base
/// boundary edge `e` (directed `a0 -> a1`) with the edge `f` of the neighbour
/// copy that abuts it -- the neighbour traverses the shared edge the other way
/// (`a1 -> a0`). The recorded `f` is chosen so [`gluing_iso`] reconstructs that
/// neighbour's placement EXACTLY: a self-symmetric tile carries the shared edge
/// at several boundary positions, and a wrong `f` would reconstruct an iso that
/// places the same tile shape but is not a tiling symmetry (it differs by the
/// tile's stabilizer), poisoning the group `verify` builds. `None` if any edge
/// has no neighbour in `placements` (the base is not fully surrounded).
fn glue_from_corona<T: IsRing>(verts: &[T], placements: &[Iso<T>]) -> Option<Vec<TileMatch>> {
    let n = verts.len();
    let mut glue = Vec::with_capacity(n);
    for e in 0..n {
        let (a0, a1) = (verts[e], verts[(e + 1) % n]);
        // The placement abutting edge e carries the reversed edge a1 -> a0.
        let neighbour = placements.iter().find(|p| {
            if p.rot == 0 && p.shift.xy() == (0.0, 0.0) {
                return false; // the base is not its own neighbour
            }
            let tile = p.tile(verts);
            (0..n).any(|f| tile[f] == a1 && tile[(f + 1) % n] == a0)
        })?;
        // The base edge f whose reconstructed glue iso IS this placement.
        let f = (0..n).find(|&f| gluing_iso(verts, e, f).as_ref() == Some(neighbour))?;
        glue.push(TileMatch::new(
            Segment::new(0, EdgeRange::new(e, 1)),
            Segment::new(0, EdgeRange::new(f, 1)),
        ));
    }
    Some(glue)
}

/// Mint a [`HeeschCert`] for a tile from a [`heesch_number_witnessed`] result:
/// the Heesch outcome `h` and the deepest corona `build` recipe captured in the
/// SAME search (no re-derivation). Records the (true) Heesch number and whether
/// the search exhausted ([`HeeschStatus::Finite`], a sound cannot-tile) or hit
/// its budget ([`HeeschStatus::Unknown`], a lower bound); `build` is the cheap
/// `>= k` witness (empty exactly when the number is 0). Intended for tiles where
/// `h` is `Finite`/`Unknown` (the reject half); for `AtLeast` it still records
/// the reached lower bound. The caller must pass the `build` that `h` came with
/// (a `verify_lower_bound` debug-check guards a mismatch).
pub fn heesch_cert<T: IsRing>(
    base: &Rat<T>,
    h: Heesch,
    build: Vec<PatchMatch>,
    bound: usize,
    budget: usize,
) -> HeeschCert {
    let (heesch, status) = match h {
        Heesch::Finite(k) => (k, HeeschStatus::Finite),
        Heesch::Unknown(k) => (k, HeeschStatus::Unknown),
        Heesch::AtLeast(b) => (b, HeeschStatus::Unknown),
    };
    // Heesch numbers / corona bounds are single digits in practice (the deep
    // bound is 6); the u8 fields are ample. Guard the invariant so a future
    // caller passing a huge bound trips a debug build instead of silently wrapping.
    debug_assert!(
        heesch <= u8::MAX as usize && bound <= u8::MAX as usize,
        "heesch/bound fit u8"
    );
    // The passed build must witness the recorded number (count_coronas >= heesch);
    // a desync here would emit an unverifiable cert.
    debug_assert!(
        count_coronas(base, &build) >= heesch,
        "build must witness >= heesch coronas"
    );
    HeeschCert {
        heesch: heesch as u8,
        status,
        build,
        bound: bound as u8,
        budget: budget.min(u32::MAX as usize) as u32,
    }
}

/// Convenience: run [`heesch_number_witnessed`] and mint a [`HeeschCert`] in one
/// call (number and witness from a single search).
pub fn heesch_cert_for<T: IsRing>(base: &Rat<T>, bound: usize, budget: usize) -> HeeschCert {
    let ts = TileSet::single(base.clone());
    let (h, build) = heesch_number_witnessed(ts, 0, bound, budget);
    heesch_cert(base, h, build, bound, budget)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::classify::cascade::AcceptBounds;
    use crate::classify::conway::build_tiling;
    use crate::classify::isohedral::isohedral_tiling;
    use crate::classify::tiling::ORBIT_RADIUS_FACTOR;
    use crate::geom::tiles;

    /// HeeschCert records the (true) Heesch number + a witness corona, and
    /// verify_lower_bound replays the witness to confirm `>= heesch`. Covers
    /// Heesch 0 (dodecagon, empty build) and Heesch 1 (a finite-Heesch n<=10
    /// tile, a real 1-corona witness).
    #[test]
    fn heesch_cert_records_and_verifies_lower_bound() {
        use crate::cyclotomic::ZZ12;

        // Heesch 0: cannot be surrounded once -> empty witness, lower bound 0.
        let dodec = Rat::<ZZ12>::from_snake_trusted(&tiles::dodecagon());
        let c0 = heesch_cert_for(&dodec, 2, 200_000);
        assert_eq!((c0.heesch, c0.status), (0, HeeschStatus::Finite));
        assert!(c0.build.is_empty());
        assert!(c0.verify_lower_bound(&dodec));

        // Heesch 1: surrounds exactly once. The witness is a real gap-free
        // corona; verify_lower_bound replays it and confirms >= 1; a cert
        // claiming >= 2 on that same witness must fail.
        let t1 = Rat::<ZZ12>::from_slice_trusted(&[-2, 1, 4, -1, 4, -1, 2, -1, 5, 1]);
        let c1 = heesch_cert_for(&t1, 2, 20_000_000);
        assert_eq!((c1.heesch, c1.status), (1, HeeschStatus::Finite));
        assert!(
            !c1.build.is_empty(),
            "Heesch-1 reject keeps a 1-corona witness"
        );
        assert!(c1.verify_lower_bound(&t1));
        let mut overclaim = c1.clone();
        overclaim.heesch = 2;
        assert!(
            !overclaim.verify_lower_bound(&t1),
            "witness only proves >= 1"
        );
    }

    /// A k=1 corona self-gluing cert mints, self-verifies and grows
    /// gap/overlap-free for the detector families the classification settles the bulk with:
    /// Conway and isohedral hand back a constructed `Tiling` (triangle is a
    /// half-turn p2 tiling -- the glue carries half-turns, not just translations;
    /// hexagon a translation monotile; iso a 4-orbit isohedral one). These MUST
    /// certify.
    ///
    /// The high-`k` torus-cover tail (tile0 k=8, the "unknown" k=3) is read
    /// off a laid torus cover; where the cover's neighbour isometries do not form
    /// a clean symmetry group this minor path returns `None` (the live pipeline
    /// would then reach the tile via aniso/deep-torus). So for those we require
    /// only that IF a cert mints here, it verifies and grows cleanly.
    #[test]
    fn periodic_cert_mints_across_detectors() {
        use crate::cyclotomic::ZZ12;
        let bounds = AcceptBounds::default();
        let tri = Rat::<ZZ12>::from_snake_trusted(&tiles::triangle());
        let hex = Rat::<ZZ12>::from_snake_trusted(&tiles::hexagon());
        // (name, seq, must_certify)
        let specimens: [(&str, &[i8], bool); 5] = [
            ("triangle", tri.seq(), true),
            ("hexagon", hex.seq(), true),
            ("iso", &[-4, 3, 4, 1, 3, 5], true),
            ("tile0", &[-4, 3, 4, 0, 4, -3, 5, 3], false),
            ("unknown", &[-2, -1, 2, 5, -2, 1, 2, 1, 2, 4], false),
        ];
        for (name, seq, must) in specimens {
            let base = Rat::<ZZ12>::from_slice_trusted(seq);
            let radius = ORBIT_RADIUS_FACTOR * seq.len() as f64;
            // The classification funnel: Conway -> isohedral (constructed Tiling, minted as
            // a corona glue), else the torus minter for cover-only tiles.
            let cert = build_tiling::<ZZ12>(seq, radius, 2_000)
                .or_else(|| isohedral_tiling::<ZZ12>(seq, radius, 2_000, bounds.iso_builds))
                .and_then(|t| cert_from_tiling(&base, &t, PeriodicVia::Conway))
                .or_else(|| {
                    torus_cert::<ZZ12>(
                        &Rat::from_slice_trusted(seq),
                        bounds.torus_kmax,
                        bounds.torus_coronas,
                    )
                });
            let Some(cert) = cert else {
                assert!(!must, "{name}: should mint a periodic cert");
                eprintln!(
                    "{name}: no cert from this minor path (high-k tail); certify_periodic would catch it"
                );
                continue;
            };
            assert!(cert.verify(&base), "{name}: minted cert must self-verify");
            let pls = cert.grow(&base, 6.0, 400).expect("grow");
            let distinct: std::collections::HashSet<_> = pls.iter().copied().collect();
            assert_eq!(
                distinct.len(),
                pls.len(),
                "{name}: grow has no duplicate placements"
            );
            eprintln!(
                "{name}: build={} glue={} grew={}",
                cert.build.len(),
                cert.glue.len(),
                pls.len()
            );
        }
    }

    #[test]
    fn torus_cert_mints_verifies_grows() {
        use crate::cyclotomic::ZZ12;

        let bounds = AcceptBounds::default();
        // Two clean torus-coverable cases: a k=2 rhombus domain (non-empty
        // build) and a k=1 translation monotile (empty build). Together they
        // exercise both PeriodicCert paths end to end (mint -> verify -> grow).
        let tri = Rat::<ZZ12>::from_snake_trusted(&tiles::triangle());
        let hex = Rat::<ZZ12>::from_snake_trusted(&tiles::hexagon());
        let candidates: [&[i8]; 2] = [
            tri.seq(), // triangle: 2-triangle rhombus meta-tile
            hex.seq(), // regular hexagon: translation monotile, k=1
        ];
        for seq in candidates {
            let cert = torus_cert::<ZZ12>(
                &Rat::from_slice_trusted(seq),
                bounds.torus_kmax,
                bounds.torus_coronas,
            )
            .unwrap_or_else(|| panic!("{seq:?}: should mint a periodic cert"));
            let base = Rat::<ZZ12>::from_slice_trusted(seq);
            assert!(cert.verify(&base), "{seq:?}: minted cert must self-verify");

            let placements = cert.grow(&base, 6.0, 400).expect("grow succeeds");
            assert!(placements.len() >= 7, "{seq:?}: grow yields a real patch");
            // Grown meta-tile copies must be lattice-distinct (no collisions).
            let distinct: std::collections::HashSet<_> = placements.iter().copied().collect();
            assert_eq!(
                distinct.len(),
                placements.len(),
                "{seq:?}: no duplicate placements"
            );

            // Verification is orbit-based: a glue stripped of its generators
            // exposes no lattice, so it cannot prove a tiling.
            let mut bad = cert.clone();
            bad.glue.clear();
            assert!(
                !bad.verify(&base),
                "{seq:?}: glue with no generators must fail verify"
            );

            eprintln!(
                "minted {seq:?}: build={} tiles, glue={} pairs, grew {} copies",
                cert.build.len(),
                cert.glue.len(),
                placements.len()
            );
        }
    }

    /// MEASUREMENT + regression (ignored: needs the ratdb asset and a stash
    /// of pre-merge n=14 Undecided store lines via WITNESS_STASH):
    /// witness_torus_cert must certify the two k=18-domain n=14 tiles
    /// (idx 16856076 / 23665356) straight from their STORED depth-6 corona
    /// witnesses -- no growth, no search. These are the tiles whose lattice
    /// hides from the coronas-4 grower; their banked witnesses are deeper
    /// and expose it.
    #[test]
    #[ignore = "needs web/ratdb asset + WITNESS_STASH (pre-merge n=14 Undecided lines)"]
    fn witness_torus_certifies_k18_pair_from_stash() {
        use crate::classify::cert::Classified;
        use crate::classify::classify_tiles::open_ratdb;
        use crate::cyclotomic::ZZ12;
        let stash = std::env::var("WITNESS_STASH").expect("WITNESS_STASH=path");
        let d = open_ratdb("web/ratdb/data/zz12_n16_free");
        let txt = std::fs::read_to_string(stash).unwrap();
        let mut hits = 0;
        for line in txt.lines() {
            let (idx_s, json) = line.split_once('\t').unwrap();
            let idx: u64 = idx_s.parse().unwrap();
            if idx != 16856076 && idx != 23665356 {
                continue;
            }
            let Ok(Classified::Undecided { corona, .. }) = serde_json::from_str(json) else {
                panic!("stash line {idx} not Undecided")
            };
            let base = Rat::<ZZ12>::from_slice_trusted(&d.get(idx).unwrap());
            let t = std::time::Instant::now();
            let pc = witness_torus_cert(&base, &corona, 40)
                .expect("stored witness exposes the k=18 lattice");
            assert!(pc.verify(&base), "idx {idx}: witness-minted cert verifies");
            eprintln!(
                "idx {idx}: via {:?}, meta {} copies, {:.2}s from stored witness",
                pc.via,
                pc.build.len() + 1,
                t.elapsed().as_secs_f64()
            );
            hits += 1;
        }
        assert_eq!(hits, 2, "both k=18 tiles certify from their witnesses");
    }

    #[test]
    fn carve_hard_torus_tiles() {
        use crate::cyclotomic::ZZ12;
        // Real ZZ12 tiles whose fundamental domain is k > 1 -- the cases the k=1
        // self-glue cannot certify. Tests JUST tiles_torus + the adjacency carve
        // (torus_cert), no cascade / aniso / heesch pipeline. Bounds
        // match run_deep's torus (deep coronas, high kmax) so the covers
        // are found. Each must mint a {build, glue} cert that self-verifies.
        let bounds = AcceptBounds {
            torus_kmax: 40,
            torus_coronas: 4,
            ..AcceptBounds::default()
        };
        let cases: [(&str, &[i8]); 3] = [
            ("14280 (k=3)", &[-2, -1, 2, 5, -2, 1, 2, 1, 2, 4]),
            ("11845 (k=4)", &[-3, 1, 3, -2, 4, 3, -2, 1, 2, 5]),
            ("2621515 (k=14)", &[-4, 0, 2, 0, 4, 0, 0, 2, 0, 2, 0, 4, 2]),
        ];
        for (name, seq) in cases {
            let base = Rat::<ZZ12>::from_slice_trusted(seq);
            let cert = torus_cert::<ZZ12>(
                &Rat::from_slice_trusted(seq),
                bounds.torus_kmax,
                bounds.torus_coronas,
            )
            .unwrap_or_else(|| panic!("{name}: torus_cert must mint a cert"));
            assert!(cert.verify(&base), "{name}: minted cert must self-verify");
            assert!(
                !cert.build.is_empty(),
                "{name}: k>1 domain has a non-empty build"
            );
            eprintln!(
                "{name}: build={} tiles, glue={} pairs",
                cert.build.len(),
                cert.glue.len()
            );
        }
    }
}