visual-cortex-vision 0.12.0

Detectors for visual-cortex: pixel/color conditions, template matching, the OcrEngine contract, and OCR text parsers.
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
//! Temporal stability mask v2: scene-anchored novelty, per-block hysteresis,
//! component fill. See docs/superpowers/specs/2026-07-06-stability-mask-v2-design.md
//! for the measured failure analysis of v1 that drove this algebra.
//!
//! Core ideas:
//! - 17-byte block signatures (16 sub-block luma means + contrast) compared
//!   by vote, so single noisy components cannot flip decisions and flat
//!   panels over textured scenes are legibly novel (dark-on-dark).
//! - An IDLE/KEPT/HOLDOVER state machine per block: kept blocks that start
//!   changing KEEP RENDERING (a re-rendering tooltip stays live instead of
//!   going black) and re-latch when they settle.
//! - Scene-anchored re-seeding: frame-global perturbation (a scene change)
//!   makes settling blocks adopt the new scene as baseline instead of
//!   becoming "kept" — novelty is always measured against the actual scene.

use std::sync::Arc;
use std::time::Duration;

use visual_cortex_capture::{Frame, FrameView, Rate};

use crate::debug::{DebugSink, DebugStage};
use crate::detector::DetectorError;
use crate::preprocessor::Preprocessor;

/// 16 sub-block means + 1 contrast byte.
pub(crate) const SIG_LEN: usize = 17;
/// Vote threshold: this many components must move/differ to flip a decision.
const VOTE: usize = 2;
/// Corroboration band: a perturbation episode only counts as "scene motion"
/// if some tick of it perturbed at least this fraction of the frame.
const CORROBORATION_FRAC: f32 = 0.35;
/// Mass-settle census: long-perturbed blocks settling together must cover at
/// least this fraction of the frame to trigger re-seeding.
const CENSUS_FRAC: f32 = 0.60;
/// Global-drift guard: if this fraction of the IDLE blocks would enter KEPT
/// via the slow-drift rule on the same tick, it is ambient lighting (a fade
/// below the movement vote) — re-seed instead. Fresh pop-in entries are
/// never drift-guarded.
const DRIFT_FRAC: f32 = 0.50;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Signature(pub [u8; SIG_LEN]);

impl Default for Signature {
    fn default() -> Self {
        Signature([0; SIG_LEN])
    }
}

/// Per-component movement vote between consecutive ticks.
pub(crate) fn is_moving(cur: &Signature, last: &Signature, tol: u8) -> bool {
    cur.0
        .iter()
        .zip(&last.0)
        .filter(|(a, b)| a.abs_diff(**b) > tol)
        .count()
        >= VOTE
}

/// Novelty vote against a u8 reference: >= VOTE sub-means differ beyond
/// `nov`, OR the contrast byte differs beyond `con` (the dark-on-dark
/// clause: a flat panel replacing textured scene at equal mean luma).
pub(crate) fn is_novel_vs(cur: &Signature, reference: &[u8; SIG_LEN], nov: u8, con: u8) -> bool {
    let sub_votes = cur.0[..16]
        .iter()
        .zip(&reference[..16])
        .filter(|(a, b)| a.abs_diff(**b) > nov)
        .count();
    sub_votes >= VOTE || cur.0[16].abs_diff(reference[16]) > con
}

/// Baseline is stored 8.8 fixed-point so the EMA can move slowly.
fn narrow(base: &[u16; SIG_LEN]) -> [u8; SIG_LEN] {
    let mut out = [0u8; SIG_LEN];
    for (o, b) in out.iter_mut().zip(base) {
        *o = (b >> 8) as u8;
    }
    out
}

fn widen(sig: &Signature) -> [u16; SIG_LEN] {
    let mut out = [0u16; SIG_LEN];
    for (o, s) in out.iter_mut().zip(&sig.0) {
        *o = (*s as u16) << 8;
    }
    out
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Phase {
    Idle,
    Kept,
    Holdover,
}

#[derive(Debug, Clone)]
pub(crate) struct Block {
    pub last: Signature,
    /// Scene reference, 8.8 fixed-point EMA. Frozen while the block is kept.
    pub base: [u16; SIG_LEN],
    /// Snapshot of the kept content — the fast re-latch reference.
    pub ovl: Signature,
    pub stable_ticks: u16,
    pub unstable_run: u16,
    pub holdover: u16,
    pub phase: Phase,
    pub initialized: bool,
    pub base_frozen: bool,
    /// Set when a scene-scale event fires during this block's perturbation
    /// episode (frame-global tick, or the mass-settle census). Resolved by
    /// re-seed or by settling back to baseline.
    pub scene_flag: bool,
    /// The current perturbation episode was corroborated by frame-wide
    /// motion — required for the long-run re-seed (locally confined churn,
    /// e.g. fast tooltip browsing, must never re-seed).
    pub run_corroborated: bool,
    /// Debug: this block re-seeded this tick.
    pub reseeded: bool,
}

impl Default for Block {
    fn default() -> Self {
        Self {
            last: Signature::default(),
            base: [0; SIG_LEN],
            ovl: Signature::default(),
            stable_ticks: 0,
            unstable_run: 0,
            holdover: 0,
            phase: Phase::Idle,
            initialized: false,
            base_frozen: false,
            scene_flag: false,
            run_corroborated: false,
            reseeded: false,
        }
    }
}

pub(crate) struct MaskParams {
    /// K: consecutive stable ticks before "settled".
    pub stable_ticks: u16,
    /// T: EMA horizon (ticks) while IDLE and unfrozen.
    pub baseline_ticks: u32,
    /// Per-component movement tolerance.
    pub signature_tolerance: u8,
    /// Per-sub-mean novelty threshold.
    pub novelty_threshold: u8,
    /// Contrast-byte novelty threshold.
    pub contrast_threshold: u8,
    /// H: ticks a kept block keeps rendering after it starts changing.
    pub holdover_ticks: u16,
    /// U: minimum corroborated unstable run that re-seeds on settle.
    pub long_run: u16,
}

/// Frame-global signals for one tick, computed in phase 1.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Globals {
    /// The whole frame perturbed this tick (scene transition band).
    pub scene_tick: bool,
    /// Enough of the frame perturbed to corroborate motion episodes.
    pub corroborated_tick: bool,
    /// Mass-settle census fired: long-perturbed blocks settling together
    /// cover a scene-scale area.
    pub census_hit: bool,
    /// Too many blocks would enter KEPT simultaneously — ambient change.
    pub drift_guard: bool,
}

fn reseed(b: &mut Block, sig: &Signature) {
    b.base = widen(sig);
    b.base_frozen = false;
    b.scene_flag = false;
    b.run_corroborated = false;
    b.unstable_run = 0;
    b.phase = Phase::Idle;
    b.reseeded = true;
}

fn ema_update(b: &mut Block, sig: &Signature, horizon: u32) {
    let t = i64::from(horizon.max(1));
    for (base, s) in b.base.iter_mut().zip(&sig.0) {
        let target = i64::from(*s) << 8;
        let delta = target - i64::from(*base);
        let mut step = delta / t;
        if step == 0 && delta != 0 {
            step = delta.signum(); // truncation must never stall convergence
        }
        *base = (i64::from(*base) + step) as u16;
    }
}

/// Advance one block one tick. `mv` and `census_eligible` come from phase 1.
/// Returns whether the block renders (pre component-pass keep flag).
pub(crate) fn step_block(
    b: &mut Block,
    sig: &Signature,
    mv: bool,
    census_eligible: bool,
    g: &Globals,
    p: &MaskParams,
) -> bool {
    b.reseeded = false;
    if !b.initialized {
        b.last = *sig;
        b.base = widen(sig);
        b.ovl = *sig;
        b.initialized = true;
        return false; // cold start: nothing is settled yet
    }

    // Tick bookkeeping (phase-independent).
    b.last = *sig;
    if mv {
        b.stable_ticks = 0;
        b.unstable_run = b.unstable_run.saturating_add(1);
        if g.corroborated_tick {
            b.run_corroborated = true;
        }
        if g.scene_tick {
            b.scene_flag = true;
        }
    } else {
        b.stable_ticks = b.stable_ticks.saturating_add(1);
    }
    if census_eligible && g.census_hit {
        b.scene_flag = true;
    }

    let base_u8 = narrow(&b.base);
    let stable = b.stable_ticks >= p.stable_ticks;
    let settled_now = !mv && b.stable_ticks == p.stable_ticks;
    let novel = is_novel_vs(sig, &base_u8, p.novelty_threshold, p.contrast_threshold);

    match b.phase {
        Phase::Kept => {
            // Base stays frozen: the no-ghosting invariant — a held tooltip
            // is never absorbed, so it stays revealed indefinitely.
            if mv {
                b.phase = Phase::Holdover;
                b.holdover = p.holdover_ticks;
            } else {
                b.ovl = *sig;
                b.unstable_run = 0;
                b.run_corroborated = false;
            }
            true // renders in both arms: the re-render stays live
        }
        Phase::Holdover => {
            // 1. ovl re-latch FIRST (ordering pinned by the
            //    flash-over-held-tooltip test): if the content matches what
            //    was kept, return to KEPT immediately — no K-tick wait, and
            //    NO base_stale re-seed (a flash is not a scene change).
            if !mv && !is_novel_vs(sig, &b.ovl.0, p.novelty_threshold, p.contrast_threshold) {
                b.phase = Phase::Kept;
                b.unstable_run = 0;
                b.run_corroborated = false;
                return true;
            }
            if settled_now {
                if novel {
                    // A different tooltip settled: seamless hand-off. If a
                    // scene event fired while this block was occluded, the
                    // base is suspect and we CANNOT tell "new overlay" from
                    // "revealed new scene" — prefer revealing (a suppressed
                    // tooltip is a hard failure; extra revealed scene is
                    // benign and re-anchors on the next frame-global
                    // motion). scene_flag rides along unresolved.
                    b.phase = Phase::Kept;
                    b.ovl = *sig;
                    b.unstable_run = 0;
                    b.run_corroborated = false;
                    return true;
                }
                // Content matches the base: the scene did not actually
                // change under the overlay — thaw, clear any suspect flag,
                // and suppress.
                b.phase = Phase::Idle;
                b.base_frozen = false;
                b.scene_flag = false;
                b.unstable_run = 0;
                b.run_corroborated = false;
                return false;
            }
            b.holdover = b.holdover.saturating_sub(1);
            if b.holdover == 0 {
                b.phase = Phase::Idle;
                return false;
            }
            true // still rendering the live (changing) content
        }
        Phase::Idle => {
            if settled_now {
                let long_run = b.unstable_run >= p.long_run && b.run_corroborated;
                let scene = b.scene_flag;
                b.unstable_run = 0;
                b.run_corroborated = false;
                if long_run || scene {
                    // Sustained corroborated motion or a scene-scale event:
                    // adopt the new scene, never keep it.
                    reseed(b, sig);
                    return false;
                }
                b.scene_flag = false;
                if novel {
                    // Fresh pop-in entry: deliberately NOT drift-guarded —
                    // a tooltip may legitimately cover most of a cropped
                    // watcher region (the guard is for drifting ambient
                    // change, which never trips the movement vote).
                    b.phase = Phase::Kept;
                    b.base_frozen = true;
                    b.ovl = *sig;
                    return true;
                }
            } else if stable && novel {
                // Slow-drift entry (fades that never trip the movement vote).
                if g.drift_guard {
                    reseed(b, sig);
                    return false;
                }
                b.phase = Phase::Kept;
                b.base_frozen = true;
                b.ovl = *sig;
                b.unstable_run = 0;
                b.run_corroborated = false;
                return true;
            }
            if b.base_frozen && stable && !novel {
                b.base_frozen = false; // v1 thaw: overlay content actually left
            }
            // The EMA only absorbs content that AGREES with the baseline
            // (slow scene evolution). Novel content is either a settling
            // overlay (must not bias the scene reference — repeated
            // browsing would drift the baseline toward tooltip luma) or a
            // scene change (handled by re-seeding, not drift).
            if !b.base_frozen && !mv && !novel {
                ema_update(b, sig, p.baseline_ticks);
            }
            false
        }
    }
}

