File size: 39,047 Bytes
8b6b2d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba145f2
 
 
 
 
 
 
8b6b2d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba145f2
 
 
 
8b6b2d0
ba145f2
8b6b2d0
 
 
 
 
 
ba145f2
 
 
 
 
 
8b6b2d0
 
ba145f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b6b2d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba145f2
 
8b6b2d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba145f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b6b2d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba145f2
 
 
8b6b2d0
ba145f2
8b6b2d0
ba145f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b6b2d0
ba145f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b6b2d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba145f2
8b6b2d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba145f2
 
 
8b6b2d0
 
 
ba145f2
 
 
 
8b6b2d0
 
 
 
 
 
ba145f2
 
 
8b6b2d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba145f2
 
 
 
 
 
8b6b2d0
 
 
 
 
 
 
 
 
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
<title>Beatrix Byte Scope</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans+Condensed:wght@500;600;700&family=IBM+Plex+Sans:wght@400;500;600&display=swap">
<style>
:root{
  --ground:#F1F2F4; --surface:#FFFFFF; --sunk:#E8EAEE;
  --line:#D6DAE0; --line-2:#C2C8D1;
  --ink:#14171B; --ink-2:#5A626D; --ink-3:#878F9A;
  --pos:#A85A12; --pos-soft:#E7C79B;
  --neg:#0E6A65; --neg-soft:#9FCFCB;
  --warn:#9A2F2F;
  --cursor:#14171B;
  --sans:"IBM Plex Sans",ui-sans-serif,system-ui,sans-serif;
  --cond:"IBM Plex Sans Condensed","IBM Plex Sans",ui-sans-serif,sans-serif;
  --mono:"IBM Plex Mono",ui-monospace,"SF Mono",Menlo,monospace;
}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
  --ground:#0C0E11; --surface:#15181D; --sunk:#1B1F26;
  --line:#242A33; --line-2:#333B47;
  --ink:#E6E9ED; --ink-2:#98A1AD; --ink-3:#6C7683;
  --pos:#E7A354; --pos-soft:#6A4715;
  --neg:#44B6AA; --neg-soft:#11534E;
  --warn:#E07272;
  --cursor:#E6E9ED;
}}
:root[data-theme="dark"]{
  --ground:#0C0E11; --surface:#15181D; --sunk:#1B1F26;
  --line:#242A33; --line-2:#333B47;
  --ink:#E6E9ED; --ink-2:#98A1AD; --ink-3:#6C7683;
  --pos:#E7A354; --pos-soft:#6A4715;
  --neg:#44B6AA; --neg-soft:#11534E;
  --warn:#E07272;
  --cursor:#E6E9ED;
}
*{box-sizing:border-box}
body{background:var(--ground);color:var(--ink);font-family:var(--sans);
  font-size:14px;line-height:1.5;margin:0;padding-block:0 40px;padding-left:16px;padding-right:16px;
  -webkit-font-smoothing:antialiased}
.wrap{max-width:1360px;margin:0 auto}

h1{font-family:var(--cond);font-weight:700;font-size:26px;letter-spacing:.01em;
  margin:0;text-wrap:balance;line-height:1.15}
.sub{color:var(--ink-2);margin:6px 0 0;max-width:68ch}
.lede{padding-block:26px 18px;border-bottom:1px solid var(--line)}
.meta{display:flex;flex-wrap:wrap;gap:6px 14px;margin-top:12px;
  font-family:var(--mono);font-size:11.5px;color:var(--ink-3)}
.meta b{color:var(--ink-2);font-weight:500}
a{color:var(--pos)}

/* ---- controls ---- */
.bar{position:sticky;top:env(safe-area-inset-top,0px);z-index:20;
  background:var(--ground);border-bottom:1px solid var(--line);
  padding-block:10px;margin-bottom:14px}
.row{display:flex;flex-wrap:wrap;gap:10px 18px;align-items:flex-end}
.fld{display:flex;flex-direction:column;gap:4px;min-width:0}
label,.lab{font-family:var(--cond);font-size:10.5px;font-weight:600;
  letter-spacing:.09em;text-transform:uppercase;color:var(--ink-3)}
select{font-family:var(--sans);font-size:13px;color:var(--ink);
  background:var(--surface);border:1px solid var(--line-2);border-radius:3px;
  padding:5px 8px;max-width:100%}
.seg{display:flex;border:1px solid var(--line-2);border-radius:3px;overflow:hidden}
.seg button{font-family:var(--cond);font-size:12px;font-weight:600;letter-spacing:.04em;
  background:var(--surface);color:var(--ink-2);border:0;
  border-left:1px solid var(--line-2);padding:6px 11px;cursor:pointer}
.seg button:first-child{border-left:0}
.seg button[aria-pressed="true"]{background:var(--ink);color:var(--ground)}
button:focus-visible,select:focus-visible,input:focus-visible,
.byte:focus-visible{outline:2px solid var(--pos);outline-offset:1px}
.ib{font-family:var(--cond);font-size:12px;font-weight:600;background:var(--surface);
  color:var(--ink);border:1px solid var(--line-2);border-radius:3px;
  padding:6px 11px;cursor:pointer}
input[type=range]{width:100%;accent-color:var(--pos)}
.status{font-family:var(--mono);font-size:11px;color:var(--ink-3);min-height:16px}

/* ---- byte strip ---- */
.strip{background:var(--surface);border:1px solid var(--line);border-radius:4px;
  padding:10px;margin-bottom:14px}
.bytes{display:flex;flex-wrap:wrap;gap:1px;max-height:168px;overflow-y:auto}
.byte{font-family:var(--mono);font-size:12px;line-height:1;width:17px;height:21px;
  display:flex;align-items:center;justify-content:center;border:0;padding:0;
  background:var(--sunk);color:var(--ink-2);cursor:pointer;border-radius:2px}
