File size: 139,549 Bytes
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609fb78
bf8519f
 
 
 
 
e1b3e71
bf8519f
609fb78
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609fb78
 
 
 
 
 
bf8519f
 
 
 
 
 
 
 
 
 
e1b3e71
 
 
 
 
 
 
bf8519f
e1b3e71
 
 
 
 
 
bf8519f
 
 
 
 
 
 
 
609fb78
 
 
bf8519f
 
609fb78
 
 
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
051f280
 
 
 
bf8519f
051f280
bf8519f
 
 
 
 
 
609fb78
 
 
 
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
 
 
 
 
 
 
 
 
 
 
bf8519f
e1b3e71
 
 
 
 
 
 
 
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609fb78
 
 
 
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
051f280
 
 
 
 
 
bf8519f
 
 
 
051f280
 
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
051f280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609fb78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf8519f
 
 
 
 
 
 
 
 
609fb78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf8519f
 
 
609fb78
bf8519f
 
 
 
 
 
 
 
 
 
609fb78
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
051f280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
051f280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
 
 
 
 
 
 
 
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
609fb78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609fb78
 
 
 
 
bf8519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
// ---------------------------------------------------------------------------
// shell/Shell.tsx β€” the STANDALONE React shell (wave-4 scaffold; EXIT wave 1
// gives it a real door and a real nav).
//
// WHAT THIS IS. The successor-shaped outer frame the 2026-07-23 decision named
// ("React over a thin API β€” the same contract the OM-6 MCP server exposes").
// It STRANGLES, it does not replace: exactly one surface is native today β€” the
// Customer table, the component tree the Streamlit embed already ships β€” and
// every other surface is an honest link into the current application. A page
// moves here when its data contract is served by the API, never before; the
// nav never pretends otherwise.
//
// WHAT CHANGED IN EXIT WAVE 1 (X5 + X6):
//   Β· The door is per-user (`core/users` accounts over X2/X3), not a shared
//     HTTP Basic password. SHELL.md's ladder step-1 "SANDBOX user key until
//     real auth lands" is SUPERSEDED β€” there are real sessions from day one.
//   Β· The nav is SERVER-FILTERED and registry-driven (`GET /api/v1/nav`), not a
//     static array hand-mirroring core/registry.py. What a user sees is what
//     `may_open` granted them.
//   Β· There is NO client-side nav fallback and no hard-coded surface. An
//     undeclared surface is denied β€” including by omission from the payload.
//
// WHAT THIS IS NOT. Not Next.js β€” recorded decision: one component tree, one
// build system (the same Vite workspace whose OTHER config builds the embed
// bundle), no SSR/SEO need behind a login gate. The shell frame is the cheap,
// swappable part; the components are the asset. Revisit at the white-label
// trigger (OM-7), where multi-tenant routing might earn Next.
//
// Routing is a ~20-line hash router on purpose: a handful of routes do not earn
// a dependency the embed bundle would have to keep excluded.
// ---------------------------------------------------------------------------

import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import type { MouseEvent as ReactMouseEvent, ReactNode } from "react";
/**
 * ⭐ WAVE-27 item 34 (I5) β€” ROUTE-LEVEL CODE SPLITTING.
 *
 * Six surfaces that are already mounted CONDITIONALLY (an automation route, the settings modal,
 * the connectors page, home, the template picker, the alerts pane) become their own chunks. The
 * shell downloads them when a person actually opens one β€” which for most sessions is never, and
 * for every session is not the first paint.
 *
 * ⚠ EVERY ONE OF THESE WAS ALREADY BEHIND A CONDITION IN THE JSX, and that is what makes the
 * split real rather than cosmetic: a `lazy` whose mount renders unconditionally downloads on the
 * first paint anyway and buys a Suspense boundary for nothing. `CustomerGrid` is deliberately NOT
 * in this list, for the mirror-image reason β€” it IS the first paint on nearly every route, so
 * splitting it would add a round trip to the common case. (The build reports it as an INEFFECTIVE
 * dynamic import from `RecordDetail`; that is expected and correct β€” that import exists to break
 * a module CYCLE, not to move bytes. See the note beside it.)
 *
 * ⚠ `SettingsModal` is a NAMED export, so its loader maps to `{ default }`. A default-import
 * `lazy()` over a named export fails at RUNTIME, on click, and only for that one surface.
 */
const AutomationSurface = lazy(() => import("../automation/AutomationSurface"));
import CustomerGrid from "../customer-grid/CustomerGrid";
import { clearCustomersCache } from "../customer-grid/apiBridge";
import { OverlayProvider } from "../customer-grid/OverlaySurface";
// ROWS_STALE_EVENT left with `addRecord` (wave 20 item 4): the shell no longer writes rows,
// so it no longer has to tell the grid that it did.
import { API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, VIEW_OPEN_EVENT, signal } from "../apiContract";
import { PageSurface } from "../pages/PageSurface";
const SettingsModal = lazy(() =>
  import("../settings/SettingsModal").then((m) => ({ default: m.SettingsModal })));
import type { SettingsSection } from "../settings/SettingsModal";
import { Brand } from "./Brand";
import { ErrorBoundary } from "./ErrorBoundary";
import LoginPage from "./LoginPage";
import { CONNECTORS_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, HOME_ROUTE, INBOX_ROUTE, MAX_NAV_FOLDERS, NAV_TIMEOUT_STATUS, appLink, canonicalRoute, databaseEntries, dbChipClass, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchTableFootprint, foldNav, postOpened, QUERY_ROUTE, resolveRoute, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, Recent } from "./nav";
const HomePage = lazy(() => import("../home/HomePage"));
const TemplatePicker = lazy(() => import("../home/TemplatePicker"));
const ConnectorsPage = lazy(() => import("../connectors/ConnectorsPage"));
// WAVE 23 C9 (W23-W2) β€” SESSION D's public page. A STATIC import, not a lazy one: the wave's own
// rule is that a required import fails the build when the file is not there, which is the whole
// difference between a mount and an intention (verify_wiring's header).
import FormPublic from "../forms/FormPublic";
import { mergeRecents } from "../home/homeModel";
import type { AutomationTile } from "../home/homeModel";
// ⭐ WAVE 24 item 13 (R10, wiring W24-W3) β€” Home's Automations section.
// ⚠ WAVE 26 ITEM 18 (R14): `stateOf` came out of this import with Home's status dot. The old note
// here said it was imported rather than re-derived because it is the ONE place "is this running"
// is decided β€” still true, and still why nobody should re-add a local copy; the frame simply has
// no reason to ask any more. `listAutomations` brings the credentials and the error shape with
// it, so the frame adds a fetch, not a protocol.
import { listAutomations } from "../automation/automationApi";
import { CreateNewRow, FolderHead, RowMenu, SchemaDrawer } from "./NavExtras";
/** ⭐⭐ W32-T04 (R7, wiring 1): the Inbox MODULE replaces the Alerts pop-up pane. `AlertsPane` is
 *  no longer imported here β€” C's `W32-T21` deletes the file, and an unmounted-but-imported
 *  component is [[artifact-with-no-importer]] wearing the other mask. */
const InboxPage = lazy(() => import("../inbox/InboxPage"));
/** ⭐⭐ W32-T05 (R1, C5, wiring 2): the Query module β€” E's page, A's mount. */
const QueryPage = lazy(() => import("../query/QueryPage"));

/**
 * Item 34's Suspense boundary, one definition for all six surfaces.
 *
 * β›” THE FALLBACK IS DELIBERATELY EMPTY, and that is a design decision rather than a stub. The
 * standing R6 rule is that this product shows a shared spinner mark and never load TEXT
 * (`verify_icons` asserts it across every source file, so a "Loading..." here would go red).
 * These chunks are tens of kilobytes off the same origin that just served the shell, so the
 * honest choice between a flash of a spinner and a frame of nothing is nothing β€” a spinner that
 * appears and vanishes within one frame reads as a glitch, not as progress.
 *
 * ⭐ WAVE 30 (R5) β€” AND AN ERROR BOUNDARY, INSIDE THE HELPER RATHER THAN AT SIX CALL SITES.
 * Three of these six (`TemplatePicker`, `SettingsModal`, `AlertsPane`) are siblings of `<main>`,
 * so the content-area boundary below cannot cover them; putting it here covers all six with one
 * edit. It also catches what `Suspense` alone cannot: a REJECTED chunk fetch. `lazy()` throws its
 * rejection at render, which before today unmounted the whole product because one deploy-time
 * cache miss made a modal's JavaScript unreachable.
 */
function Lazily({ children, surface }: { children: ReactNode; surface: string }) {
  return (
    <ErrorBoundary surface={surface}>
      <Suspense fallback={null}>{children}</Suspense>
    </ErrorBoundary>
  );
}

import { createAlert, fetchInbox } from "../alerts/alertsApi";
import {
  ALERT_CREATE_EVENT,
  EMPTY_INBOX,
  badgeText,
  parseAlertCreate,
  // ⚠ `routeForTopic` left this import with the pane (W32-T04). It is still exported and still
  // used β€” `inboxModel.routeForTarget` is its caller now β€” but the FRAME no longer asks the
  // topic→route question directly, which is the point of C3: one owner for that table.
} from "../alerts/alertsModel";
import type { Inbox } from "../alerts/alertsModel";
// ⭐ W32-T04 (C3): the targetβ†’surface question lives in C's module, so the frame's
// dispatcher is a switch over two literals rather than a second copy of the route table.
import { retryEmit, routeForTarget } from "../inbox/inboxModel";
import ShareDialog from "./ShareDialog";
import { SHARE_OPEN_EVENT, parseShareRequest } from "./shareModel";
import type { ShareRequest } from "./shareModel";
// WAVE 19 R8 β€” the chosen database mark. Read-only across the session fence.
import { FolderMark, LockMark } from "../customer-grid/icons";
import type { FolderIcon } from "../customer-grid/types";
import { isAdmin, logout, me } from "./session";
import type { SessionUser } from "./session";

/** The current application β€” where every not-yet-ported surface actually runs.
 *  Deep links (`?page=<registry key>`) are the app's own, so a strangler link
 *  lands on the exact page, not a landing screen. */
const APP_BASE =
  (import.meta.env.VITE_AIOS_APP_URL as string | undefined) ??
  "https://royal-imports-cfo-os.hf.space";

/** X5's hash route. Also the route an unauthenticated shell is pinned to. */
const LOGIN_ROUTE = "login";
/** Wave 14 C-NAVFOLD β€” the nav drag's PRIVATE dataTransfer MIME. Private so a drop on any
 *  text-editable surface types nothing (a textarea is a native drop target for text/plain β€”
 *  the wave-13 C-LAYOUT scar). */
const NAV_DRAG_TYPE = "application/x-loopable-nav";

/** A stable identity for "no nav yet" β€” see its use below. */
const NO_ENTRIES: NavEntry[] = [];

/**
 * WAVE 23 C10 β€” the Database flyout's anchor, CLAMPED to the viewport.
 *
 * β›” `NavExtras.MenuShell` clamps both axes and this panel first did not, which is the same
 * omission with a bigger blast radius: the Database button sits ~200px down the rail and the
 * panel is up to 560px tall, so on a short laptop viewport its create footer β€” the three rows
 * that are the whole point of the redesign β€” lands below the fold with no way to scroll to it
 * (the panel's own scroll is INSIDE the list, deliberately, so the footer stays put).
 *
 * The height here is the CSS `max-height: min(70vh, 560px)`, restated. Two copies of one number
 * is a real cost; the alternative is measuring the panel after it mounts, which means rendering
 * it in the wrong place for a frame. Named and kept beside the rule it mirrors.
 */
const DBFLY_MAX_H = 560;

export function flyoutAt(rect: { right: number; top: number }, vw: number, vh: number) {
  const h = Math.min(Math.round(vh * 0.7), DBFLY_MAX_H);
  return {
    x: Math.min(Math.round(rect.right + 6), Math.max(8, vw - 268 - 8)),
    y: Math.max(8, Math.min(Math.round(rect.top), vh - h - 8)),
  };
}

/**
 * ⭐ THE ONE PLACE the Database flyout's position is measured off its button (wave-23 close-out).
 *
 * Two open-paths grew this wave β€” the button's own click, and "+ Create new…" opening the panel so
 * a just-named folder is visible β€” and each measured the element itself. That is the shape D-20
 * exists to prevent, one pattern over: **the null case and the measurement should live in exactly
 * one place**, or the second caller is one refactor away from forgetting the guard.
 *
 * ⚠ Honest note on the gate, because the fix should not be mistaken for a rename. `verify_overlay`
 * greps for a LITERAL token β€” a variable named `anchor`, followed by a measure call β€” so the
 * click-path (which reads `e.currentTarget`) always passed while the ref-path failed. The needle
 * is a proxy for "a call site measured its own anchor", and a proxy can be satisfied by renaming a
 * variable. This change satisfies it STRUCTURALLY instead: there is now one measurement, one null
 * guard, and no second call site to keep honest. Booked as DEBT (D-49) so the gate's real subject
 * (anchor-rect logic outside the overlay layer) can be tightened deliberately rather than by grep.
 *
 * β›” AND DO NOT SPELL THE TOKEN OUT IN THIS COMMENT. The first draft of this note quoted the exact
 * string it was describing, and the gate β€” which greps raw file text β€” matched the explanation and
 * went red on a file with no defect in it. Prose about a pattern IS the pattern to a text scan;
 * the same trap as a marker comment placed mid-selector (verify_catalog, wave 21).
 */
export function flyoutFrom(el: HTMLElement | null) {
  if (!el) return null;
  return flyoutAt(el.getBoundingClientRect(), window.innerWidth, window.innerHeight);
}

/**
 * WAVE 23 C9 (wiring W23-W2) β€” the PUBLIC form route: `#/form/<token>`.
 *
 * β›” THE TOKEN IS WHITELISTED, NOT SLICED. `secrets.token_urlsafe` mints `[A-Za-z0-9_-]`, so
 * anything else in that position is not a token this product issued β€” and passing it through
 * would let a crafted hash decide what `FormPublic` puts in a URL. Refusing here means the frame
 * falls through to its normal routing (and the visitor meets the login page), which is the
 * correct answer for a link that is not one of ours.
 *
 * `null` for every other route, so the branch that reads it is a single truthiness test.
 */
export function formTokenOf(route: string): string | null {
  const m = /^form\/([A-Za-z0-9_-]{8,128})$/.exec(route);
  return m ? m[1] : null;
}

type Session =
  | { phase: "checking" }
  | { phase: "anon" }
  | { phase: "authed"; user: SessionUser };

type Nav =
  | { phase: "idle" }
  | { phase: "loading" }
  | {
      phase: "ready";
      entries: NavEntry[];
      utility: NavPage[];
      /** WAVE 23 C10 β€” the Home landing's recently-opened list, per user, off the nav payload. */
      recents: Recent[];
      empty?: string;
      /** ⭐ W31-T11 β€” registry keys this workspace's catalogue leaves out. Deliberate. */
      omitted?: string[];
      /** β›” W31-T11 β€” parts of the payload the SERVER could not read. Not deliberate. */
      degraded?: string[];
    }
  | { phase: "error"; timedOut?: boolean };

const NO_UTILITY: NavPage[] = [];
/** Stable identity, like `NO_ENTRIES` β€” a fresh `[]` per render would re-run Home's memo. */
const NO_RECENTS: Recent[] = [];