/// Morphological close (fill interior holes) then dilate by `dilate` rings,
/// on a row-major block grid. Used when component fill is disabled.
pub(crate) fn close_and_dilate(keep: &[bool], cols: usize, rows: usize, dilate: u32) -> Vec<bool> {
    let d1 = dilate_grid(keep, cols, rows, 1);
    let closed = erode_grid(&d1, cols, rows, 1);
    if dilate == 0 {
        closed
    } else {
        dilate_grid(&closed, cols, rows, dilate as usize)
    }
}

pub(crate) fn dilate_grid(grid: &[bool], cols: usize, rows: usize, rings: usize) -> Vec<bool> {
    let mut out = grid.to_vec();
    for _ in 0..rings {
        let src = out.clone();
        for r in 0..rows {
            for c in 0..cols {
                if src[r * cols + c] {
                    continue;
                }
                let neighbors_on = (r > 0 && src[(r - 1) * cols + c])
                    || (r + 1 < rows && src[(r + 1) * cols + c])
                    || (c > 0 && src[r * cols + c - 1])
                    || (c + 1 < cols && src[r * cols + c + 1]);
                if neighbors_on {
                    out[r * cols + c] = true;
                }
            }
        }
    }
    out
}

fn erode_grid(grid: &[bool], cols: usize, rows: usize, rings: usize) -> Vec<bool> {
    let mut out = grid.to_vec();
    for _ in 0..rings {
        let src = out.clone();
        for r in 0..rows {
            for c in 0..cols {
                if !src[r * cols + c] {
                    continue;
                }
                let all_on = (r == 0 || src[(r - 1) * cols + c])
                    && (r + 1 >= rows || src[(r + 1) * cols + c])
                    && (c == 0 || src[r * cols + c - 1])
                    && (c + 1 >= cols || src[r * cols + c + 1]);
                if !all_on {
                    out[r * cols + c] = false;
                }
            }
        }
    }
    out
}

/// One 4-connected component of the keep grid.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Component {
    /// Member block indices (row-major).
    pub members: Vec<usize>,
    /// Inclusive block-coordinate bounding box (r0, r1, c0, c1).
    pub bbox: (usize, usize, usize, usize),
}

/// Extract 4-connected components of the keep grid, dropping components
/// smaller than `min_size` (speckle).
pub(crate) fn components(
    keep: &[bool],
    cols: usize,
    rows: usize,
    min_size: usize,
) -> Vec<Component> {
    let mut out = Vec::new();
    let mut seen = vec![false; keep.len()];
    let mut stack = Vec::new();
    for start in 0..keep.len() {
        if !keep[start] || seen[start] {
            continue;
        }
        let (mut r0, mut r1, mut c0, mut c1) = (rows, 0usize, cols, 0usize);
        let mut members = Vec::new();
        stack.push(start);
        seen[start] = true;
        while let Some(i) = stack.pop() {
            members.push(i);
            let (r, c) = (i / cols, i % cols);
            r0 = r0.min(r);
            r1 = r1.max(r);
            c0 = c0.min(c);
            c1 = c1.max(c);
            let mut push = |j: usize| {
                if keep[j] && !seen[j] {
                    seen[j] = true;
                    stack.push(j);
                }
            };
            if r > 0 {
                push(i - cols);
            }
            if r + 1 < rows {
                push(i + cols);
            }
            if c > 0 {
                push(i - 1);
            }
            if c + 1 < cols {
                push(i + 1);
            }
        }
        if members.len() >= min_size {
            out.push(Component {
                members,
                bbox: (r0, r1, c0, c1),
            });
        }
    }
    out
}

/// Component pass for the non-panel path: drop kept components smaller
/// than `min_size` (speckle), fill the bounding box of each survivor.
pub(crate) fn fill_components_bbox(
    keep: &[bool],
    cols: usize,
    rows: usize,
    min_size: usize,
) -> Vec<bool> {
    let mut out = vec![false; keep.len()];
    for comp in components(keep, cols, rows, min_size) {
        let (r0, r1, c0, c1) = comp.bbox;
        for r in r0..=r1 {
            for c in c0..=c1 {
                out[r * cols + c] = true;
            }
        }
    }
    out
}

/// Panel-layer tuning (documented constants; builder knobs if tuning
/// demands emerge).
/// A panel counts as quiet when at most this fraction of its members moved.
const PANEL_MOVING_FRAC: f32 = 0.20;
/// Kept content must fill at least this fraction of its own bbox for the
/// rect to present: real panels are dense rectangles; sparse kept scatter
/// (e.g. a whole scene settling at once) must not bbox-fill into huge
/// rects.
const PANEL_DENSITY_FLOOR: f32 = 0.35;
/// Kept-subset growth below this fraction of the footprint per tick is a
/// straggler trickle, not assembly — do not postpone presentation for it.
/// (Fixture trace: a settled 932-block tooltip gained 6-8 blocks per tick
/// indefinitely; strict growth gating starved it until the next hover's
/// onset superseded it.)
const PANEL_GROWTH_SLACK: f32 = 0.02;
/// A moving component belongs to a panel when at least this fraction of it
/// lies inside the panel footprint (else it is neighboring motion).
const PANEL_OVERLAP_FRAC: f32 = 0.30;
/// Pending panels that never settle within this many multiples of K are
/// gameplay churn: dropped.
const PANEL_PENDING_DEADLINE_K: u16 = 8;
/// A pending panel accepts footprint extensions only this many ticks after
/// its onset (the measured fade-in stagger) — a pending panel is a
/// short-lived hypothesis, not an accretion target. Without this bound,
/// successive distinct onsets (cursor, tooltips, panel updates) chain into
/// a region-sized mega-panel that never settles and starves real tooltips
/// of their own panels (seen on the D4 fixture).
const PANEL_ONSET_WINDOW: u16 = 3;

#[derive(Debug, Clone)]
pub(crate) struct Panel {
    /// Co-onset footprint: the blocks that changed together (plus later
    /// extensions from overlapping churn). Never pruned — late-settling
    /// stragglers must still be able to join the kept subset.
    members: Vec<usize>,
    /// The rect rendered while presented; sticky through flux, snapped to
    /// the kept-content bbox at each settle.
    sticky: (usize, usize, usize, usize),
    presented: bool,
    /// Consecutive quiet ticks (<= PANEL_MOVING_FRAC of members moving).
    quiet: u16,
    /// Ticks since creation (pending only; deadline drops churn panels).
    age: u16,
    /// Kept-subset size at the previous evaluation (growth detector).
    last_kept: usize,
    /// Consecutive evaluations without slack-exceeding kept growth.
    no_growth: u16,
    /// Consecutive ticks (any, not just quiet) with kept support below
    /// min_component — the settle-independent withdrawal clock.
    low_support: u16,
}

/// Panel-level presentation driven by CO-ONSET: blocks that start changing
/// together form one panel (the owner's insight — a UI panel re-renders as
/// a unit). The panel settles as a GROUP (quantile: animated members and
/// the cursor cannot hold it hostage) and presents its WHOLE rect at once,
/// even when only part of its members individually re-stabilized (the
/// per-block kept set can be fragmentary during fast browsing; the group
/// decision is what reaches the output). Presented rects stay whole
/// through churn and withdraw whole.
#[derive(Debug, Default)]
pub(crate) struct PanelTracker {
    panels: Vec<Panel>,
}

fn bbox_of(
    blocks: impl Iterator<Item = usize>,
    cols: usize,
) -> Option<(usize, usize, usize, usize)> {
    let mut b: Option<(usize, usize, usize, usize)> = None;
    for i in blocks {
        let (r, c) = (i / cols, i % cols);
        b = Some(match b {
            None => (r, r, c, c),
            Some((r0, r1, c0, c1)) => (r0.min(r), r1.max(r), c0.min(c), c1.max(c)),
        });
    }
    b
}

impl PanelTracker {
    pub(crate) fn reset(&mut self) {
        self.panels.clear();
    }