.byte.gen{background:var(--pos-soft);color:var(--ink)}
.byte.sel{background:var(--cursor);color:var(--ground);font-weight:600}
.legend{display:flex;flex-wrap:wrap;gap:10px 16px;margin-top:8px;
  font-family:var(--mono);font-size:11px;color:var(--ink-3);align-items:center}
.sw{display:inline-block;width:10px;height:10px;border-radius:2px;
  vertical-align:-1px;margin-right:5px}

/* ---- panels ---- */
.grid{display:grid;grid-template-columns:repeat(12,1fr);gap:14px}
.p{grid-column:span 12;background:var(--surface);border:1px solid var(--line);
  border-radius:4px;padding:13px 14px 15px;min-width:0}
.p.half{grid-column:span 6}
.p.third{grid-column:span 4}
.p.twothird{grid-column:span 8}
@media (max-width:900px){.p.half,.p.third,.p.twothird{grid-column:span 12}}
.ph{display:flex;justify-content:space-between;align-items:baseline;gap:10px;
  flex-wrap:wrap;margin-bottom:3px}
h2{font-family:var(--cond);font-size:14px;font-weight:700;letter-spacing:.03em;
  text-transform:uppercase;margin:0}
.note{color:var(--ink-2);font-size:12.5px;margin:0 0 10px;max-width:74ch}
.rdg{font-family:var(--mono);font-size:11.5px;color:var(--ink-2);
  font-variant-numeric:tabular-nums}
canvas{display:block;width:100%;height:auto;image-rendering:pixelated;
  background:var(--sunk);border-radius:2px}
#attmap{max-width:380px;aspect-ratio:1}
#exp{max-width:150px}
#head{max-width:230px;aspect-ratio:1}
.cw{overflow-x:auto}
.axis{display:flex;justify-content:space-between;font-family:var(--mono);
  font-size:10px;color:var(--ink-3);margin-top:3px}

/* ---- prediction list ---- */
.pred{display:grid;grid-template-columns:auto 1fr auto;gap:4px 9px;align-items:center;
  font-family:var(--mono);font-size:12px;font-variant-numeric:tabular-nums}
.pred .g{background:var(--sunk);border-radius:2px;padding:1px 6px;text-align:center;
  min-width:30px}
.pred .took .g{background:var(--cursor);color:var(--ground)}
.barbg{background:var(--sunk);border-radius:2px;height:9px;overflow:hidden}
.barfg{background:var(--pos);height:100%}
.pred .num{color:var(--ink-2)}

/* ---- stats ---- */
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(112px,1fr));
  gap:9px 14px;font-variant-numeric:tabular-nums}
.stat .k{font-family:var(--cond);font-size:10px;font-weight:600;letter-spacing:.08em;
  text-transform:uppercase;color:var(--ink-3)}
.stat .v{font-family:var(--mono);font-size:17px;color:var(--ink)}
.stat .u{font-family:var(--mono);font-size:11px;color:var(--ink-3)}

/* ---- table ---- */
.tw{overflow-x:auto}
table{border-collapse:collapse;font-family:var(--mono);font-size:11.5px;
  font-variant-numeric:tabular-nums;width:100%;min-width:430px}
th{font-family:var(--cond);font-size:10px;font-weight:600;letter-spacing:.07em;
  text-transform:uppercase;color:var(--ink-3);text-align:right;
  padding:4px 8px;border-bottom:1px solid var(--line-2)}
th:first-child,td:first-child{text-align:left}
td{padding:3px 8px;border-bottom:1px solid var(--line);color:var(--ink-2)}
tr.on td{color:var(--ink);background:var(--sunk)}
td.num{text-align:right}

.foot{margin-top:22px;padding-top:14px;border-top:1px solid var(--line);
  color:var(--ink-3);font-size:12px}
@media (prefers-reduced-motion:reduce){*{transition:none!important}}
</style>

<div class="wrap">
<header class="lede">
  <h1>Beatrix Byte Scope</h1>
  <p class="sub">Two real inferences through mini-beatrix-2s, opened byte by byte.
  Every number here was read out of one instrumented forward pass over the bytes
  the model actually produced &mdash; the splat address reads, the blackboard each
  layer writes to, the anchored experts, the head, and what one mounted arm changes.</p>
  <div class="meta" id="meta"></div>
</header>

<div class="bar">
  <div class="row">
    <div class="fld" style="flex:1 1 300px">
      <label for="cap">Inference</label>
      <select id="cap"></select>
    </div>
    <div class="fld">
      <span class="lab">Weights</span>
      <div class="seg" role="group" aria-label="Which weights">
        <button id="c-core" data-cfg="core" aria-pressed="false">Core</button>
        <button id="c-arm" data-cfg="arm" aria-pressed="true">Core + arm</button>
        <button id="c-diff" data-cfg="diff" aria-pressed="false">Difference</button>
      </div>
    </div>
    <div class="fld">
      <label for="lay">Layer</label>
      <select id="lay"></select>
    </div>
    <div class="fld">
      <span class="lab">Anchor views show</span>
      <div class="seg" role="group" aria-label="What the anchor views show">
        <button id="m-dev" data-mode="dev" aria-pressed="true">This byte's move</button>
        <button id="m-abs" data-mode="abs" aria-pressed="false">Absolute</button>
      </div>
    </div>
    <div class="fld">
      <span class="lab">Byte</span>
      <div style="display:flex;gap:6px;align-items:center">
        <button class="ib" id="prev" aria-label="Previous byte">&larr;</button>
        <button class="ib" id="play">Play</button>
        <button class="ib" id="next" aria-label="Next byte">&rarr;</button>
      </div>
    </div>
  </div>
  <div class="row" style="margin-top:8px">
    <div class="fld" style="flex:1 1 100%">
      <input type="range" id="pos" min="0" max="10" value="0" aria-label="Byte position">
      <div class="status" id="status">Loading the capture&hellip;</div>
    </div>
  </div>
