visual-cortex-vision 0.10.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
//! 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
}

/// Component pass: 4-connected components over the keep grid; drop
/// components smaller than `min_size` (speckle), fill the bounding box of
/// each survivor (tooltips are rectangles — interior holes become impossible
/// by construction).
pub(crate) fn fill_components_bbox(
    keep: &[bool],
    cols: usize,
    rows: usize,
    min_size: usize,
) -> Vec<bool> {
    let mut out = vec![false; keep.len()];
    let mut seen = vec![false; keep.len()];
    let mut stack = Vec::new();
    for start in 0..keep.len() {
        if !keep[start] || seen[start] {
            continue;
        }
        // Flood-fill one component, tracking size and bbox.
        let (mut r0, mut r1, mut c0, mut c1) = (rows, 0usize, cols, 0usize);
        let mut size = 0usize;
        stack.push(start);
        seen[start] = true;
        while let Some(i) = stack.pop() {
            size += 1;
            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 size < min_size {
            continue; // speckle: dropped entirely
        }
        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,
    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,
            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
    }

    /// 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.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.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;
                }
            }
        }
        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()
        ));
    }

    // ---------- 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:?}");
    }

    // ---------- 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),
            ]
        );
    }
}