    pub(crate) fn panels(&self) -> impl Iterator<Item = (bool, (usize, usize, usize, usize))> + '_ {
        self.panels.iter().map(|p| (p.presented, p.sticky))
    }

    /// Advance one tick.
    /// - `moving`: phase-1 movement votes (the onset signal);
    /// - `keep_raw`: phase-2 per-block keep flags (the settled-content
    ///   signal).
    ///
    /// Camera/scene motion needs no special-casing here: churn panels it
    /// spawns either never settle (deadline) or settle over re-seeded
    /// blocks and fail the group kept-test — the block machine's scene
    /// wisdom is inherited through keep_raw. Returns the presented keep
    /// grid.
    pub(crate) fn tick(
        &mut self,
        moving: &[bool],
        keep_raw: &[bool],
        cols: usize,
        rows: usize,
        k_panel: u16,
        min_component: usize,
    ) -> Vec<bool> {
        let n = cols * rows;
        // Routable owners: presented panels (content churn belongs to
        // them) and pending panels still inside their onset window. The
        // map is dilated one ring: a staggered onset wave (a fade sweeping
        // down a tooltip) lands ADJACENT to the footprint, not on it.
        // Presented panels win collisions.
        let mut owner = vec![usize::MAX; n];
        // A pending panel is routable while its onset window is open OR
        // once it has settled with content: a new onset over a panel that
        // was about to present is a HAND-OFF (route in, re-settle, present
        // the new content), not a stale hypothesis to supersede — the
        // supersede race otherwise starves every tooltip whose hover
        // interval is shorter than the presentation pipeline.
        for pass in 0..2 {
            for (pi, p) in self.panels.iter().enumerate() {
                let settled_content = p.quiet >= k_panel && p.last_kept >= min_component;
                let routable = if pass == 0 {
                    !p.presented && (p.age < PANEL_ONSET_WINDOW || settled_content)
                } else {
                    p.presented
                };
                if routable {
                    for &m in &p.members {
                        owner[m] = pi;
                    }
                }
            }
        }
        let core = owner.clone();
        for (i, &own) in core.iter().enumerate() {
            if own == usize::MAX {
                continue;
            }
            let (r, c) = (i / cols, i % cols);
            let mut mark = |j: usize| {
                if owner[j] == usize::MAX {
                    owner[j] = own;
                }
            };
            if r > 0 {
                mark(i - cols);
            }
            if r + 1 < rows {
                mark(i + cols);
            }
            if c > 0 {
                mark(i - 1);
            }
            if c + 1 < cols {
                mark(i + 1);
            }
        }

        // Route ALL moving components (min_size 1: sub-speckle motion
        // inside a panel is churn, not noise to drop). A component may
        // touch several panels — the spec's multi-match rule MERGES them
        // (a bridging band of a disjoint-band reveal unifies its panel
        // fragments). Presented panels require >=30% containment (edge
        // motion must not bloat them); young pending panels match on any
        // overlap. `redirect` resolves merged panel indices.
        let len = self.panels.len();
        let mut extend: Vec<Vec<usize>> = vec![Vec::new(); len];
        let mut dead = vec![false; len];
        let mut redirect: Vec<usize> = (0..len).collect();
        let mut fresh: Vec<Component> = Vec::new();
        fn resolve(redirect: &[usize], mut i: usize) -> usize {
            while redirect[i] != i {
                i = redirect[i];
            }
            i
        }
        for comp in components(moving, cols, rows, 1) {
            let mut counts = vec![0usize; len];
            for &m in &comp.members {
                if owner[m] != usize::MAX {
                    counts[resolve(&redirect, owner[m])] += 1;
                }
            }
            let mut matched: Vec<usize> = (0..len)
                .filter(|&pi| counts[pi] > 0 && !dead[pi])
                .filter(|&pi| {
                    let p = &self.panels[pi];
                    !p.presented
                        || counts[pi] as f32 / comp.members.len() as f32 >= PANEL_OVERLAP_FRAC
                })
                .collect();
            if matched.is_empty() {
                if comp.members.len() >= min_component {
                    fresh.push(comp);
                }
                continue;
            }
            // Survivor: presented preferred (stable identity), else oldest
            // (lowest index). Deterministic — no hash iteration order.
            matched.sort_by_key(|&pi| (!self.panels[pi].presented, pi));
            let survivor = matched[0];
            for &victim in &matched[1..] {
                let (v_members, v_presented, v_sticky, v_last) = {
                    let v = &mut self.panels[victim];
                    (
                        std::mem::take(&mut v.members),
                        v.presented,
                        v.sticky,
                        v.last_kept,
                    )
                };
                let moved = std::mem::take(&mut extend[victim]);
                let sv = &mut self.panels[survivor];
                sv.members.extend(v_members);
                sv.last_kept += v_last;
                if v_presented {
                    sv.presented = true;
                    let a = sv.sticky;
                    sv.sticky = (
                        a.0.min(v_sticky.0),
                        a.1.max(v_sticky.1),
                        a.2.min(v_sticky.2),
                        a.3.max(v_sticky.3),
                    );
                }
                extend[survivor].extend(moved);
                dead[victim] = true;
                redirect[victim] = survivor;
            }
            extend[survivor].extend_from_slice(&comp.members);
        }

        // A fresh onset supersedes stale pending hypotheses it covers:
        // the newest event owns the region.
        let mut in_fresh = vec![false; n];
        for comp in &fresh {
            for &m in &comp.members {
                in_fresh[m] = true;
            }
        }
        for (pi, p) in self.panels.iter().enumerate() {
            if dead[pi] || p.presented || !extend[pi].is_empty() {
                continue;
            }
            let covered = p.members.iter().filter(|&&m| in_fresh[m]).count();
            if covered * 2 >= p.members.len() {
                dead[pi] = true;
            }
        }

        // Update panels.
        let deadline = k_panel.saturating_mul(PANEL_PENDING_DEADLINE_K);
        for (pi, p) in self.panels.iter_mut().enumerate() {
            if dead[pi] {
                continue;
            }
            if !p.presented && p.age >= deadline {
                dead[pi] = true; // never presented in time: churn/scatter
                continue;
            }
            // Footprint extension: presented churn always; pending while
            // the onset window is open or after settling with content
            // (hand-off). Members are NEVER pruned — a late-settling
            // straggler must always be able to join the kept subset
            // (present-time pruning permanently truncated tooltips whose
            // edge cohort settled after presentation).
            if !extend[pi].is_empty() {
                p.members.extend_from_slice(&extend[pi]);
                p.members.sort_unstable();
                p.members.dedup();
            }
            let total = p.members.len().max(1) as f32;
            let mv = p.members.iter().filter(|&&m| moving[m]).count() as f32;
            if mv / total <= PANEL_MOVING_FRAC {
                p.quiet = p.quiet.saturating_add(1);
            } else {
                p.quiet = 0;
                p.no_growth = 0;
            }
            p.age = p.age.saturating_add(1);

            // Settle-independent withdrawal: a presented panel whose
            // content support collapses must withdraw even if the pixels
            // underneath never stop moving (dismissal into churning
            // gameplay would otherwise leave a permanent live rect).
            let support = p.members.iter().filter(|&&m| keep_raw[m]).count();
            if p.presented {
                if support < min_component {
                    p.low_support = p.low_support.saturating_add(1);
                    if p.low_support >= k_panel {
                        dead[pi] = true; // withdraw whole
                        continue;
                    }
                } else {
                    p.low_support = 0;
                }
                // Sticky union while in flux.
                if let Some(b) = bbox_of(p.members.iter().copied(), cols) {
                    let sk = p.sticky;
                    p.sticky = (sk.0.min(b.0), sk.1.max(b.1), sk.2.min(b.2), sk.3.max(b.3));
                }
            }

            if p.quiet >= k_panel {
                // The group is settled: evaluate its kept CONTENT each
                // tick (never a one-shot — late-settling stragglers keep
                // joining, and the onset halo must not dilute anything).
                let kept: Vec<usize> = p.members.iter().copied().filter(|&m| keep_raw[m]).collect();
                // Growth beyond the slack means assembly is in progress;
                // DECREASES are flicker and a sub-slack trickle is
                // stragglers. Presentation needs TWO consecutive
                // non-growing evaluations (a one-tick plateau mid-assembly
                // must not present a partial rect).
                let slack = ((p.members.len() as f32 * PANEL_GROWTH_SLACK) as usize).max(2);
                let growing = kept.len() > p.last_kept.saturating_add(slack);
                p.last_kept = kept.len();
                p.no_growth = if growing {
                    0
                } else {
                    p.no_growth.saturating_add(1)
                };
                let dense_bbox = bbox_of(kept.iter().copied(), cols).filter(|b| {
                    let area = ((b.1 - b.0 + 1) * (b.3 - b.2 + 1)) as f32;
                    kept.len() as f32 / area >= PANEL_DENSITY_FLOOR
                });
                if p.presented {
                    if let Some(b) = dense_bbox {
                        if p.no_growth >= 2 {
                            p.sticky = b; // stable content: atomic snap
                        }
                    }
                } else if kept.len() >= min_component && p.no_growth >= 2 {
                    // Novel content settled and stopped growing: present
                    // the whole rect at once — if it is a dense panel and
                    // not scene-settle scatter. Sparse panels wait (the
                    // deadline reaps them).
                    if let Some(b) = dense_bbox {
                        p.presented = true;
                        p.sticky = b;
                    }
                }
            }
        }
        let mut di = dead.iter();
        self.panels.retain(|_| !*di.next().unwrap());

        // Fresh hypotheses from unrouted onsets.
        for comp in fresh {
            self.panels.push(Panel {
                sticky: comp.bbox,
                members: comp.members,
                presented: false,
                quiet: 0,
                age: 0,
                last_kept: 0,
                no_growth: 0,
                low_support: 0,
            });
        }

        // Orphan-kept seeding: content that entered keep_raw WITHOUT ever
        // tripping the movement vote (slow-drift fades, or content already
        // settled when the grid reset) has no onset — seed panels from
        // settled kept components no panel covers, or it can never
        // present.
        let mut member_of = vec![false; n];
        for p in &self.panels {
            for &m in &p.members {
                member_of[m] = true;
            }
        }
        let orphan: Vec<bool> = (0..n)
            .map(|i| keep_raw[i] && !member_of[i] && !moving[i])
            .collect();
        for comp in components(&orphan, cols, rows, min_component) {
            self.panels.push(Panel {
                sticky: comp.bbox,
                members: comp.members,
                presented: false,
                quiet: 0,
                age: 0,
                last_kept: 0,
                no_growth: 0,
                low_support: 0,
            });
        }

        // Field-debugging facility (spec-documented): VC_PANEL_TRACE=1
        // dumps per-tick lifecycles for panels of consequence.
        if std::env::var_os("VC_PANEL_TRACE").is_some() {
            for (pi, p) in self.panels.iter().enumerate() {
                if p.members.len() >= 40 {
                    let mv = p.members.iter().filter(|&&m| moving[m]).count();
                    let kept = p.members.iter().filter(|&&m| keep_raw[m]).count();
                    eprintln!(
                        "PANEL {pi}: presented={} age={} quiet={} members={} moving={} kept={} last_kept={} sticky={:?}",
                        p.presented, p.age, p.quiet, p.members.len(), mv, kept, p.last_kept, p.sticky
                    );
                }
            }
            eprintln!("PANEL --- tick done ({} panels)", self.panels.len());
        }

        let mut out = vec![false; n];
        for p in self.panels.iter().filter(|p| p.presented) {
            let (r0, r1, c0, c1) = p.sticky;
            for r in r0..=r1 {
                for c in c0..=c1 {
                    out[r * cols + c] = true;
                }
            }
        }
        out
    }
}

/// Temporal stability mask: passes through only newly-appeared, now-static
/// overlays (item tooltips, dialogs); moving gameplay and the permanent
/// scene render black. Kept blocks are byte-identical to the input. Tick it
/// fast (5–10 Hz): the frame-diff gate downstream keeps detector cost
/// unchanged while nothing changes.
pub struct StabilityMask {
    block: u32,
    params: MaskParams,
    dilate: u32,
    scene_threshold: f32,
    fill_components: bool,
    min_component: usize,
    atomic_panels: bool,
    tracker: PanelTracker,
    holdover_explicit: bool,
    /// Grid state; reset when the view dimensions change.
    state: Vec<Block>,
    dims: (u32, u32),
    tick: u64,
    sinks: Vec<Box<dyn DebugSink>>,
}

impl Default for StabilityMask {
    fn default() -> Self {
        Self::new()
    }
}

impl StabilityMask {
    pub fn new() -> Self {
        Self {
            block: 16,
            params: MaskParams {
                stable_ticks: 6,
                baseline_ticks: 100,
                signature_tolerance: 10,
                novelty_threshold: 18,
                contrast_threshold: 14,
                holdover_ticks: 12,
                long_run: 18,
            },
            dilate: 1,
            scene_threshold: 0.65,
            fill_components: true,
            min_component: 4,
            atomic_panels: true,
            tracker: PanelTracker::default(),
            holdover_explicit: false,
            state: Vec::new(),
            dims: (0, 0),
            tick: 0,
            sinks: Vec::new(),
        }
    }