</div>

<div class="strip">
  <div class="bytes" id="bytes"></div>
  <div class="legend">
    <span><span class="sw" style="background:var(--sunk)"></span>prompt</span>
    <span><span class="sw" style="background:var(--pos-soft)"></span>the model's reply</span>
    <span><span class="sw" style="background:var(--cursor)"></span>selected byte</span>
    <span id="replies"></span>
  </div>
</div>

<div class="grid">

  <section class="p twothird">
    <div class="ph"><h2>Depth &times; byte</h2><span class="rdg" id="depth-rdg"></span></div>
    <p class="note" id="depth-note">Each row is one of the twenty decoder blocks, each column one
    byte. Click anywhere to move the cursor.</p>
    <div class="fld" style="margin-bottom:8px">
      <label for="chan">Channel</label>
      <select id="chan">
        <option value="attn_norm">What the splat read contributed</option>
        <option value="bank_disp">What the dispatched experts contributed</option>
        <option value="bank_trunk">What the always-on expert contributed</option>
        <option value="resid_out">Residual stream size leaving the block</option>
        <option value="den">Agreement mass (the splat denominator)</option>
        <option value="arm_patch">What the arm's patch contributed</option>
      </select>
    </div>
    <div class="cw"><canvas id="depth" height="200"></canvas></div>
    <div class="axis"><span>byte 0</span><span id="depth-ax"></span></div>
  </section>

  <section class="p third">
    <div class="ph"><h2>At this byte</h2></div>
    <p class="note" id="pred-note">What the model predicted for the next byte here, and
    what it took.</p>
    <div class="stats" id="stats"></div>
    <div style="height:12px"></div>
    <div class="pred" id="pred"></div>
  </section>

  <section class="p half">
    <div class="ph"><h2>Where this byte reads</h2><span class="rdg" id="att-rdg"></span></div>
    <p class="note">There is no softmax over positions in this architecture. This row is the
    exact byte-to-byte weight implied by the same bilinear forms the scan sums, so it is
    derived from the read, not an approximation of it. Each bar is one earlier byte.</p>
    <div class="cw"><canvas id="attrow" height="120"></canvas></div>
    <div class="axis"><span>byte 0</span><span id="att-ax"></span></div>
  </section>

  <section class="p half">
    <div class="ph"><h2>The whole layer's reading</h2><span class="rdg" id="attm-rdg"></span></div>
    <p class="note">Every byte's row at once for this layer, rows normalized to their own
    maximum. The diagonal is a byte reading itself; a bright column is a byte the whole
    sequence keeps returning to.</p>
    <div class="cw"><canvas id="attmap" height="260"></canvas></div>
  </section>

  <section class="p half">
    <div class="ph"><h2>Address read</h2><span class="rdg" id="read-rdg"></span></div>
    <p class="note">Four constellations of sixty-four anchors each. The read is
    <em>signed</em>: a negative weight is inhibition, a first-class result of the closed
    form, not an absence. Amber excites, teal inhibits.</p>
    <div class="cw"><canvas id="readc" height="96"></canvas></div>
    <div class="axis"><span>anchor 0</span><span>anchor 63</span></div>
    <div style="height:12px"></div>
    <p class="note" style="margin-bottom:6px">The same read down the full depth &mdash;
    twenty blocks against the anchors, all four books side by side unless you pick one.
    The books are independent frames that compose by budget, never by a choice between
    them, so reading them together is reading the whole address.</p>
    <div class="fld" style="margin-bottom:6px">
      <label for="cst">Books shown (here and in the write below)</label>
      <select id="cst"></select>
    </div>
    <div class="cw"><canvas id="readd" height="200"></canvas></div>
  </section>

  <section class="p half">
    <div class="ph"><h2>What this byte writes</h2><span class="rdg" id="write-rdg"></span></div>
    <p class="note">The blackboard each layer keeps is a <em>running sum</em>: it only ever
    grows, so plotting it directly plots the position in the sequence and almost nothing
    else. What moves byte to byte is the <em>write</em> — what this one byte puts on the
    board, before it is added in. That is what these two show.</p>
    <div class="cw"><canvas id="writec" height="96"></canvas></div>
    <div class="axis"><span>anchor 0</span><span>anchor 63</span></div>
    <div style="height:12px"></div>
    <p class="note" style="margin-bottom:6px">The same write down the full depth.</p>
    <div class="cw"><canvas id="writed" height="200"></canvas></div>
  </section>

  <section class="p half">
    <div class="ph"><h2>How many anchors carry the load</h2>
      <span class="rdg" id="used-rdg"></span></div>
    <p class="note">The board's width in use: the effective number of anchors holding the
    accumulated mass, out of sixty-four, at every byte. This is the one reading of the
    cumulative board that is worth watching, because it moves while the board itself
    barely does. A fall means the layer has settled onto a few anchors and is keeping
    them.</p>
    <div class="cw"><canvas id="used" height="200"></canvas></div>
    <div class="axis"><span>byte 0</span><span id="used-ax"></span></div>
    <p class="note" style="margin:8px 0 0">Rows are blocks, top to bottom; brighter is
    wider. Each row is scaled to its own range, so read a row along its length rather
    than against its neighbours.</p>
  </section>

  <section class="p half">
    <div class="ph"><h2>Anchored experts</h2><span class="rdg" id="exp-rdg"></span></div>
    <p class="note">Three fat experts per block under the same signed dispatch, with an
    always-on trunk beside them. Every expert contributes at every byte, weighted by sign;
    nothing is selected and nothing is dropped.</p>
    <div class="cw"><canvas id="exp" height="200"></canvas></div>
    <div class="axis"><span>expert 1</span><span>expert 3</span></div>
  </section>

  <section class="p half">
    <div class="ph"><h2>Head address</h2><span class="rdg" id="head-rdg"></span></div>
    <p class="note">The readout's own 256-atom signed read on the final hidden state,
    laid out sixteen by sixteen. This path was born at exactly zero weight and had to earn
    its way in during training.</p>
    <div class="cw"><canvas id="head" height="200"></canvas></div>
  </section>

  <section class="p">
    <div class="ph"><h2>Codebook frames</h2><span class="rdg">static, per block</span></div>
    <p class="note">The anchors themselves, not the activity on them. Drift is how far each
    frame moved from where it was born; effective rank is how much of its own space it still
    spans; the largest off-diagonal cosine says whether any two anchors have crowded
    together. The governor holds them apart from birth, so none of these frames collapsed.</p>
    <div class="tw"><table id="cb"><thead><tr>
      <th>Block</th><th>Constellation</th><th>Drift, mean</th><th>Drift, max</th>
      <th>Effective rank</th><th>Max |cos|</th><th>Merged pairs</th>
    </tr></thead><tbody></tbody></table></div>
  </section>