function useHashRoute(): string {
  // ⭐ W32-T04 (C3): a RETIRED key is translated here, before anything reads it β€” so the whole
  // shell (`resolveRoute`, `active`, every `route === X` below) sees one vocabulary and no reader
  // has to know a rename happened. `canonicalRoute` is identity for every live key.
  const read = () => canonicalRoute(window.location.hash.replace(/^#\/?/, ""));
  const [route, setRoute] = useState<string>(read);
  useEffect(() => {
    const onChange = () => setRoute(read());
    window.addEventListener("hashchange", onChange);
    return () => window.removeEventListener("hashchange", onChange);
  }, []);
  return route;
}

/** A surface that still lives in the current application. Honest copy, one
 *  action β€” never a mock of the page it is not. */
function StranglerPage({ entry }: { entry: NavEntry }) {
  return (
    <div className="shell-placeholder">
      <h1>{entry.label}</h1>
      <p>This surface runs in the current application.</p>
      <a className="shell-link" href={entry.href} target="_blank" rel="noreferrer">
        Open {entry.label}
      </a>
    </div>
  );
}

// --- the three nav glyphs (SVG, never emoji β€” the platform's own rule) ------

/** The database cylinder every source-backed row carries, mirroring the host
 *  nav's Material `database` glyph. */
function DbIcon() {
  return (
    <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
      <ellipse cx="8" cy="3.6" rx="5.3" ry="2.1" />
      <path d="M2.7 3.6v8.8c0 1.16 2.37 2.1 5.3 2.1s5.3-.94 5.3-2.1V3.6" />
      <path d="M2.7 8c0 1.16 2.37 2.1 5.3 2.1S13.3 9.16 13.3 8" />
    </svg>
  );
}

/** The host's `auto_awesome` sparkle for the AI-assistant slot (app.py:8166). */
function SparkIcon() {
  return (
    <svg className="shell-nav-icon is-spark" viewBox="0 0 16 16" aria-hidden="true">
      <path d="M6.2 2.2 7.5 5.5l3.3 1.3-3.3 1.3-1.3 3.3-1.3-3.3-3.3-1.3 3.3-1.3z" />
      <path d="M12.2 9.4l.8 2 2 .8-2 .8-.8 2-.8-2-2-.8 2-.8z" />
    </svg>
  );
}

/** The new-tab affordance on a hand-off row: this destination opens in the
 *  current application, and the arrow says so before the click does. */
function ExtIcon() {
  return (
    <svg className="shell-nav-open" viewBox="0 0 12 12" aria-hidden="true">
      <path d="M4.6 3h4.4v4.4M8.8 3.2 3.2 8.8" />
    </svg>
  );
}

/**
 * WAVE 20 item 4 (R8 / C-ADDROW) β€” THE UNIVERSAL DATABASE HEADER.
 *
 * One header, identical on every database (`reference/Airtable 6.png`): a chip in
 * a bold colour carrying the database's mark, then its name. It replaces
 * `shell-ut-bar`, which existed on USER TABLES only β€” so the two built-in
 * databases had no header at all, and the one place the product named the thing
 * you were looking at appeared or vanished depending on where the table came
 * from. R8 makes it universal.
 *
 * The "Add record" button the old bar carried is GONE with it, deliberately: R8
 * replaces it with the grid's own trailing "+" row (S3's half of C-ADDROW), on
 * user databases only β€” a connector-backed table's rows are read-synced, and a
 * "+" that must refuse is a fake affordance.
 *
 * The chip is decorative and says so: the name beside it is real text, so a
 * second announcement of the same fact is noise to a screen reader.
 */
function DbHead({ label, icon, glyph }: { label: string; icon?: FolderIcon; glyph?: ReactNode }) {
  return (
    <div className="shell-db-head">
      <span className={dbChipClass(icon)} aria-hidden="true">
        {/* The database's own mark when it has one, the cylinder when it does not β€”
            the same pair the rail row draws, so the header and the nav agree. Both
            paint in the chip's ink (the stylesheet's two overrides): `FolderMark`
            would otherwise stroke its pastel `-deep`, which is measured against the
            WHITE rail and disappears on its own tone.

            WAVE 23 C13 β€” `glyph` overrides only the FALLBACK, never a chosen mark, and
            that ordering is the contract. Automation is not a database and must not wear
            the cylinder; but it CAN wear a `nav_meta` icon (the rail already draws one,
            Shell:1026), and a header that ignored it would be the one surface where the
            rail and the frame disagreed about the same row. So: chosen icon > caller's
            glyph > the cylinder. */}
        {icon ? <FolderMark icon={icon} size={16} /> : (glyph ?? <DbIcon />)}
      </span>
      {/* An `h1`, not a styled span: this is the first time the work surface has NAMED itself,
          and the name of the thing you are looking at is what a heading is for. Every other
          full-pane surface in this shell (`shell-placeholder`) already uses one, and they never
          render together β€” so the page gains a heading rather than a second one. */}
      <h1 className="shell-db-name">{label}</h1>
    </div>
  );
}

/** The β‹― affordance on the account row. */
function DotsIcon() {
  return (
    <svg className="shell-account-dots" viewBox="0 0 16 16" aria-hidden="true">
      <circle cx="3.5" cy="8" r="1.25" />
      <circle cx="8" cy="8" r="1.25" />
      <circle cx="12.5" cy="8" r="1.25" />
    </svg>
  );
}

/** WAVE 19 R12 β€” the gear beside the account menu's one Settings row. Drawn in
 *  the same 16x16 stroke vocabulary as the rest of this file (SVG, never an
 *  emoji β€” the platform's own rule), so it sits beside `DbIcon` and `SparkIcon`
 *  as one family rather than as an icon borrowed from somewhere else. */
function GearIcon() {
  return (
    <svg className="shell-menu-icon" viewBox="0 0 16 16" aria-hidden="true">
      <circle cx="8" cy="8" r="2.15" />
      <path d="M8 1.9l.9 1.5 1.7-.4.5 1.7 1.7.5-.4 1.7 1.2 1.1-1.2 1.1.4 1.7-1.7.5-.5 1.7-1.7-.4-.9 1.5-.9-1.5-1.7.4-.5-1.7-1.7-.5.4-1.7L1.7 8l1.2-1.1-.4-1.7 1.7-.5.5-1.7 1.7.4z" />
    </svg>
  );
}

/** WAVE 19 R10 β€” Automation's own mark, now that it is a standalone rail button
 *  rather than a row in the database list. Two nodes and the edge between them:
 *  a flow, which is what the surface actually is, and visibly not a database. */
function AutoIcon() {
  return (
    <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
      <rect x="1.9" y="5.4" width="4.6" height="5.2" rx="1.1" />
      <rect x="9.5" y="5.4" width="4.6" height="5.2" rx="1.1" />
      <path d="M6.5 8h3" />
    </svg>
  );
}

/** WAVE 20 item 25 β€” the Alerts row's mark. A bell, in the same 16x16 stroke
 *  vocabulary as its neighbours, so it sits beside the sparkle and the flow rather
 *  than arriving from another icon set. */
function BellIcon() {
  return (
    <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
      <path d="M8 2.4a3.5 3.5 0 0 1 3.5 3.5v2.3l1.2 2H3.3l1.2-2V5.9A3.5 3.5 0 0 1 8 2.4Z" />
      <path d="M6.6 12.4a1.5 1.5 0 0 0 2.8 0" />
    </svg>
  );
}

/** WAVE 23 R7 β€” Home's mark. A house, in the same 16x16 stroke vocabulary as its neighbours;
 *  the reference rail uses one and there is no more literal glyph for "the landing". */
function HomeIcon() {
  return (
    <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
      <path d="M2.4 7.2 8 2.6l5.6 4.6" />
      <path d="M3.9 8.2v5.2h8.2V8.2" />
    </svg>
  );
}

/** WAVE 23 R8 β€” Connectors: two links of a chain, which is exactly what a connector is. The
 *  same glyph the Home card draws, so the nav row and the card that leads to it agree. */
function PlugIcon() {
  return (
    <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
      <path d="M6.7 9.3 9.3 6.7" />
      <path d="M7.6 4.6 9.1 3.1a2.7 2.7 0 0 1 3.8 3.8l-1.5 1.5" />
      <path d="M8.4 11.4l-1.5 1.5a2.7 2.7 0 0 1-3.8-3.8l1.5-1.5" />
    </svg>
  );
}

/* β›” `PlusMark` LIVED HERE AND IS DELETED WITH THE THREE BUTTONS THAT DREW IT (wave 24 item 15a,
   ruling R9). It was the flyout footer's plus, used by nothing else β€” `CreateNewRow` brings its
   own `PlusIcon`, which is private to `NavExtras`. `tsc` named it the moment the last call site
   went (TS6133), which is the argument for a REQUIRED prop and an unused-locals check doing the
   remembering: the CSS twins `.shell-dbfly-make` and `.shell-dbfly-plus` went to zero call sites
   in the same edit and no compiler says a word about those β€” they are swept by hand below, in
   this session's own index.css region, rather than left as the D-42 residue class. */

/** WAVE 23 R7 β€” the disclosure caret on the "Database" row: this opens a panel, and the mark
 *  says so before the click does (the same job `ExtIcon` does for a hand-off). */
function CaretIcon() {
  return (
    <svg className="shell-nav-open shell-nav-caret" viewBox="0 0 12 12" aria-hidden="true">
      <path d="M4.4 2.6 8 6l-3.6 3.4" />
    </svg>
  );
}

/** Owner item 11 β€” the rail toggle: three horizontal bars. One glyph for both rails (the
 *  views rail draws the same geometry), so "minimize a panel" reads as one idea. */
function RailToggleIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path
        d="M2.5 4.4h11M2.5 8h11M2.5 11.6h11"
        stroke="currentColor"
        strokeWidth="1.35"
        strokeLinecap="round"
      />
    </svg>
  );
}

/**
 * The account corner: ONE line (monogram + name + role, the host's
 * `_account_css` card) that opens a small menu, instead of three buttons
 * crushed into a 236px row β€” which is what the owner met as "the logout
 * button broke": Sign out wrapped into a 42px two-line stub beside a clipped
 * name. Every action keeps its full label inside the menu.
 */