    /// Analysis block size in pixels (default 16).
    pub fn block_size(mut self, px: u32) -> Self {
        assert!(px > 0, "block size must be positive");
        self.block = px;
        self
    }

    /// K: consecutive stable ticks before a block counts as settled
    /// (default 6). Holdover (2K) and the long-run threshold (3K) derive
    /// from this unless set explicitly.
    pub fn stable_ticks(mut self, k: u32) -> Self {
        let k = k.clamp(1, u16::MAX as u32) as u16;
        self.params.stable_ticks = k;
        self.params.long_run = k.saturating_mul(3);
        if !self.holdover_explicit {
            self.params.holdover_ticks = k.saturating_mul(2);
        }
        self
    }

    /// Duration form of [`Self::stable_ticks`]; converted via the watcher's
    /// rate (tick-based internals keep paused-time tests deterministic).
    pub fn stable_for(self, rate: Rate, duration: Duration) -> Self {
        let ticks = (duration.as_secs_f64() / rate.period().as_secs_f64()).ceil() as u32;
        self.stable_ticks(ticks.max(1))
    }

    /// T: baseline EMA horizon in ticks (default 100). The EMA only runs
    /// while a block is idle and unfrozen; scene changes re-seed instantly.
    pub fn baseline_ticks(mut self, t: u32) -> Self {
        self.params.baseline_ticks = t.max(1);
        self
    }

    /// Duration form of [`Self::baseline_ticks`].
    pub fn baseline(self, rate: Rate, duration: Duration) -> Self {
        let ticks = (duration.as_secs_f64() / rate.period().as_secs_f64()).ceil() as u32;
        self.baseline_ticks(ticks.max(1))
    }

    /// Keep-mask dilation rings applied after the component pass
    /// (default 1) — keeps glyphs off the fill boundary.
    pub fn dilate(mut self, rings: u32) -> Self {
        self.dilate = rings;
        self
    }

    /// Per-component movement tolerance on the signature vote (default 10).
    pub fn signature_tolerance(mut self, tol: u8) -> Self {
        self.params.signature_tolerance = tol;
        self
    }

    /// Per-sub-mean novelty threshold on the baseline vote (default 18).
    pub fn baseline_threshold(mut self, thr: u8) -> Self {
        self.params.novelty_threshold = thr;
        self
    }

    /// Contrast-byte novelty threshold (default 14) — the dark-on-dark
    /// discriminator: a flat panel over textured scene is novel even at
    /// identical mean luma.
    pub fn contrast_threshold(mut self, thr: u8) -> Self {
        self.params.contrast_threshold = thr;
        self
    }

    /// Fraction of the frame that must perturb in one tick to count as a
    /// scene transition (default 0.65). Settling blocks then adopt the new
    /// scene instead of becoming "kept".
    pub fn scene_threshold(mut self, frac: f32) -> Self {
        assert!((0.0..=1.0).contains(&frac), "fraction in 0..=1");
        self.scene_threshold = frac;
        self
    }

    /// Panel-level presentation (default on): kept blocks are grouped
    /// into panels with identity across ticks; a panel renders only once
    /// its assembly is quiet — then its WHOLE rect at once — stays whole
    /// through internal churn, and withdraws whole. Off = per-block v2
    /// rendering (`fill_components`/`close+dilate`).
    pub fn atomic_panels(mut self, on: bool) -> Self {
        self.atomic_panels = on;
        self
    }

    /// Component pass (default on): drop kept components smaller than
    /// [`Self::min_component`], fill each survivor's bounding box. Off =
    /// v1-style morphological close.
    pub fn fill_components(mut self, on: bool) -> Self {
        self.fill_components = on;
        self
    }

    /// Minimum kept-component size in blocks (default 4); smaller
    /// components are treated as speckle and dropped.
    pub fn min_component(mut self, blocks: usize) -> Self {
        self.min_component = blocks.max(1);
        self
    }

    /// H: ticks a kept block keeps rendering after its content starts
    /// changing (default 2×stable_ticks) — the anti-patchwork hysteresis.
    pub fn holdover_ticks(mut self, h: u32) -> Self {
        self.params.holdover_ticks = h.clamp(1, u16::MAX as u32) as u16;
        self.holdover_explicit = true;
        self
    }

    /// Attach a debug tap (e.g. [`PngDump`](crate::PngDump)) receiving
    /// per-tick Input/Baseline/Overlay/State/Output frames. Composable —
    /// multiple sinks allowed. Stage frames are only materialized when at
    /// least one sink is attached.
    pub fn debug_sink(mut self, sink: impl DebugSink) -> Self {
        self.sinks.push(Box::new(sink));
        self
    }

    fn grid(&self, w: u32, h: u32) -> (usize, usize) {
        (
            (w as usize).div_ceil(self.block as usize),
            (h as usize).div_ceil(self.block as usize),
        )
    }
}

/// Compute all block signatures in one pass over the view.
fn compute_signatures(
    view: &FrameView<'_>,
    block: u32,
    cols: usize,
    rows: usize,
) -> Vec<Signature> {
    let n = cols * rows;
    let b = block as usize;
    let mut sub_sum = vec![[0u64; 16]; n];
    let mut sub_cnt = vec![[0u32; 16]; n];
    let mut sum = vec![0u64; n];
    let mut sum_sq = vec![0u64; n];
    let mut cnt = vec![0u64; n];

    for (y, row) in view.rows().enumerate() {
        let br = y / b;
        let sr = ((y % b) * 4) / b; // sub-row 0..4
        for (x, px) in row.chunks_exact(4).enumerate() {
            let bc = x / b;
            let sc = ((x % b) * 4) / b;
            // Integer BT.601 luma, same weights as the detectors.
            let luma = (px[2] as u32 * 299 + px[1] as u32 * 587 + px[0] as u32 * 114) / 1000;
            let bi = br * cols + bc;
            let si = sr * 4 + sc;
            sub_sum[bi][si] += luma as u64;
            sub_cnt[bi][si] += 1;
            sum[bi] += luma as u64;
            sum_sq[bi] += (luma as u64) * (luma as u64);
            cnt[bi] += 1;
        }
    }

    (0..n)
        .map(|i| {
            let mut sig = [0u8; SIG_LEN];
            let mean = sum[i].checked_div(cnt[i]).unwrap_or(0) as u8;
            for s in 0..16 {
                // Empty sub-cells inherit the block mean (no phantom edges).
                sig[s] = sub_sum[i][s]
                    .checked_div(sub_cnt[i][s] as u64)
                    .map_or(mean, |v| v as u8);
            }
            sig[16] = if cnt[i] == 0 {
                0
            } else {
                let m = sum[i] as f64 / cnt[i] as f64;
                let var = (sum_sq[i] as f64 / cnt[i] as f64) - m * m;
                var.max(0.0).sqrt().min(255.0) as u8
            };
            Signature(sig)
        })
        .collect()
}

impl Preprocessor for StabilityMask {
    fn process(&mut self, view: &FrameView<'_>) -> Result<Arc<Frame>, DetectorError> {
        let (w, h) = (view.width(), view.height());
        let (cols, rows) = self.grid(w, h);
        if self.dims != (w, h) {
            self.state = vec![Block::default(); cols * rows];
            self.tracker.reset();
            self.dims = (w, h);
        }
        let n = cols * rows;
        let p = &self.params;

        // ---- Phase 1: signatures + frame-global signals ----
        let sigs = compute_signatures(view, self.block, cols, rows);
        let mut moving = vec![false; n];
        let mut initialized = 0usize;
        let mut idle = 0usize;
        let mut perturbed = 0usize;
        let mut census_eligible = vec![false; n];
        let mut census_count = 0usize;
        let mut would_enter = 0usize;
        for i in 0..n {
            let b = &self.state[i];
            if !b.initialized {
                continue;
            }
            initialized += 1;
            if b.phase == Phase::Idle {
                idle += 1;
            }
            let mv = is_moving(&sigs[i], &b.last, p.signature_tolerance);
            moving[i] = mv;
            if mv {
                perturbed += 1;
            } else {
                if b.unstable_run >= p.stable_ticks {
                    census_eligible[i] = true;
                    census_count += 1;
                }
                // Slow-drift candidates only: blocks ALREADY stable before
                // this tick (a settling pop-in has stable_ticks < K here).
                if b.phase == Phase::Idle
                    && b.stable_ticks >= p.stable_ticks
                    && is_novel_vs(
                        &sigs[i],
                        &narrow(&b.base),
                        p.novelty_threshold,
                        p.contrast_threshold,
                    )
                {
                    would_enter += 1;
                }
            }
        }
        let denom = initialized.max(1) as f32;
        let frac = perturbed as f32 / denom;
        let globals = Globals {
            scene_tick: frac >= self.scene_threshold,
            corroborated_tick: frac >= CORROBORATION_FRAC,
            census_hit: (census_count as f32 / denom) >= CENSUS_FRAC,
            drift_guard: (would_enter as f32 / idle.max(1) as f32) >= DRIFT_FRAC,
        };

        // ---- Phase 2: per-block state machine ----
        let mut keep_raw = vec![false; n];
        for i in 0..n {
            keep_raw[i] = step_block(
                &mut self.state[i],
                &sigs[i],
                moving[i],
                census_eligible[i],
                &globals,
                p,
            );
        }

        // ---- Render stage ----
        let keep = if self.atomic_panels {
            let presented = self.tracker.tick(
                &moving,
                &keep_raw,
                cols,
                rows,
                p.stable_ticks,
                self.min_component,
            );
            if self.dilate == 0 {
                presented
            } else {
                dilate_grid(&presented, cols, rows, self.dilate as usize)
            }
        } else if self.fill_components {
            let filled = fill_components_bbox(&keep_raw, cols, rows, self.min_component);
            if self.dilate == 0 {
                filled
            } else {
                dilate_grid(&filled, cols, rows, self.dilate as usize)
            }
        } else {
            close_and_dilate(&keep_raw, cols, rows, self.dilate)
        };

        // Kept blocks byte-identical, suppressed blocks black.
        let mut data = vec![0u8; w as usize * h as usize * 4];
        for px in data.chunks_exact_mut(4) {
            px[3] = 255;
        }
        for (y, row) in view.rows().enumerate() {
            let br = y / self.block as usize;
            for bc in 0..cols {
                if !keep[br * cols + bc] {
                    continue;
                }
                let x0 = bc * self.block as usize * 4;
                let x1 = (((bc + 1) * self.block as usize) * 4).min(row.len());
                let dst = y * w as usize * 4;
                data[dst + x0..dst + x1].copy_from_slice(&row[x0..x1]);
            }
        }
        let output = Frame::new(w, h, data)
            .map(Arc::new)
            .map_err(|e| DetectorError::Other(format!("mask render: {e}")))?;

        if !self.sinks.is_empty() {
            self.emit_debug(view, &keep, cols, &output);
        }
        self.tick += 1;
        Ok(output)
    }