</div>

<p class="foot" id="foot"></p>
</div>

<script>
"use strict";
const $ = s => document.querySelector(s);
const clamp = (v,a,b) => v<a?a:(v>b?b:v);
const cssv = n => getComputedStyle(document.documentElement).getPropertyValue(n).trim();

const S = {man:null, cap:null, cfg:"arm", byte:0, layer:10, cst:"all",
           mode:"dev", chan:"attn_norm", sum:{}, bin:{}, playing:0};

/* ---------------------------------------------------------- data loading
   The same page serves two homes: the published artifact keeps the capture
   under data/, and the dataset repo keeps it beside (or one level above)
   this file. BASE is settled once at boot; EXT likewise, because the
   artifact host serves the arrays as base64 text and the dataset keeps
   them as raw uint8. */
let BASE = "data/", EXT = null;
const key = (c,g) => c+"/"+g;
async function summary(capId,cfg){
  const k = key(capId,cfg);
  if(!S.sum[k]) S.sum[k] = fetch(`${BASE}${capId}/${cfg}/summary.json`).then(r=>r.json());
  return S.sum[k];
}
const unb64 = t => {
  const s = atob(t.trim());
  const u = new Uint8Array(s.length);
  for(let i=0;i<s.length;i++) u[i] = s.charCodeAt(i);
  return u;
};
async function bin(capId,cfg,name){
  const k = key(capId,cfg)+"/"+name;
  if(!S.bin[k]) S.bin[k] = (async () => {
    const stem = `${BASE}${capId}/${cfg}/${name}`;
    if(EXT === null){                       // settle the form once
      const r = await fetch(stem + ".u8").catch(() => null);
      if(r && r.ok){ EXT = ".u8"; return new Uint8Array(await r.arrayBuffer()); }
      EXT = ".b64.txt";
    }
    const r = await fetch(stem + EXT);
    if(!r.ok) throw new Error(`${name}${EXT} did not load (${r.status})`);
    return EXT === ".u8" ? new Uint8Array(await r.arrayBuffer())
                         : unb64(await r.text());
  })();
  return S.bin[k];
}
const desS = (u,s) => (u-128)/127*s;      // signed dequantize
const desU = (u,s) => u/255*s;            // unsigned dequantize

/* The anchor arrays are stored as a per-anchor MEAN over the sequence plus
   a quantized DEVIATION from it, one scale per (block, constellation).
   Every anchor picture is dominated by a large constant part — neighbouring
   bytes are 0.98+ alike — so the deviation is what a byte-by-byte reader
   wants, and it is also the only form in which the per-byte signal survives
   eight bits. `abs` adds the mean back. Returns a reader plus the range to
   colour against. */
async function anchors(capId,cfg,name){
  const [s,a] = await Promise.all([summary(capId,cfg), bin(capId,cfg,name)]);
  const [L,C,n,K] = s.shapes[name];
  const mean = s.mean[name], scale = s.scales[name];
  const dev = (l,c,i,k) => desS(a[((l*C+c)*n + i)*K + k], scale[l][c]);
  const abs = (l,c,i,k) => mean[l][c][k] + dev(l,c,i,k);
  return {L, C, n, K, scale,
          get: S.mode === "abs" ? abs : dev,
          signed: true};
}
function spanOf(get, cs, ls, i, K){        // symmetric range over what is drawn
  let m = 0;
  for(const l of ls) for(const c of cs) for(let k=0;k<K;k++){
    const v = Math.abs(get(l,c,i,k)); if(v>m) m = v;
  }
  return m || 1;
}
/* Four constellations side by side: 4*K columns with the book index folded
   into x. One book: K columns. */
const books = C => S.cst === "all" ? Array.from({length:C},(_,i)=>i) : [S.cst|0];

/* ------------------------------------------------------------- colouring */
function ramp(t){                          // sequential: ground -> amber
  t = clamp(t,0,1);
  const a = hex(cssv("--sunk")), b = hex(cssv("--pos"));
  return mix(a,b,Math.pow(t,0.75));
}
function diverge(t){                       // signed: teal <- ground -> amber
  t = clamp(t,-1,1);
  const g = hex(cssv("--sunk"));
  const c = hex(cssv(t<0?"--neg":"--pos"));
  return mix(g,c,Math.pow(Math.abs(t),0.65));
}
function hex(h){
  h = h.replace("#","");
  if(h.length===3) h = h[0]+h[0]+h[1]+h[1]+h[2]+h[2];
  return [parseInt(h.slice(0,2),16),parseInt(h.slice(2,4),16),parseInt(h.slice(4,6),16)];
}
const mix = (a,b,t) => [Math.round(a[0]+(b[0]-a[0])*t),
                        Math.round(a[1]+(b[1]-a[1])*t),
                        Math.round(a[2]+(b[2]-a[2])*t)];