function AccountMenu({
  user,
  utility,
  onSignOut,
  onSettings,
}: {
  user: SessionUser;
  /** `chrome:'utility'` pages other than the Analyst slot β€” placed here, where
   *  the host keeps them (Settings in the chrome, not the module list). */
  utility: NavPage[];
  onSignOut: () => void;
  onSettings: (s: SettingsSection) => void;
}) {
  const [open, setOpen] = useState(false);
  const wrap = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e: MouseEvent) => {
      if (wrap.current && !wrap.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  // ⚠ Unicode letter/number, not [a-z0-9]: the app's `_account_css` uses
  // Python's `str.isalnum()`, so an ASCII-only class here would give a
  // non-Latin name an initial in one shell and a blank circle in the other.
  const initial = (user.name.match(/[\p{L}\p{N}]/u)?.[0] ?? "").toUpperCase();
  const extras = utility.filter((p) => p.key !== "analyst");

  return (
    <div className="shell-account-wrap" ref={wrap}>
      {open ? (
        <div className="shell-menu" role="menu">
          {/* ⚠ WAVE 19 R12 SUPERSEDES WAVE 15 R12, IN BOTH HALVES.
              Wave 15 renamed this row "Settings" β†’ "Profile" and kept a second,
              admin-only "Manage users" beside it. The owner has now ruled the
              opposite: ONE row, called **Settings**, with a gear, shown to
              EVERYONE, landing on Account β€” and admins meet "Manage users" where
              it always really lived, as a tab in the modal's own rail.

              The two rows were the problem, not either label. They opened the
              SAME modal at two different tabs, so the account menu was quietly
              acting as a second navigation for a surface that already has one;
              an admin had to decide which door to use before knowing which tab
              they wanted. Landing everyone on Account and letting the rail do
              the rest removes the decision.

              β›” `verify_ui.py`'s naming gate was inverted in the same change
              (its R12 check asserted the wave-15 wording, so it would have gone
              red on the correct edit). Wave-19 amendment 1 in the wave doc. */}
          <button
            type="button"
            className="shell-menu-item"
            role="menuitem"
            onClick={() => {
              setOpen(false);
              onSettings("account");
            }}
          >
            <GearIcon />
            Settings
          </button>
          {extras.length ? <div className="shell-menu-rule" role="separator" /> : null}
          {extras.map((p) => (
            <a
              key={p.key}
              className="shell-menu-item"
              role="menuitem"
              href={appLink(APP_BASE, p.key)}
              target="_blank"
              rel="noreferrer"
              onClick={() => setOpen(false)}
            >
              {/* WAVE 17 ITEM 15b (R8) β€” the `settings` special-case is GONE.
                  This row used to relabel one registry key on its way to the
                  screen, which is a client deciding what the payload meant. R8
                  deletes the host surface itself, so the honest client change
                  is not to HIDE the key here β€” hard-coding an exclusion would
                  outlive the thing it excludes β€” but to stop treating any key
                  specially and let the payload decide. When `nav_pages` stops
                  emitting it, the row stops existing, with nothing here to
                  update. Every utility row now wears its registry label. */}
              {p.label}
              <ExtIcon />
            </a>
          ))}
          <div className="shell-menu-rule" role="separator" />
          <button
            type="button"
            className="shell-menu-item is-signout"
            role="menuitem"
            onClick={() => {
              setOpen(false);
              onSignOut();
            }}
          >
            Sign out
          </button>
        </div>
      ) : null}
      <button
        type="button"
        className="shell-account"
        aria-haspopup="menu"
        aria-expanded={open}
        onClick={() => setOpen((v) => !v)}
      >
        {user.avatar ? (
          // Wave 14 C-AVATAR β€” the chip wears the photo. Inline-styled: `.shell-avatar`'s
          // stylesheet is another wave-14 session's file (index.css), so the img carries
          // its own fit rules and inherits the span's box from the class.
          <img
            className="shell-avatar"
            src={user.avatar}
            alt=""
            aria-hidden="true"
            style={{ objectFit: "cover", padding: 0 }}
          />
        ) : (
          <span className="shell-avatar" aria-hidden="true">{initial}</span>
        )}
        <span className="shell-account-who">
          <span className="shell-account-name">{user.name}</span>
          <span className="shell-account-role">{isAdmin(user) ? "Admin" : "Member"}</span>
        </span>
        <DotsIcon />
      </button>
    </div>
  );
}

/**
 * ⭐ WAVE 30 (R5) β€” THE OUTERMOST BOUNDARY, and the ONLY one that can cover the three
 * EARLY RETURNS below (`FormPublic`, the boot card, `LoginPage`) plus this component's own
 * body: its route resolution, its nav shaping and its derivations all run BEFORE any JSX
 * exists to wrap. A throw in any of them used to take the document with it, and a person
 * who cannot get past the login screen has no navigation left to escape with.
 *
 * ⚠ Split rather than nested inline for one reason: a boundary cannot catch a throw from
 * its OWN render. `ErrorBoundary` has to be the parent of the component that fails, so the
 * frame becomes a child and the default export becomes the wrapper.
 */
export default function Shell() {
  return (
    <ErrorBoundary surface="Loopable">
      <ShellFrame />
    </ErrorBoundary>
  );
}

function ShellFrame() {
  const [session, setSession] = useState<Session>({ phase: "checking" });
  const [nav, setNav] = useState<Nav>({ phase: "idle" });
  // Wave 18 (C3-UT): bumped after "+ New database" so the rail refetches and the new ut_ key
  // appears without a reload. Wave 19 (R8/C1) adds the second and only other bumper β€” a
  // rename or an icon change, for the same reason: the override lives in the SERVER's nav
  // payload, so the rail re-asks rather than the client inventing what the answer will be.
  // Both bumps are "the server changed, ask it again"; nothing may bump this to paint state
  // the server does not hold β€” the nav stays server-driven.
  const [navEpoch, setNavEpoch] = useState(0);
  const [dataError, setDataError] = useState("");
  const [toast, setToast] = useState("");
  // `null` = closed. The SECTION is the open state, so "Settings" and
  // "Users" are one component reached two ways rather than two dialogs.
  const [settings, setSettings] = useState<SettingsSection | null>(null);
  // ── WAVE 20 items 18/23/26 (R10, C-SHARE): the access editor, for all three kinds ──
  //
  // The dialog is the SHELL's, and it is opened from two places that must not import
  // each other: this frame (a database's β‹―) and the views rail (a view's or folder's
  // β‹―), which is host-neutral `customer-grid/` code. So the rail raises a window event
  // β€” the same channel the grid already uses for toasts and staleness β€” and the frame,
  // which owns modals, renders it.
  const [shareFor, setShareFor] = useState<ShareRequest | null>(null);
  // ── WAVE 20 item 25 (C-ALERT): the inbox lives beside the nav, not in it ──────
  //
  // `inbox` is held HERE rather than inside the pane because the badge outlives the
  // pane: the count has to be on screen while the panel is shut, which is the only
  // state in which a badge is useful at all.
  const [inbox, setInbox] = useState<Inbox>(EMPTY_INBOX);
  /** ⭐ W32 (ASK C-17) β€” the in-flight VIEW_OPEN retry ladder's canceller, if one is running.
   *  A reader who clicks a second notification while the first is still retrying would otherwise
   *  have TWO ladders racing, and the older one would yank them back to the previous view. */
  const viewEmitCancel = useRef<null | (() => void)>(null);
  const route = useHashRoute();
  // WAVE 23 C9 β€” non-null on `#/form/<token>` only. Computed here rather than inside the render
  // branch because the hash normaliser below has to read it too, and two copies of "is this the
  // public form?" is how one of them ends up answering differently.
  const formToken = formTokenOf(route);
  // Owner items 10/11 β€” the navigation folds to a slim strip: by the toggle in the rail head,
  // or automatically when the user clicks into the work surface (NAV_MINIMIZE_EVENT from the
  // grid). Remembered per browser; expanding is always one click on the same toggle.
  const [navCollapsed, setNavCollapsed] = useState<boolean>(() => {
    try {
      return localStorage.getItem("aios-nav-collapsed") === "1";
    } catch {
      return false;
    }
  });
  useEffect(() => {
    try {
      localStorage.setItem("aios-nav-collapsed", navCollapsed ? "1" : "0");
    } catch {
      // storage can be blocked; the toggle still works for the session
    }
  }, [navCollapsed]);
  // Owner item 3 (2026-07-31) β€” the collapsed strip names its icons on hover. A real DOM
  // tooltip positioned FIXED beside the rail: the rail scrolls and clips (overflow), so a
  // CSS ::after inside it could never escape; and it is pointer-events:none by standing rule
  // ([[ui-invisible-to-assertions]] β€” a tooltip that can receive the pointer swallows the
  // next click).
  const [navTip, setNavTip] = useState<{ label: string; y: number } | null>(null);
  useEffect(() => {
    if (!navCollapsed) setNavTip(null);
  }, [navCollapsed]);
  const tipEnter = useCallback(
    (label: string) => (e: ReactMouseEvent<HTMLElement>) => {
      const r = e.currentTarget.getBoundingClientRect();
      setNavTip({ label, y: r.top + r.height / 2 });
    },
    []
  );
  const tipLeave = useCallback(() => setNavTip(null), []);
  // ── WAVE 20 item 7 (R9): the collapsed strip expands from its own BACKGROUND ──
  //
  // Until now the 56px strip had exactly one way back β€” the logo β€” and the owner
  // kept clicking the empty space beside an icon, which did nothing at all. R9:
  // "clicking the collapsed strip's blank/background area EXPANDS it; page icons
  // keep navigating directly."
  //
  // ⚠ THE TEST IS THE TARGET, NOT THE CURRENT ELEMENT. `e.currentTarget === e.target`
  // would only fire on the aside's own few pixels of padding β€” every gap the user
  // actually clicks belongs to `.shell-nav` or `.shell-nav-list`, which are not
  // interactive but ARE elements. So the rule is inverted: a click that landed on
  // (or inside) a control does what that control does; anything else is background.
  // β›” `closest` and not a tag check: the click usually lands on the `<svg>` or the
  // `<span>` INSIDE the link, so testing the target's own tagName would treat every
  // icon click as background and swallow the navigation R9 explicitly preserves.
  const expandOnBlank = useCallback((e: ReactMouseEvent<HTMLElement>) => {
    const hit = e.target as Element | null;
    if (hit?.closest?.('a,button,input,textarea,select,[role="menuitem"],[role="dialog"]')) return;
    setNavCollapsed(false);
  }, []);

  // ── WAVE 23 items 9/10 (R7/R8, contract C10): the DATABASE FLYOUT ──────────────────────────
  //
  // R7 takes the databases OUT of the rail: the always-on `.shell-nav-list` band becomes a panel
  // behind a "Database" button, so the rail is a fixed set of destinations instead of a list
  // whose height is a function of how many tables the tenant made.
  //
  // `dbAt` is the anchor rect (null = shut), `dbQuery` the search. The panel renders OUTSIDE the
  // `<aside>` and `position: fixed`, for the same reason `shell-nav-tip` does: the rail scrolls
  // and clips, so anything that must escape it cannot be its descendant.
  const [dbAt, setDbAt] = useState<{ x: number; y: number } | null>(null);
  const [dbQuery, setDbQuery] = useState("");
  const dbPanel = useRef<HTMLDivElement | null>(null);
  const dbButton = useRef<HTMLButtonElement | null>(null);
  const closeDbFly = useCallback(() => {
    setDbAt(null);
    setDbQuery("");
  }, []);
  // ⚠ Declared here and READ inside the close effect below, because that effect must not
  // re-subscribe on every drag state change β€” and because the guard it needs is "a drag is in
  // flight", which is state this component already holds (`dragKey`, declared further down with
  // the other prefs state). A ref keeps the effect's dependency list honest.
  const draggingRef = useRef(false);

  /**
   * β›” THREE WAYS OUT, AND ONE THING THAT MUST NOT CLOSE IT.
   *
   * Out: an outside mousedown, Escape, or a database link (handled at the link β€” a click on the
   * row's β‹― must NOT close the panel the menu is anchored inside).
   *
   * NOT out: a DRAG. This panel carries the folder drag-and-drop the rail used to (`NAV_DRAG_TYPE`,
   * the `__root__` drop target, `draggable` rows). A pointer that leaves the panel mid-drag would
   * otherwise trip the outside-click rule and unmount the drop target under the cursor β€” the
   * folder move silently fails and the panel vanishes, which reads as a crash. The wirings this
   * wave must keep green (W-3/W-5 live on these rows) would still pass, because a gate cannot
   * see a drop that never lands.
   *
   * And NOT the trigger button: without that exemption the mousedown closes the panel and the
   * button's own click immediately reopens it, so the control could never be used to shut the
   * thing it opened. (`useMenu` in NavExtras has this quirk; a rail button is used far more often
   * than a row's β‹―, so it is worth the ref here.)
   */
  useEffect(() => {
    if (!dbAt) return;
    const onDown = (e: MouseEvent) => {
      if (draggingRef.current) return;
      const t = e.target as Node | null;
      if (dbPanel.current?.contains(t as Node)) return;
      if (dbButton.current?.contains(t as Node)) return;
      closeDbFly();
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") closeDbFly();
    };
    document.addEventListener("mousedown", onDown, true);
    document.addEventListener("keydown", onKey, true);
    return () => {
      document.removeEventListener("mousedown", onDown, true);
      document.removeEventListener("keydown", onKey, true);
    };
  }, [dbAt, closeDbFly]);

  // ── WAVE 23 C10: the recents stamp ────────────────────────────────────────────────────────
  //
  // `opened` mirrors the stamps this session made, so Home shows the database you opened one
  // click ago rather than the state of the world at sign-in (`mergeRecents`' own note). It is
  // NOT persisted: a reload re-asks the server, which is the only end that knows.
  const [opened, setOpened] = useState<Record<string, number>>({});
  const lastStamped = useRef("");

  // The window signals the data layer raises (apiContract.ts). It talks to the
  // frame this way because `customer-grid/**` is host-neutral β€” the same tree
  // the Streamlit embed ships β€” and must not import a shell.
  useEffect(() => {
    const onUnauthorized = () => setSession({ phase: "anon" });
    const onDataError = (e: Event) =>
      setDataError(String((e as CustomEvent).detail ?? "") || "The data could not be loaded.");
    const onToast = (e: Event) => setToast(String((e as CustomEvent).detail ?? ""));
    const onNavMinimize = () => setNavCollapsed(true);
    // C-SHARE: the rail asks, the frame opens. A malformed detail opens NOTHING β€”
    // `parseShareRequest` fail-closes on an unknown kind rather than launching a
    // dialog whose every save would 400.
    const onShareOpen = (e: Event) =>
      setShareFor(parseShareRequest((e as CustomEvent).detail));
    window.addEventListener(UNAUTHORIZED_EVENT, onUnauthorized);
    window.addEventListener(DATA_ERROR_EVENT, onDataError);
    window.addEventListener(TOAST_EVENT, onToast);
    window.addEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
    window.addEventListener(SHARE_OPEN_EVENT, onShareOpen);
    return () => {
      window.removeEventListener(UNAUTHORIZED_EVENT, onUnauthorized);
      window.removeEventListener(DATA_ERROR_EVENT, onDataError);
      window.removeEventListener(TOAST_EVENT, onToast);
      window.removeEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
      window.removeEventListener(SHARE_OPEN_EVENT, onShareOpen);
    };
  }, []);

  // The toast clears itself; nothing else depends on it having been seen.
  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(""), 6000);
    return () => clearTimeout(t);
  }, [toast]);

  // DEBT D-38 (wave 22): the error card is ABOUT a surface, so leaving that surface clears
  // it β€” before this, one failed fetch left the card over every module until sign-out
  // (`setDataError("")` at the nav effect runs only on a WHO change). Clearing on the route
  // commit cannot suppress a real failure: the failing surface raises DATA_ERROR_EVENT from
  // its own fetch, which resolves after this effect has run.
  useEffect(() => {
    setDataError("");
  }, [route]);

  // Boot: ask the server who we are. ⚠ Every boot, no cache β€” the X3 cookie is
  // HttpOnly and revocable by epoch bump, so the server is the only thing that
  // can answer this and a remembered answer is a stale one.
  useEffect(() => {
    let dead = false;
    void me().then((user) => {
      if (!dead) setSession(user ? { phase: "authed", user } : { phase: "anon" });
    });
    return () => {
      dead = true;
    };
  }, []);

  // Keyed on the USERNAME, not the session object: a new object identity on
  // every state write would re-fetch the nav for no reason.
  const who = session.phase === "authed" ? session.user.username : null;

  useEffect(() => {
    if (who === null) {
      setNav({ phase: "idle" });
      return;
    }
    let dead = false;
    // ⚠ WAVE 19 β€” STALE-WHILE-REFRESH, and this line is why the icon picker works
    // at all. This effect re-runs on every `navEpoch` bump, and it used to blank
    // the nav to `loading` each time: `entries` reads as `NO_ENTRIES` whenever the
    // phase is not `ready`, so the whole database list unmounted behind a spinner
    // and remounted a round trip later. Every row's `RowMenu` went with it β€”
    // taking the OPEN icon picker's state with it, so "pick a shape, then pick a
    // tone" was impossible and every click flashed the rail. "+ Create new…"
    // (gated on `ready`) disappeared too.
    //
    // It was invisible before because the only bumper was "+ New database", which
    // navigates away in the same beat. R8 made the bump a frequent, EXPLORATORY
    // action, which is what turned a flash into a broken control.
    //
    // β›” SAFE ACROSS ACCOUNTS, which is the only thing that could make it
    // dangerous: an account switch always passes through `anon` (sign-out, or the
    // 401 event), so `who` becomes null, this effect takes the branch above and
    // sets `idle` β€” a stale nav can never survive into a different session's
    // render. Same stale-while-refresh doctrine the data cache already follows.
    setNav((cur) => (cur.phase === "ready" ? cur : { phase: "loading" }));
    // ⚠ Clear the last session's failures. Without this, a read error survives
    // a sign-out/sign-in and the freshly authenticated user lands on an error
    // panel describing something that happened to somebody else's session.
    setDataError("");
    setToast("");
    void fetchNav().then((r) => {
      if (dead) return;
      if (r.ok) {
        // `chrome:'utility'` rows leave the module list β€” the payload has said
        // so since X6; the Analyst slot and the account menu place them where
        // the host does (`core.perms.nav_pages`' own contract).
        const { main, utility } = splitChrome(r.pages);
        setNav({ phase: "ready", entries: shapeNav(main, APP_BASE), utility,
                 recents: r.recents,
                 ...(r.empty ? { empty: r.empty } : {}),
                 // ⭐ W31-T11 β€” carried onto the state, not dropped here. A flag parsed off the
                 // wire and discarded before render is a wiring that goes nowhere, which is
                 // exactly how wave 20 shipped four of them.
                 ...(r.omitted ? { omitted: r.omitted } : {}),
                 ...(r.degraded ? { degraded: r.degraded } : {}) });
      }
      // 401 is not "the nav is broken", it is "the session died under us" β€”
      // conflating them would leave a signed-out user staring at a frame.
      else if (r.status === 401) setSession({ phase: "anon" });
      else setNav({ phase: "error",
                    ...(r.status === NAV_TIMEOUT_STATUS ? { timedOut: true } : {}) });
    });
    return () => {
      dead = true;
    };
  }, [who, navEpoch]);

  // NO_ENTRIES, not a fresh `[]`: a new array identity on every render would
  // re-run the hash effect below on every render for no reason.
  const entries = nav.phase === "ready" ? nav.entries : NO_ENTRIES;
  // Wave 18: a fresh TENANT (server says `no_databases`) is welcomed, not warned.
  const tenantEmptyState =
    nav.phase === "ready" && entries.length === 0 && nav.empty === "no_databases";

  // ── C-SCHEMA (2026-08-02): per-user folders over the database list + the
  // schema drawer. Placement is cosmetic per-user state β€” the server-filtered
  // nav still decides what exists; prefs only arrange it.
  const [navPrefs, setNavPrefs] = useState<NavPrefs>(EMPTY_NAV_PREFS);
  const navPrefsRef = useRef(navPrefs);
  navPrefsRef.current = navPrefs;
  const [closedFolders, setClosedFolders] = useState<ReadonlySet<string>>(new Set());
  const [schemaFor, setSchemaFor] = useState<string | null>(null);
  useEffect(() => {
    if (who === null) {
      setNavPrefs(EMPTY_NAV_PREFS);
      setSchemaFor(null);
      return;
    }
    let dead = false;
    void fetchNavPrefs().then((p) => {
      if (!dead) setNavPrefs(p);
    });
    return () => {
      dead = true;
    };
  }, [who]);
  // Optimistic with an honest revert: the rail moves now; a refused write puts
  // it back and says so rather than leaving a lie on screen.
  const commitPrefs = useCallback((next: NavPrefs) => {
    const prev = navPrefsRef.current;
    setNavPrefs(next);
    void saveNavPrefs(next).then((ok) => {
      if (!ok) {
        setNavPrefs(prev);
        setToast("The folder change was not saved β€” the store refused the write.");
      }
    });
  }, []);
  const movePage = useCallback(
    (key: string, folderId: string | null) => {
      const cur = navPrefsRef.current;
      const placement = { ...cur.placement };
      if (folderId) placement[key] = folderId;
      else delete placement[key];
      commitPrefs({ folders: cur.folders, placement });
    },
    [commitPrefs]
  );
  const renameFolder = useCallback(
    (id: string, name: string) => {
      const cur = navPrefsRef.current;
      commitPrefs({
        folders: cur.folders.map((f) => (f.id === id ? { ...f, name } : f)),
        placement: cur.placement,
      });
    },
    [commitPrefs]
  );
  const deleteFolder = useCallback(
    (id: string) => {
      const cur = navPrefsRef.current;
      commitPrefs({
        folders: cur.folders.filter((f) => f.id !== id),
        placement: Object.fromEntries(
          Object.entries(cur.placement).filter(([, v]) => v !== id)
        ),
      });
    },
    [commitPrefs]
  );
  const toggleFolder = useCallback((id: string) => {
    setClosedFolders((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }, []);
  // ── Wave 14 C-NAVFOLD (items 4/6): drag replaces the menu's Move-to-folder. A PRIVATE
  // dataTransfer MIME so a drop anywhere text-editable types nothing (the wave-13 C-LAYOUT
  // scar); `dropTarget` is a folder id or "__root__" (drag out = drop on the list itself).
  const [dragKey, setDragKey] = useState<string | null>(null);
  const [dropTarget, setDropTarget] = useState<string | null>(null);
  // WAVE 23 C10 β€” read by the flyout's outside-click rule, which must NOT fire mid-drag (see
  // its note). Assigned during render like `navPrefsRef` above: the effect keeps a stable
  // dependency list and still sees the current answer.
  draggingRef.current = dragKey !== null;
  const createFolder = useCallback(
    (name: string) => {
      const cur = navPrefsRef.current;
      if (cur.folders.length >= MAX_NAV_FOLDERS) {
        setToast(`At most ${MAX_NAV_FOLDERS} folders.`);
        return;
      }
      const id = `nf_${Date.now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`;
      commitPrefs({ folders: [...cur.folders, { id, name }], placement: cur.placement });
      // ⭐ WAVE 23 C10 β€” SHOW THE THING THAT WAS JUST MADE. "+ Create new…" stayed in the RAIL
      // while the folders it creates moved into the FLYOUT, so naming a folder produced no
      // visible result at all: the only surface that draws one was a closed panel. The
      // affordance and its effect ended up in different places, which is the class of defect
      // this rework was supposed to remove rather than introduce. Opening the panel is the
      // smaller of the two fixes and keeps C10's rail order exactly as ruled.
      const at = flyoutFrom(dbButton.current);
      if (at) setDbAt(at);
    },
    [commitPrefs]
  );

  // ── WAVE 19 R8 / C1: the tenant-wide name + icon overrides (`nav_meta`) ──────
  //
  // ⚠ NOT OPTIMISTIC, unlike `commitPrefs` two blocks up, and the asymmetry is
  // the point. Prefs are this user's own arrangement held in this component's
  // state, so the rail can move now and revert if the write is refused.
  // `nav_meta` is TENANT-WIDE and lives in the SERVER's nav payload β€” the shell
  // holds no copy to update. Painting a new name locally would mean rendering a
  // label from one source while every other reader of the nav still had the old
  // one; re-asking is one cheap round trip and it cannot disagree with itself.
  // ── C-ALERT: the unread count, and the door that MAKES an alert ───────────────
  //
  // Polled once per session boot and after every write this frame knows about β€”
  // never on a timer. A nav badge that re-fetches every 30 seconds is a background
  // request per user per minute for a number nobody is looking at; the honest
  // refresh points are "the app just started" and "you just did something".
  useEffect(() => {
    if (who === null) {
      setInbox(EMPTY_INBOX);
      return;
    }
    let dead = false;
    const pull = () => {
      void fetchInbox().then((r) => {
        if (!dead && r.ok) setInbox(r.value);
      });
    };
    pull();
    // ...and again when the tab is looked at, which is the honest substitute for a
    // timer: news arrives while you are elsewhere, and "elsewhere" is exactly when a
    // poll would be wasted. One request per return to the tab, none while it sits.
    window.addEventListener("focus", pull);
    return () => {
      dead = true;
      window.removeEventListener("focus", pull);
    };
  }, [who]);

  // The rail asks for an alert on a view; the FRAME answers, because the rail does
  // not know its own topic β€” it holds views, and the scope key is the route's.
  useEffect(() => {
    const onCreate = (e: Event) => {
      const req = parseAlertCreate((e as CustomEvent).detail);
      if (!req) return;
      const key = window.location.hash.replace(/^#\/?/, "");
      const topic =
        key === "product_data" ? "product" : key.startsWith("ut_") ? key : "customer";
      void createAlert(req.viewId, topic, req.label).then((r) => {
        if (!r.ok) {
          // ⚠ The 400 `no_filter` is a real answer and rides through verbatim: a
          // view with no active filter matches everything, so an alert on it could
          // never see an entrant. "Refused, and here is why" beats a dead bell.
          setToast(r.message);
          return;
        }
        setToast(`Alerting on "${req.label}". New records that enter it appear under Alerts.`);
        void fetchInbox().then((got) => {
          if (got.ok) setInbox(got.value);
        });
      });
    };
    window.addEventListener(ALERT_CREATE_EVENT, onCreate);
    return () => window.removeEventListener(ALERT_CREATE_EVENT, onCreate);
  }, []);

  const commitNavMeta = useCallback(async (key: string, patch: NavMetaPatch) => {
    const ok = await saveNavMeta(key, patch);
    if (ok) setNavEpoch((e) => e + 1);
    else setToast("That change was not saved β€” the store refused the write.");
  }, []);

  /**
   * ⭐ WAVE 21 item 6 (R3, contract C3) β€” delete a user database, and then leave.
   *
   * The confirm face owns the QUESTION; this owns the round trip and the two
   * things that have to happen after a yes:
   *
   *   Β· the nav is refetched (`navEpoch`), because the row must go β€” and because
   *     the server is the only end that knows what else went with it;
   *   Β· if the deleted table is the one on screen, the route moves. The hash
   *     would otherwise still name a key the payload no longer carries, and
   *     `resolveRoute` answers that with a blank main pane β€” a shell that looks
   *     broken as the reward for a successful delete.
   *
   * The route change is deliberately NOT optimistic. It fires after the server
   * confirms, so a refused delete leaves the user exactly where they were, still
   * looking at the table they asked about.
   */
  const removeDatabase = useCallback(
    async (key: string): Promise<{ ok: boolean; error?: string }> => {
      const r = await deleteTable(key);
      if (!r.ok) return r;
      // The grid's cached rows for THIS table die with it: a remount inside the
      // cache window would otherwise re-paint a table that no longer exists.
      clearCustomersCache();
      setNavEpoch((e) => e + 1);
      setToast("Database deleted.");
      // An EMPTY hash, not a computed one: `resolveRoute` answers "" with
      // `defaultRoute(entries)`, so the landing surface is chosen by the same
      // rule a fresh sign-in uses β€” and it is chosen from the REFETCHED nav,
      // which a key computed here (from the list still holding the dead row)
      // could not be.
      if (route === key) window.location.hash = "";
      return { ok: true };
    },
    [route]
  );

  // Keep the URL honest in both directions: an anonymous shell sits on
  // `#/login`, and a signed-in one never does.
  //
  // ⭐ WAVE 23 C10 β€” THE LANDING MOVED, AND ALL THREE SITES MOVED TOGETHER. `LANDING_PREFERENCE`
  // and `defaultRoute` are the other two (nav.ts); this is the redirect a fresh sign-in takes.
  // C10's own warning is that a half-move strands logins on a dead hash, so:
  //
  //   Β· the `entries.length` gate is GONE. It existed because `defaultRoute([])` was `""` β€” a
  //     redirect to `#/` β€” so the frame had to wait for the nav before it could name a landing.
  //     `home` is chrome and needs no entry, so there is nothing left to wait for, and the
  //     tenant whose nav is legitimately empty (a fresh workspace, wave 18) now lands somewhere
  //     real instead of sitting on the login hash until a database exists.
  //   Β· an EMPTY hash normalises to the landing too. `removeDatabase` sets `hash = ""` after a
  //     delete and relies on this; before, an empty hash silently rendered `customer_data` while
  //     the URL said nothing.
  useEffect(() => {
    // β›” WAVE 23 C9 β€” THE PUBLIC FORM IS EXEMPT FROM BOTH DIRECTIONS. Without the first
    // exemption an anonymous visitor at `#/form/<token>` is bounced to `#/login` before the
    // render branch is ever reached, and the public door is public only to people who already
    // have an account. Without the second, a SIGNED-IN person testing their own form link is
    // yanked to Home mid-read.
    if (formToken) return;
    if (session.phase === "anon" && route !== LOGIN_ROUTE) {
      window.location.hash = `#/${LOGIN_ROUTE}`;
    } else if (session.phase === "authed" && (route === LOGIN_ROUTE || route === "")) {
      window.location.hash = `#/${defaultRoute(entries)}`;
    }
  }, [session.phase, route, entries, formToken]);

  // ── WAVE 24 item 13 (R10, wiring W24-W3): Home's automations ────────────────────────────
  //
  // ⚠ FETCHED HERE, NOT IN `HomePage`. Home holds no state of its own by contract β€” its whole
  // C10 argument for being CHROME rather than a granted surface is that it draws only what the
  // frame already has. A fetch inside it would make it a surface with a data contract.
  //
  // β›” A 403 BECOMES `[]`, NOT AN ERROR. An account without the automation grant is not a
  // failure β€” it is an account that has no automations to show, and the section simply does not
  // render. Raising DATA_ERROR_EVENT here would put an error card over Home for every member of
  // a tenant whose automations they were never granted.
  //
  // ⚠ RE-ASKED ON `navEpoch`, so Home does not go stale behind a write it did not make: creating
  // or deleting a database bumps the nav, and a deleted database's automations are paused and
  // re-stamped by the same route (C3's footprint contract), so their tiles have to be re-read.
  // ⚠ WAVE 25 (R8): this used to say `navEpoch` "is what makes create an automated database
  // land". That door is deleted, and the epoch bump has never been what refreshed THIS list
  // anyway β€” `createAndOpen` happens on the automation surface, which reloads its own list.
  const [autoTiles, setAutoTiles] = useState<AutomationTile[]>([]);
  useEffect(() => {
    if (who === null) {
      setAutoTiles([]);
      return;
    }
    const ac = new AbortController();
    let dead = false;
    void listAutomations(ac.signal)
      .then((r) => {
        if (dead) return;
        setAutoTiles(
          (r.automations || []).map((a) => ({
            id: a.id,
            name: a.name,
            /* ⭐ WAVE 26 Β· ITEM 18 (R14) β€” `state: stateOf(a)` is GONE with Home's status dot.
               `AutomationTile` dropped the field, so leaving the call here would be a computed
               fact with no reader. `stateOf` itself stays exported and alive in `automationApi`
               (the automation module still decides "is this running" for its own surfaces) β€” this
               is one CONSUMER leaving, not the definition. */
            // The rail's own second line, one fact not two: the forward-looking one when a
            // schedule exists (it answers "does this run itself?"), the last run otherwise.
            sub: a.schedule?.enabled
              ? a.nextRunAt
                ? `Next ${a.nextRunAt}`
                : "Scheduled"
              : a.status?.lastRunAt
                ? `Last run ${a.status.lastRunAt.replace("T", " ").slice(0, 16)}`
                : "Manual only",
          }))
        );
      })
      .catch(() => {
        if (!dead) setAutoTiles([]);
      });
    return () => {
      dead = true;
      ac.abort();
    };
  }, [who, navEpoch]);

  // WAVE 23 C10 β€” stamp the route as opened, for Home's recents.
  //
  // ⚠ ABOVE THE EARLY RETURNS with every other hook (the React #310 scar at the block below),
  // so it re-resolves the route itself rather than reading the `active` computed after them.
  //
  // THREE THINGS IT DELIBERATELY DOES NOT STAMP: a chrome route (Home and Connectors resolve to
  // no entry, so `hit` is undefined); a route the nav has not answered for yet (same reason β€”
  // `entries` is empty in flight, and stamping an unresolved key would record a page that may
  // not exist); and a hand-off, which opens the current application in another tab and is not a
  // surface this shell can put a recents tile back into.
  //
  // `lastStamped` suppresses the REPEAT write a `navEpoch` bump would otherwise cause (new
  // `entries` identity, same route) β€” and clears whenever the route resolves to nothing, so
  // leaving a table and coming back to it does re-stamp, which is what makes the ordering on
  // Home mean "most recently opened".
  useEffect(() => {
    if (session.phase !== "authed") return;
    const hit = resolveRoute(entries, route);
    if (!hit || hit.kind !== "native") {
      lastStamped.current = "";
      return;
    }
    if (lastStamped.current === hit.key) return;
    lastStamped.current = hit.key;
    postOpened(hit.key);
    setOpened((cur) => ({ ...cur, [hit.key]: Math.floor(Date.now() / 1000) }));
  }, [session.phase, route, entries]);

  const signOut = useCallback(() => {
    // The cached customer payload dies with the session: the next sign-in on
    // this browser may be a different account, and a cached book crossing that
    // boundary would be the cross-user leak EXIT-3b exists to prevent.
    clearCustomersCache();
    void logout().then(() => setSession({ phase: "anon" }));
  }, []);

  // ── Wave 18 hooks β€” β›” ABOVE the early returns, or they run conditionally. The first
  // version of this block sat below the `anon` return and blanked the whole app with React
  // error #310 on the first authed render (found by SESSION B's probe, booked in the wave
  // doc): the anon render mounted N hooks, the authed render mounted N+5, and React refuses
  // a component whose hook count changes between renders. Every hook in this component stays
  // above `if (session.phase …) return`, whatever lands here next wave.
  // (owner item 3): the assistant's under-construction note.
  // ⭐ WAVE 24 item 14 β€” it carries WHICH boarded door was knocked on, not just "open". Two
  // surfaces are now under construction (the assistant, and Home's templates card) and they are
  // the same dialog with a different sentence β€” a second near-identical modal would be the
  // "variety is a defect" failure, and a shared one that could not say which door you came
  // through would tell a reader about the wrong feature.
  const [assistOpen, setAssistOpen] = useState<false | "assistant" | "templates">(false);
  // β›” ESCAPE CLOSES A MODAL, or its scrim becomes a trap. The assistant note shipped with only
  // a scrim-click and a Close button, and the first close-out probe to press Escape found every
  // subsequent click swallowed by an invisible full-screen div β€” the
  // painted-but-unclickable failure [[ui-invisible-to-assertions]] names, in reverse. The
  // new-database dialog had Escape only while its INPUT held focus, which is not the same thing.
  useEffect(() => {
    if (!assistOpen && !newDbOpenRef.current) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== "Escape") return;
      setAssistOpen(false);
      setNewDb((cur) => (cur && cur.busy ? cur : null));
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  });
  // (C3-UT): "+ New database" + the user-table Add-record bar.
  //
  // WAVE 23 C10 β€” the dialog grew a `mode`: blank, or from a template.
  //
  // ⭐ WAVE 25 (R8) β€” IT WAS A THREE-WAY CHOICE AND THE THIRD ANSWER IS DELETED. The chooser's
  // third row ("Automated") never selected a mode at all: it closed the dialog and handed off to
  // the automation surface, which is why the union has only ever had two members. So this type is
  // unchanged and the ROW is what goes β€” the tell that the third option was never really a way of
  // creating a database, which is exactly what R8 rules.
  const [newDb, setNewDb] = useState<null | {
    mode: "blank" | "template";
    name: string;
    busy: boolean;
    err: string;
  }>(null);
  const newDbOpenRef = useRef(false);
  newDbOpenRef.current = newDb !== null;
  const openNewDb = useCallback((mode: "blank" | "template") => {
    setNewDb({ mode, name: "", busy: false, err: "" });
  }, []);
  /*
   * β›” `openAutomated` STOOD HERE AND IS DELETED WITH ITS THREE DOORS (wave 25 item 5a, R8).
   *
   * It closed the dialog, routed to `#/automation` and signalled `AUTOMATION_CREATE_EVENT` β€” and
   * it was that event's ONLY signaller, which is why the constant and its listener go in the same
   * change (see the tombstones in `apiContract.ts` and `AutomationSurface.tsx`). Leaving either
   * side behind rebuilds the wave-24 defect from the opposite end.
   */
  /**
   * ⭐ WAVE-27 item 19 (owner ruling R15) β€” WHAT A HAND-MADE DATABASE STARTS WITH.
   *
   * `user_tables.create()` mints exactly ONE column (`Name`) and zero rows, so a new database
   * opened as a single blank column with nothing in it β€” a surface with no shape to copy. R15
   * seeds four columns and three blank records instead.
   *
   * β›” IT LIVES AT THIS DOOR, NOT IN `create()`, AND THAT IS THE RULING'S OWN SCOPE. R15 is
   * "hand-created databases only; preset/automation spawns untouched", and `source` cannot
   * express that: MEASURED, `automation_engine.py:1983` mints a database for the automation
   * builder's "+ New database" through the same `create()` with the DEFAULT source, i.e. `Blank`.
   * Seeding inside `create()` would therefore put four columns and three empty rows in front of
   * every automation target as well β€” and `_vestigial_name_field` (the wave-26 migration) is
   * written against `create()` minting EXACTLY ONE column, so it would start reading the seed as
   * somebody's work. This dialog is the only door a person names a database at.
   *
   * β›” `status` SHIPS WITH ITS OPTIONS. A select declaring none is the W26 item-24 defect
   * verbatim β€” `if ([])` is truthy, so a panel hands back an empty list as an ANSWER and the
   * filter reads as dead β€” and `aios_grid` separately degrades an option-less select to text on
   * read, so the column would not even stay a select.
   *
   * β›” `name` DECLARES `pinned`. D-80 is exactly this key going unwritten: the primary column
   * resolves as `fields.find(f => f.pinned) ?? fields[0]`, and because nothing ever set the flag,
   * "whichever column was created first" WAS the rule. With four columns arriving at once,
   * leaving it implicit stops being harmless.
   */
  const SEED_FIELDS = [
    { key: "name", label: "Name", type: "text", pinned: true },
    { key: "status", label: "Status", type: "select",
      options: ["Todo", "In progress", "Done"] },
    { key: "assignee", label: "Assignee", type: "user" },
    { key: "date", label: "Date", type: "date" },
  ];
  const SEED_ROWS = 3;
  const createDb = useCallback(async () => {
    setNewDb((cur) => {
      if (!cur || cur.busy || !cur.name.trim()) return cur;
      const name = cur.name;
      void (async () => {
        try {
          // WAVE 23 C10 β€” `source` rides the body the route ALREADY forwards
          // (`routes_tables.py:192` passes it to `user_tables.create`). It is the literal
          // `"Blank"` because that is the enum member the server accepts; ⚠ an unknown source is
          // SILENTLY DOWNGRADED to Blank there (user_tables.py:165), so a third literal invented
          // here would create a table that quietly disagrees with the word the dialog used.
          // ⚠ "Automated" is not one of these values and never was. The engine stamps that source
          // itself when an automation spawns its own target β€” which is now the ONLY way a
          // database becomes automated, R8 having deleted the doors that implied otherwise.
          const res = await fetch(`${API_V1}/tables`, {
            method: "POST",
            credentials: CREDENTIALS,
            headers: { "Content-Type": "application/json" },
            // R15's four columns ride the SAME body the route already forwards to
            // `user_tables.create(fields=...)` β€” no new endpoint, no server change.
            body: JSON.stringify({ label: name.trim(), source: "Blank", fields: SEED_FIELDS }),
          });
          const body = (await res.json().catch(() => null)) as
            | { key?: string; error?: { message?: string } }
            | null;
          if (!res.ok || !body?.key) {
            setNewDb({ mode: "blank", name, busy: false,
                       err: body?.error?.message || `The server answered ${res.status}.` });
            return;
          }
          // R15's three blank records, through the ORDINARY row door the grid's own "+" uses.
          //
          // ⚠ SEQUENTIAL, not `Promise.all`: three concurrent writes race the same store
          // document, and the last read-modify-write would win with two rows lost.
          //
          // ⚠ FAILURE HERE DOES NOT FAIL THE CREATE, and that asymmetry is deliberate. The
          // database and its four columns already exist; reporting "could not create it" over a
          // missing blank row would be false, and rolling the database back would destroy the
          // part that worked. A database that opens with two blank rows instead of three is not
          // a state anybody can be harmed by β€” the grid's "+" adds the third.
          for (let i = 0; i < SEED_ROWS; i += 1) {
            try {
              await fetch(`${API_V1}/tables/${body.key}/rows`, {
                method: "POST",
                credentials: CREDENTIALS,
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ values: {} }),
              });
            } catch {
              break;      // the store is unreachable; the next two would fail the same way
            }
          }
          setNewDb(null);
          setNavEpoch((e) => e + 1);
          window.location.hash = `#/${body.key}`;
        } catch {
          setNewDb({ mode: "blank", name, busy: false, err: "Cannot reach the server." });
        }
      })();
      return { ...cur, busy: true, err: "" };
    });
  }, []);
  // β›” `addRecord` LIVED HERE AND IS DELETED WITH THE BAR THAT CALLED IT (wave 20 item 4,
  // R8 / C-ADDROW). The shell was POSTing `/tables/{key}/rows` itself, clearing the grid's
  // cache and firing ROWS_STALE_EVENT to make the new row appear β€” a write path owned by
  // the frame, for a surface the grid owns. R8 moves the affordance into the grid as a
  // trailing "+" row (S3's half), where the row it adds is the row you are looking at, so
  // the shell stops being a second writer of table data.

  // ⭐ WAVE 23 C9 (SESSION D's page, E's mount β€” wiring W23-W2) β€” THE PUBLIC FORM, BEFORE THE
  // AUTH WALL.
  //
  // β›” THE POSITION IS THE ENTIRE CONTRACT. It sits above BOTH early returns: above `anon`,
  // obviously, but also above `checking` β€” a person filling in a public form should not watch a
  // brand mark while `me()` resolves a session they do not have. It is below every hook, which
  // is the other half of the rule (the React #310 scar the block at :828 documents): the hook
  // count may not change between renders, and this branch would be the shortest possible path
  // to breaking that.
  //
  // ⚠ THE SMALLEST POSSIBLE BRANCH, deliberately (C9's own words). It reads a token out of the
  // hash and renders D's page; it does not fetch, does not touch the session, does not import
  // anything of the grid's. Nothing else in this frame is reachable from it.
  //
  // β›” AND THE HASH NORMALISER HAS TO KNOW. The effect at :812 pins an anonymous shell to
  // `#/login` β€” which would have bounced every anonymous form visitor to a login screen before
  // this branch ever rendered. `isPublicForm` is read there too; a mount without that exemption
  // is a public door that only signed-in people can reach.
  //
  // ⚠ The SERVER side of this is genuinely public (D's `routes_forms.py`, the automation-hook
  // pattern β€” uniform 403, constant-time compare). This branch adds no new public SURFACE: the
  // SPA bundle is already served unauthenticated (main.py:257-295, `_DEV_FIXTURES` guard), so
  // `#/form/<token>` has always loaded for free. What it adds is a client route that renders
  // something there instead of the login page.
  if (formToken) {
    return <FormPublic token={formToken} />;
  }

  if (session.phase === "checking") {
    // Deliberately wordless. A "Loading…" line here would flash for one round
    // trip on every load, and the mark says everything the moment needs.
    return (
      <div className="shell-boot">
        <Brand size={44} className="login-brand" />
      </div>
    );
  }

  if (session.phase === "anon") {
    return (
      <LoginPage
        onSignedIn={(user) => {
          // Same rule as sign-out, from the other side: a fresh session never
          // reads the previous session's cached rows.
          clearCustomersCache();
          setSession({ phase: "authed", user });
        }}
      />
    );
  }

  const active = resolveRoute(entries, route);
  const utility = nav.phase === "ready" ? nav.utility : NO_UTILITY;
  const analyst = utility.find((p) => p.key === "analyst");
  // ── WAVE 19 R10 / C3: Automation LEAVES THE DATABASE LIST ────────────────────
  //
  // Strategy A, chosen at the grill: a CLIENT-SIDE relocation. The registry row,
  // `NATIVE_KEYS`, the API payload and the `#/automation` render branch below are
  // all untouched β€” Automation is still a granted surface the server decides on,
  // it simply stops being drawn among the databases, because it is not one.
  //
  // ⚠ THE FILTER FEEDS `foldNav`, IT IS NOT APPLIED INSIDE THE `.map()`, and the
  // difference is a bug you would find weeks later. `foldNav` counts a folder's
  // members from `prefs.placement`, so a user who had already dragged Automation
  // into a folder would get a folder head reading "1" with nothing underneath it
  // β€” the count derived from a list that still had the row, the rows drawn from
  // one that did not.
  //
  // β›” AND `entries` STAYS WHOLE. `resolveRoute`, `active`, `defaultRoute`, the
  // empty-nav note and `tenantEmptyState` all read it: filtering there would
  // break the hash route this button navigates to, and would tell a tenant whose
  // only granted surface is Automation that it has no surfaces at all.
  //
  // ⭐ WAVE 25 (D-54) β€” THE FILTER IS NO LONGER WRITTEN HERE. It was
  // `entries.filter(e => e.key !== "automation")`, i.e. a local expression every consumer had to
  // remember, and Home did not (it drew the Automation surface a tile under "Databases"). The
  // split is a PROPERTY of the row now (`shapeNav` stamps `surface`) and `databaseEntries` is the
  // one accessor β€” which also returns the BRANDED `DatabaseEntry[]`, so handing a database
  // surface the raw `entries` is a compile error rather than one extra tile nobody looks at.
  const automation = entries.find((e) => e.key === "automation" && e.kind === "native");
  /**
   * ⭐⭐ W31-T11 (owner item 6b) β€” WHAT TO DRAW WHERE AUTOMATION GOES WHEN IT IS NOT THERE.
   *
   * β›” THE DEFECT, in one line: `{automation ? … : null}` renders **literally nothing** for
   * three completely different situations, and the reader cannot tell them apart:
   *   1. `/nav` is in flight β€” `entries` is `NO_ENTRIES` until `phase === "ready"`, so the rail
   *      shows its four static rows and a complete-looking gap. `/nav` measured a **9.5–14.0 s
   *      band** on tenant #0, and `reference/ERROR 5.png` is exactly this screen. The owner read
   *      it as the module disappearing, and reported it across several waves.
   *   2. the payload came back and this workspace's catalogue does not include the module β€”
   *      deliberate, and the rail should stay quiet.
   *   3. the payload came back INCOMPLETE (`degraded`) or never came back at all β€” not
   *      deliberate, and silence is a lie about what exists.
   * ⚠ ONLY CASE 2 DRAWS NOTHING. The other two get the slot, so an absence is never mistaken for
   * a workspace that simply does not have the feature. (The rail already had a region-level
   * spinner and error line four rows below β€” far enough away that nothing connected them to this
   * gap, which is why "there is a loading state" was true and did not help.)
   */
  const automationSlot: "row" | "pending" | "unavailable" | "silent" = automation
    ? "row"
    : nav.phase === "loading" || nav.phase === "idle"
      ? "pending"
      : nav.phase === "error"
        ? "unavailable"
        : nav.phase === "ready" && (nav.degraded?.length ?? 0) > 0
          ? "unavailable"
          : "silent";
  const dbEntries = databaseEntries(entries);
  // WAVE 23 C10 β€” the flyout's search. A plain label substring, case-folded: this list is at
  // most a few dozen rows, so anything cleverer (fuzzy, ranked) would be a scoring function
  // nobody can predict over a set small enough to read.
  //
  // ⚠ SEARCHING RENDERS FLAT. `foldNav` is called with EMPTY prefs while a query is live,
  // because a folder head whose members were filtered out would report a count it is not
  // showing β€” the same "count derived from one list, rows from another" defect the R10
  // relocation note two blocks up already documents.
  const dbQ = dbQuery.trim().toLowerCase();
  const shownEntries = dbQ
    ? dbEntries.filter((e) => e.label.toLowerCase().includes(dbQ))
    : dbEntries;
  // WAVE 23 C10 β€” what Home draws: the server's recents plus this session's own stamps.
  const recents = mergeRecents(nav.phase === "ready" ? nav.recents : NO_RECENTS, opened);

  return (
    <div className="shell-root">
      <aside
        className={"shell-side" + (navCollapsed ? " is-collapsed" : "")}
        // Item 7 (R9) β€” background click expands. Bound only while collapsed, so the
        // open rail is exactly what it was; the accessible route stays the labelled
        // brand button below ("Expand navigation"), which is what a keyboard reaches.
        onClick={navCollapsed ? expandOnBlank : undefined}
      >
        {/* The PRODUCT brand β€” the same mark the Streamlit host paints, from the
            same generated file, so the two shells cannot drift. "Royal Imports"
            stays on business documents only. */}
        <div className="shell-side-head">
          {/* Owner item 2 (2026-07-31) β€” collapsed, the LOGO is the way back and the
              three-bars toggle disappears (CSS hides it). One stable element in both states
              so the mark can animate rather than swap; disabled while expanded, where it is
              brand, not control. */}
          <button
            type="button"
            className="shell-brand-btn"
            disabled={!navCollapsed}
            aria-label={navCollapsed ? "Expand navigation" : undefined}
            onMouseEnter={navCollapsed ? tipEnter("Expand navigation") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
            onClick={() => setNavCollapsed(false)}
          >
            <Brand size={26} className="shell-brand" />
          </button>
          <button
            type="button"
            className="shell-rail-toggle"
            aria-label="Minimize navigation"
            aria-expanded={!navCollapsed}
            title="Minimize navigation"
            onClick={() => setNavCollapsed(true)}
          >
            <RailToggleIcon />
          </button>
        </div>

        <nav className="shell-nav">
          {/* ⭐ WAVE 23 item 9 (R7, contract C10) β€” HOME, the new landing, at the top of the rail.
              An `<a>` to a CHROME route: it needs no grant because it renders nothing the server
              did not already send (nav.ts' `CHROME_ROUTES` note carries the full argument, and
              the :1039 law below is unchanged β€” an undeclared SURFACE is still denied). */}
          <a
            className={"shell-nav-item shell-nav-home" + (route === HOME_ROUTE ? " is-active" : "")}
            href={`#/${HOME_ROUTE}`}
            onMouseEnter={navCollapsed ? tipEnter("Home") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
          >
            <HomeIcon />
            <span className="shell-nav-label">Home</span>
          </a>

          {/* The Analyst slot, above the database list β€” the host's own IA
              (app.py:8166 pins "AI assistant" over the nav tree, same label,
              same sparkle). Wave 18 (owner item 3): the hand-off into Streamlit
              is PAUSED β€” the click opens an in-app "under construction" note
              instead. The nav item, the registry row and the Streamlit Analyst
              page all stay (kept-not-ported, never delete); only the door is
              boarded until a later wave expands it. */}
          {analyst ? (
            <button
              type="button"
              className="shell-nav-item shell-nav-assist"
              onClick={() => setAssistOpen("assistant")}
              onMouseEnter={navCollapsed ? tipEnter("AI assistant") : undefined}
              onMouseLeave={navCollapsed ? tipLeave : undefined}
            >
              <SparkIcon />
              <span className="shell-nav-label">AI assistant</span>
            </button>
          ) : null}

          {/* ⭐⭐ W32-T05 (item 7, ruling R1) β€” QUERY, directly under the AI assistant because that is
              what it IS: the place the assistant's work goes. R1 β€” "every AI-built view lands under
              the Query module".
              ⚠ THE OWNER'S SIX-ROW ORDER IS UNCHANGED ABOVE AND BELOW IT (Home / AI assistant /
              Inbox / Automation / Database / Connectors, wave 24 item 1). Query is a SEVENTH row,
              inserted beside its own producer rather than appended β€” appending would have put the
              newest surface furthest from the thing that fills it, and re-ordering the six would
              have re-opened a decision the owner already made. */}
          <a
            className={"shell-nav-item shell-nav-query" + (route === QUERY_ROUTE ? " is-active" : "")}
            href={`#/${QUERY_ROUTE}`}
            onMouseEnter={navCollapsed ? tipEnter("Query") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
          >
            <SparkIcon />
            <span className="shell-nav-label">Query</span>
          </a>

          {/* WAVE 20 item 25 (C-ALERT) β€” "Alerts".
              ⭐ WAVE 24 item 1 β€” IT MOVED UP, above Automation. The owner's order is
              Home / AI assistant / Alerts / Automation / Database / Connectors, and the
              two pairs that swapped are Alerts↔Automation here and Database↔Connectors
              below. Nothing else about these rows changed: MEASURED on staging v12, all
              six already render 13.8125px / w500 / Inter / rgb(32,36,51), `<a>` and
              `<button>` alike (wave 19 R11's reset holding). The one row in this band
              that differed was "+ Create new…" (12.75px / w400 / muted), and item 15a
              takes it out of the rail entirely β€” see `CreateNewRow`'s own note.
              ⭐⭐ W32-T04 (owner item 16, ruling R7) β€” IT IS A NAV LINK NOW, AND THE
              PARAGRAPH THIS REPLACES WAS RIGHT ON ITS PREMISE AND WRONG ON ITS
              CONCLUSION. Its premise β€” the nav is server-filtered and an undeclared
              surface is denied β€” still holds and is why Inbox is CHROME rather than a
              `registry.py` module (see `nav.INBOX_ROUTE`: a registry key outside a
              tenant's `modules` list is silently omitted in every tenant). Its
              conclusion, that the surface must therefore be a PANEL, does not follow:
              Home and Connectors are routes under the same law, because a chrome route
              renders nothing the server did not already grant β€” and `GET /notifications`
              is this account's own notifications, composed by the server, for this
              session. The owner asked for an inbox that reads like email; a dropdown
              that closes when you look away is the one shape that cannot. */}
          <a
            className={"shell-nav-item shell-nav-alerts" + (route === INBOX_ROUTE ? " is-active" : "")}
            href={`#/${INBOX_ROUTE}`}
            onMouseEnter={navCollapsed ? tipEnter("Inbox") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
          >
            <BellIcon />
            <span className="shell-nav-label">Inbox</span>
            {badgeText(inbox.unread) ? (
              <span
                className="shell-nav-badge"
                // Not aria-hidden: the count IS the information, and a badge a screen
                // reader cannot see makes the row read as an empty inbox.
                aria-label={`${inbox.unread} unread`}
              >
                {badgeText(inbox.unread)}
              </span>
            ) : null}
          </a>

          {/* WAVE 19 R10 / C3 β€” Automation. An `<a>` to the route it already had: the
              surface, its rail and its editor are another session's tree this wave and
              are not touched by any of this. The LABEL comes off the payload, never a
              literal here β€” the registry owns what this surface is called, and a client
              that hard-codes the word is the drift that outlives the row. */}
          {automation ? (
            <a
              className={
                "shell-nav-item shell-nav-auto" +
                (active && active.key === automation.key ? " is-active" : "")
              }
              href={automation.href}
              onMouseEnter={navCollapsed ? tipEnter(automation.label) : undefined}
              onMouseLeave={navCollapsed ? tipLeave : undefined}
            >
              {/* ⚠ R8 lists Automation among the databases that get an icon
                  ("Customer/Product/Automation/custom"); R10 moves it out of the
                  list where the β‹― that SETS one lives. So it DISPLAYS a chosen
                  mark β€” the store and the route already accept `automation` as a
                  key β€” while the entry point to choose one is the open question
                  booked as amendment 6 for the integrator. Rendering the default
                  glyph unconditionally would have made this the one database
                  that could never show an icon, which is the half of R8 a client
                  has no business deciding. */}
              {automation.icon ? (
                <span className="shell-nav-mark" aria-hidden="true">
                  <FolderMark icon={automation.icon} size={16} />
                </span>
              ) : (
                <AutoIcon />
              )}
              <span className="shell-nav-label">{automation.label}</span>
            </a>
          ) : automationSlot === "pending" ? (
            /* ⭐ W31-T11 β€” THE PENDING STATE, IN AUTOMATION'S OWN SLOT. The shared spinner mark
               (R6: the mark, never the word "Loading…", which `verify_icons` enforces), on a row
               that occupies the space the real one will. `aria-busy` is what makes it a pending
               ROW to a screen reader rather than a decorative glyph. */
            <div
              className="shell-nav-item shell-nav-auto is-pending"
              aria-busy="true"
              aria-label="Automation is loading"
            >
              <span className="lp-spin" aria-hidden="true" />
              <span className="shell-nav-label shell-nav-label--muted">Automation</span>
            </div>
          ) : automationSlot === "unavailable" ? (
            /* β›” W31-T11 β€” NOT LOADING, AND NOT ABSENT-ON-PURPOSE: the server said this payload
               is incomplete (`degraded`), or it never answered. The row states that rather than
               leaving a gap the reader has to interpret β€” which is the whole of owner item 6b. */
            <div
              className="shell-nav-item shell-nav-auto is-unavailable"
              title={
                nav.phase === "error" && nav.timedOut
                  ? "The navigation request timed out. Reload to retry."
                  : "This list could not be loaded in full. Reload to retry."
              }
            >
              <AutoIcon />
              <span className="shell-nav-label shell-nav-label--muted">Automation</span>
              <span className="shell-nav-note-dot" aria-hidden="true" />
            </div>
          ) : null}

          {/* ⭐ WAVE 23 item 9 (R7) β€” THE DATABASE BUTTON, and the end of the always-on band.
              R7: "databases LEAVE the always-on rail; a 'Database' nav button opens the flyout".
              The rail is now a fixed set of destinations whose height does not depend on how many
              tables the tenant made β€” which is the actual complaint behind the ruling.
              β›” A BUTTON, NOT A ROUTE, and for the same reason Alerts is one (:1039): there is no
              `#/databases` surface and inventing one would be the hard-coded page this frame
              refuses to have. It opens a panel over the list the server already sent. */}
          <button
            type="button"
            ref={dbButton}
            className={"shell-nav-item shell-nav-db" + (dbAt ? " is-active" : "")}
            aria-haspopup="dialog"
            aria-expanded={!!dbAt}
            onMouseEnter={navCollapsed ? tipEnter("Database") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
            onClick={(e) => {
              if (dbAt) {
                closeDbFly();
                return;
              }
              const at = flyoutFrom(e.currentTarget);
              if (at) setDbAt(at);
            }}
          >
            <DbIcon />
            <span className="shell-nav-label">Database</span>
            <CaretIcon />
          </button>

          {/* ⭐ WAVE 23 item 10 (R8, contract C11, wiring W23-W3) β€” CONNECTORS.
              ⭐ WAVE 24 item 1 β€” it moved BELOW Database. R8 put it above; the owner's wave-24
              order puts the two destinations that open panels-over-server-data (Database, then
              Connectors) at the foot of the rail. A chrome route like Home: the DIRECTORY it
              renders is composed by the server and session-gated, so this row can no more invent
              a connector than Home can invent a database. */}
          <a
            className={
              "shell-nav-item shell-nav-connectors" +
              (route === CONNECTORS_ROUTE ? " is-active" : "")
            }
            href={`#/${CONNECTORS_ROUTE}`}
            onMouseEnter={navCollapsed ? tipEnter("Connectors") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
          >
            <PlugIcon />
            <span className="shell-nav-label">Connectors</span>
          </a>

          {/* β›” "+ Create new…" IS NO LONGER A RAIL ROW (item 15a, ruling R9). It moved into the
              Database flyout's footer, where the things it creates actually live β€” and where the
              three `.shell-dbfly-make` buttons used to be. See the footer below, and
              `CreateNewRow`'s own note for why this is also item 1's fix rather than a separate
              cosmetic change: it was the one row in this band whose type differed. */}

          {/* ── THE DATABASE FLYOUT (C10) ────────────────────────────────────────────────────
              β›” PORTALLED TO `<body>`, and it has to be. Left inside the `<aside>` it would be a
              descendant of `.shell-side.is-collapsed`, whose rules hide `.shell-nav-label`,
              `.shell-nav-badge` and `.shell-nav-open` β€” so with the rail folded the panel would
              render a column of unlabelled icons, which is the one state this control exists to
              rescue the user from. `createPortal` is already this tree's answer for exactly this
              (OverlaySurface, CatalogView); the panel is not part of the rail, it only points at
              it. */}
          {dbAt
            ? createPortal(
                <div
                  className="shell-dbfly"
                  ref={dbPanel}
                  role="dialog"
                  aria-label="Databases"
                  style={{ left: dbAt.x, top: dbAt.y }}
                >
                  <div className="shell-dbfly-head">
                    <input
                      autoFocus
                      className="shell-dbfly-search"
                      placeholder="Search databases"
                      value={dbQuery}
                      maxLength={60}
                      onChange={(e) => setDbQuery(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === "Escape") closeDbFly();
                      }}
                    />
                  </div>
                  <div
            className={
              "shell-nav-list" + (dropTarget === "__root__" ? " is-drop-root" : "")
            }
            onDragOver={(e) => {
              if (!e.dataTransfer.types.includes(NAV_DRAG_TYPE)) return;
              e.preventDefault();
              e.dataTransfer.dropEffect = "move";
              setDropTarget("__root__");
            }}
            onDragLeave={(e) => {
              if (e.currentTarget.contains(e.relatedTarget as Node)) return;
              setDropTarget(null);
            }}
            onDrop={(e) => {
              const key = e.dataTransfer.getData(NAV_DRAG_TYPE);
              setDropTarget(null);
              setDragKey(null);
              if (!key) return;
              e.preventDefault();
              movePage(key, null);
            }}
          >
            {/* C-SCHEMA: the list folds under the user's folders.
                ⭐ WAVE 23 C10 β€” the `navCollapsed ? EMPTY_NAV_PREFS :` gate is GONE with the band
                it belonged to. It existed because the 44px strip had no room for folder chrome;
                this panel is 268px wide whatever the rail is doing, so the folders always render
                and the reason for the gate no longer exists. A SEARCH still flattens (see
                `shownEntries`) β€” that is a different fact about a different state. */}
            {foldNav(shownEntries, dbQ ? EMPTY_NAV_PREFS : navPrefs, closedFolders).map(
              (row) => {
                if (row.kind === "folder") {
                  return (
                    <FolderHead
                      key={`folder:${row.folder.id}`}
                      folder={row.folder}
                      count={row.count}
                      open={row.open}
                      // WAVE 23 C10 β€” always false in the flyout: the panel has full width in
                      // either rail state, so folder chrome is never the thing being squeezed.
                      collapsed={false}
                      onToggle={() => toggleFolder(row.folder.id)}
                      onRename={(name) => renameFolder(row.folder.id, name)}
                      onDelete={() => deleteFolder(row.folder.id)}
                      isDrop={dropTarget === row.folder.id}
                      dropProps={{
                        onDragOver: (e) => {
                          if (!e.dataTransfer.types.includes(NAV_DRAG_TYPE)) return;
                          e.preventDefault();
                          e.stopPropagation();
                          e.dataTransfer.dropEffect = "move";
                          setDropTarget(row.folder.id);
                        },
                        onDrop: (e) => {
                          const key = e.dataTransfer.getData(NAV_DRAG_TYPE);
                          setDropTarget(null);
                          setDragKey(null);
                          if (!key) return;
                          e.preventDefault();
                          e.stopPropagation();
                          movePage(key, row.folder.id);
                        },
                      }}
                    />
                  );
                }
                const item = row.entry;
                // Wave 17 item 12 β€” ONE answer, read by the row AND the link.
                // The row paints the tint (so it reaches under the β‹―, matching
                // the Views rail); the link keeps the class because the weight
                // and the full-strength icon hang off `.shell-nav-item.is-active`.
                const isActive = !!active && active.key === item.key;
                const cls =
                  "shell-nav-item" +
                  (item.depth > 0 ? " is-child" : "") +
                  (isActive ? " is-active" : "");
                const inner = (
                  <>
                    {/* WAVE 19 R8 β€” the tenant's chosen mark, or the cylinder.
                        ⚠ `FolderMark` paints its OWN pastel fill and `-deep`
                        stroke, so it must not wear `.shell-nav-icon` (which sets
                        `stroke: currentColor` and dims to 0.55 β€” that rule would
                        repaint a deliberately-coloured glyph in the row's ink and
                        then half-erase it). The wrapper span carries only the
                        box, which is why the class is the shell's own and not the
                        grid's `.cg-folder-mark`: that one belongs to another
                        session's CSS region this wave. */}
                    {item.icon ? (
                      <span className="shell-nav-mark" aria-hidden="true">
                        <FolderMark icon={item.icon} size={16} />
                      </span>
                    ) : (
                      <DbIcon />
                    )}
                    <span className="shell-nav-label">{item.label}</span>
                    {/* ⭐ WAVE 27 item 3 (contract C9) β€” A LOCKED DATABASE SAYS SO HERE.
                        The nav flyout is the only place every database is listed, so it is
                        where the fact belongs β€” you learn it before you open the thing and
                        go looking for a "+" that will not be there.

                        ⚠ THE TITLE NAMES **WHICH** LOCK, and that is a standing rule rather
                        than politeness: ONE `LockMark` glyph carries all three of the owner's
                        locks (locked database / pre-set field / locked view β€” DESIGN.md Β§4),
                        so a bare padlock says only "something here is restricted". This one
                        means records, and it says the half that STAYS OPEN in the same breath,
                        because "locked" reads as read-only and fields are not. */}
                    {item.locked ? (
                      <span
                        className="shell-nav-lock"
                        title="Locked database β€” records are added by an automation. You can still add and edit fields."
                      >
                        <LockMark size={11} />
                      </span>
                    ) : null}
                    {/* A hand-off opens the current application in a new tab; the
                        arrow declares that before the click finds out. */}
                    {item.kind === "handoff" ? <ExtIcon /> : null}
                    {/* Wave 14 item 6: the "Odoo" provenance badge is GONE β€” the schema
                        drawer still names the source for whoever asks. */}
                  </>
                );
                if (item.kind === "group") {
                  // A registry family head is not a destination β€” the app has no
                  // page for it either. A label, never a link.
                  return (
                    <div key={item.key} className="shell-nav-group">
                      {inner}
                    </div>
                  );
                }
                // ⭐ WAVE 23 C10 β€” the collapsed-rail hover tip is GONE from these rows, with
                // the band it belonged to. It named a database whose LABEL was hidden at 44px;
                // inside the flyout the label is always on screen, so the tip would have been a
                // second copy of the word beside itself. `tipEnter`/`tipLeave` still serve the
                // rail's own rows above.
                //
                // Clicking a database CLOSES the panel: you asked for it, you got it. The
                // handler is on the LINK and not on the list, deliberately β€” a click on the
                // row's β‹― must leave the panel open, because that menu is anchored inside it.
                const link =
                  item.kind === "native" ? (
                    <a className={cls} href={item.href} onClick={closeDbFly}>
                      {inner}
                    </a>
                  ) : (
                    <a
                      className={cls}
                      href={item.href}
                      target="_blank"
                      rel="noreferrer"
                      onClick={closeDbFly}
                    >
                      {inner}
                    </a>
                  );
                // The three-dots rides TOP-LEVEL rows in the open rail only β€”
                // children move with their family, and the folded rail has no
                // horizontal room for a second control.
                return (
                  <div
                    key={item.key}
                    className={
                      "shell-nav-row" +
                      (isActive ? " is-active" : "") +
                      (row.folderId ? " is-foldered" : "") +
                      (dragKey === item.key ? " is-dragging" : "")
                    }
                    // WAVE 23 C10 β€” `!navCollapsed &&` dropped from both gates below: the panel
                    // is the same width in either rail state, so the two things that gate
                    // referred to (no horizontal room for a β‹―, no room to drag) are no longer
                    // true. The folder-reorder drag and the row menu therefore keep working with
                    // the rail folded, which is the state a user who opened this panel is most
                    // likely to be in.
                    draggable={item.depth === 0}
                    onDragStart={(e) => {
                      e.dataTransfer.setData(NAV_DRAG_TYPE, item.key);
                      e.dataTransfer.effectAllowed = "move";
                      setDragKey(item.key);
                    }}
                    onDragEnd={() => {
                      setDragKey(null);
                      setDropTarget(null);
                    }}
                  >
                    {link}
                    {item.depth === 0 && (
                      <RowMenu
                        entryLabel={item.label}
                        canSchema
                        onSchema={() => setSchemaFor(item.key)}
                        // ── WAVE 19 R8 / C1, walled by R14 ──────────────────
                        // RENAME is `ut_*` only: a built-in label is a compiled
                        // registry literal, and renaming one would leave the nav
                        // and every other reader of `core/registry.py` calling
                        // the same module two different things. ICONS ride every
                        // database β€” that half of R8 is explicitly "ALL".
                        //
                        // β›” WHO MAY IS THE SERVER'S ANSWER, NOT A ROLE CHECK
                        // HERE. R14 put the `ut_` half on `user_tables.may_open`
                        // β€” the table's CREATOR or a tenant admin β€” and this
                        // client cannot see who created a user table. So the nav
                        // payload carries `manage` per row and the rail simply
                        // obeys it. Absent reads as NO (fail-closed), and
                        // `POST /nav/meta` re-checks regardless: this is the
                        // courtesy half of "the client hides, the server
                        // forbids", the same one `reachableSection` pays in
                        // Settings. An earlier build gated on `isAdmin` here and
                        // was wrong in the direction that matters β€” it hid a
                        // control from the person who owned the thing.
                        canRename={!!item.manage && item.key.startsWith("ut_")}
                        onRename={(name) => void commitNavMeta(item.key, { name })}
                        canIcon={!!item.manage}
                        {...(item.icon ? { icon: item.icon } : {})}
                        onIcon={(icon: FolderIcon) =>
                          void commitNavMeta(item.key, { icon })
                        }
                        onIconClear={() => void commitNavMeta(item.key, { icon: null })}
                        // WAVE 20 item 18 (R10) β€” share THIS database. Offered on the
                        // user's own tables only: `customer_data` and `product_data` are
                        // registry surfaces whose reach is the permission wall's answer,
                        // not one person's to grant ([[aios-permission-wall]]), and a
                        // dialog that recorded a grant the module gate would then ignore
                        // is the "shared, silently inert" failure in reverse.
                        {...(item.key.startsWith("ut_")
                          ? {
                              onShare: () =>
                                setShareFor({
                                  kind: "database",
                                  id: item.key,
                                  label: item.label,
                                }),
                            }
                          : {})}
                        // ⭐ WAVE 21 item 6 (R3, C3, wiring W-5) β€” THE MOUNT.
                        //
                        // `canDelete` is the SERVER's answer and a REQUIRED prop, so
                        // this expression not being here is a compile error rather
                        // than a feature that quietly does not exist (wave 20's
                        // lesson, written into the type β€” see RowMenu's own note).
                        //
                        // β›” NOT `manage`, and the difference is the whole ruling.
                        // `manage` rides `may_open`, which R14/D-32 widened to
                        // everyone the table is SHARED with; R3 puts delete on the
                        // creator or an admin alone, and refuses it outright for
                        // connector-backed databases. Two questions, two flags.
                        canDelete={!!item.canDelete}
                        onLoadFootprint={() => fetchTableFootprint(item.key)}
                        onDelete={() => removeDatabase(item.key)}
                      />
                    )}
                  </div>
                );
              }
            )}
                    {/* The panel's own empty state: ONE line, and it is different from "this
                        workspace has none" β€” a search that matched nothing is not a workspace
                        with nothing in it, and saying the second when the first is true is how a
                        reader concludes their data is gone. */}
                    {shownEntries.length === 0 ? (
                      <p className="shell-dbfly-empty">
                        {dbQuery ? "No database matches that." : "No databases yet."}
                      </p>
                    ) : null}
                  </div>
                  {/* ── the create footer ─────────────────────────────────────────────────
                      ⭐ WAVE 24 item 15a (ruling R9, wiring W24-W4) β€” ONE CONTROL, THE CREATE
                      DOORS. C10's three `.shell-dbfly-make` buttons are deleted and
                      "+ Create new…" moves here from the rail, carrying New database Β·
                      From a template Β· New folder.

                      ⭐ WAVE 25 item 5a (R8) β€” IT WAS FOUR DOORS AND IS NOW THREE. "Automated
                      database" is deleted here, on Home, and in the New-database dialog. Making
                      an automation is not a way of making a database, and a menu that offered it
                      beside "New database" said it was.

                      ⚠ NOTHING THE THREE BUTTONS OPENED IS LOST, and that was the constraint:
                      blank and template still open the same New-database dialog with the choice
                      pre-selected β€” and FOLDERS, which the rail row owned and the three buttons
                      never offered, keep their only creation door.

                      ⚠ EACH DOOR CLOSES THE PANEL FIRST, exactly as the buttons did. `New
                      folder` is the one that must NOT: it opens an inline naming form inside
                      this footer, and `createFolder` re-opens the panel so the new folder is
                      visible (C10's own fix for an affordance whose effect was invisible).
                      `CreateNewRow` keeps that form internal, so closing here would unmount the
                      thing the user is typing into. */}
                  <div className="shell-dbfly-foot">
                    <CreateNewRow
                      collapsed={navCollapsed}
                      onExpand={() => setNavCollapsed(false)}
                      onCreateFolder={createFolder}
                      onNewDatabase={() => {
                        closeDbFly();
                        openNewDb("blank");
                      }}
                      onFromTemplate={() => {
                        closeDbFly();
                        openNewDb("template");
                      }}
                      canFolder={entries.length > 0}
                    />
                  </div>
                </div>,
                document.body
              )
            : null}
          {/* Wave 17 item 3 (R6) β€” the mark, never the word. "Loading…" under an
              empty rail told the reader what they could already see, and it read
              as a nav ITEM for the beat before it vanished. */}
          {nav.phase === "loading" ? (
            <div className="shell-nav-note is-spin">
              <span className="lp-spin" role="status" aria-label="Loading" />
            </div>
          ) : null}
          {/* Honest, and it names the fix. Inventing a nav here would show
              surfaces the server never granted. */}
          {nav.phase === "error" ? (
            <div className="shell-nav-note">
              {nav.timedOut
                ? /* ⭐ W31-T11 β€” A DEADLINE IS A DIFFERENT FACT FROM A DEAD SERVER, and it earns
                     its own sentence: before this ticket `fetchNav` had no timeout at all, so
                     this state was UNREACHABLE and the rail waited for ever. */
                  "Navigation took too long to load. Reload to retry."
                : "Navigation unavailable. Reload to retry."}
            </div>
          ) : null}
          {/* β›” W31-T11 β€” A 200 THAT COULD NOT READ THE DATABASES SAYS SO. This is the case that
              had no surface at all: the server swallowed a store failure, answered 200 with every
              `ut_*` row missing, and the rail drew a confident, complete-looking list of nothing.
              It is NOT `phase: "error"` β€” the registry rows are real and usable β€” so it renders
              beside them rather than replacing them. */}
          {nav.phase === "ready" && (nav.degraded?.length ?? 0) > 0 ? (
            <div className="shell-nav-note">
              Some databases could not be loaded. Reload to retry.
            </div>
          ) : null}
          {/* ⚠ Wave 18: this line is for a MISCONFIGURED ACCOUNT β€” one whose grants give it
              nothing β€” and it must not fire for a freshly provisioned TENANT, which has no
              modules by design and is being welcomed on Home. Both at once said "something is
              wrong here" and "welcome, start here" in one screen (caught in the close-out
              visual pass, not by any gate). "+ Create new…" above is the honest affordance in
              the tenant case. */}
          {nav.phase === "ready" && entries.length === 0 && !tenantEmptyState ? (
            <div className="shell-nav-note">No surfaces are available to this account.</div>
          ) : null}
        </nav>

        <div
          className="shell-side-bottom"
          // Collapsed, the 56px strip cannot hold the account POPOVER β€” so the row's one
          // honest behaviour is "expand me first". Capture-phase, so the menu never opens
          // half-clipped behind the grid.
          onClickCapture={
            navCollapsed
              ? (e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  setNavCollapsed(false);
                }
              : undefined
          }
          onMouseEnter={navCollapsed ? tipEnter(session.user.name) : undefined}
          onMouseLeave={navCollapsed ? tipLeave : undefined}
        >
          <AccountMenu
            user={session.user}
            utility={utility}
            onSignOut={signOut}
            onSettings={setSettings}
          />
        </div>
      </aside>

      {/* Item 3 β€” the collapsed rail's hover tip: fixed beside the strip, outside the
          scrolling rail that would clip it, and pointer-transparent by standing rule. */}
      {navTip ? (
        <div
          className="shell-nav-tip"
          style={{ top: navTip.y }}
          role="tooltip"
          aria-hidden="true"
        >
          {navTip.label}
        </div>
      ) : null}

      <main className="shell-main">
        {/* ⭐ WAVE 30 (R5) β€” THE CONTENT-AREA BOUNDARY, and the reason it is HERE and not around
            the whole shell: the `<aside>` rail is its SIBLING, so a surface that throws leaves the
            navigation mounted and the user can walk away from the broken page instead of reloading
            a blank document. That is the difference the ticket's done-when is naming.
            ⚠ `key={route}` is load-bearing. A boundary LATCHES β€” once it holds an error it renders
            the panel until it is remounted β€” so without the key, navigating away from a failing
            database would carry its failure card onto every page afterwards. */}
        <ErrorBoundary key={route} surface={active?.label ?? "This page"}>
        {/* ⚠ An honest failure, never a fallback to the bundled sample. Behind
            a login, plausible-looking sample revenue is fabricated data on a
            screen the user has every reason to trust. */}
        {dataError && active?.kind === "native" ? (
          <div className="shell-placeholder">
            <h1>{active.label}</h1>
            <p>{dataError}</p>
            <button className="login-submit shell-retry" type="button" onClick={() => window.location.reload()}>
              Retry
            </button>
          </div>
        ) : active?.kind === "native" && ENVELOPE_KEYS.has(active.key) ? (
          // EXIT wave 2 β€” a Y1-envelope page. The KEY is the only thing that
          // varies: wave 3's Collections and Procurement come through this same
          // branch, which is the whole return on the envelope contract.
          <PageSurface key={active.key} pageKey={active.key} label={active.label} />
        ) : active?.kind === "native" && active.key === "automation" ? (
          // Wave 18 (C-AUTONAV): the Automation surface β€” its OWN secondary rail + editor,
          // props-free by contract (it fetches /api/v1/automations itself). SESSION D's tree.
          //
          // ⭐ WAVE 23 C13 (owner item 2), wiring W23-W1 β€” THE SAME FRAME AS EVERY DATABASE.
          //
          // This branch used to mount the surface BARE: no `shell-db-frame`, no `DbHead`. So
          // the one page in the product that is not a database was also the one page whose
          // name was drawn by its own component, at its own size and weight β€” three title
          // treatments (the surface's 16px/700 editable input, its 20px/600 empty-state h1,
          // and the frame's 16px/650 `shell-db-name`) against the grid's one. The fix is not
          // to restyle the stand-in but to delete the reason it exists: one title system,
          // owned by the shell, mounted here.
          //
          // ⚠ THE LABEL COMES OFF THE PAYLOAD, exactly as the rail's does (:1006). C13 words
          // it "label 'Automation'" and that IS `active.label` β€” the registry's literal, or a
          // tenant's `nav_meta` override of it. Hard-coding the word here would put the same
          // surface's name in two places and let them drift on the day someone renames it.
          //
          // β›” THE HEIGHT CHAIN. `.auto-surface` is `height: 100%`, so dropping it straight
          // into the frame's flex column would size it against the WHOLE frame and push its
          // rail a header's height below the fold. `.shell-auto-host` is the same `flex: 1 1
          // auto; min-height: 0` link `.shell-grid-host` is for glide β€” and it is the shell's
          // OWN class rather than a `.shell-db-frame > .auto-surface` rule, because
          // `.auto-*` is SESSION B's CSS region this wave and a frame has no business
          // reaching into its child's namespace to make itself fit.
          <div className="shell-db-frame">
            <DbHead
              label={active.label}
              glyph={<AutoIcon />}
              {...(active.icon ? { icon: active.icon } : {})}
            />
            <div className="shell-auto-host">
              <Lazily surface="Automation"><AutomationSurface /></Lazily>
            </div>
          </div>
        ) : active?.kind === "native" ? (
          // The native grid surfaces β€” ONE component, topic decided by the route. Wave 16:
          // the `#/cohort` route left with the cohort registry row (cohorts are LOCKED VIEWS
          // in the Customer rail, C-LOCK; `scope=cohort` stays a working server surface for
          // stored artifacts), and `#/product_data` arrived (C-TOPIC) β€” the same tree over
          // the SKU catalogue. The `key` forces a remount on a route change so one topic's
          // view state never bleeds into the other's. Wave 18 (C3-UT): a `ut_` route is a
          // USER TABLE through the same tree β€” scope IS the key β€” with the shell-owned
          // Add-record bar above it (the doc's amendment: zero CustomerGrid edits).
          // WAVE 20 item 4 (R8): ONE frame for every database. The old branch gave user
          // tables a header-plus-grid frame and the built-ins a bare grid, which is why
          // Customer and Product had nowhere to put a name.
          <div className="shell-db-frame">
            <DbHead
              label={active.label}
              {...(active.icon ? { icon: active.icon } : {})}
            />
            <div className="shell-grid-host">
              <OverlayProvider>
                <CustomerGrid
                  key={active.key}
                  scope={
                    active.key === "product_data"
                      ? "product"
                      : active.key.startsWith("ut_")
                        ? (active.key as `ut_${string}`)
                        : "customer"
                  }
                />
              </OverlayProvider>
            </div>
          </div>
        ) : active ? (
          <StranglerPage entry={active} />
        ) : route === CONNECTORS_ROUTE ? (
          // ⭐ WAVE 23 item 10 (R8, C11, wiring W23-W3) β€” the connectors directory.
          //
          // The one action the page cannot perform itself: a `manage: "keychain"` row opens
          // Settings on the Keychains tab, and the Settings MODAL is the frame's. Same division
          // as every other panel here β€” the page knows what it wants, the frame owns the door.
          <Lazily surface="Connectors"><ConnectorsPage onKeychain={() => setSettings("keychains")} /></Lazily>
        ) : route === INBOX_ROUTE ? (
          // ⭐⭐ W32-T04 (R7, C3, wirings 1+5) β€” THE INBOX MODULE. Same division as Connectors:
          // the module owns the QUESTION, the frame owns the DOOR.
          //
          // β›” `onOpenTarget` IS REQUIRED ON THE CALLEE, and that is a lesson written as a type.
          // An optional callback the frame forgot to pass degrades to "clicking an Inbox item
          // does nothing" β€” indistinguishable from "the feature was never built", and red in no
          // gate. Required means `tsc` fails the moment this is unmounted.
          <Lazily surface="Inbox">
            <InboxPage
              onInbox={setInbox}
              onToast={setToast}
              /* The frame has ALREADY fetched this β€” it is what painted the badge the user just
                 clicked β€” so the module opens knowing the count instead of asserting "Nothing
                 new." while its own read is in flight (W31-T23, measured 3,280 ms live). */
              seed={inbox}
              onOpenTarget={(t) => {
                // ⭐ C3's dispatch is DATA, not a branch: `inboxModel.routeForTarget` owns the
                // target→surface question, so this is a switch over two literals it can exhaust
                // rather than a second copy of the topic→route table.
                const dest = routeForTarget(t);
                if (!dest) {
                  // β›” AN UNKNOWN MODULE MUST SAY SO, NEVER SILENTLY DO NOTHING. It means this
                  // tab is older than the server that sent the notification; a reader who clicks
                  // and sees no change concludes the Inbox is broken rather than that they should
                  // reload. `inboxModel.routeForTarget`'s own docstring requires this half.
                  setToast("This notification points at something this version cannot open yet β€” reload to update.");
                  return;
                }
                // ⚠ THE ORDER IS LOAD-BEARING, and it is the old pane's rule kept verbatim: the
                // hash is set FIRST so the surface is mounting (or already mounted) when the
                // event arrives. Dispatching first fires into a route that does not exist yet.
                // `signal` is `apiContract`'s helper β€” the same channel those surfaces' own
                // listeners use β€” rather than a second hand-rolled `dispatchEvent` here.
                if (dest.surface === "automation") {
                  window.location.hash = "#/automation";
                  signal(AUTOMATION_OPEN_EVENT, { autoId: dest.autoId, tab: dest.tab });
                  return;
                }
                window.location.hash = `#/${dest.key}`;
                // β›”β›” W32 (ASK C-17) β€” A SINGLE EMIT HERE IS SILENTLY DISCARDED ON A COLD
                // CLICK, and that is item 19's own failure mode surviving item 19.
                // `CustomerGrid` guards its listener with `detail.topic !== scope` and
                // `!views.some(v => v.id === detail.viewId)` β€” both CORRECT (an alert outlives
                // its view; one grid must not react to another's event) β€” so an emit fired the
                // instant the hash changes lands on a grid that has not fetched its views yet,
                // is dropped, and there is NO ACK. The table opens, the view is not selected,
                // and the click "worked".
                // ⚠ The ladder is C's, already built and gated in their module (5 attempts over
                // 0–2,600 ms; a truthy `emit` ends it early, which VIEW_OPEN never returns, so
                // it simply runs out). Cancel any ladder still running from a previous click.
                if (dest.viewId) {
                  viewEmitCancel.current?.();
                  viewEmitCancel.current = retryEmit(() => {
                    signal(VIEW_OPEN_EVENT, { topic: dest.key, viewId: dest.viewId });
                  });
                }
              }}
            />
          </Lazily>
        ) : route === QUERY_ROUTE ? (
          // ⭐⭐ W32-T05 (R1, C5, wirings 2 and 6) β€” THE QUERY MODULE, where AI-built views live.
          //
          // β›” `granted` IS REQUIRED, AND IT IS ALSO WHAT MAKES THIS A LEGAL CHROME ROUTE. It is
          // the nav entries this shell ALREADY holds from `/nav` β€” the set the SERVER decided this
          // session may see β€” so the page makes no listing call of its own and *"a chrome route
          // renders nothing the server did not already grant"* is true by construction. The AI
          // therefore cannot name a database the caller was not already given: C5's permission
          // clause is the existing wall re-used, never a second one built beside it.
          <Lazily surface="Query"><QueryPage granted={entries} /></Lazily>
        ) : nav.phase === "ready" ? (
          // ⭐ WAVE 23 item 9 (R7, C10) β€” HOME, AND IT IS THE FALLBACK RATHER THAN A ROUTE MATCH.
          //
          // β›” WHY `!active` AND NOT `route === HOME_ROUTE`. Three states have to land here and
          // only one of them is the literal hash: `#/home`, an EMPTY hash, and a route that no
          // longer resolves (a deleted table, a stale bookmark, a hand-typed key). `resolveRoute`
          // already funnels all three to "no entry" now that `defaultRoute` returns a chrome
          // route, so testing the literal would have left the other two on the "Nothing to show"
          // branch β€” a shell that looks broken as the reward for deleting a database, which is
          // the exact failure `removeDatabase`'s own note warns about from the other side.
          //
          // ⚠ AND THIS BRANCH ABSORBED WAVE 18's TENANT HERO (R4), which used to live below.
          // That hero said "Welcome β€” this workspace has no databases yet" plus one create
          // button, on precisely the state Home now owns: a ready nav with zero entries. Leaving
          // both reachable would put two welcome messages on one screen, which is the defect the
          // rail's own note at the empty-nav line already documents. Home's four cards ARE the
          // hero's create door, and its empty line carries the hero's sentence (HomePage's
          // `home-empty`, which branches on `entries.length === 0` for exactly this reason).
          // Booked as a dated amendment in the wave doc, since it moves an R4 surface.
          <Lazily surface="Home">
            <HomePage
              // ⭐ `dbEntries`, NOT `entries` β€” found by LOOKING at it (wave 24 close-out visual
              // pass), which is the only way it could have been found. The Automation SURFACE is a
              // granted nav entry with an href, so `allDatabases` drew it a tile under the heading
              // "Databases" β€” beside an "Automations" section listing the things it contains. The
              // rail has excluded it since wave 19 R10 for exactly this reason (`dbEntries`, :1261);
              // Home was drawing the unfiltered list.
              // ⚠ STILL THE GRANTED NAV, so the C10 law is untouched: `dbEntries` is `entries` minus
              // one key, not a list this frame invented.
              entries={dbEntries}
              recents={recents}
              automations={autoTiles}
              // ⭐ WAVE 24 item 14 β€” the templates CARD is boarded. It opens the same
              // under-construction note the AI assistant uses, rather than the picker.
              // ⚠ The flyout's "From a template" row is UNAFFECTED (R9 keeps it working) β€” see
              // HomePage's own note on why that asymmetry is deliberate rather than a miss.
              onTemplates={() => setAssistOpen("templates")}
              onNewDatabase={() => openNewDb("blank")}
              /* β›” `onAutomated` LEFT WITH THE CARD IT OPENED (wave 25 item 5a, R8). */
              onConnectors={() => {
                window.location.hash = `#/${CONNECTORS_ROUTE}`;
              }}
              // The same two-part move every click-through in this frame makes: the frame owns the
              // hash, the surface owns which automation is selected. Route, then ASK.
              onOpenAutomation={(autoId) => {
                window.location.hash = "#/automation";
                signal(AUTOMATION_OPEN_EVENT, { autoId });
              }}
            />
          </Lazily>
        ) : nav.phase === "error" ? (
          // ⚠ WAVE 17 ITEM 4 (R6) β€” THE ERROR AND THE EMPTY ARE DIFFERENT SENTENCES, and this
          // branch is what keeps them apart. `active` resolves from `entries`, which is empty
          // while the nav is IN FLIGHT, so every first login used to land on a pane stating the
          // single worst thing this frame could say to a new user for as long as a round trip
          // took. WAVE 23 keeps that separation and simplifies its shape: `ready` now goes to
          // Home above (which welcomes an empty workspace properly), so this is only ever the
          // nav that FAILED, and the nested ternary that used to sort the two is gone.
          <div className="shell-placeholder">
            <h1>Nothing to show</h1>
            <p>The navigation service did not answer. Reload to retry.</p>
          </div>
        ) : (
          // Still asking (`loading`, or the `idle` beat before the effect runs).
          <div className="shell-loading">
            <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" />
          </div>
        )}
        </ErrorBoundary>
      </main>

      {/* The server's own confirmation of a write (X2's `toast`). In standalone
          it is the ONLY feedback for the events whose effect the payload does
          not yet echo back β€” cohort membership, list adds, folder moves. */}
      {/* Wave 18 (owner item 3): the assistant's boarded door. */}
      {assistOpen ? (
        <div className="shell-newdb-scrim" onClick={() => setAssistOpen(false)}>
          <div
            className="shell-newdb shell-assist-note"
            role="dialog"
            aria-label={assistOpen === "templates" ? "Templates" : "AI assistant"}
            onClick={(e) => e.stopPropagation()}
          >
            {assistOpen === "templates" ? (
              <>
                <h2>Templates</h2>
                <p className="shell-newdb-sub">
                  Under construction. Curated template sets are being built and will open here in
                  a later release.
                </p>
              </>
            ) : (
              <>
                <h2>
                  <SparkIcon /> AI assistant
                </h2>
                <p className="shell-newdb-sub">
                  Under construction. The assistant is being trained on this workspace's data
                  model and will open here in a later release.
                </p>
              </>
            )}
            <div className="shell-newdb-actions">
              <button type="button" className="login-submit" onClick={() => setAssistOpen(false)}>
                Close
              </button>
            </div>
          </div>
        </div>
      ) : null}

      {/* Wave 18 (C3-UT): the New-database dialog. Scrim click cancels unless mid-create. */}
      {newDb ? (
        <div
          className="shell-newdb-scrim"
          onClick={() => {
            if (!newDb.busy) setNewDb(null);
          }}
        >
          <div
            className="shell-newdb"
            role="dialog"
            aria-label="New database"
            onClick={(e) => e.stopPropagation()}
          >
            <h2>New database</h2>
            {/* ⭐ WAVE 23 C10 β€” THE CHOICE. One-line rows, not paragraphs: the explanation lives
                where the DECISION is made and stops there (R13). The dialog's old sub-line ("a
                blank database… nothing here connects to a source") said one of these things as if
                it were the only one, so it moved onto the row it actually describes.
                ⭐ WAVE 25 item 5a (R8) β€” IT WAS A THREE-WAY CHOICE AND THE THIRD ROW IS DELETED.
                Two rows now, and they are both genuinely modes of this dialog, which the third
                never was: "Automated" wore no `role="radio"` because it LEFT (see its own deleted
                note) β€” a row inside a `radiogroup` that could not be checked. R8 removes the
                option; the anomaly in its markup was the shape of the problem all along. */}
            <div className="shell-newdb-kinds" role="radiogroup" aria-label="What to create">
              <button
                type="button"
                role="radio"
                aria-checked={newDb.mode === "blank"}
                className={"shell-newdb-kind" + (newDb.mode === "blank" ? " is-on" : "")}
                disabled={newDb.busy}
                onClick={() => setNewDb({ ...newDb, mode: "blank", err: "" })}
              >
                <span className="shell-newdb-kind-name">Blank</span>
                <span className="shell-newdb-kind-detail">
                  An empty database β€” add fields and records once it opens.
                </span>
              </button>
              <button
                type="button"
                role="radio"
                aria-checked={newDb.mode === "template"}
                className={"shell-newdb-kind" + (newDb.mode === "template" ? " is-on" : "")}
                disabled={newDb.busy}
                onClick={() => setNewDb({ ...newDb, mode: "template", err: "" })}
              >
                <span className="shell-newdb-kind-name">From a template</span>
                <span className="shell-newdb-kind-detail">
                  Add a curated set of views to a database you already have.
                </span>
              </button>
            </div>
            {newDb.mode === "template" ? (
              // WAVE 23 C12 (wiring W23-W6) β€” the picker. It applies views to an EXISTING
              // database rather than making one, which is what a platform-curated template is:
              // a set of saved views, not a table (R10).
              <Lazily surface="Templates">
                <TemplatePicker
                  entries={dbEntries}
                  onToast={setToast}
                  onDone={(tableKey) => {
                    setNewDb(null);
                    window.location.hash = `#/${tableKey}`;
                  }}
                />
              </Lazily>
            ) : (
              <>
                <input
                  autoFocus
                  className="shell-newdb-input"
                  placeholder="Database name"
                  value={newDb.name}
                  maxLength={60}
                  disabled={newDb.busy}
                  onChange={(e) => setNewDb({ ...newDb, name: e.target.value })}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") void createDb();
                    if (e.key === "Escape" && !newDb.busy) setNewDb(null);
                  }}
                />
                {newDb.err ? <p className="shell-newdb-err">{newDb.err}</p> : null}
                <div className="shell-newdb-actions">
                  <button
                    type="button"
                    onClick={() => setNewDb(null)}
                    disabled={newDb.busy}
                  >
                    Cancel
                  </button>
                  <button
                    type="button"
                    className="login-submit"
                    onClick={() => void createDb()}
                    disabled={newDb.busy || !newDb.name.trim()}
                  >
                    {newDb.busy ? "Creating…" : "Create database"}
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      ) : null}

      {settings ? (
        <Lazily surface="Settings">
          <SettingsModal
            user={session.user}
            section={settings}
            onSection={setSettings}
            onClose={() => setSettings(null)}
            onUser={(u) => setSession({ phase: "authed", user: u })}
            // Wave 15 β€” the nav already holds a server-filtered {key: label} for
            // every surface this account may open, so "Your access" names its
            // restrictions in the words the rail uses rather than in registry
            // keys. Derived here rather than mapped in the modal so there is only
            // one place either door learns what a module is called.
            moduleLabels={Object.fromEntries(entries.map((e) => [e.key, e.label]))}
          />
        </Lazily>
      ) : null}

      {/* ⭐⭐ W32-T04 / R7 β€” THE ALERTS POP-UP PANE IS GONE, NOT HIDDEN. It was mounted here as
          a sibling of <main>; its surface is now the `#/inbox` route above. C's `W32-T21` deletes
          `AlertsPane.tsx` itself and retargets `verify_alerts.py` onto the module β€” this frame no
          longer imports it, which is the half that makes the file dead rather than merely unused
          ([[artifact-with-no-importer]]). */}

      {/* C-SHARE (items 18/23/26): the access editor β€” one dialog, three kinds. */}
      {shareFor ? (
        <ShareDialog
          kind={shareFor.kind}
          id={shareFor.id}
          label={shareFor.label}
          me={session.user.username}
          onClose={() => setShareFor(null)}
          onToast={setToast}
        />
      ) : null}

      {/* C-SCHEMA: the database schema drawer, over everything but the toast. */}
      {schemaFor ? (
        <SchemaDrawer schemaKey={schemaFor} onClose={() => setSchemaFor(null)} />
      ) : null}

      {toast ? (
        <div className="shell-toast" role="status" aria-live="polite">
          {toast}
        </div>
      ) : null}
    </div>
  );
}