    fn set_label(&mut self, label: &str) {
        for sink in &mut self.sinks {
            sink.set_label(label);
        }
    }
}

impl StabilityMask {
    /// Materialize the debug stage frames and fan them out. Only called
    /// when sinks exist; sinks themselves must never block (drop-on-lag).
    fn emit_debug(&mut self, view: &FrameView<'_>, keep: &[bool], cols: usize, output: &Frame) {
        let (w, h) = (view.width(), view.height());
        let input = Frame::new(w, h, view.to_vec()).expect("view-sized buffer");

        // Baseline: each block's scene-reference mean as gray.
        // Overlay: input with suppressed blocks dimmed to 25%.
        // State: false-color block phases — IDLE black, frozen-IDLE dim
        // blue, KEPT green, HOLDOVER yellow, re-seed red.
        let mut baseline = vec![0u8; w as usize * h as usize * 4];
        let mut state = vec![0u8; w as usize * h as usize * 4];
        let mut overlay = input.data().to_vec();
        for y in 0..h as usize {
            let br = y / self.block as usize;
            for x in 0..w as usize {
                let bc = x / self.block as usize;
                let i = (y * w as usize + x) * 4;
                let blk = &self.state[br * cols + bc];
                let mean: u32 = blk.base[..16].iter().map(|v| (*v >> 8) as u32).sum::<u32>() / 16;
                baseline[i] = mean as u8;
                baseline[i + 1] = mean as u8;
                baseline[i + 2] = mean as u8;
                baseline[i + 3] = 255;
                let bgra: [u8; 4] = if blk.reseeded {
                    [0, 0, 220, 255] // red: re-seeded this tick
                } else {
                    match blk.phase {
                        Phase::Kept => [0, 200, 0, 255],                     // green
                        Phase::Holdover => [0, 200, 200, 255],               // yellow
                        Phase::Idle if blk.base_frozen => [120, 40, 0, 255], // dim blue
                        Phase::Idle => [0, 0, 0, 255],
                    }
                };
                state[i..i + 4].copy_from_slice(&bgra);
                if !keep[br * cols + bc] {
                    overlay[i] /= 4;
                    overlay[i + 1] /= 4;
                    overlay[i + 2] /= 4;
                }
            }
        }
        // Panel borders on the State view: white = presented, gray =
        // forming (drawn at block granularity).
        if self.atomic_panels {
            let bpx = self.block as usize;
            for (presented, (r0, r1, c0, c1)) in self.tracker.panels() {
                let shade = if presented { 255u8 } else { 110 };
                let mut paint = |br: usize, bc: usize| {
                    let y0 = br * bpx;
                    let x0 = bc * bpx;
                    for y in y0..(y0 + bpx).min(h as usize) {
                        for x in x0..(x0 + bpx).min(w as usize) {
                            let i = (y * w as usize + x) * 4;
                            state[i] = shade;
                            state[i + 1] = shade;
                            state[i + 2] = shade;
                        }
                    }
                };
                for bc in c0..=c1 {
                    paint(r0, bc);
                    paint(r1, bc);
                }
                for br in r0..=r1 {
                    paint(br, c0);
                    paint(br, c1);
                }
            }
        }
        let baseline = Frame::new(w, h, baseline).expect("view-sized buffer");
        let state = Frame::new(w, h, state).expect("view-sized buffer");
        let overlay = Frame::new(w, h, overlay).expect("view-sized buffer");

        for sink in &mut self.sinks {
            sink.write(self.tick, DebugStage::Input, &input);
            sink.write(self.tick, DebugStage::Baseline, &baseline);
            sink.write(self.tick, DebugStage::Overlay, &overlay);
            sink.write(self.tick, DebugStage::State, &state);
            sink.write(self.tick, DebugStage::Output, output);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    fn params() -> MaskParams {
        MaskParams {
            stable_ticks: 3,
            baseline_ticks: 20,
            signature_tolerance: 10,
            novelty_threshold: 18,
            contrast_threshold: 14,
            holdover_ticks: 6,
            long_run: 9,
        }
    }

    /// Uniform-content signature: all sub-means equal, zero contrast.
    fn flat(luma: u8) -> Signature {
        let mut s = [luma; SIG_LEN];
        s[16] = 0;
        s.into()
    }

    /// Textured signature: alternating sub-means around `luma`, contrast c.
    fn textured(luma: u8, spread: u8, c: u8) -> Signature {
        let mut s = [0u8; SIG_LEN];
        for (i, v) in s[..16].iter_mut().enumerate() {
            *v = if i % 2 == 0 {
                luma.saturating_add(spread)
            } else {
                luma.saturating_sub(spread)
            };
        }
        s[16] = c;
        Signature(s)
    }

    impl From<[u8; SIG_LEN]> for Signature {
        fn from(v: [u8; SIG_LEN]) -> Self {
            Signature(v)
        }
    }

    const QUIET: Globals = Globals {
        scene_tick: false,
        corroborated_tick: false,
        census_hit: false,
        drift_guard: false,
    };

    /// Drive one block with (signature, globals) pairs; phase-1 movement is
    /// recomputed exactly like process() does.
    fn run(b: &mut Block, script: &[(Signature, Globals)], p: &MaskParams) -> Vec<bool> {
        script
            .iter()
            .map(|(sig, g)| {
                let mv = b.initialized && is_moving(sig, &b.last, p.signature_tolerance);
                let census = b.initialized && !mv && b.unstable_run >= p.stable_ticks;
                step_block(b, sig, mv, census, g, p)
            })
            .collect()
    }

    fn quiet(sigs: &[Signature]) -> Vec<(Signature, Globals)> {
        sigs.iter().map(|s| (*s, QUIET)).collect()
    }

    fn rep(sig: Signature, n: usize) -> Vec<Signature> {
        vec![sig; n]
    }

    // ---------- signature and vote tests ----------

    #[test]
    fn single_component_noise_cannot_flip_movement_or_novelty() {
        let a = flat(100);
        let mut b = a;
        b.0[3] = 140; // one sub-cell jumps
        assert!(!is_moving(&b, &a, 10), "one component is not movement");
        assert!(
            !is_novel_vs(&b, &a.0, 18, 14),
            "one component is not novelty"
        );
        b.0[7] = 140; // two sub-cells
        assert!(is_moving(&b, &a, 10));
        assert!(is_novel_vs(&b, &a.0, 18, 14));
    }

    #[test]
    fn dark_on_dark_flat_panel_is_novel_via_contrast() {
        // Textured dark scene vs flat dark panel at the SAME mean luma:
        // v1's mean-only comparator called this "not novel" (the measured
        // hole-punching); the contrast clause must catch it.
        let scene = textured(30, 12, 40);
        let panel = flat(30);
        assert!(
            is_novel_vs(&panel, &scene.0, 18, 14),
            "flat panel over textured scene must be novel"
        );
    }

    #[test]
    fn signatures_capture_subblock_structure() {
        let frame = Frame::from_fn(16, 16, |x, _| {
            if x < 8 {
                [0, 0, 0, 255]
            } else {
                [255, 255, 255, 255]
            }
        });
        let view = frame
            .view(visual_cortex_capture::PxRect {
                x: 0,
                y: 0,
                w: 16,
                h: 16,
            })
            .unwrap();
        let sigs = compute_signatures(&view, 16, 1, 1);
        let s = &sigs[0].0;
        assert!(s[0] < 10 && s[1] < 10, "left sub-cells dark");
        assert!(s[2] > 245 && s[3] > 245, "right sub-cells bright");
        assert!(s[16] > 100, "half-and-half block has high contrast");
    }

    // ---------- state machine: v1 regressions ----------

    #[test]
    fn constant_hud_block_is_never_kept() {
        let mut b = Block::default();
        let out = run(&mut b, &quiet(&rep(textured(100, 20, 30), 30)), &params());
        assert!(out.iter().all(|k| !k), "HUD must stay suppressed");
    }

    #[test]
    fn noisy_gameplay_block_is_never_kept() {
        let mut b = Block::default();
        let sigs: Vec<Signature> = (0..30)
            .map(|i| flat(if i % 2 == 0 { 40 } else { 200 }))
            .collect();
        let out = run(&mut b, &quiet(&sigs), &params());
        assert!(out.iter().all(|k| !k), "churn must stay suppressed");
    }

    #[test]
    fn tooltip_becomes_kept_after_k_stable_ticks() {
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 10)), &params());
        let out = run(&mut b, &quiet(&rep(flat(200), 6)), &params());
        // Jump tick resets; settled at K=3 (index 3), then stays.
        assert_eq!(out, vec![false, false, false, true, true, true]);
        assert_eq!(b.phase, Phase::Kept);
    }

    #[test]
    fn held_tooltip_survives_indefinitely() {
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 10)), &params());
        let out = run(&mut b, &quiet(&rep(flat(200), 200)), &params());
        assert!(out[10..].iter().all(|k| *k), "no ghosting, ever");
        assert!(b.base_frozen, "baseline frozen under the kept overlay");
    }

    #[test]
    fn dismissed_tooltip_thaws_and_suppresses() {
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 10)), &params());
        run(&mut b, &quiet(&rep(flat(200), 10)), &params());
        let out = run(&mut b, &quiet(&rep(flat(60), 10)), &params());
        assert_eq!(b.phase, Phase::Idle);
        assert!(!b.base_frozen, "baseline resumed after departure");
        assert!(!out.last().unwrap(), "restored scene suppressed");
    }

    // ---------- red-team scenarios ----------

    #[test]
    fn browsing_hand_off_never_goes_dark() {
        // Tooltip A held, then re-renders into tooltip B (different content),
        // then B is held: the block must RENDER CONTINUOUSLY (HOLDOVER) —
        // the v1 patchwork went black here for K ticks.
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 10)), &params());
        run(&mut b, &quiet(&rep(flat(200), 10)), &params()); // A kept
        let mut script = rep(flat(150), 1); // one transition tick
        script.extend(rep(flat(230), 8)); // B settles and holds
        let out = run(&mut b, &quiet(&script), &params());
        assert!(
            out.iter().all(|k| *k),
            "hand-off must render every tick, got {out:?}"
        );
        assert_eq!(b.phase, Phase::Kept, "re-latched onto tooltip B");
    }

    #[test]
    fn flash_over_held_tooltip_relatches_without_reseed() {
        // Red-team scenario 10 (the pinned invariant probe): a 2-tick
        // frame-global flash washes out a held tooltip. The block must ride
        // HOLDOVER through the flash and re-latch via the ovl snapshot the
        // moment the tooltip pixels return — no K wait, no re-seed.
        let p = params();
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 10)), &p);
        run(&mut b, &quiet(&rep(flat(200), 10)), &p); // tooltip kept
        let flash = Globals {
            scene_tick: true,
            corroborated_tick: true,
            census_hit: false,
            drift_guard: false,
        };
        let script = vec![
            (flat(255), flash),
            (flat(255), flash),
            (flat(200), QUIET), // tooltip pixels return
            (flat(200), QUIET),
        ];
        let out = run(&mut b, &script, &p);
        assert!(out.iter().all(|k| *k), "renders through the flash: {out:?}");
        assert_eq!(b.phase, Phase::Kept, "immediate ovl re-latch");
        assert!(!b.reseeded, "a flash is not a scene change");
        assert!(b.base_frozen, "invariant intact: base still frozen");
    }

    #[test]
    fn reveal_after_occluded_scene_change_resolves_on_next_motion() {
        // The scene changes while a tooltip occludes a block, then the
        // tooltip is dismissed. Per-block, "revealed new scene" and "new
        // overlay" are indistinguishable (the base went stale unseen), so
        // the reveal is RENDERED (reveal-over-suppress: extra revealed
        // scene is benign; a suppressed tooltip is a hard failure). The
        // next corroborated motion episode re-anchors it.
        let p = params();
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 10)), &p);
        run(&mut b, &quiet(&rep(flat(200), 10)), &p); // tooltip kept
        let scene = Globals {
            scene_tick: true,
            corroborated_tick: true,
            census_hit: false,
            drift_guard: false,
        };
        run(&mut b, &[(flat(150), scene)], &p); // occluded scene event
        run(&mut b, &quiet(&rep(flat(200), 6)), &p); // tooltip re-latches
        assert_eq!(b.phase, Phase::Kept, "tooltip survives the event");
        // Dismissal reveals the NEW scene (120): ambiguous -> rendered.
        let out = run(&mut b, &quiet(&rep(flat(120), 8)), &p);
        assert!(*out.last().unwrap(), "ambiguous reveal stays rendered");
        // Next corroborated motion episode (player walks) re-anchors.
        let walking = Globals {
            scene_tick: false,
            corroborated_tick: true,
            census_hit: false,
            drift_guard: false,
        };
        let script: Vec<(Signature, Globals)> = (0..12)
            .map(|i| (flat(if i % 2 == 0 { 80 } else { 170 }), walking))
            .collect();
        run(&mut b, &script, &p);
        let out = run(&mut b, &quiet(&rep(flat(140), 8)), &p);
        assert!(!out.last().unwrap(), "re-anchored after motion");
        let base = narrow(&b.base);
        assert!(
            base[0].abs_diff(140) < 10,
            "baseline follows the real scene"
        );
    }

    #[test]
    fn browsing_hand_off_survives_a_prior_flash() {
        // Regression for the review finding: scene_flag set during a flash
        // must NOT re-seed the next tooltip hand-off (which would corrupt
        // the baseline with overlay content and suppress tooltip B).
        let p = params();
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 10)), &p);
        run(&mut b, &quiet(&rep(flat(200), 10)), &p); // A kept
        let flash = Globals {
            scene_tick: true,
            corroborated_tick: true,
            census_hit: false,
            drift_guard: false,
        };
        run(&mut b, &[(flat(255), flash), (flat(255), flash)], &p);
        run(&mut b, &quiet(&rep(flat(200), 4)), &p); // re-latch on A
        assert_eq!(b.phase, Phase::Kept);
        // Hand off to tooltip B: must be KEPT, not re-seeded.
        let mut script = rep(flat(150), 1);
        script.extend(rep(flat(230), 8));
        let out = run(&mut b, &quiet(&script), &p);
        assert!(
            out.iter().all(|k| *k),
            "hand-off renders throughout: {out:?}"
        );
        assert_eq!(b.phase, Phase::Kept, "tooltip B kept");
        let base = narrow(&b.base);
        assert!(
            base[0].abs_diff(60) < 10,
            "baseline still the scene, never overlay content: base={} frozen={} scene_flag={}",
            base[0],
            b.base_frozen,
            b.scene_flag
        );
    }

    #[test]
    fn walk_and_stop_reseeds_instead_of_keeping() {
        // Red-team scenario 3 / measured ratchet: sustained corroborated
        // motion (walking) then stopping must re-seed, not keep the grass.
        let p = params();
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 5)), &p);
        let walking = Globals {
            scene_tick: false,
            corroborated_tick: true, // frame-wide motion corroborates
            census_hit: false,
            drift_guard: false,
        };
        let script: Vec<(Signature, Globals)> = (0..12)
            .map(|i| (flat(if i % 2 == 0 { 90 } else { 180 }), walking))
            .collect();
        run(&mut b, &script, &p); // 12 corroborated unstable ticks >= U=9
        let out = run(&mut b, &quiet(&rep(flat(140), 8)), &p);
        assert!(
            out.iter().all(|k| !k),
            "new scene must not be kept: {out:?}"
        );
        let base = narrow(&b.base);
        assert!(base[0].abs_diff(140) < 10, "re-seeded to the new scene");
    }

    #[test]
    fn fast_browsing_churn_is_not_corroborated_and_final_tooltip_is_kept() {
        // Red-team scenario 7 (BREAKS without the corroboration gate):
        // tooltips changing every 2 ticks for a long stretch build a long
        // unstable run, but the churn is locally confined (quiet globals) —
        // it must NOT re-seed, and the finally-held tooltip must be kept.
        let p = params();
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 10)), &p);
        // 20 ticks of item-flipping (uncorroborated churn), run >= U.
        let script: Vec<Signature> = (0..20)
            .map(|i| flat(if i % 2 == 0 { 200 } else { 120 }))
            .collect();
        run(&mut b, &quiet(&script), &p);
        assert!(!b.run_corroborated, "local churn is never corroborated");
        // User finally holds one item.
        let out = run(&mut b, &quiet(&rep(flat(200), 6)), &p);
        assert!(*out.last().unwrap(), "final tooltip must be kept: {out:?}");
        assert_eq!(b.phase, Phase::Kept);
    }

    #[test]
    fn minimap_pulse_train_is_never_kept() {
        // Red-team scenario 6: N stable / 2 perturbed / N stable, returning
        // to identical pixels each time.
        let p = params();
        let mut b = Block::default();
        let mut script = Vec::new();
        for _ in 0..6 {
            script.extend(rep(textured(80, 15, 25), 8)); // stable HUD
            script.extend(rep(textured(140, 15, 25), 2)); // pulse
        }
        let out = run(&mut b, &quiet(&script), &p);
        assert!(out.iter().all(|k| !k), "pulsing HUD must stay suppressed");
    }

    #[test]
    fn census_flag_reseeds_short_global_motion() {
        // A hard cut below theta_scene per-tick but caught by the census:
        // blocks with a long run settling on a census tick re-seed.
        let p = params();
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 5)), &p);
        let script: Vec<(Signature, Globals)> = (0..5)
            .map(|i| (flat(if i % 2 == 0 { 90 } else { 180 }), QUIET))
            .collect();
        run(&mut b, &script, &p); // unstable_run = 5 >= K
        let census = Globals {
            scene_tick: false,
            corroborated_tick: false,
            census_hit: true,
            drift_guard: false,
        };
        // The census stays hot while the long-perturbed mass settles
        // (process() recomputes it per tick from grid state).
        let mut settle = vec![(flat(140), census); 3];
        settle.extend(quiet(&rep(flat(140), 6)));
        let out = run(&mut b, &settle, &p);
        assert!(out.iter().all(|k| !k), "census settle re-seeds: {out:?}");
    }

    #[test]
    fn drift_guard_reseeds_slow_drift_but_never_pop_ins() {
        let p = params();
        let guard = Globals {
            scene_tick: false,
            corroborated_tick: false,
            census_hit: false,
            drift_guard: true,
        };
        // Slow drift: luma creeps below the movement vote each tick (steps
        // of 8 < tol 10) until it is novel vs the lagging baseline — with
        // the guard up this re-seeds (ambient lighting), never keeps.
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 10)), &p);
        let script: Vec<(Signature, Globals)> =
            (0..12).map(|i| (flat(60 + 8 * (i + 1)), guard)).collect();
        let out = run(&mut b, &script, &p);
        assert!(out.iter().all(|k| !k), "ambient fade must not be kept");
        // Pop-in: trips the movement vote, so the guard must NOT apply —
        // a tooltip can legitimately cover most of a cropped region.
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 10)), &p);
        let script: Vec<(Signature, Globals)> =
            rep(flat(200), 6).into_iter().map(|s| (s, guard)).collect();
        let out = run(&mut b, &script, &p);
        assert!(*out.last().unwrap(), "pop-in is kept even under the guard");
    }

    #[test]
    fn holdover_expires_to_idle_when_content_keeps_churning() {
        let p = params();
        let mut b = Block::default();
        run(&mut b, &quiet(&rep(flat(60), 10)), &p);
        run(&mut b, &quiet(&rep(flat(200), 10)), &p); // kept
                                                      // Content churns without ever settling: render for H ticks, then dark.
        let script: Vec<Signature> = (0..12)
            .map(|i| flat(if i % 2 == 0 { 90 } else { 170 }))
            .collect();
        let out = run(&mut b, &quiet(&script), &p);
        assert!(out[0], "holdover renders at first");
        assert!(!out.last().unwrap(), "expired holdover suppresses");
        assert_eq!(b.phase, Phase::Idle);
    }

    // ---------- grid geometry ----------

    #[test]
    fn component_fill_drops_speckle_and_fills_bboxes() {
        // 6x6 grid: an L-shaped 5-block component + a 1-block speckle.
        let cols = 6;
        let mut keep = vec![false; 36];
        for (r, c) in [(1, 1), (2, 1), (3, 1), (3, 2), (3, 3)] {
            keep[r * cols + c] = true;
        }
        keep[5 * cols + 5] = true; // speckle
        let out = fill_components_bbox(&keep, cols, 6, 4);
        assert!(out[cols + 2] && out[cols + 3], "bbox filled the L's notch");
        assert!(!out[5 * cols + 5], "speckle dropped");
    }

    #[test]
    fn close_fills_interior_holes_and_dilate_expands() {
        let cols = 5;
        let mut keep = vec![false; 25];
        for (r, c) in [
            (1usize, 1usize),
            (1, 2),
            (1, 3),
            (2, 1),
            (2, 3),
            (3, 1),
            (3, 2),
            (3, 3),
        ] {
            keep[r * cols + c] = true;
        }
        let out = close_and_dilate(&keep, cols, 5, 0);
        assert!(out[2 * cols + 2], "interior hole must be closed");
        let out = close_and_dilate(&keep, cols, 5, 1);
        assert!(out[cols], "edge cell reached by one dilation ring");
        assert!(
            !out[0],
            "corner is two steps away; one ring must not reach it"
        );
    }

    #[test]
    fn cold_start_keeps_nothing() {
        let mut b = Block::default();
        assert!(!step_block(
            &mut b,
            &flat(200),
            false,
            false,
            &QUIET,
            &params()
        ));
    }

    // ---------- panel tracker (co-onset) ----------

    /// Build a grid from rects (r0, r1, c0, c1) inclusive.
    fn grid(cols: usize, rows: usize, rects: &[(usize, usize, usize, usize)]) -> Vec<bool> {
        let mut g = vec![false; cols * rows];
        for &(r0, r1, c0, c1) in rects {
            for r in r0..=r1 {
                for c in c0..=c1 {
                    g[r * cols + c] = true;
                }
            }
        }
        g
    }

    const K_PANEL: u16 = 3;

    fn ptick(
        t: &mut PanelTracker,
        cols: usize,
        rows: usize,
        moving: &[(usize, usize, usize, usize)],
        keep: &[(usize, usize, usize, usize)],
    ) -> Vec<bool> {
        t.tick(
            &grid(cols, rows, moving),
            &grid(cols, rows, keep),
            cols,
            rows,
            K_PANEL,
            1,
        )
    }

    /// The owner's screenshot bug, root form: the panel's blocks CHANGED
    /// together, but during fast browsing only a fraction re-stabilize
    /// individually (fragmentary keep_raw). The GROUP decision must
    /// present the whole rect anyway.
    #[test]
    fn onset_group_presents_whole_despite_fragmentary_keeps() {
        let (c, r) = (10, 10);
        let mut t = PanelTracker::default();
        let rect = (1, 6, 1, 6);
        // Onset: the whole footprint changes in one tick.
        let out = ptick(&mut t, c, r, &[rect], &[]);
        assert!(out.iter().all(|k| !k), "onset tick: nothing rendered");
        // Group quiets; per-block keeps are CONFETTI (only two fragments).
        let frags = [(1, 2, 1, 6), (5, 6, 1, 3)];
        for _ in 0..(K_PANEL + 1) {
            let out = ptick(&mut t, c, r, &[], &frags);
            assert!(out.iter().all(|k| !k), "still settling: no render");
        }
        // Kept subset stable across evaluations: the WHOLE kept bbox
        // presents at once (rows 1..=6 x cols 1..=6) despite the confetti.
        let out = ptick(&mut t, c, r, &[], &frags);
        assert_eq!(out, grid(c, r, &[(1, 6, 1, 6)]), "whole rect at once");
    }

    #[test]
    fn gameplay_churn_never_presents_and_expires() {
        let (c, r) = (10, 10);
        let mut t = PanelTracker::default();
        // A region that keeps moving forever (grass), scattered keeps.
        for _ in 0..(K_PANEL * PANEL_PENDING_DEADLINE_K + 2) {
            let out = ptick(&mut t, c, r, &[(2, 7, 2, 7)], &[(3, 3, 3, 3)]);
            assert!(out.iter().all(|k| !k), "churn must never present");
        }
        // A fresh pending panel from the latest churn tick may exist, but
        // nothing ever presents and expired ones are gone.
        assert!(
            t.panels().all(|(presented, _)| !presented),
            "churn never presents"
        );
    }

    #[test]
    fn camera_pan_settles_to_nothing_via_the_group_kept_test() {
        // A pan spawns a pending panel, but the block machine re-seeds the
        // settled scene (keep_raw empty), so the group kept-test drops it:
        // the tracker inherits the scene wisdom through keep_raw.
        let (c, r) = (10, 10);
        let mut t = PanelTracker::default();
        for _ in 0..3 {
            ptick(&mut t, c, r, &[(0, 9, 0, 9)], &[]);
        }
        for _ in 0..(K_PANEL * PANEL_PENDING_DEADLINE_K + 2) {
            let out = ptick(&mut t, c, r, &[], &[]);
            assert!(out.iter().all(|k| !k), "no panel from a pan");
        }
        assert_eq!(t.panels().count(), 0, "churn panel reaped at deadline");
    }

    fn present_panel(t: &mut PanelTracker, c: usize, r: usize, rect: (usize, usize, usize, usize)) {
        ptick(t, c, r, &[rect], &[]);
        // Two consecutive non-growing evaluations required: K quiet ticks
        // to start evaluating, then two more.
        for _ in 0..(K_PANEL + 2) {
            ptick(t, c, r, &[], &[rect]);
        }
    }

    #[test]
    fn hand_off_keeps_the_rect_and_dismissal_withdraws_whole() {
        let (c, r) = (10, 10);
        let mut t = PanelTracker::default();
        let rect = (1, 6, 1, 6);
        present_panel(&mut t, c, r, rect);
        let full = grid(c, r, &[rect]);
        // Hand-off: the panel's content churns for 2 ticks (rendered
        // throughout), then settles with new (smaller) keeps.
        for _ in 0..2 {
            let out = ptick(&mut t, c, r, &[rect], &[]);
            assert_eq!(out, full, "rect stays whole through churn");
        }
        for _ in 0..K_PANEL {
            let out = ptick(&mut t, c, r, &[], &[(1, 4, 1, 6)]);
            assert_eq!(out, full, "still whole while settling");
        }
        // Snap fires on the second non-growing evaluation: content rows 1..=4.
        let out = ptick(&mut t, c, r, &[], &[(1, 4, 1, 6)]);
        assert_eq!(out, grid(c, r, &[(1, 4, 1, 6)]), "atomic snap");
        // Dismissal: churn then nothing kept -> support collapses ->
        // withdraw whole after K low-support ticks.
        ptick(&mut t, c, r, &[(1, 4, 1, 6)], &[]);
        for _ in 0..(K_PANEL - 2) {
            let out = ptick(&mut t, c, r, &[], &[]);
            assert!(!out.iter().all(|k| !k), "grace while support collapses");
        }
        let out = ptick(&mut t, c, r, &[], &[]);
        assert!(out.iter().all(|k| !k), "withdrawn whole");
        assert_eq!(t.panels().count(), 0);
    }

    #[test]
    fn straggler_trickle_does_not_postpone_presentation() {
        // Fixture trace regression: after the group settles, a couple of
        // blocks keep joining the kept subset EVERY tick with no plateau.
        // Presentation must not wait for one (the next hover would
        // supersede the panel first). Growth of 2 blocks/tick on a
        // 100-block footprint sits exactly at the slack floor.
        let (c, r) = (60, 4);
        let mut t = PanelTracker::default();
        ptick(&mut t, c, r, &[(1, 2, 1, 50)], &[]); // 100-block onset
        let mut presented = false;
        for i in 0..(K_PANEL as usize + 4) {
            let cols_kept = (30 + i).min(50);
            let out = ptick(&mut t, c, r, &[], &[(1, 2, 1, cols_kept)]);
            presented = out.iter().any(|k| *k);
            if presented {
                break;
            }
        }
        assert!(presented, "trickle must not starve presentation");
    }

    #[test]
    fn stale_pending_hypotheses_never_starve_a_new_onset() {
        // The D4 fixture mega-panel regression: a region churns for a
        // while (building a stale pending panel past its onset window),
        // then a REAL tooltip onset lands there. The new onset must get
        // its own panel and present — the stale hypothesis must not
        // accrete it and block presentation forever.
        let (c, r) = (10, 10);
        let mut t = PanelTracker::default();
        // Churn builds a stale pending panel (past the onset window).
        for _ in 0..6 {
            ptick(&mut t, c, r, &[(1, 8, 1, 8)], &[]);
        }
        // Tooltip onset over a subregion; unrelated churn CONTINUES far
        // from the tooltip (>=2 blocks away so the dilated owner map
        // cannot route it there) while the tooltip settles.
        ptick(&mut t, c, r, &[(2, 6, 2, 6), (9, 9, 1, 8)], &[]);
        for _ in 0..(K_PANEL + 2) {
            ptick(&mut t, c, r, &[(9, 9, 1, 8)], &[(2, 6, 2, 6)]);
        }
        let out = ptick(&mut t, c, r, &[(9, 9, 1, 8)], &[(2, 6, 2, 6)]);
        assert_eq!(
            out,
            grid(c, r, &[(2, 6, 2, 6)]),
            "the settled tooltip must present despite the stale hypothesis"
        );
    }

    #[test]
    fn sparse_scene_settle_scatter_never_presents() {
        // Round-5 pin: a whole region settling with sparse kept scatter
        // (~14% density) must never bbox-fill into a huge presented rect.
        let (c, r) = (20, 20);
        let mut t = PanelTracker::default();
        ptick(&mut t, c, r, &[(0, 19, 0, 19)], &[]);
        let scatter: Vec<(usize, usize, usize, usize)> = (0..400)
            .filter(|i| i % 7 == 0)
            .map(|i| (i / 20, i / 20, i % 20, i % 20))
            .collect();
        for _ in 0..(K_PANEL + 6) {
            let out = ptick(&mut t, c, r, &[], &scatter);
            assert!(out.iter().all(|k| !k), "sparse scatter must not present");
        }
    }

    #[test]
    fn sparse_settle_waits_for_assembly_instead_of_dying() {
        // Round-6 pin: assembly flicker can leave the kept subset SPARSE
        // (scattered singles, low density in their own bbox) for a while
        // after the group quiets. The panel must WAIT (not be killed) and
        // present once dense content lands.
        let (c, r) = (10, 10);
        let mut t = PanelTracker::default();
        ptick(&mut t, c, r, &[(1, 6, 1, 6)], &[]);
        let scatter = [(1, 1, 1, 1), (3, 3, 3, 3), (5, 5, 5, 5), (6, 6, 2, 2)];
        for _ in 0..(K_PANEL * 4) {
            let out = ptick(&mut t, c, r, &[], &scatter);
            assert!(out.iter().all(|k| !k), "sparse: waiting, not rendering");
        }
        // Dense content finally settles.
        for _ in 0..2 {
            ptick(&mut t, c, r, &[], &[(1, 6, 1, 6)]);
        }
        let out = ptick(&mut t, c, r, &[], &[(1, 6, 1, 6)]);
        assert_eq!(out, grid(c, r, &[(1, 6, 1, 6)]), "presents once dense");
    }

    #[test]
    fn disjoint_band_onsets_merge_into_one_panel() {
        // Spec merge rule: a reveal sweeping in disjoint adjacent bands is
        // ONE panel; a bridging band must unify earlier fragments so the
        // rect presents once, whole.
        let (c, r) = (10, 10);
        let mut t = PanelTracker::default();
        ptick(&mut t, c, r, &[(1, 2, 1, 6)], &[]); // band 1
        ptick(&mut t, c, r, &[(5, 6, 1, 6)], &[]); // band 2 (disjoint)
        ptick(&mut t, c, r, &[(3, 4, 1, 6)], &[]); // bridge: touches both
        for _ in 0..(K_PANEL + 1) {
            let out = ptick(&mut t, c, r, &[], &[(1, 6, 1, 6)]);
            assert!(out.iter().all(|k| !k), "no partial band presents");
        }
        let out = ptick(&mut t, c, r, &[], &[(1, 6, 1, 6)]);
        assert_eq!(out, grid(c, r, &[(1, 6, 1, 6)]), "one whole rect");
        assert_eq!(t.panels().count(), 1, "bands merged into one panel");
    }

    #[test]
    fn disjoint_panels_present_and_withdraw_independently() {
        let (c, r) = (12, 12);
        let mut t = PanelTracker::default();
        let (a, b) = ((1, 3, 1, 3), (7, 10, 7, 10));
        // Both onset together; both settle kept.
        ptick(&mut t, c, r, &[a, b], &[]);
        for _ in 0..(K_PANEL + 2) {
            ptick(&mut t, c, r, &[], &[a, b]);
        }
        let both = grid(c, r, &[a, b]);
        let out = ptick(&mut t, c, r, &[], &[a, b]);
        assert_eq!(out, both, "both panels presented");
        // Dismiss only the second: its support collapses while the first
        // stays kept and presented.
        ptick(&mut t, c, r, &[b], &[a]);
        for _ in 0..(K_PANEL + 1) {
            ptick(&mut t, c, r, &[], &[a]);
        }
        let out = ptick(&mut t, c, r, &[], &[a]);
        assert_eq!(out, grid(c, r, &[a]), "only the first remains");
    }

    #[test]
    fn slow_drift_kept_content_presents_via_orphan_seeding() {
        // A fade below the movement vote never produces an onset; the
        // orphan-kept seeding path must still present the settled content.
        let (c, r) = (10, 10);
        let mut t = PanelTracker::default();
        for _ in 0..(K_PANEL + 4) {
            ptick(&mut t, c, r, &[], &[(2, 6, 2, 6)]); // kept, never moving
        }
        let out = ptick(&mut t, c, r, &[], &[(2, 6, 2, 6)]);
        assert_eq!(out, grid(c, r, &[(2, 6, 2, 6)]), "fade content presents");
    }

    #[test]
    fn cursor_blip_inside_presented_panel_is_harmless() {
        let (c, r) = (10, 10);
        let mut t = PanelTracker::default();
        let rect = (1, 6, 1, 6);
        present_panel(&mut t, c, r, rect);
        let full = grid(c, r, &[rect]);
        // A 1-block blip inside: routed to the panel (fully inside), the
        // group stays quiet (1/36 < 20%), rect never flinches.
        for _ in 0..6 {
            let out = ptick(&mut t, c, r, &[(3, 3, 3, 3)], &[rect]);
            assert_eq!(out, full);
        }
        assert_eq!(t.panels().count(), 1);
    }

    #[test]
    fn neighboring_motion_does_not_extend_a_panel() {
        let (c, r) = (12, 12);
        let mut t = PanelTracker::default();
        let rect = (1, 4, 1, 4);
        present_panel(&mut t, c, r, rect);
        let full = grid(c, r, &[rect]);
        // Gameplay motion brushing the panel edge: mostly outside, so it
        // must not extend the footprint or bloat the rect.
        for _ in 0..4 {
            let out = ptick(&mut t, c, r, &[(5, 10, 1, 10)], &[rect]);
            assert_eq!(out, full, "edge motion must not bloat the rect");
        }
    }

    // ---------- process-level regressions ----------

    /// Review regression: a pop-in overlay covering most of the watched
    /// region (55-62%: above DRIFT/CENSUS floors, below the scene band)
    /// must be revealed — the drift guard and census apply to fades and
    /// long-perturbed mass settles, never to fresh pop-ins.
    #[test]
    fn large_pop_in_covering_most_of_the_region_is_revealed() {
        use visual_cortex_capture::PxRect;
        let mut mask = StabilityMask::new()
            .block_size(8)
            .stable_ticks(3)
            .min_component(1)
            .dilate(0);
        let full = PxRect {
            x: 0,
            y: 0,
            w: 48,
            h: 48,
        }; // 6x6 blocks
           // Tooltip covers the top 22 of 36 blocks (~61%).
        let bg = Frame::solid(48, 48, [60, 60, 60, 255]);
        let tip = Frame::from_fn(48, 48, |x, y| {
            if y < 24 || (y < 32 && x < 32) {
                [230, 230, 230, 255]
            } else {
                [60, 60, 60, 255]
            }
        });
        for _ in 0..8 {
            mask.process(&bg.view(full).unwrap()).unwrap();
        }
        let mut last = None;
        for _ in 0..8 {
            last = Some(mask.process(&tip.view(full).unwrap()).unwrap());
        }
        let out = last.unwrap();
        let px = &out.data()[(4 * 48 + 4) * 4..(4 * 48 + 4) * 4 + 3];
        assert_eq!(px, &[230, 230, 230], "pop-in region revealed, got {px:?}");
    }

    // ---------- atomic panel presentation (process level) ----------

    /// The owner's screenshot bug: blocks joining across ticks must never
    /// produce a partially-assembled rect in the output.
    #[test]
    fn staggered_pop_in_reveals_atomically_through_process() {
        use visual_cortex_capture::PxRect;
        let mut mask = StabilityMask::new()
            .block_size(8)
            .stable_ticks(3)
            .min_component(1)
            .dilate(0);
        let full = PxRect {
            x: 0,
            y: 0,
            w: 64,
            h: 64,
        }; // 8x8 blocks
        let bg = Frame::solid(64, 64, [60, 60, 60, 255]);
        // Wave 1: rows 8..24 of the tooltip; wave 2 (one tick later): rows
        // 8..40 — the fade-in stagger.
        let wave = |rows_to: u32| {
            Frame::from_fn(64, 64, move |x, y| {
                if (8..rows_to).contains(&y) && (8..40).contains(&x) {
                    [230, 230, 230, 255]
                } else {
                    [60, 60, 60, 255]
                }
            })
        };
        for _ in 0..8 {
            mask.process(&bg.view(full).unwrap()).unwrap();
        }
        let mut outputs = Vec::new();
        outputs.push(mask.process(&wave(24).view(full).unwrap()).unwrap());
        for _ in 0..12 {
            outputs.push(mask.process(&wave(40).view(full).unwrap()).unwrap());
        }
        // Classify each output within the final tooltip area: fraction of
        // its pixels visible must be 0.0 until presentation, then jump to
        // 1.0 in a single tick — no partial frames.
        let mut fractions = Vec::new();
        for out in &outputs {
            let mut vis = 0usize;
            let mut tot = 0usize;
            for y in 8..40usize {
                for x in 8..40usize {
                    let i = (y * 64 + x) * 4;
                    tot += 1;
                    if out.data()[i] == 230 {
                        vis += 1;
                    }
                }
            }
            fractions.push(vis as f64 / tot as f64);
        }
        assert!(
            fractions.iter().all(|f| *f < 0.05 || *f > 0.95),
            "no partial reveals allowed: {fractions:?}"
        );
        assert!(
            fractions.last().unwrap() > &0.95,
            "tooltip presented: {fractions:?}"
        );
    }

    #[test]
    fn dismissal_withdraws_atomically_through_process() {
        use visual_cortex_capture::PxRect;
        let mut mask = StabilityMask::new()
            .block_size(8)
            .stable_ticks(3)
            .min_component(1)
            .dilate(0);
        let full = PxRect {
            x: 0,
            y: 0,
            w: 64,
            h: 64,
        };
        let bg = Frame::solid(64, 64, [60, 60, 60, 255]);
        let tip = Frame::from_fn(64, 64, |x, y| {
            if (8..40).contains(&y) && (8..40).contains(&x) {
                [230, 230, 230, 255]
            } else {
                [60, 60, 60, 255]
            }
        });
        for _ in 0..8 {
            mask.process(&bg.view(full).unwrap()).unwrap();
        }
        for _ in 0..10 {
            mask.process(&tip.view(full).unwrap()).unwrap();
        }
        let mut fractions = Vec::new();
        for _ in 0..10 {
            let out = mask.process(&bg.view(full).unwrap()).unwrap();
            let mut vis = 0usize;
            for y in 8..40usize {
                for x in 8..40usize {
                    if out.data()[(y * 64 + x) * 4] != 0 {
                        vis += 1;
                    }
                }
            }
            fractions.push(vis as f64 / 1024.0);
        }
        assert!(
            fractions.iter().all(|f| *f < 0.05 || *f > 0.95),
            "withdraw must be atomic: {fractions:?}"
        );
        assert!(fractions.last().unwrap() < &0.05, "gone: {fractions:?}");
    }

    // ---------- builder derivations ----------

    #[test]
    fn builder_derives_holdover_and_long_run_from_stable_ticks() {
        let m = StabilityMask::new().stable_ticks(5);
        assert_eq!(m.params.holdover_ticks, 10, "H = 2K");
        assert_eq!(m.params.long_run, 15, "U = 3K");
        // Explicit holdover survives a later stable_ticks call.
        let m = StabilityMask::new().holdover_ticks(5).stable_ticks(10);
        assert_eq!(m.params.holdover_ticks, 5, "explicit H wins");
        assert_eq!(m.params.long_run, 30);
        // Large K no longer clamps H (u16 storage).
        let m = StabilityMask::new().stable_ticks(300);
        assert_eq!(m.params.holdover_ticks, 600);
    }

    // ---------- edge blocks ----------

    #[test]
    fn partial_edge_blocks_average_available_pixels_only() {
        use visual_cortex_capture::PxRect;
        // 19x13 with block 16: right edge block is 3px wide, bottom-right
        // corner is 3x13... grid is 2x1 blocks wide? 19/16 -> 2 cols, 13/16
        // -> 1 row. Right block = 3x13 bright pixels.
        let frame = Frame::from_fn(19, 13, |x, _| {
            if x < 16 {
                [40, 40, 40, 255]
            } else {
                [220, 220, 220, 255]
            }
        });
        let view = frame
            .view(PxRect {
                x: 0,
                y: 0,
                w: 19,
                h: 13,
            })
            .unwrap();
        let sigs = compute_signatures(&view, 16, 2, 1);
        // Partial right block: every populated sub-cell averages only
        // bright pixels; empty sub-cells inherit the block mean (also
        // bright) — nothing collapses to 0.
        assert!(
            sigs[1].0[..16].iter().all(|v| *v > 200),
            "partial block averages available pixels: {:?}",
            sigs[1].0
        );
        assert!(sigs[0].0[..16].iter().all(|v| *v < 60));
    }

    // ---------- debug sink fan-out ----------

    #[test]
    fn debug_sinks_receive_all_five_stages_per_tick() {
        struct Recording(Arc<Mutex<Vec<(u64, DebugStage)>>>);
        impl DebugSink for Recording {
            fn write(&mut self, tick: u64, stage: DebugStage, _frame: &Frame) {
                self.0.lock().unwrap().push((tick, stage));
            }
        }

        let log = Arc::new(Mutex::new(Vec::new()));
        let mut mask = StabilityMask::new()
            .block_size(8)
            .debug_sink(Recording(log.clone()));
        let frame = Frame::solid(8, 8, [60, 60, 60, 255]);
        let view = frame
            .view(visual_cortex_capture::PxRect {
                x: 0,
                y: 0,
                w: 8,
                h: 8,
            })
            .unwrap();
        mask.process(&view).unwrap();
        mask.process(&view).unwrap();

        use DebugStage::*;
        assert_eq!(
            *log.lock().unwrap(),
            vec![
                (0, Input),
                (0, Baseline),
                (0, Overlay),
                (0, State),
                (0, Output),
                (1, Input),
                (1, Baseline),
                (1, Overlay),
                (1, State),
                (1, Output),
            ]
        );
    }
}