/** Paint a cols x rows grid of values into a canvas, one pixel per cell. */
function paint(cv, cols, rows, val, signed, scale){
  cv.width = cols; cv.height = rows;
  const ctx = cv.getContext("2d");
  const img = ctx.createImageData(cols, rows);
  const d = img.data;
  for(let y=0;y<rows;y++) for(let x=0;x<cols;x++){
    const v = val(x,y);
    const c = signed ? diverge(v/scale) : ramp(v/scale);
    const i = (y*cols+x)*4;
    d[i]=c[0]; d[i+1]=c[1]; d[i+2]=c[2]; d[i+3]=255;
  }
  ctx.putImageData(img,0,0);
}
/** Cursor lines over a painted grid, drawn in CSS pixels on an overlay pass. */
function cursor(cv, cols, rows, cx, cy){
  const ctx = cv.getContext("2d");
  ctx.save(); ctx.globalAlpha=.9; ctx.fillStyle="rgb("+hex(cssv("--cursor")).join(",")+")";
  if(cx!=null && cx>=0) ctx.fillRect(cx,0,1,rows);
  if(cy!=null && cy>=0) ctx.fillRect(0,cy,cols,1);
  ctx.restore();
}

/* ------------------------------------------------------------ byte glyphs */
function glyph(b){
  if(b===10) return "⏎";
  if(b===13) return "¬";
  if(b===9)  return "⇥";
  if(b===32) return "·";
  if(b>=33 && b<=126) return String.fromCharCode(b);
  return "▫";
}
function glyphName(b){
  if(b===10) return "newline"; if(b===32) return "space"; if(b===9) return "tab";
  if(b>=33&&b<=126) return "'"+String.fromCharCode(b)+"'";
  return "byte "+b;
}

/* --------------------------------------------------------------- helpers */
function cap(){ return S.man.captures.find(c=>c.id===S.cap); }
function cfgsNeeded(){ return S.cfg==="diff" ? ["arm","core"] : [S.cfg]; }
function armMissing(){ return S.cfg==="core"; }

/** A per-layer scalar series, resolved through the current weights mode. */
async function series(chan){
  const c = cap();
  const get = s => s.per_layer.map(L=>{
    if(chan==="den") return L.den[0].map((_,i)=>L.den.reduce((a,r)=>a+r[i],0));
    const v = L[chan];
    return v || new Array(c.n).fill(0);
  });
  if(S.cfg==="diff"){
    const [a,b] = await Promise.all([summary(c.id,"arm"), summary(c.id,"core")]);
    const A=get(a), B=get(b);
    return A.map((r,li)=>r.map((v,i)=>v-B[li][i]));
  }
  return get(await summary(c.id,S.cfg));
}

/* ----------------------------------------------------------------- panels */
async function drawDepth(){
  const c = cap(), n = c.n, rows = 20;
  const data = await series(S.chan);
  const signed = S.cfg==="diff";
  let m = 0; for(const r of data) for(const v of r) m = Math.max(m, Math.abs(v));
  m = m || 1;
  const cv = $("#depth");
  paint(cv, n, rows, (x,y)=>data[y][x], signed, m);
  cursor(cv, n, rows, S.byte, S.layer);
  cv.style.height = "200px";
  const lbl = $("#chan").selectedOptions[0].textContent;
  $("#depth-rdg").textContent =
    `${lbl.toLowerCase()} · ${signed?"±":"0–"}${m.toPrecision(3)}` +
    (S.chan==="arm_patch" && armMissing() ? " · no arm mounted" : "");
  $("#depth-ax").textContent = "byte "+(n-1);
  $("#depth-note").textContent = S.chan==="arm_patch" && armMissing()
    ? "The arm is detached in this view, so this channel is flat. Switch the weights to Core + arm."
    : "Each row is one of the twenty decoder blocks, each column one byte. Click anywhere to move the cursor.";
}

async function drawPred(){
  const c = cap(), i = S.byte;
  const base = await summary(c.id, S.cfg==="diff" ? "arm" : S.cfg);
  const other = S.cfg==="diff" ? await summary(c.id,"core") : null;
  const ids = base.top_ids[i], ps = base.top_p[i];
  const took = i+1 < c.n ? c.bytes[i+1] : null;
  let html = "";
  for(let k=0;k<ids.length;k++){
    const isTook = took!==null && ids[k]===took;
    html += `<div class="${isTook?"took":""}" style="display:contents">`+
      `<span class="g">${glyph(ids[k])}</span>`+
      `<span class="barbg"><span class="barfg" style="width:${(ps[k]*100).toFixed(1)}%"></span></span>`+
      `<span class="num">${(ps[k]*100).toFixed(1)}%</span></div>`;
  }
  $("#pred").innerHTML = html;
  const st = [
    ["Byte", glyphName(c.bytes[i]), "position "+i],
    ["Entropy", base.entropy[i].toFixed(2), "bits"],
    ["Took", took===null?"—":glyphName(took),
      took===null?"end of capture":(base.p_actual[i]*100).toFixed(1)+"% given"],
  ];
  if(other) st.push(["Entropy, core", other.entropy[i].toFixed(2),
    (base.entropy[i]-other.entropy[i]>=0?"+":"")+(base.entropy[i]-other.entropy[i]).toFixed(2)+" with arm"]);
  $("#stats").innerHTML = st.map(([k,v,u])=>
    `<div class="stat"><div class="k">${k}</div><div class="v">${v}</div>`+
    `<div class="u">${u}</div></div>`).join("");
  $("#pred-note").textContent = i+1 >= c.n
    ? "The last byte of the capture has nothing after it, so there is no target here."
    : (i < c.n_prompt ? "Still inside the prompt: the model is reading, and this is what it would have written instead."
                      : "Inside the reply: this is the choice it actually made.");
}

async function attRow(capId,cfg,layer,i,n){
  const a = await bin(capId,cfg,"attn");
  const off = layer*n*n + i*n;
  const out = new Float32Array(i+1);
  for(let j=0;j<=i;j++) out[j] = a[off+j]/255;
  return out;
}
async function drawAtt(){
  const c = cap(), n = c.n, i = S.byte;
  let row, signed=false;
  if(S.cfg==="diff"){
    const [A,B] = await Promise.all([attRow(c.id,"arm",S.layer,i,n),
                                     attRow(c.id,"core",S.layer,i,n)]);
    row = A.map((v,j)=>v-B[j]); signed = true;
  } else row = await attRow(c.id,S.cfg,S.layer,i,n);
  let m=0; for(const v of row) m=Math.max(m,Math.abs(v)); m=m||1;
  const cv = $("#attrow");
  paint(cv, n, 1, (x)=> x<=i ? row[x] : 0, signed, m);
  cv.style.height = "34px";
  const top = Array.from(row).map((v,j)=>[Math.abs(v),j]).sort((a,b)=>b[0]-a[0]).slice(0,3);
  $("#att-rdg").textContent = top.length
    ? "strongest: " + top.map(([,j])=>`${glyph(c.bytes[j])}@${j}`).join(" ")
    : "";
  $("#att-ax").textContent = "byte "+(n-1);

  const cm = $("#attmap");
  if(S.cfg==="diff"){
    const [A,B] = await Promise.all([bin(c.id,"arm","attn"), bin(c.id,"core","attn")]);
    const o = S.layer*n*n;
    paint(cm, n, n, (x,y)=> x<=y ? (A[o+y*n+x]-B[o+y*n+x])/255 : 0, true, 1);
    $("#attm-rdg").textContent = "arm minus core, block "+S.layer;
  } else {
    const A = await bin(c.id,S.cfg,"attn");
    const o = S.layer*n*n;
    paint(cm, n, n, (x,y)=> x<=y ? A[o+y*n+x]/255 : 0, false, 1);
    $("#attm-rdg").textContent = "block "+S.layer;
  }
  cursor(cm, n, n, null, i);
}

/** One anchor array drawn twice: across the four books at this byte, and
    down the twenty blocks at this byte. `name` is read or write. */
async function drawAnchors(name, cTop, cDepth, rdg, label){
  const c = cap(), i = S.byte;
  let A = await anchors(c.id, S.cfg==="diff" ? "arm" : S.cfg, name), get = A.get;
  if(S.cfg==="diff"){
    const B = await anchors(c.id,"core",name);
    get = (l,cc,ii,k) => A.get(l,cc,ii,k) - B.get(l,cc,ii,k);
  }
  const {L,C,K} = A;
  const all = Array.from({length:C},(_,x)=>x);

  const mTop = spanOf(get, all, [S.layer], i, K);
  paint(cTop, K, C, (x,y)=>get(S.layer,y,i,x), true, mTop);
  cTop.style.height = "96px";

  const bs = books(C), W = K*bs.length;
  const mD = spanOf(get, bs, Array.from({length:L},(_,x)=>x), i, K);
  paint(cDepth, W, L, (x,y)=>get(y, bs[(x/K)|0], i, x%K), true, mD);
  cursor(cDepth, W, L, null, S.layer);
  cDepth.style.height = "200px";

  $(rdg).textContent = `block ${S.layer} · byte ${i} · ` +
    (S.mode==="abs" ? "absolute" : "move from this run's average") +
    ` · ±${mTop.toPrecision(2)}`;
}
const drawRead  = () => drawAnchors("read",  $("#readc"),  $("#readd"),
                                    "#read-rdg", "read");
const drawWrite = () => drawAnchors("write", $("#writec"), $("#writed"),
                                    "#write-rdg", "write");

/** The board's width in use, every block, the whole sequence. Each row is
    scaled to its own range because blocks differ by an order of magnitude. */
async function drawUsed(){
  const c = cap(), n = c.n;
  const get = s => s.per_layer.map(L =>
    L.used[0].map((_,i) => L.used.reduce((a,r)=>a+r[i],0)/L.used.length));
  let rows, signed = false;
  if(S.cfg==="diff"){
    const [a,b] = await Promise.all([summary(c.id,"arm"), summary(c.id,"core")]);
    const A=get(a), B=get(b); rows = A.map((r,li)=>r.map((v,i)=>v-B[li][i]));
    signed = true;
  } else rows = get(await summary(c.id,S.cfg));
  const lo = rows.map(r=>Math.min(...r)), hi = rows.map(r=>Math.max(...r));
  const cv = $("#used");
  paint(cv, n, rows.length, (x,y)=>{
    const s = signed ? Math.max(Math.abs(lo[y]),Math.abs(hi[y])) || 1
                     : (hi[y]-lo[y]) || 1;
    return signed ? rows[y][x]/s : (rows[y][x]-lo[y])/s;
  }, signed, 1);
  cursor(cv, n, rows.length, S.byte, S.layer);
  cv.style.height = "200px";
  $("#used-ax").textContent = "byte "+(n-1);
  const r = rows[S.layer];
  $("#used-rdg").textContent = signed
    ? `block ${S.layer}: ${(r[S.byte]>=0?"+":"")}${r[S.byte].toFixed(1)} anchors vs the core`
    : `block ${S.layer}: ${r[S.byte].toFixed(1)} of 64 at byte ${S.byte}` +
      ` · ${Math.min(...r).toFixed(1)}–${Math.max(...r).toFixed(1)} over the run`;
}


async function drawExp(){
  const c = cap(), i = S.byte;
  const get = s => s.per_layer.map(L=>L.experts[i]);
  let rows, signed = true;
  if(S.cfg==="diff"){
    const [a,b] = await Promise.all([summary(c.id,"arm"), summary(c.id,"core")]);
    const A=get(a), B=get(b); rows = A.map((r,li)=>r.map((v,k)=>v-B[li][k]));
  } else rows = get(await summary(c.id,S.cfg));
  let m=0; for(const r of rows) for(const v of r) m=Math.max(m,Math.abs(v));
  const E = rows[0].length;
  const cv = $("#exp");
  paint(cv, E, rows.length, (x,y)=>rows[y][x], signed, m||1);
  cursor(cv, E, rows.length, null, S.layer);
  cv.style.height = "200px";
  const r = rows[S.layer];
  $("#exp-rdg").textContent = `block ${S.layer}: ` +
    r.map(v=>(v>=0?"+":"")+v.toFixed(3)).join("  ");
}

async function drawHead(){
  const c = cap(), i = S.byte;
  const cfg = S.cfg==="diff" ? "arm" : S.cfg;
  const s = await summary(c.id,cfg);
  const [n,Kh] = s.shapes.head;
  const a = await bin(c.id,cfg,"head");
  let f = k => desS(a[i*Kh+k], s.scales.head);
  if(S.cfg==="diff"){
    const sb = await summary(c.id,"core");
    const b = await bin(c.id,"core","head");
    const fa = f; f = k => fa(k) - desS(b[i*Kh+k], sb.scales.head);
  }
  const side = Math.round(Math.sqrt(Kh));
  let m=0; for(let k=0;k<Kh;k++) m=Math.max(m,Math.abs(f(k)));
  const cv = $("#head");
  paint(cv, side, side, (x,y)=>f(y*side+x), true, m||1);
  cv.style.height = "200px";
  $("#head-rdg").textContent = `${Kh} atoms · ±${(m||0).toPrecision(3)}` +
    (S.cfg==="diff" ? " · arm minus core" : "");
}

function drawCodebooks(){
  const tb = $("#cb tbody");
  tb.innerHTML = S.man.codebooks.map(r=>
    `<tr class="${r.layer===S.layer?"on":""}"><td>${r.layer}</td><td>${r.const}</td>`+
    `<td class="num">${r.drift_mean.toFixed(4)}</td><td class="num">${r.drift_max.toFixed(4)}</td>`+
    `<td class="num">${r.erank.toFixed(1)}</td><td class="num">${r.max_abs_cos.toFixed(3)}</td>`+
    `<td class="num">${r.merge_pairs}</td></tr>`).join("");
}

/* ------------------------------------------------------------- byte strip */
function drawBytes(){
  const c = cap();
  const f = document.createDocumentFragment();
  for(let i=0;i<c.n;i++){
    const b = document.createElement("button");
    b.className = "byte" + (i>=c.n_prompt?" gen":"") + (i===S.byte?" sel":"");
    b.textContent = glyph(c.bytes[i]);
    b.title = `byte ${i}: ${glyphName(c.bytes[i])}`;
    b.onclick = () => setByte(i);
    f.appendChild(b);
  }
  const el = $("#bytes"); el.innerHTML = ""; el.appendChild(f);
}
function markByte(){
  const el = $("#bytes");
  const prev = el.querySelector(".sel"); if(prev) prev.classList.remove("sel");
  const cur = el.children[S.byte];
  if(cur){ cur.classList.add("sel");
    const r = cur.getBoundingClientRect(), p = el.getBoundingClientRect();
    if(r.top < p.top || r.bottom > p.bottom) cur.scrollIntoView({block:"nearest"});
  }
}

/* ---------------------------------------------------------------- driving */
let pending = 0;
async function redraw(all){
  const id = ++pending;
  $("#status").textContent = "reading…";
  try{
    if(all) drawBytes();
    markByte();
    drawCodebooks();
    await Promise.all([drawDepth(), drawPred(), drawAtt(), drawRead(),
                       drawWrite(), drawUsed(), drawExp(), drawHead()]);
    if(id!==pending) return;
    const c = cap();
    $("#status").textContent =
      `byte ${S.byte} of ${c.n-1} · ${S.byte<c.n_prompt?"prompt":"reply"} · `+
      `block ${S.layer} · ${S.cfg==="diff"?"arm minus core":(S.cfg==="arm"?"core + rules arm":"bare core")}`;
  }catch(e){
    $("#status").textContent = "could not read that view: "+e.message;
  }
}
function setByte(i){
  const c = cap();
  S.byte = clamp(i,0,c.n-1);
  $("#pos").value = S.byte;
  redraw(false);
}
function setCapture(id){
  S.cap = id;
  const c = cap();
  S.byte = Math.min(c.n_prompt, c.n-1);
  $("#pos").max = c.n-1; $("#pos").value = S.byte;
  $("#replies").innerHTML =
    `arm &rarr; <b style="color:var(--ink-2)">${esc(c.reply_arm).slice(0,64)}</b>` +
    ` &nbsp;|&nbsp; core &rarr; <b style="color:var(--ink-2)">${esc(c.reply_core).slice(0,64)}</b>` +
    (c.gold ? ` &nbsp;|&nbsp; expected <b style="color:var(--ink-2)">${esc(c.gold)}</b>` : "");
  redraw(true);
}
const esc = s => String(s).replace(/[&<>]/g,m=>({"&":"&amp;","<":"&lt;",">":"&gt;"}[m]));

function canvasNav(cv, cols, rows, onPick){
  cv.style.cursor = "crosshair";
  cv.addEventListener("click", ev=>{
    const r = cv.getBoundingClientRect();
    const x = Math.floor((ev.clientX-r.left)/r.width*cols());
    const y = Math.floor((ev.clientY-r.top)/r.height*rows());
    onPick(x,y);
  });
}

/* ------------------------------------------------------------------- boot */
(async function(){
  for(const b of ["data/", "./", "../"]){
    try{
      const r = await fetch(b + "manifest.json");
      if(r.ok){ S.man = await r.json(); BASE = b; break; }
    }catch(e){ /* try the next home */ }
  }
  if(!S.man){
    $("#status").textContent =
      "manifest.json is not beside this page. Serve this file from the folder "+
      "that holds the capture (a plain local server — a file:// page cannot "+
      "read its own folder).";
    return;
  }
  const m = S.man;
  $("#meta").innerHTML = [
    ["model", m.core],
    ["arm", `${m.arm.id} — ${m.arm.cell}, ${(m.arm.params/1e6).toFixed(1)}M over ${m.arm.sites} sites`],
    ["decode", m.precision],
    ["captures", m.captures.length + " inferences, each traced twice"],
  ].map(([k,v])=>`<span><b>${k}</b> ${esc(v)}</span>`).join("");
  $("#foot").innerHTML =
    `The arm is <b>${esc(m.arm.id)}</b>: ${esc(m.arm.title)} — measured ${esc(m.arm.score)}, ${esc(m.arm.status)}. ` +
    `Weights and the arm library: <a href="https://huggingface.co/AbstractPhil/mini-beatrix-2.5s">mini-beatrix-2.5s</a>. ` +
    `These captures, with the script that made them: ` +
    `<a href="https://huggingface.co/datasets/AbstractPhil/beatrix-captured-interactive-inferences">beatrix-captured-interactive-inferences</a>.`;

  $("#cap").innerHTML = m.captures.map(c=>
    `<option value="${c.id}">${esc(c.title)} — ${esc(c.prompt.slice(0,54))}…</option>`).join("");
  $("#lay").innerHTML = Array.from({length:20},(_,i)=>
    `<option value="${i}"${i===S.layer?" selected":""}>Block ${i}${i===0?" (first)":(i===19?" (last)":"")}</option>`).join("");
  $("#cst").innerHTML = '<option value="all" selected>All four books</option>' +
    Array.from({length:4},(_,i)=>
      `<option value="${i}">Constellation ${i+1} of 4</option>`).join("");

  $("#cap").onchange = e => setCapture(e.target.value);
  $("#lay").onchange = e => { S.layer = +e.target.value; redraw(false); };
  $("#cst").onchange = e => {
    S.cst = e.target.value === "all" ? "all" : +e.target.value;
    redraw(false);
  };
  $("#chan").onchange = e => { S.chan = e.target.value; drawDepth(); };
  $("#pos").oninput = e => setByte(+e.target.value);
  $("#prev").onclick = () => setByte(S.byte-1);
  $("#next").onclick = () => setByte(S.byte+1);
  document.querySelectorAll(".seg button").forEach(b=>{
    b.onclick = () => {
      const grp = b.dataset.cfg ? "cfg" : "mode";
      if(grp === "cfg") S.cfg = b.dataset.cfg; else S.mode = b.dataset.mode;
      b.parentElement.querySelectorAll("button").forEach(o=>
        o.setAttribute("aria-pressed", String(o===b)));
      redraw(false);
    };
  });
  $("#play").onclick = function(){
    if(S.playing){ clearInterval(S.playing); S.playing=0; this.textContent="Play"; return; }
    this.textContent = "Stop";
    S.playing = setInterval(()=>{
      const c = cap();
      if(S.byte >= c.n-1){ clearInterval(S.playing); S.playing=0; $("#play").textContent="Play"; return; }
      setByte(S.byte+1);
    }, 220);
  };
  addEventListener("keydown", e=>{
    if(e.target.tagName==="SELECT"||e.target.tagName==="INPUT") return;
    if(e.key==="ArrowLeft"){ setByte(S.byte-1); e.preventDefault(); }
    if(e.key==="ArrowRight"){ setByte(S.byte+1); e.preventDefault(); }
    if(e.key==="ArrowUp"){ S.layer=clamp(S.layer-1,0,19); $("#lay").value=S.layer; redraw(false); e.preventDefault(); }
    if(e.key==="ArrowDown"){ S.layer=clamp(S.layer+1,0,19); $("#lay").value=S.layer; redraw(false); e.preventDefault(); }
  });

  canvasNav($("#depth"), ()=>cap().n, ()=>20, (x,y)=>{
    S.layer = clamp(y,0,19); $("#lay").value = S.layer; setByte(x);
  });
  canvasNav($("#attmap"), ()=>cap().n, ()=>cap().n, (x,y)=>setByte(y));
  canvasNav($("#attrow"), ()=>cap().n, ()=>1, (x)=>setByte(x));
  const pickLayer = (x,y)=>{ S.layer = clamp(y,0,19); $("#lay").value = S.layer;
                             redraw(false); };
  canvasNav($("#readd"),  ()=>64, ()=>20, pickLayer);
  canvasNav($("#writed"), ()=>64, ()=>20, pickLayer);
  canvasNav($("#used"), ()=>cap().n, ()=>20, (x,y)=>{
    S.layer = clamp(y,0,19); $("#lay").value = S.layer; setByte(x);
  });
  canvasNav($("#exp"), ()=>3, ()=>20, (x,y)=>{
    S.layer = clamp(y,0,19); $("#lay").value = S.layer; redraw(false);
  });

  setCapture(m.captures[0].id);
  matchMedia("(prefers-color-scheme:dark)").addEventListener("change", ()=>redraw(false));
})();
</script>