File size: 79,711 Bytes
4cfab62
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
4cfab62
 
 
 
 
8873406
8cbc29f
dec006b
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
4cfab62
19b91ce
 
8cbc29f
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
19b91ce
 
 
8cbc29f
 
4cfab62
19aed6d
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e174d2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
 
 
 
4cfab62
 
 
82cdb59
 
 
ce9586e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
971c29d
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
ce9586e
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10ab9ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
10ab9ba
4cfab62
 
 
10ab9ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10ab9ba
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10ab9ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
19aed6d
 
4cfab62
19b91ce
 
8cbc29f
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
4cfab62
816fa8a
4cfab62
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
4cfab62
 
 
 
 
 
 
8873406
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19b91ce
8cbc29f
 
19aed6d
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
82cdb59
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
dec006b
 
 
8873406
dec006b
 
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
8cbc29f
c1fc133
2e7e617
 
 
 
 
 
 
c1fc133
dec006b
c1fc133
 
 
 
 
 
 
 
dec006b
c1fc133
 
 
 
 
 
 
 
 
8cbc29f
 
c1fc133
 
 
 
 
 
dec006b
 
c1fc133
 
4cfab62
 
 
 
 
 
 
 
 
 
89af3b2
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
89af3b2
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
4cfab62
c1fc133
4cfab62
 
ce9586e
4cfab62
 
 
 
 
89af3b2
82cdb59
 
 
 
c1fc133
82cdb59
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
89af3b2
 
82cdb59
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
 
4cfab62
 
ce9586e
4cfab62
ce9586e
82cdb59
4cfab62
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
4cfab62
 
 
 
 
 
 
 
 
 
8cbc29f
 
82cdb59
 
8cbc29f
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ---------------------------------------------------------------------------
// shell/nav.ts β€” X6: the shell's nav, shaped from `GET /api/v1/nav`.
//
// WHAT CHANGED, AND WHY IT MATTERS MORE THAN IT LOOKS. The wave-4 nav was a
// STATIC array in Shell.tsx β€” a hand-kept mirror of `core/registry.py` that
// nobody's build would notice going stale, and that showed every surface to
// everybody. It is now rendered from a SERVER-FILTERED payload: the API applies
// `may_open` (incl. `_LEGACY_KEYS` migration-on-read) and drops archived
// modules, so what a user sees IS what the server granted. Registry-driven at
// one end, permission-filtered at the other.
//
// ⚠ THERE IS NO CLIENT-SIDE FALLBACK LIST, deliberately. If `/api/v1/nav`
// fails or answers with a malformed envelope, the shell renders a bounded retry
// state, never a hard-coded list. A fallback would put surfaces on screen that
// the server never authorised, which is precisely the fail-closed rule the wave
// is built on ("an undeclared surface is denied"), and it would mask a broken API
// as a working one.
//
// No `import.meta` here either: `appBase` is a PARAMETER so this module
// compiles and runs under node in `verify_login.py` (see session.ts).
// ---------------------------------------------------------------------------

import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract";
import { APP_PATH_PREFIX, canonicalDataHash, decodeDataFilters } from "../customer-grid/dataPath";
import type { DataPath } from "../customer-grid/dataPath";
// ⚠ WAVE 19 R8 / C1 β€” the icon vocabulary is the GRID's, imported not redefined.
// A VALUE import (not type-only) because the whitelist has to exist at runtime:
// `FolderMark` indexes `FOLDER_SHAPE_PATHS[shape]` and maps the result, so one
// unrecognised shape off the wire is `undefined.map` β€” a white screen, from a
// stored preference. `customer-grid/types` imports only `./windows`, which
// imports nothing, so this stays runnable under plain node (verify_login
// compiles this module and executes it there β€” see the header note on
// `appBase` being a parameter for exactly that reason).
import { FOLDER_SHAPES, FOLDER_TONES } from "../customer-grid/types";
import type { FolderIcon } from "../customer-grid/types";

/** One entry of X2's nav payload. `source` is the registry's connector fact
 *  (wave-9 I8: "Sales Β· Odoo"); `parent` names a sub-module's family head. */
export interface NavPage {
  key: string;
  label: string;
  /** C1's injected system-table descriptor. The client displays it but never offers generic mutation. */
  managedBy?: "loopable";
  protected?: boolean;
  source?: string;
  /** Authoritative Data-rail grouping label (for example Odoo or Custom). */
  sourceGroup?: string;
  group?: string;
  sync?: { at: string | null; empty: boolean | null };
  parent?: string;
  /**
   * The registry's `group_only`: this key names a FOLDER, never a destination
   * (`customers` is the only one today β€” the head of customer_data + cohort).
   *
   * ⚠ ADDED BY S1 2026-07-30, additive, present only when true. It supersedes
   * the client's has-children DERIVATION, which stays as the fallback for a
   * payload that predates the flag: the registry knows this fact, and a client
   * re-deriving a fact the server holds is drift waiting to happen.
   */
  group_only?: boolean;
  /**
   * `core.perms.nav_pages`' placement flag: `'main'` is the module list,
   * `'utility'` is a live surface the HOST renders outside it (Analyst,
   * Settings, the Metric Dictionary). The payload has carried it since X6;
   * rendering utility rows in the main list was this client's own gap β€”
   * `nav_pages`' docstring says "the client places them where the host does".
   */
  chrome?: "main" | "utility";
  /**
   * WAVE 19 R8 / C1 β€” the mark this database wears, from the tenant-wide
   * `nav_meta` bucket. Absent β‡’ the default cylinder, which is every database
   * that has never been given one.
   *
   * ⚠ TENANT-WIDE, not per-user, and that is the whole difference between this
   * and `nav_prefs` two fields down. Folders and placement are one person's
   * arrangement of their own rail; an icon and a name are what the DATABASE is
   * called, and a workspace where two people call the same table different
   * things has no shared vocabulary to hold a conversation in.
   */
  icon?: FolderIcon;
  /**
   * WAVE 19 R14 β€” may THIS session change this row's icon (and, for a `ut_` key,
   * its name)? The SERVER answers, because it is the only end that can: the
   * client cannot see who created a user table.
   *
   * β›” FAIL-CLOSED BY ABSENCE, like every other flag on this payload. A row that
   * does not say `manage: true` offers no rename and no icon picker β€” and the
   * route re-checks regardless, so this is the courtesy half of "the client
   * hides, the server forbids", never the wall.
   */
  manage?: boolean;
  /**
   * WAVE 21 item 6 (ruling R3, contract C3) β€” may THIS session DELETE this
   * database?
   *
   * β›” A SEPARATE FLAG FROM `manage`, deliberately, and reusing that one would
   * have been the bug. `manage` rides `user_tables.may_open` β€” which R14 widened
   * to include everyone a table has been SHARED with (D-32, `user_tables.py:511`).
   * That is the right reach for renaming and re-iconing; it is far too wide for
   * a verb that destroys ten artifact families. R3 scopes delete to the CREATOR
   * or a tenant admin, so the server answers a second, narrower question and
   * this is where the answer lands.
   *
   * Absent β‡’ no, like every flag here. Connector-backed databases never carry
   * it (R3: "NO delete verb for connector-backed databases β€” Pause stays their
   * only off-switch"), so the entry is absent rather than refused.
   */
  canDelete?: boolean;
  /**
   * ⭐ WAVE 27 item 3 (contract C9) β€” IS THIS A **LOCKED DATABASE**?
   *
   * The owner's item-4 vocabulary, and it means exactly one thing (DESIGN.md Β§4, THE THREE
   * LOCKS): RECORDS cannot be added, deleted or edited β€” **FIELDS STILL CAN BE**. It is not
   * "read-only", and a UI that hid the add-field door on the strength of this flag would be a
   * defect, not caution.
   *
   * Answered server-side from `user_tables.records_mutable`'s own condition (`routes_nav.py`),
   * because the client cannot see a table's `recordMode`.
   *
   * ⚠ ABSENT β‡’ UNLOCKED, which is the OPPOSITE direction from `manage`/`canDelete` above and
   * is deliberate: those two gate CONTROLS, so absence must deny. This one draws a HINT beside a
   * name, while the real refusal is the route's 403. A store blip should cost a missing padlock,
   * never a control that silently disappears.
   */
  locked?: boolean;
  /**
   * ⭐⭐ WAVE 34 (ruling R1, contract C1) β€” HOW MANY RECORDS THIS DATABASE'S **IMPORTANT** VIEWS
   * RESOLVE TO.
   *
   * R1 moves the mark-important number OFF the view sidebar's header and INTO the database
   * navigation, and that move is what forces this onto the wire: the flyout has no grid, so the
   * client cannot compute it the way `CustomerGrid::importantTotal` does.
   *
   * β›” THE THREE FIELDS ARE NOT REDUNDANT AND `partial` IS THE LOAD-BEARING ONE. `marked` counts
   * VIEWS, `counted` counts RECORDS, and `partial` says at least one marked view could not be
   * counted at all. `/nav` holds a rows-free projection, so a FILTERED view is uncountable there
   * by construction; a sum that silently skipped those would be short by an unknown amount, which
   * is exactly the silent absence `D-205` exists to end, one level up.
   *
   * ⚠ PER USER, never tenant-wide. Views live in a per-database bucket split by username, so the
   * same database answers `{marked: 1, counted: 13}` for one account and `{marked: 0}` for
   * another. Measured on tenant #0: `leadership` vs `admin` on `customer_data`.
   *
   * ⚠ ABSENT means "not a database, or the server could not read its views" β€” the second case is
   * named in `degraded`, exactly like the `ut_*` merge. It does NOT mean zero: a database with
   * nothing marked ships `{marked: 0, counted: 0, partial: false}`, because a key a consumer has
   * to test for is a key a consumer forgets to test for.
   */
  important?: NavImportant;
}

/** C1's per-database important payload. See `NavPage.important` for why all three fields exist. */
export interface NavImportant {
  marked: number;
  counted: number;
  partial: boolean;
}

/**
 * The wire's important block, validated like every other flag on this payload: prune, never
 * invent. A malformed one reads as ABSENT, which renders no badge β€” the safe direction, because
 * the alternative is a confident number derived from junk.
 */
export function parseNavImportant(raw: unknown): NavImportant | undefined {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
  const r = raw as { marked?: unknown; counted?: unknown; partial?: unknown };
  const int = (v: unknown): number | null =>
    typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : null;
  const marked = int(r.marked);
  const counted = int(r.counted);
  if (marked === null || counted === null) return undefined;
  // `=== true`, the same strictness `manage`/`canDelete`/`locked` use: a drifted server sending a
  // truthy string must not turn a real count into a `+`.
  return { marked, counted, partial: r.partial === true };
}

/**
 * ⭐⭐ THE BADGE TEXT, AND IT IS ONE FUNCTION BECAUSE THERE ARE TWO CALLERS.
 *
 * A database row and a COLLAPSED FOLDER both draw this number, from different inputs (one entry's
 * block, a sum over a folder's members). Two renderers deciding "is there a number here" by their
 * own rules is [[one-question-two-normalizers]] with the answer on screen, so the rule lives here
 * and both call it.
 *
 * The four cases, and the third is the one the ticket calls out by name:
 *   Β· nothing marked        -> `null`. R1's own clause: NOT a zero. Most databases are this.
 *   Β· a real count          -> the number, plus `+` when at least one view could not be counted.
 *   Β· nothing countable     -> `"+"` ALONE. β›” NEVER `"0+"`: that string is `D-205` itself, the
 *                              thing the owner photographed, and rendering it here would be the
 *                              same defect moved into the nav. A bare `+` says "there is something
 *                              here we could not count" without claiming the something is zero.
 *   Β· a genuine zero        -> `"0"`. A marked view that matches no records is a fact worth
 *                              seeing, and it is distinguishable from the case above because
 *                              nothing was skipped.
 */
export function importantBadge(imp?: NavImportant): string | null {
  if (!imp || imp.marked <= 0) return null;
  if (imp.counted > 0) return `${imp.counted}${imp.partial ? "+" : ""}`;
  return imp.partial ? "+" : "0";
}

/**
 * The wire's icon, validated against the vocabulary the renderer can actually
 * draw. Anything unrecognised reads as ABSENT (the default mark) rather than as
 * an error: a stored preference is not worth a broken rail, and the server
 * applies the same whitelist on the way in, so a mismatch here means the two
 * ends have drifted β€” which shows up as an icon quietly reverting, the loudest
 * safe symptom available.
 */
export function parseNavIcon(raw: unknown): FolderIcon | undefined {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
  const r = raw as { shape?: unknown; tone?: unknown };
  if (!(FOLDER_SHAPES as readonly string[]).includes(String(r.shape))) return undefined;
  if (!(FOLDER_TONES as readonly string[]).includes(String(r.tone))) return undefined;
  return { shape: r.shape as FolderIcon["shape"], tone: r.tone as FolderIcon["tone"] };
}

/**
 * WAVE 20 item 4 (R8) β€” the class list for the universal database header's icon
 * chip: `shell-db-chip`, plus a tone modifier when the database wears a mark.
 *
 * R8 asks for "an icon chip on a bold colour background on EVERY database", and
 * that sentence hides a decision the JSX would otherwise bury: what colour does a
 * database that never chose one get? Three cases, and they are here rather than
 * inline so a gate can hold them (and so the answer is written once, not once per
 * render branch):
 *
 *   Β· no icon at all β€” every built-in and every un-styled table β€” takes the BASE
 *     chip, which the stylesheet paints in the brand primary. That is the
 *     "sensible default where unset" the ruling asks for, and it is why the base
 *     class carries a colour instead of leaving the chip transparent.
 *   Β· an icon takes its own TONE at the bold `-deep` weight, so the header agrees
 *     with the mark the same database wears in the rail.
 *   Β· an UNRECOGNISED tone falls back to the base, never `--unknown`: emitting a
 *     class no stylesheet defines would paint a chip with no background at all,
 *     and a white glyph on white is an invisible header. Same fail-safe posture
 *     as `parseNavIcon` above β€” a drifted vocabulary reverts to the default mark
 *     rather than breaking the frame.
 */
export function dbChipClass(icon?: FolderIcon): string {
  const base = "shell-db-chip";
  const tone = icon?.tone;
  if (!tone || !(FOLDER_TONES as readonly string[]).includes(tone)) return base;
  return `${base} ${base}--${tone}`;
}

/**
 * Read X2's `{pages:[…]}`. An entry with no key or no label is DROPPED rather
 * than rendered: a nav row with no name is a door with no sign on it, and
 * guessing the sign from the key would put an internal identifier in the UI.
 */
/** S78-T02: a nav row's sync stamp, `at` a string or null and `empty` a boolean or null. */
function isNavSync(value: unknown): value is { at: string | null; empty: boolean | null } {
  if (!value || typeof value !== "object") return false;
  const v = value as Record<string, unknown>;
  return (typeof v.at === "string" || v.at === null) &&
    (typeof v.empty === "boolean" || v.empty === null);
}

export function parsePages(body: unknown): NavPage[] {
  const raw = (body as { pages?: unknown } | null)?.pages;
  if (!Array.isArray(raw)) return [];
  const out: NavPage[] = [];
  for (const item of raw) {
    if (!item || typeof item !== "object") continue;
    const p = item as Record<string, unknown>;
    const key = typeof p.key === "string" ? p.key.trim() : "";
    const label = typeof p.label === "string" ? p.label.trim() : "";
    if (!key || !label) continue;
    out.push({
      key,
      label,
      ...(typeof p.source === "string" && p.source ? { source: p.source } : {}),
      ...(typeof p.sourceGroup === "string" && p.sourceGroup.trim()
        ? { sourceGroup: p.sourceGroup.trim() }
        : {}),
      ...(typeof p.group === "string" && p.group.trim() ? { group: p.group.trim() } : {}),
      ...(isNavSync(p.sync) ? { sync: { at: p.sync.at, empty: p.sync.empty } } : {}),
      ...(typeof p.parent === "string" && p.parent ? { parent: p.parent } : {}),
      ...(p.managedBy === "loopable" ? { managedBy: "loopable" as const } : {}),
      ...(p.protected === true ? { protected: true } : {}),
      ...(p.group_only === true ? { group_only: true } : {}),
      ...(p.chrome === "main" || p.chrome === "utility" ? { chrome: p.chrome } : {}),
      ...(parseNavIcon(p.icon) ? { icon: parseNavIcon(p.icon)! } : {}),
      ...(p.manage === true ? { manage: true } : {}),
      // C3 (W-5): read with the same `=== true` strictness as `manage` β€” a
      // truthy-but-not-true value from a drifted server must not open a delete.
      ...(p.canDelete === true ? { canDelete: true } : {}),
      // ⭐ WAVE 27 item 3 / C9 β€” same `=== true` strictness. A locked database is a padlock
      // beside a name, so a drifted server sending a truthy string must not paint one.
      ...(p.locked === true ? { locked: true } : {}),
      // ⭐⭐ WAVE 34 R1 / C1 β€” the important block, validated on the way in like the icon.
      ...(parseNavImportant(p.important) ? { important: parseNavImportant(p.important)! } : {}),
    });
  }
  return out;
}

/**
 * Split the payload by placement. `main` feeds `shapeNav`; `utility` rows are
 * placed where the host places them (the Analyst slot above the list, the rest
 * behind the account menu). An absent flag reads as `main` β€” a payload that
 * predates the flag keeps today's behaviour rather than losing rows.
 */
export function splitChrome(pages: NavPage[]): { main: NavPage[]; utility: NavPage[] } {
  const main: NavPage[] = [];
  const utility: NavPage[] = [];
  for (const p of pages) (p.chrome === "utility" ? utility : main).push(p);
  return { main, utility };
}

/**
 * WAVE 23 (C10 / R7) β€” one entry of the Home landing's recents.
 *
 * `at` is EPOCH SECONDS, and the type says so because the alternative bit this product once:
 * a formatted naive-local stamp read by a browser in another zone (D-18). An integer instant
 * has one reading everywhere, and the two things Home renders from it β€” "Opened N minutes ago"
 * and the Today / Past 7 days / Older bucket β€” are both statements about THE READER'S OWN
 * CLOCK, which is the one case where using it is correct rather than forbidden (contrast
 * `alertsModel.stampText`, which must NOT touch a clock because it re-states a server event).
 */
export interface Recent {
  key: string;
  at: number;
}

/** `empty` (wave 18): the SERVER's reason for an empty page list. `"no_databases"` means a
 *  freshly provisioned tenant with no modules and no databases YET β€” a legitimate starting
 *  state, not a broken account. Absent means "no reason given", which the shell reads as the
 *  misconfigured-account case it always did. Distinguishing them is what stops the rail saying
 *  "no surfaces are available" beside a hero saying "welcome, create your first database". */
export type NavResult =
  | {
      ok: true;
      pages: NavPage[];
      recents: Recent[];
      empty?: string;
      /**
       * ⭐ W31-T11 (owner item 6b) β€” REGISTRY KEYS THIS WORKSPACE'S CATALOGUE DOES NOT INCLUDE.
       *
       * A DELIBERATE absence. Every provisioned tenant carries a restricted `modules` list
       * (`gtmlab`/`loopable`/`nurilab` are all `['analyst','automation']`), so this is normal and
       * the rail draws nothing for these keys β€” as it always has. The value of naming them is
       * that it makes the OTHER absence distinguishable.
       */
      omitted?: string[];
      /**
       * β›” W31-T11 β€” PARTS OF THIS PAYLOAD THE SERVER COULD NOT READ.
       *
       * `["databases"]` means the `ut_*` merge raised and every database is missing from a
       * **200 OK**. Before this the two absences were identical on the wire and the shell
       * rendered `null` for both β€” which is pixel-identical to still-loading, with no timeout on
       * `fetchNav` at all. That is the owner's *"Connectors and Automation still disappear"*
       * report: not a permission bug, an unmarked failure.
       */
      degraded?: string[];
    }
  | { ok: false; status: number };

/**
 * A conditional module's settled rail state. `absent` means the server completed
 * navigation and did not grant or provide that module; it is intentionally not
 * a visual placeholder. `unavailable` remains visible because the navigation
 * response is incomplete and silence would falsely claim the module is absent.
 */
export type RailSlot = "row" | "unavailable" | "absent";

/**
 * Whether a conditional rail section has any visible module row. This is kept
 * beside the nav contract so layout can decide from settled slot state before
 * it renders separators; a known-absent module must not reserve rail geometry.
 */
export function hasVisibleRailSlot(slots: ReadonlyArray<RailSlot>): boolean {
  return slots.some((slot) => slot !== "absent");
}

/**
 * How long the shell waits for `/nav` before calling it unavailable.
 *
 * β›” THE POINT IS NOT SPEED, IT IS THAT `phase:"loading"` CAN END. `fetchNav` had no
 * `AbortSignal`, no deadline and no retry, so a request that never resolved left a rail that
 * looked *almost* complete β€” the four static rows plus a spinner β€” for ever, and the owner read
 * that screen as modules disappearing. **20 seconds is chosen to sit ABOVE the measured worst
 * case, not near it**: `/nav` measured a 9.5–14.0 s band on tenant #0 before W31-T10, so a
 * shorter deadline would have converted a slow success into a manufactured failure. It is a
 * backstop for "never", not a performance budget.
 */
export const NAV_TIMEOUT_MS = 20_000;

/** Initial request plus two quiet retries before the shell offers manual recovery. */
export const NAV_ATTEMPTS = 3;
export const NAV_RETRY_DELAYS_MS = [1000, 3000];

/** Our encoding for "the deadline passed", distinct from 0 (transport) and any HTTP status. */
export const NAV_TIMEOUT_STATUS = -1;

/** Our encoding for "the server answered, but not with a readable navigation envelope". */
export const NAV_MALFORMED_STATUS = -2;

/** Record one timed-out attempt without letting telemetry interrupt navigation recovery. */
export function reportNavTimeout(elapsedMs: number, attempt: number): void {
  try {
    const message = "nav_timeout " + JSON.stringify({ elapsed_ms: Math.round(elapsedMs), attempt });
    void fetch(`${API_V1}/client-error`, {
      method: "POST",
      credentials: CREDENTIALS,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ message, componentStack: "" }),
    }).catch(() => undefined);
  } catch {
    // Navigation recovery must survive a failed reporter too.
  }
}

/**
 * A readable nav envelope has a pages list whose every destination carries a nonblank key and
 * label. Optional decoration on a valid destination may still be pruned by `parsePages`, but a
 * malformed destination cannot disappear into a confident partial rail. An empty list remains
 * valid because a newly provisioned tenant can legitimately have no destinations yet.
 */
export function isReadableNavEnvelope(body: unknown): boolean {
  if (!body || typeof body !== "object" || Array.isArray(body)) return false;
  const raw = (body as { pages?: unknown }).pages;
  if (!Array.isArray(raw)) return false;
  return raw.every((item) => {
    if (!item || typeof item !== "object" || Array.isArray(item)) return false;
    const page = item as { key?: unknown; label?: unknown };
    return typeof page.key === "string" && !!page.key.trim()
      && typeof page.label === "string" && !!page.label.trim();
  });
}

/**
 * `{recents:[…]}` β†’ the list, fail-closed. An entry with no key or an unreadable stamp is
 * DROPPED rather than rendered at the epoch, which would file it under "Older" for ever and
 * put a tile on Home for something nobody opened.
 */
export function parseRecents(body: unknown): Recent[] {
  const raw = (body as { recents?: unknown } | null)?.recents;
  if (!Array.isArray(raw)) return [];
  const out: Recent[] = [];
  for (const item of raw) {
    if (!item || typeof item !== "object") continue;
    const r = item as Record<string, unknown>;
    const key = typeof r.key === "string" ? r.key.trim() : "";
    const at = typeof r.at === "number" && isFinite(r.at) ? Math.floor(r.at) : 0;
    if (!key || at <= 0) continue;
    out.push({ key, at });
  }
  return out;
}

/**
 * WAVE 23 (C10) β€” stamp a page as opened. FIRE AND FORGET, by design.
 *
 * β›” IT RETURNS `void` AND SWALLOWS EVERYTHING. A recents stamp is the least important write in
 * the product: it decorates a landing page. Nothing the user is doing may wait on it, and no
 * failure of it may reach a screen β€” a toast saying "we could not record that you opened this
 * table" is noise about a feature nobody asked for, printed over the table they successfully
 * opened. The server answers 503 honestly when the store is down; this end simply does not
 * care, which is the only correct posture for telemetry-shaped state.
 */
export function postOpened(key: string): void {
  if (!key) return;
  void fetch(`${API_V1}/nav/opened`, {
    method: "POST",
    credentials: CREDENTIALS,
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ key }),
  }).catch(() => {});
}

/**
 * X2 `GET /api/v1/nav`. `status` rides the failure so the caller can tell the
 * two apart that must not be conflated: **401 means the session is gone** (drop
 * to the login screen), anything else means the nav is unavailable (stay signed
 * in, say so). `status: 0` is our encoding for a transport failure, as in
 * session.ts.
 */
export function parseKeyList(raw: unknown): string[] {
  if (!Array.isArray(raw)) return [];
  const out: string[] = [];
  for (const k of raw) if (typeof k === "string" && k.trim()) out.push(k.trim());
  return out;
}

export async function fetchNav(timeoutMs: number = NAV_TIMEOUT_MS): Promise<NavResult> {
  // ⚠ `setTimeout` + `AbortController`, not `AbortSignal.timeout` β€” the latter is unavailable in
  // the plain-node context `verify_login.py` compiles and RUNS this module in (see the header
  // note on `appBase` being a parameter for exactly that reason). A helper that throws on import
  // in the gate's environment is a helper that silently stops being tested.
  const ctl = typeof AbortController === "function" ? new AbortController() : null;
  let timedOut = false;
  let timer: ReturnType<typeof setTimeout> | null = null;
  // β›” THE DEADLINE IS A RACE, NOT ONLY AN ABORT β€” and this is the shape a probe found the hour
  // it was written. Aborting the request tells the TRANSPORT to stop; it does not, on its own,
  // make this function's promise settle. A `fetch` that ignores its signal therefore leaves the
  // caller awaiting for ever, which is precisely the state the deadline exists to end: the shell
  // would sit in `phase:"loading"` exactly as it did before, with an abort controller in the
  // source to prove it had been handled ([[flag-shipped-without-its-writer]]). Racing settles
  // this promise whatever the transport does, and the abort still fires so the request is not
  // left running behind it.
  const deadline =
    timeoutMs > 0
      ? new Promise<null>((resolve) => {
          timer = setTimeout(() => {
            timedOut = true;
            ctl?.abort();
            resolve(null);
          }, timeoutMs);
        })
      : null;
  try {
    const call = fetch(`${API_V1}/nav`, {
      credentials: CREDENTIALS,
      ...(ctl ? { signal: ctl.signal } : {}),
    });
    const res = deadline ? await Promise.race([call, deadline]) : await call;
    if (res === null) return { ok: false, status: NAV_TIMEOUT_STATUS };
    if (!res.ok) return { ok: false, status: res.status };
    let body: unknown;
    try {
      // Headers and body share one deadline, including transports that ignore abort.
      const read = res.json();
      body = deadline ? await Promise.race([read, deadline]) : await read;
      if (timedOut) return { ok: false, status: NAV_TIMEOUT_STATUS };
    } catch (error) {
      if (timedOut || (error as { name?: unknown } | null)?.name === "AbortError") {
        return { ok: false, status: NAV_TIMEOUT_STATUS };
      }
      return { ok: false, status: NAV_MALFORMED_STATUS };
    }
    if (!isReadableNavEnvelope(body)) {
      return { ok: false, status: NAV_MALFORMED_STATUS };
    }
    const envelope = body as { empty?: unknown; omitted?: unknown; degraded?: unknown };
    const empty = typeof envelope.empty === "string" ? envelope.empty : undefined;
    const omitted = parseKeyList(envelope.omitted);
    const degraded = parseKeyList(envelope.degraded);
    return {
      ok: true,
      pages: parsePages(body),
      recents: parseRecents(body),
      ...(empty ? { empty } : {}),
      ...(omitted.length ? { omitted } : {}),
      ...(degraded.length ? { degraded } : {}),
    };
  } catch {
    // The deadline has its own status so the shell can record timed-out attempts separately
    // from transport failures while both take the same quiet retry path.
    return { ok: false, status: timedOut ? NAV_TIMEOUT_STATUS : 0 };
  } finally {
    if (timer !== null) clearTimeout(timer);
  }
}

// ── C-SCHEMA (wave 2026-08-02): per-user folders over the database list ─────────────────────

export interface NavFolder {
  id: string;
  name: string;
}

/** Per-user, cosmetic, server-validated β€” placement never grants or hides a surface. */
export interface NavPrefs {
  folders: NavFolder[];
  placement: Record<string, string>;
}

export const EMPTY_NAV_PREFS: NavPrefs = { folders: [], placement: {} };
export const MAX_NAV_FOLDERS = 16;

/** Mirror of the server's `_clean_nav_prefs` pruning (minus the page-key check β€” the client
 *  prunes against folders only; a stale page key is harmless and drops on the next save). */
export function parseNavPrefs(body: unknown): NavPrefs {
  const raw = (body as { prefs?: unknown } | null)?.prefs ?? body;
  if (!raw || typeof raw !== "object") return EMPTY_NAV_PREFS;
  const p = raw as { folders?: unknown; placement?: unknown };
  const folders: NavFolder[] = [];
  const seen = new Set<string>();
  if (Array.isArray(p.folders)) {
    for (const f of p.folders.slice(0, MAX_NAV_FOLDERS)) {
      if (!f || typeof f !== "object") continue;
      const id = String((f as NavFolder).id ?? "").trim().slice(0, 40);
      const name = String((f as NavFolder).name ?? "").trim().replace(/\s+/g, " ").slice(0, 40);
      if (!id || seen.has(id) || !name) continue;
      seen.add(id);
      folders.push({ id, name });
    }
  }
  const placement: Record<string, string> = {};
  if (p.placement && typeof p.placement === "object") {
    for (const [k, v] of Object.entries(p.placement as Record<string, unknown>)) {
      const fid = String(v ?? "").slice(0, 40);
      if (k && seen.has(fid)) placement[k.slice(0, 60)] = fid;
    }
  }
  return { folders, placement };
}

export async function fetchNavPrefs(): Promise<NavPrefs> {
  try {
    const res = await fetch(`${API_V1}/nav/prefs`, { credentials: CREDENTIALS });
    if (!res.ok) return EMPTY_NAV_PREFS;
    return parseNavPrefs(await res.json());
  } catch {
    return EMPTY_NAV_PREFS;
  }
}

/** Wholesale replace, like the table folder stratum. Resolves false on any failure so the
 *  caller can revert its optimistic copy and say so. */
export async function saveNavPrefs(prefs: NavPrefs): Promise<boolean> {
  try {
    const res = await fetch(`${API_V1}/nav/prefs`, {
      method: "POST",
      credentials: CREDENTIALS,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(prefs),
    });
    return res.ok;
  } catch {
    return false;
  }
}

// ── WAVE 19 R8 / C1: `nav_meta` β€” the TENANT-WIDE name + icon overrides ────────────────────

/** One database's overrides. `name` is `ut_*`-only and the SERVER enforces that
 *  (a built-in label is a compiled registry literal); `icon` rides every key. */
export interface NavMetaPatch {
  icon?: FolderIcon | null;
  name?: string;
}

/**
 * `POST /api/v1/nav/meta`. A PATCH of ONE key, not a wholesale replace β€” the
 * opposite posture to `saveNavPrefs` above, and deliberately so. Prefs are one
 * user's complete picture of their own rail, so replacing it whole is how a
 * deleted folder stays deleted. `nav_meta` is TENANT-WIDE and every admin edits
 * the same document: sending a whole picture there means the last writer erases
 * whatever the previous one named while their tab was open. Explicit `null`
 * clears the icon; an absent field is untouched, which is what makes a
 * rename-and-an-icon two independent writes instead of a race.
 *
 * Resolves false on any failure so the caller reverts its optimistic copy and
 * says so, rather than leaving a name on screen that the store never took.
 */
export async function saveNavMeta(key: string, patch: NavMetaPatch): Promise<boolean> {
  try {
    const res = await fetch(`${API_V1}/nav/meta`, {
      method: "POST",
      credentials: CREDENTIALS,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ key, ...patch }),
    });
    return res.ok;
  } catch {
    return false;
  }
}

// ───────────────────────────── WAVE 21 item 6 (R3, contract C3): delete a database
/**
 * What deleting this database would actually destroy.
 *
 * β›” EVERY FIELD IS A COUNT THE USER CAN ACT ON, which is the whole reason the
 * confirm face exists. R3: "Confirm dialog discloses the footprint (rows/fields/
 * views/shared users/bound automations) before DELETE." A dialog that said only
 * "are you sure?" would be asking about a thing whose size nobody can see β€” and
 * the thing that makes a user-table delete different from a view delete is that
 * nine other artifact families go with it (cohorts, comments, docs + their
 * dataset bytes, asset refs, grants, nav meta, alerts, automations).
 *
 * `automations` are NAMED, not counted, and that asymmetry is deliberate: they
 * are the only footprint entry that keeps existing after the delete (C3 pauses
 * them and stamps "target deleted" rather than removing them), so the user has
 * to be able to go and find them.
 */
export interface TableFootprint {
  rows: number;
  fields: number;
  views: number;
  sharedUsers: number;
  automations: { id: string; name: string }[];
}

const intOf = (v: unknown): number =>
  typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0;

/**
 * `GET /api/v1/tables/{key}/footprint` (C3, A serves).
 *
 * Returns null when the server would not or could not answer. The caller shows
 * the confirm face WITHOUT counts in that case rather than substituting zeros:
 * "0 rows" is a specific, checkable claim about the user's data, and inventing
 * it to keep a dialog tidy is the fabrication this repo's counts rule forbids
 * ([[no-unverifiable-aggregates]]).
 */
export async function fetchTableFootprint(key: string): Promise<TableFootprint | null> {
  try {
    const res = await fetch(`${API_V1}/tables/${encodeURIComponent(key)}/footprint`, {
      credentials: CREDENTIALS,
    });
    if (!res.ok) return null;
    const raw = (await res.json()) as Record<string, unknown> | null;
    if (!raw || typeof raw !== "object") return null;
    const autos: { id: string; name: string }[] = [];
    for (const item of Array.isArray(raw.automations) ? raw.automations : []) {
      if (!item || typeof item !== "object") continue;
      const a = item as Record<string, unknown>;
      const id = typeof a.id === "string" ? a.id : String(a.id ?? "");
      const name = typeof a.name === "string" && a.name.trim() ? a.name.trim() : id;
      if (id) autos.push({ id, name });
    }
    return {
      rows: intOf(raw.rows),
      fields: intOf(raw.fields),
      views: intOf(raw.views),
      sharedUsers: intOf(raw.sharedUsers),
      automations: autos,
    };
  } catch {
    return null;
  }
}

/**
 * `DELETE /api/v1/tables/{key}` (C3). The route has existed since wave 18 with
 * NO client caller at all β€” this is that caller.
 *
 * Resolves the server's own message on failure so the rail can say why, and
 * `true` only on a 2xx. The nav is refetched by the caller either way: a delete
 * that half-succeeded server-side must not leave a row on screen whose absence
 * is the only evidence anything happened.
 */
export async function deleteTable(key: string): Promise<{ ok: boolean; error?: string }> {
  try {
    const res = await fetch(`${API_V1}/tables/${encodeURIComponent(key)}`, {
      method: "DELETE",
      credentials: CREDENTIALS,
    });
    if (res.ok) return { ok: true };
    let detail = "";
    try {
      const body = (await res.json()) as { detail?: unknown; error?: unknown } | null;
      const d = body?.detail ?? body?.error;
      if (typeof d === "string") detail = d;
    } catch {
      /* a non-JSON error body is not itself an error worth surfacing */
    }
    return { ok: false, error: detail || `The server answered ${res.status}.` };
  } catch {
    return { ok: false, error: "Cannot reach the server." };
  }
}

/** One rendered row of the folded nav: a folder head, or an entry (optionally inside one).
 *
 *  ⚠ `count` and `important` are DIFFERENT NUMBERS and neither is a version of the other.
 *  `count` is how many BLOCKS the folder holds (a top-level entry plus its depth-1 children counts
 *  as one), which is the number that has been drawn beside a folder name since wave 14.
 *  `important` is R1's aggregate over its members' record counts. Putting them in one slot would
 *  make a folder head say "3" and mean two different things depending on whether anything inside
 *  it was ever marked. */
export type NavRow =
  | {
      kind: "folder";
      folder: NavFolder;
      count: number;
      open: boolean;
      important?: NavImportant;
    }
  | { kind: "entry"; entry: NavEntry; folderId?: string };

/**
 * Fold the shaped entries under the user's folders. A BLOCK (a top-level entry plus its
 * depth-1 children) moves as one unit β€” filing a family head files the family. Folders render
 * in prefs order first, loose blocks after in registry order; a folder with no members still
 * renders (it was just created β€” it must exist on screen to receive its first member).
 * A closed folder contributes only its head row.
 */
export function foldNav(
  entries: NavEntry[],
  prefs: NavPrefs,
  closed: ReadonlySet<string>
): NavRow[] {
  interface Block {
    head: NavEntry;
    children: NavEntry[];
  }
  const blocks: Block[] = [];
  for (const e of entries) {
    if (e.depth > 0 && blocks.length > 0) blocks[blocks.length - 1].children.push(e);
    else blocks.push({ head: e, children: [] });
  }
  const byFolder = new Map<string, Block[]>();
  const loose: Block[] = [];
  const ids = new Set(prefs.folders.map((f) => f.id));
  for (const b of blocks) {
    const fid = prefs.placement[b.head.key];
    if (fid && ids.has(fid)) {
      const list = byFolder.get(fid);
      if (list) list.push(b);
      else byFolder.set(fid, [b]);
    } else {
      loose.push(b);
    }
  }
  const out: NavRow[] = [];
  const emit = (b: Block, folderId?: string) => {
    out.push({ kind: "entry", entry: b.head, ...(folderId ? { folderId } : {}) });
    for (const c of b.children)
      out.push({ kind: "entry", entry: c, ...(folderId ? { folderId } : {}) });
  };
  // ⭐⭐ WAVE 34 R1 / C1 β€” a COLLAPSED folder carries the SUM of its members' numbers.
  //
  // β›” SUMMED FROM THE SAME `members` ARRAY THAT PRODUCES `count`, in the same pass, and that is
  // the whole correctness of it. The alternative β€” a second lookup in `Shell.tsx` keyed off
  // `dbEntries` β€” would derive the number from one list while the rows came from another, which is
  // the defect `shell.test.ts` already pins for `count` ("a folder whose only member was filtered
  // out counts 0, not 1"). It bites hardest during SEARCH, when the caller passes
  // `EMPTY_NAV_PREFS` and no folder renders at all.
  //
  // ⚠ CHILDREN CONTRIBUTE. A block is a head plus its depth-1 children, and a child is its own
  // database with its own marked views, so the head's number would be short without them.
  const aggregate = (blocks: Block[]): NavImportant | undefined => {
    let marked = 0;
    let counted = 0;
    let partial = false;
    for (const b of blocks) {
      for (const e of [b.head, ...b.children]) {
        if (!e.important) continue;
        marked += e.important.marked;
        counted += e.important.counted;
        partial = partial || e.important.partial;
      }
    }
    return marked > 0 ? { marked, counted, partial } : undefined;
  };
  for (const f of prefs.folders) {
    const members = byFolder.get(f.id) ?? [];
    const open = !closed.has(f.id);
    // β›” ONLY WHEN CLOSED. An open folder shows its members' own numbers directly underneath, so a
    // head number there would be the same records counted twice on one screen β€” the ticket's
    // "an expanded one does not double-count", enforced at the source rather than in the renderer.
    const imp = open ? undefined : aggregate(members);
    out.push({ kind: "folder", folder: f, count: members.length, open,
               ...(imp ? { important: imp } : {}) });
    if (open) for (const b of members) emit(b, f.id);
  }
  for (const b of loose) emit(b);
  return out;
}

// ── C-SCHEMA: the schema drawer payload ─────────────────────────────────────────────────────

export interface SchemaField {
  key: string;
  label: string;
  type: string;
  source: string;
  description: string;
  options?: string[];
}

/** One field a database editor may use for one half of a Map coordinate pair. */
export interface SchemaMapField {
  key: string;
  label: string;
  type: string;
}

/** Database-owned Map setup, served alongside the schema rather than a saved View. */
export interface SchemaMapSetup {
  canConfigure: boolean;
  fields: SchemaMapField[];
  latField?: string;
  lonField?: string;
  /** Prerelease compatibility only; new setup saves the explicit pair above. */
  coordField?: string;
}

export interface SchemaPayload {
  key: string;
  label: string;
  source: string;
  fields: SchemaField[];
  measures: { key: string; label: string; type: string }[];
  map: SchemaMapSetup;
  note?: string;
}

function parseSchemaMap(raw: unknown): SchemaMapSetup {
  const source = raw && typeof raw === "object" ? raw as Record<string, unknown> : {};
  const fields: SchemaMapField[] = [];
  if (Array.isArray(source.fields)) {
    for (const field of source.fields) {
      if (!field || typeof field !== "object") continue;
      const f = field as Record<string, unknown>;
      if (typeof f.key !== "string" || !f.key) continue;
      fields.push({
        key: f.key,
        label: typeof f.label === "string" && f.label ? f.label : f.key,
        type: String(f.type ?? ""),
      });
    }
  }
  return {
    canConfigure: source.canConfigure === true,
    fields,
    ...(typeof source.coordField === "string" && source.coordField
      ? { coordField: source.coordField }
      : {}),
    ...(typeof source.latField === "string" && source.latField
      ? { latField: source.latField }
      : {}),
    ...(typeof source.lonField === "string" && source.lonField
      ? { lonField: source.lonField }
      : {}),
  };
}

export function parseSchema(body: unknown): SchemaPayload | null {
  if (!body || typeof body !== "object") return null;
  const b = body as Record<string, unknown>;
  if (typeof b.key !== "string" || typeof b.label !== "string") return null;
  const fields: SchemaField[] = [];
  if (Array.isArray(b.fields)) {
    for (const f of b.fields) {
      if (!f || typeof f !== "object") continue;
      const r = f as Record<string, unknown>;
      if (typeof r.key !== "string" || typeof r.label !== "string") continue;
      fields.push({
        key: r.key,
        label: r.label,
        type: String(r.type ?? ""),
        source: String(r.source ?? ""),
        description: String(r.description ?? ""),
        ...(Array.isArray(r.options) ? { options: r.options.map(String) } : {}),
      });
    }
  }
  const measures: SchemaPayload["measures"] = [];
  if (Array.isArray(b.measures)) {
    for (const m of b.measures) {
      if (!m || typeof m !== "object") continue;
      const r = m as Record<string, unknown>;
      if (typeof r.key !== "string" || !r.key) continue;
      measures.push({ key: r.key, label: String(r.label ?? r.key), type: String(r.type ?? "") });
    }
  }
  return {
    key: b.key,
    label: b.label,
    source: String(b.source ?? ""),
    fields,
    measures,
    map: parseSchemaMap(b.map),
    ...(typeof b.note === "string" && b.note ? { note: b.note } : {}),
  };
}

export async function fetchSchema(key: string): Promise<SchemaPayload | null> {
  try {
    const res = await fetch(`${API_V1}/nav/schema/${encodeURIComponent(key)}`, {
      credentials: CREDENTIALS,
    });
    if (!res.ok) return null;
    return parseSchema(await res.json());
  } catch {
    return null;
  }
}

/** Persist one database's Map coordinate pair; two absent keys restore built-in `lat`/`lon`. */
export async function saveSchemaMap(
  key: string,
  latField: string | undefined,
  lonField: string | undefined,
): Promise<SchemaMapSetup | null> {
  try {
    const res = await fetch(`${API_V1}/nav/schema/${encodeURIComponent(key)}/map`, {
      method: "PUT",
      credentials: CREDENTIALS,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ latField: latField || null, lonField: lonField || null }),
    });
    if (!res.ok) return null;
    const body = await res.json() as { map?: unknown } | null;
    if (!body || !("map" in body)) return null;
    return parseSchemaMap(body.map);
  } catch {
    return null;
  }
}

/**
 * What the shell does with an entry:
 *   native   β€” this tree renders it (a hash route)
 *   handoff  β€” a labelled link into the current application (`?page=<key>`)
 *   group    β€” a FOLDER head, not a destination: a label row, never a link
 */
export type NavKind = "native" | "handoff" | "group";

export interface NavEntry {
  key: string;
  label: string;
  managedBy?: "loopable";
  protected?: boolean;
  source?: string;
  /** Server-authored Data-rail group; kept separate from the descriptive source badge. */
  sourceGroup?: string;
  group?: string;
  sync?: { at: string | null; empty: boolean | null };
  kind: NavKind;
  /** 0 = top level, 1 = a sub-module rail entry (indented, like the app's rail). */
  depth: number;
  /** Absent for a group head β€” there is nowhere to go. */
  href?: string;
  /** WAVE 19 R8 β€” the tenant's chosen mark; absent β‡’ the default cylinder. */
  icon?: FolderIcon;
  /** WAVE 19 R14 β€” the server's answer to "may this session rename/re-icon it".
   *  Absent β‡’ no, and the route refuses independently. */
  manage?: boolean;
  /** WAVE 21 R3/C3 β€” the server's answer to "may this session DELETE it": the
   *  CREATOR or an admin, never the whole `may_open` set `manage` rides on (see
   *  the long note on `NavPage.canDelete`). Absent β‡’ no. */
  canDelete?: boolean;
  /** ⭐ WAVE 27 item 3 / C9 β€” a LOCKED database: no new records, fields still fine (see the
   *  long note on `NavPage.locked`). Absent β‡’ unlocked. */
  locked?: boolean;
  /** ⭐⭐ WAVE 34 R1 / C1 β€” the mark-important counts (see the long note on `NavPage.important`).
   *  THE SECOND HALF of that flag, and it is here for the reason `canDelete` and `locked` are:
   *  a value parsed onto the payload and dropped in `shapeNav` reaches no row anybody renders,
   *  which is precisely how wave 20 shipped four wirings that went nowhere. */
  important?: NavImportant;
  /**
   * ⭐ WAVE 25 (D-54) β€” THIS ROW IS A SURFACE, NOT A DATABASE.
   *
   * Absent β‡’ it is a database (or a folder head over some). Set by `shapeNav` from
   * `SURFACE_KEYS`, so the fact is decided ONCE, where rows are built, rather than
   * re-derived by every consumer that happens to remember.
   *
   * β›” THE DEBT THIS CLOSES IS NOT "Home had a bug", it is that the FILTER WAS A
   * LOCAL EXPRESSION. The rail has excluded Automation since wave 19 R10 with an
   * inline `entries.filter(e => e.key !== "automation")`; Home was written against
   * the raw list a wave later and drew the Automation SURFACE a tile under the
   * heading "Databases", beside an "Automations" section listing what it contains.
   * No gate could see it β€” rendering a tile per granted entry is exactly what that
   * code was asked to do. A rule every consumer must remember is not a control
   * ([[rules-need-gates]]), so it became a property of the row plus one accessor.
   */
  surface?: true;
}

/**
 * Granted nav rows that are NOT databases.
 *
 * ⚠ A CLIENT CAPABILITY FACT, NOT A PERMISSION ONE, exactly like `NATIVE_KEYS` two
 * screens down: the server decides what this account may open, and this decides
 * which of those rows a DATABASE list is entitled to draw. A key here that the
 * server never sends simply never matches.
 *
 * Intelligence and Automation (key `automation`) never appear as databases.
 */
export const SURFACE_KEYS: ReadonlySet<string> = new Set(["automation", "intelligence"]);

// W60-T39 / R16: the shell and gallery both need the Agents address. Keep it here because
// AutomationSurface is a lazily loaded chunk that neither may statically import.
export function readAgentAddress(
  hash = typeof window === "undefined" ? "" : window.location.hash,
): { agent: string; voice: string } {
  const query = hash.indexOf("?");
  if (query < 0 || hash.slice(0, query) !== "#/automation") return { agent: "", voice: "" };
  const params = new URLSearchParams(hash.slice(query + 1));
  return { agent: params.get("agent") || "", voice: params.get("voice") || "" };
}

export function agentAddressHash(kind: "agent" | "voice", id: string): string {
  return `#/automation?${kind}=${encodeURIComponent(id)}`;
}

/**
 * A `NavEntry` that has been through {@link databaseEntries} β€” and the brand is the
 * point, not decoration.
 *
 * β›” IT MAKES THE WRONG LIST A COMPILE ERROR RATHER THAN A CODE REVIEW. A component
 * that draws databases declares `DatabaseEntry[]`, so handing it the raw `entries`
 * does not type-check and `npx tsc -b` says so on the day it is written. That is the
 * same lesson this repo learned about optional props (`verify_wiring.py`'s header:
 * an optional prop degrades to "the feature does not exist"), applied to a LIST: an
 * unfiltered one degrades to "one extra tile", which nobody notices for a wave.
 *
 * ⚠ `DatabaseEntry` IS a `NavEntry`, so anything taking the wider type still accepts
 * these. The brand only blocks the unsafe direction.
 */
export type DatabaseEntry = NavEntry & { readonly __isDatabase: true };

/**
 * The granted nav, minus the surfaces that are not databases. **The only supported
 * way to obtain a database list** (D-54).
 *
 * β›” IT NARROWS, IT NEVER WIDENS β€” `entries` stays the outer bound, so the server's
 * grant is never re-litigated here. Nothing is added, reordered or renamed; rows are
 * dropped, and only rows this module has declared to be surfaces.
 */
export function databaseEntries(entries: NavEntry[]): DatabaseEntry[] {
  return entries.filter((e) => !e.surface) as DatabaseEntry[];
}

/**
 * The surfaces THIS TREE can actually render:
 *   Β· `customer_data` / `cohort` β€” the Customer table, the same `customer-grid`
 *     component the Streamlit embed ships.
 *
 * ⚠ This is a CLIENT capability list, not a permission list, and the two must
 * not be confused. The server decides what a user MAY open; this decides what
 * the shell KNOWS HOW to draw. A key here that the server did not send is
 * simply never rendered β€” the payload is the outer bound, always.
 *
 * β­’ THE NEXT PORTED SURFACE (Collections / Procurement) JOINS BY ADDING ITS KEY
 * HERE + a server-side builder. That is the whole bet of the Y1 envelope: a
 * ported page is a registry entry plus a builder, never a new component tree.
 * `sales` was the proof (EXIT wave 2) and LEFT wave 16 (owner item 7, R3/R11):
 * the registry row is archived, the builder unregistered, and the owner
 * rebuilds sales views from the grid's chart/dashboard modes β€” so the envelope
 * machinery (PageView, ui/, viz/) is currently a capability with no shipped
 * page, kept warm by the render-smoke fixture.
 */
export const NATIVE_KEYS: ReadonlySet<string> = new Set<string>(
  // `cohort` joined 2026-07-30 and LEFT wave 16 (owner item 5, R10): every cohort now
  // projects as a LOCKED VIEW in the Customer rail's "Cohorts" section (wave-15 C-LOCK),
  // so the separate route is gone. The cohort MACHINERY stays β€” `scope=cohort`,
  // `workspace.cohortMode`, the events β€” reachable from the Customer surface.
  // `product_data` joined wave 16 (C-TOPIC, owner items 9+10): the SAME grid tree over the
  // SKU catalogue β€” Shell maps it to `scope="product"` and everything else is the topic's.
  // `automation` joined wave 18 (C-AUTONAV): SESSION D's surface, its own rail + editor.
  // User tables are native BY PREFIX (`ut_`), decided in `shapeNav`, not listed here.
  ["customer_data", "product_data", "automation", "intelligence"]);

/** The native keys the Y1 page envelope drives (as opposed to `customer_data`,
 *  which is its own component tree). Kept beside NATIVE_KEYS so the two cannot
 *  drift: everything here MUST also be native, asserted in the gate. EMPTY
 *  since wave 16 (sales retired) β€” the next builder's key lands here. */
export const ENVELOPE_KEYS: ReadonlySet<string> = new Set<string>([]);

/** Hash routes ignore the legacy host argument and stay on the serving origin. */
export function appLink(_appBase: string, key: string): string {
  return `#/${encodeURIComponent(key)}`;
}

/**
 * Payload β†’ rendered rows, in registry order, children under their parent.
 *
 * THE GROUP RULE IS DERIVED, NOT RECEIVED. X2's nav item carries no
 * `group_only` flag, but `customers` IS one (registry: the folder head of
 * customer_data + cohort β€” "it has no PAGE_FUNCS entry, the nav never renders
 * it as a leaf"). So a page that is the `parent` of at least one page IN THE
 * SAME PAYLOAD renders as a group head. Derived from the contracted payload
 * alone; if the API later emits an explicit flag, prefer it (posted to S1 β€”
 * additive, no amendment).
 *
 * ⚠ AN ORPHANED CHILD RENDERS AT TOP LEVEL. If `may_open` granted `cohort` but
 * not its parent `customers`, the payload has the child and not the head β€” and
 * hiding it because its family head is missing would take away a surface the
 * server explicitly granted. Display never re-litigates a server grant.
 */
export function shapeNav(pages: NavPage[], appBase: string): NavEntry[] {
  const present = new Set(pages.map((p) => p.key));
  const childrenOf = new Map<string, NavPage[]>();
  for (const p of pages) {
    if (!p.parent || !present.has(p.parent)) continue;
    const list = childrenOf.get(p.parent);
    if (list) list.push(p);
    else childrenOf.set(p.parent, [p]);
  }

  const entry = (p: NavPage, depth: number): NavEntry => {
    // Wave 18 (C3-UT): any `ut_`-prefixed key is a USER TABLE β€” drawable by the same grid
    // tree (Shell passes the key through as the scope), so it is native BY PREFIX rather
    // than by membership. The server only emits ut rows this session may open, so this is a
    // capability rule, never a permission one.
    const isNative = NATIVE_KEYS.has(p.key) || p.key.startsWith("ut_");
    // A native surface stays native even with children β€” the shell can draw it,
    // so it is a destination first and a family head second. Otherwise: the
    // server's flag wins, and has-children is the fallback for a payload that
    // predates it.
    const kind: NavKind = isNative
      ? "native"
      : p.group_only || childrenOf.has(p.key)
        ? "group"
        : "handoff";
    return {
      key: p.key,
      label: p.label,
      ...(p.source ? { source: p.source } : {}),
      ...(p.sourceGroup ? { sourceGroup: p.sourceGroup } : {}),
      ...(p.group ? { group: p.group } : {}),
      ...(p.sync ? { sync: p.sync } : {}),
      ...(p.managedBy === "loopable" ? { managedBy: "loopable" as const } : {}),
      ...(p.protected ? { protected: true } : {}),
      ...(p.icon ? { icon: p.icon } : {}),
      ...(p.manage ? { manage: true } : {}),
      // C3 (W-5) β€” carried through `shapeNav` beside `manage`. THE SECOND HALF
      // OF THE SAME FLAG: `parseNav` reading it and this dropping it would put
      // the answer on the payload and never on the row the rail renders, which
      // is precisely how wave 20 shipped four wirings that went nowhere.
      ...(p.canDelete ? { canDelete: true } : {}),
      // ⭐ WAVE 27 item 3 / C9 β€” THE SECOND HALF, for the reason stated directly above: a flag
      // parsed onto the payload and dropped here reaches no row anybody renders.
      ...(p.locked ? { locked: true } : {}),
      // ⭐⭐ WAVE 34 R1 / C1 β€” THE SECOND HALF AGAIN, AND IT WAS MISSED ON THE FIRST TRY.
      // `parsePages` validated `important` onto the payload and this function dropped it, so the
      // number reached the wire, survived validation, and never reached a row. The `shapeNav`
      // leg in `shell.test.ts` is what found it, minutes after being written; the two comments
      // above say this exact thing about two earlier flags and it happened anyway, which is the
      // argument for the leg rather than for the comment.
      ...(p.important ? { important: p.important } : {}),
      // ⭐ D-54 β€” the databases/surfaces split, stamped at the ONE place rows are built.
      // Not `kind`: a surface is `native` (this tree renders it) and so are the grids, so the
      // existing discriminator cannot answer this question and widening it would have made
      // "can the shell draw it" and "is it a database" one field with two meanings.
      ...(SURFACE_KEYS.has(p.key) ? { surface: true as const } : {}),
      kind,
      depth,
      ...(kind === "group"
        ? {}
        : { href: isNative ? `#/${p.key}` : appLink(appBase, p.key) }),
    };
  };

  const out: NavEntry[] = [];
  for (const p of pages) {
    // Children are emitted under their head, not in payload position.
    if (p.parent && present.has(p.parent)) continue;
    const head = entry(p, 0);
    const children = childrenOf.get(p.key) ?? [];
    // ⚠ An EMPTY folder head is dropped. It is not a destination by definition,
    // so with nothing under it the row says only "here is something you cannot
    // reach" β€” which happens to a user granted `customers` but neither child.
    // This is not re-litigating a grant: a container is not a surface.
    if (head.kind === "group" && children.length === 0) continue;
    out.push(head);
    for (const c of children) out.push(entry(c, 1));
  }
  return out;
}

/**
 * The surface the shell lands on, in preference order.
 *
 * β›” IT IS AN EXPLICIT PREFERENCE, NOT "the first native entry". It used to be
 * the latter, and the result was that the shell opened on SALES β€” purely
 * because `sales` sorts first in the registry β€” which is the one module the
 * owner had said to leave alone. "Customer doesn't load on first
 * initialization" was that, exactly: Customer loaded fine, it just was not what
 * came up. A landing page is a product decision and belongs in a list somebody
 * can read, not in whatever the registry happens to order first.
 */
// (`cohort` left the list with its NATIVE_KEYS exit, wave 16 β€” a landing must be drawable.)
//
// ⭐ WAVE 23 (contract C10, ruling R7) β€” THE LANDING IS NOW `#/home`.
//
// β›” CHROME ROUTES ARE NOT GRANTED PAGES, AND THE :1039 LAW SURVIVES INTACT. This shell's
// oldest rule is that the nav is server-filtered and an undeclared surface is denied β€” which is
// why Alerts is a PANEL and not a route. Home and Connectors are routes, and they do not
// violate that rule for one reason that has to be true of every future member of this set:
//
//     A CHROME ROUTE RENDERS NOTHING THE SERVER DID NOT ALREADY GRANT.
//
// Home shows the entries `/nav` returned (its recents are RESOLVED against those entries and a
// key absent from them is dropped, `homeModel.groupRecents`) plus create affordances that were
// already in the rail. Connectors renders a SERVER-COMPOSED directory (`GET /connectors/
// directory`, session-gated) β€” it is a window onto a payload, not a surface with its own data.
// Neither can show a database, a module or a connector this session may not see; adding a route
// that could would be the hard-coded surface the frame refuses to have.
export const HOME_ROUTE = "home";
export const CONNECTORS_ROUTE = "connectors";
/** Intelligence is a granted module, never an unconditional chrome destination. */
export const INTELLIGENCE_ROUTE = "intelligence";
/**
 * WAVE 55 / R1-R3: the tenant Application registry has one chrome destination.
 *
 * App is a directory over Application definitions already permission-filtered by the server. It
 * is not a registry module and it does not replace the database Views that pre-date it. Keeping
 * the route in chrome prevents a tenant's restricted module list from hiding its own Apps.
 */
export const APP_ROUTE = "app";

export interface ApplicationTemplateRole {
  key: string;
  label: string;
  required: boolean;
  types: string[];
}

export interface ApplicationTemplate {
  kind: string;
  label: string;
  applicationType: string;
  displayMode?: string;
  fieldRoles: ApplicationTemplateRole[];
  defaultPlacement: { section: "app"; order: number };
  deepLink?: string;
  /** A template bound to one database offers only that one in the wizard (S78-T17). */
  sourceDatabase?: string;
}

/** Accept server template kinds without maintaining a second registry. */
export function parseApplicationTemplates(body: unknown): ApplicationTemplate[] {
  const rows = (body as { templates?: unknown } | null)?.templates;
  if (!Array.isArray(rows)) return [];
  return rows.filter((row): row is ApplicationTemplate => {
    if (!row || typeof row !== "object" || Array.isArray(row)) return false;
    const template = row as Partial<ApplicationTemplate>;
    return typeof template.kind === "string" && !!template.kind.trim()
      && typeof template.label === "string" && !!template.label.trim()
      && typeof template.applicationType === "string" && !!template.applicationType.trim()
      && template.defaultPlacement?.section === "app"
      && typeof template.defaultPlacement.order === "number"
      && Number.isFinite(template.defaultPlacement.order)
      && Array.isArray(template.fieldRoles) && template.fieldRoles.every((role) =>
        role && typeof role.key === "string" && !!role.key.trim()
        && typeof role.label === "string" && typeof role.required === "boolean"
        && Array.isArray(role.types) && role.types.every((type) => typeof type === "string"));
  });
}

/** Read page App addresses separately from the database-backed App address. */
export function readApplicationPageAddress(hash: string): { kind: "code" | "customer-card" | "template"; id: string } | null {
  const match = /^#\/app\/(code|customer-card|template)\/([^/?#]+)$/.exec(hash);
  if (!match || match[0] !== hash) return null;
  try {
    const id = decodeURIComponent(match[2]);
    return id && !/[/?#\x00-\x1f\x7f]/.test(id) ? { kind: match[1] as "code" | "customer-card" | "template", id } : null;
  } catch { return null; }
}

export type LegacyApplicationPage = "template" | "database" | "unavailable" | "source_unavailable";

/** Resolve the shared App before admitting its legacy source database. */
export async function resolveLegacyApplicationPage(id: string, abortSignal: AbortSignal): Promise<LegacyApplicationPage> {
  try {
    const response = await fetch(`${API_V1}/applications/${encodeURIComponent(id)}/availability`, {
      credentials: CREDENTIALS, signal: abortSignal,
    });
    if (checkTenant(response)) return "unavailable";
    if (response.status === 401) signal(UNAUTHORIZED_EVENT);
    // Routing and Catalog use the database dispatcher and have no standalone availability.
    if (response.status === 404) return "database";
    if (!response.ok) return response.status >= 500 ? "source_unavailable" : "unavailable";
    const body = await response.json();
    const app = body?.application;
    return app?.id === id && typeof app.templateView === "string" && !!app.templateView
      && app.fieldMap && typeof app.fieldMap === "object" && !Array.isArray(app.fieldMap)
      ? "template" : "unavailable";
  } catch { return "source_unavailable"; }
}
/** W62-T19 / R52: Data is a real chrome route, rendered by Shell.tsx's Home/App/Data fallback
 * branch. Joining CHROME_ROUTES is inert for firstDestination: LANDING_PREFERENCE is [HOME_ROUTE]. */
export const DATA_ROUTE = "table";

/** Commit the destination before starting any asynchronous existence or data read. */
export function commitRoute(href: string): boolean {
  const previous = window.location.hash;
  window.location.hash = href;
  return window.location.hash !== previous;
}

/** C6's Data address, including the folder stratum above the grid's database/view path. */
export interface DataAddress { database?: string; view?: string; folder?: string; filters?: DataPath["filters"] }

/** Build C6 addresses for shell/rail navigation. These helpers own the folder stratum;
 * dataPath.ts remains the grid's database/view reader and its path semantics are unchanged. */
export function dataAddressHash(address: DataAddress): string {
  const params = new URLSearchParams();
  for (const key of ["database", "view", "folder"] as const) {
    if (address[key]) params.set(key, address[key]);
  }
  if (address.filters) params.set("filters", JSON.stringify(address.filters));
  const query = params.toString();
  return `#/${DATA_ROUTE}${query ? `?${query}` : ""}`;
}

/** Read the folder stratum and address keys for shell/rail navigation, not grid path semantics.
 * dataPath.ts remains the grid reader. An explicit hash also works when evaluated under Node. */
export function readDataAddress(
  hash = typeof window === "undefined" ? "" : window.location.hash
): DataAddress {
  const [route, query = ""] = canonicalDataHash(hash).split("?", 2);
  if (!/^#\/?table(?:\/[^?#]*)?$/.test(route)) return {};
  const params = new URLSearchParams(query);
  const address: DataAddress = {};
  for (const key of ["database", "view", "folder"] as const) {
    const value = params.get(key);
    if (value !== null) address[key] = value;
  }
  const filters = decodeDataFilters(params.get("filters"));
  if (filters) address.filters = filters;
  return address;
}
/**
 * ⭐⭐ WAVE 32 (ruling R1, contract C5) β€” QUERY IS THE FOURTH CHROME ROUTE, and it satisfies the
 * law above THROUGH ITS REQUIRED PROP rather than despite it.
 *
 * `QueryPage` takes `granted: NavEntry[]` β€” the database entries the shell already holds from
 * `/nav`, which is to say the set the SERVER decided this session may see. It makes no listing
 * call of its own, so *"a chrome route renders nothing the server did not already grant"* is true
 * by construction here rather than by promise, and the AI cannot name a database the caller was
 * not already given (C5's permission clause, re-used rather than re-implemented).
 *
 * β›” NOT a `registry.py` module, because the tenant module list filters registry keys: every tenant's
 * `modules` list is `['analyst','automation']`, so a registry key would be omitted from the rail
 * in every tenant while every gate stayed green.
 */
export const QUERY_ROUTE = "query";
/**
 * ⭐⭐ 2026-08-14 (owner item 2) β€” THE AI ASSISTANT, THE FIFTH CHROME ROUTE AND THE ONLY AI DOOR.
 *
 * β›” IT REPLACES `AI_AGENT_ROUTE`, WHICH IS DELETED. Owner, verbatim: *"Remove the 'AI agent'
 * module completely. previous wave did not follow instruction. AI assistant module IS AI agent
 * module. So no need to separate it like that."* Wave 33 shipped `#/ai-agent` beside an assistant
 * row whose click opened an under-construction note; the note beside that row had already argued
 * for exactly this collapse and deferred it as ASK C-9. So the surface is not renamed, it is
 * REPLACED: the assistant row now goes somewhere, and there is one AI module rather than two.
 *
 * A CHROME route for the same reason `QUERY_ROUTE` is, and the argument is
 * load-bearing rather than filing: every provisioned tenant's `modules` list is
 * `['analyst','automation']`, so a `registry.py` key would be silently omitted from the rail in
 * every tenant while every gate stayed green.
 *
 * ⚠ AND IT MEETS THE :1039 LAW THE SAME WAY `QueryPage` DOES β€” BY ITS REQUIRED PROP.
 * `AssistantPage` takes `granted: NavEntry[]`, the entries the shell already holds from `/nav`,
 * so the AI cannot be pointed at a database the SERVER did not already grant this session. The
 * build door re-checks regardless (`routes_query._target` β†’ `routes_templates._target_or_refuse`),
 * which is the wall; this is what stops the picker offering what the wall would refuse.
 *
 * ⚠ THE RAIL ROW STAYS CONDITIONAL ON THE `analyst` NAV ENTRY, and that is not an inconsistency
 * with "chrome needs no grant". The ROUTE is chrome (typing `#/assistant` works); the ROW is the
 * registry's `analyst` utility entry, with the three arms W33-T22 built for it (ready / pending /
 * unavailable). Collapsing those into an unconditional link would re-open the owner's own
 * layout-jump report, which is what that ticket was.
 */
export const ASSISTANT_ROUTE = "assistant";
export const ARTIFACTS_ROUTE = "artifacts";

/**
 * ⭐⭐ WAVE 35 Β· T06 (owner item 13, contract C6) β€” the three ACCOUNT routes. Owner: *"add below
 * settings the following button: Feedback …, Usage credits …, and a Subscription module …
 * Specialized for the Royal Imports tenant, do not show it."*
 * β›” THE SURFACE IS CALLED "Usage" SINCE W37-T02 AND THIS QUOTE IS NOT UPDATED TO MATCH. It is
 * what the owner TYPED; editing their words to agree with a later rename destroys the only record
 * of what was actually asked for. The route key never carried the old label anyway.
 *
 * β›” THEY MUST JOIN `CHROME_ROUTES` OR THEY RENDER NOTHING BEHIND A 200. Shell's oldest law denies
 * an undeclared SURFACE; these are chrome β€” they need no grant because they show the caller its own
 * account, never a tenant's data.
 * ⚠ `SUBSCRIPTION_ROUTE` is chrome for EVERY tenant here and refused for Royal Imports at the
 * DISPATCH (C6). Excluding it from this set instead would deny it to everyone, which is a different
 * bug wearing the same screen.
 */
/**
 * WAVE 55 instruction 2 removes Starred as a module. The old key remains only as a compatibility
 * address and is rewritten to Home's starred-only filter below. Keeping the key costs no rail row,
 * preserves bookmarks, and leaves the tenant's durable star flags untouched.
 */
export const STARRED_ROUTE = "starred";

export const FEEDBACK_ROUTE = "feedback";
export const USAGE_ROUTE = "usage";
export const SUBSCRIPTION_ROUTE = "subscription";

/**
 * β›” WAVE 35 Β· T06 β€” the tenant that does NOT get a subscription page. Owner item 13, verbatim:
 * *"Specialized for the Royal Imports tenant, do not show it."* Tenant #0 is the owner's own
 * company and is not a paying customer of the platform.
 * ⚠ ONE constant, read by BOTH halves of C6 (the menu row and the route), because "hidden in the
 * menu while the route still answers" is not hidden β€” and two copies of a slug is how those two
 * halves drift apart.
 */
export const NO_SUBSCRIPTION_TENANT = "royal-imports";

export const CHROME_ROUTES: ReadonlySet<string> = new Set([
  HOME_ROUTE,
  APP_ROUTE,
  CONNECTORS_ROUTE,
  DATA_ROUTE,
  QUERY_ROUTE,
  ASSISTANT_ROUTE,
  ARTIFACTS_ROUTE,
  FEEDBACK_ROUTE,
  USAGE_ROUTE,
  SUBSCRIPTION_ROUTE,
]);

/** Home, including its Starred filter, keeps the rail expanded until the reader folds it. */
export const NAV_STAYS_EXPANDED_ROUTES: ReadonlySet<string> = new Set([
  HOME_ROUTE,
]);

// W60-T37 (R19) supersedes wave 57 R3 clause 1: App shares Data's cell-click fold, not an arrival fold.

/**
 * Old route key β†’ the key that replaced it. Applied to the hash before ANYTHING else reads it.
 *
 * ⭐ C3: *"the old `alerts` route redirects, it is not deleted β€” a stored nav preference naming
 * `alerts` must not orphan."* This is that clause, and it is the RENAME checklist's step 5
 * (*"grants and preferences migrate ON READ; never edit stored user records to migrate a
 * rename"*) expressed for a chrome route.
 *
 * ⚠ MEASURED, AND IT CHANGES WHAT THIS IS FOR: **there was no `#/alerts` route to redirect.**
 * Alerts was deliberately a PANEL β€” `Shell.tsx`'s bell is a `<button>`, and the comment beside it
 * says a client-invented `#/alerts` route *"would be exactly the hard-coded surface the frame
 * refuses to have"*. So no user has a stored `alerts` placement, and the clause was written
 * against a route that never existed. It is kept anyway, as forward insurance rather than
 * archaeology: `#/alerts` is the hash a person would GUESS, type, or have bookmarked from a
 * notification email, and answering it costs one map lookup. Retiring it would need evidence
 * nobody types it, which is not obtainable.
 */
export const LEGACY_ROUTES: Readonly<Record<string, string>> = {
  data: DATA_ROUTE,
  alerts: ASSISTANT_ROUTE,
  inbox: ASSISTANT_ROUTE,
  [STARRED_ROUTE]: HOME_ROUTE,
  /**
   * ⭐ 2026-08-14 β€” `#/ai-agent` was a REAL route for one wave (wave 33 shipped it, and the
   * owner's *"remove that AI agent module completely"* retires it). Unlike `alerts` above, this
   * one genuinely existed and genuinely was reachable, so somebody can hold the hash.
   *
   * ⚠ A REDIRECT IS NOT THE MODULE. Nothing of `ai-agent` survives β€” no page, no api file, no
   * rail row, no mount, no `AI_AGENT_ROUTE` constant, and `verify_wiring.py` asserts each of
   * those absences. This is one map entry that answers a stale hash with the surface that
   * replaced it, which is the RENAME checklist's step 5 (*"grants and preferences migrate ON
   * READ"*) for a chrome route. Without it the hash resolves to nothing and silently lands on
   * Home β€” a worse answer to the same question.
   */
  "ai-agent": ASSISTANT_ROUTE,
  // R37: saved Query answers live in Artifacts, served by the same analyst grant.
  [QUERY_ROUTE]: ARTIFACTS_ROUTE,
};

/** Rewrite retired hashes before the shell publishes their destination. */
export const REWRITTEN_ROUTES: Readonly<Record<string, string>> = {
  [QUERY_ROUTE]: ARTIFACTS_ROUTE,
  [STARRED_ROUTE]: `${HOME_ROUTE}?filter=starred`,
};

/**
 * The ROUTE KEY in a hash, with any query string or nested fragment stripped.
 *
 * β›” THE BUG THIS EXISTS TO PREVENT WAS REPORTED BY LANE D BEFORE IT COULD HAPPEN (post D-1), and
 * it is invisible until you try it: the shell read the WHOLE remainder of the hash as the key, so
 * `#/assistant?mode=query` resolved to the key `assistant?mode=query`, matched no route, and fell
 * through to Home. The redirect below would have "worked" β€” right URL, wrong screen β€” and every
 * gate keyed on the redirect's target string would have been green.
 */
export function routeKeyOf(hash: string): string {
  const key = hash.replace(/^#\/?/, "").split("?")[0].split("#")[0];
  return /^(data|table)(\/|$)/.test(key) ? key.split("/")[0] : key;
}

/**
 * The hash this one must BECOME, or null when it is already right.
 *
 * ⚠ RETURNS NULL FOR AN ALREADY-REWRITTEN HASH, which is the whole loop-safety argument: writing
 * `location.hash` fires `hashchange`, the caller asks again, the key is now `assistant`, and this
 * answers null. One rewrite, never a cycle.
 */
export function rewrittenHash(hash: string): string | null {
  const canonicalHash = canonicalDataHash(hash);
  const routeKey = routeKeyOf(canonicalHash);
  const target = REWRITTEN_ROUTES[routeKey];
  if (target) return `#/${target}`;
  if (routeKey !== DATA_ROUTE) return null;
  // Legacy database-backed App links keep their existing destination and raw query.
  if (/^#\/?table\?/.test(canonicalHash)) {
    const query = canonicalHash.slice(canonicalHash.indexOf("?") + 1);
    const application = new URLSearchParams(query).get("application")?.trim();
    if (application) return `${APP_PATH_PREFIX}${query}`;
  }
  return canonicalHash !== hash ? canonicalHash : null;
}

/** The current key for a hash that may name a retired one. Identity for everything else. */
export function canonicalRoute(route: string): string {
  return LEGACY_ROUTES[route] ?? route;
}

export const LANDING_PREFERENCE: readonly string[] = [HOME_ROUTE];

/**
 * The surface the shell lands on.
 *
 * ⚠ THE THREE LANDING SITES MOVE TOGETHER OR LOGINS STRAND (C10's own warning): this function,
 * `LANDING_PREFERENCE` above, and the post-login redirect in `Shell.tsx`. Half a move leaves a
 * signed-in user on a hash nothing renders.
 *
 * A chrome route needs no entry to be reachable β€” that is what makes it chrome β€” so the loop
 * below returns it without consulting `entries`, and the old preference chain survives beneath
 * it for the day a granted page becomes the landing again. `entries` stays a parameter for the
 * same reason: the fallback is still a real answer about a real payload.
 */
export function defaultRoute(entries: NavEntry[]): string {
  return firstDestination(entries, LANDING_PREFERENCE);
}

/**
 * The landing rule itself, over an arbitrary preference list.
 *
 * ⚠ EXTRACTED (wave 23) SO THE FALLBACK CHAIN STAYS UNDER TEST. Before C10 the chain WAS
 * `defaultRoute`, so `shell.test.ts` asserted it by calling that. With `home` at the head of the
 * preference the function now returns on its first line, and the whole "preferred native entry β†’
 * any native entry β†’ any destination" ladder became unreachable from the outside β€” three checks
 * would have had to be deleted rather than retargeted, which is how a gate quietly stops
 * asserting the thing it was written for ([[gate-can-report-green-on-nothing]]). It is one
 * function called two ways instead.
 */
export function firstDestination(
  entries: NavEntry[],
  preference: readonly string[]
): string {
  for (const key of preference) {
    // A chrome route needs no entry to be reachable β€” that is what makes it chrome.
    if (CHROME_ROUTES.has(key)) return key;
    const hit = entries.find((e) => e.key === key && e.kind === "native");
    if (hit) return hit.key;
  }
  return (
    entries.find((e) => e.kind === "native")?.key ??
    entries.find((e) => e.kind !== "group")?.key ??
    ""
  );
}

/**
 * Resolve a hash route against the nav.
 *
 * A GROUP is never a destination β€” a hand-typed `#/customers` resolves to the
 * family's first member, mirroring what the app itself does with a stale
 * `?page=customers` deep link ("redirects to the family's first visible
 * member"). An unknown route falls to the default. Both fall back rather than
 * erroring, because a URL is something a person can type or a bookmark can
 * outlive.
 *
 * ⭐ WAVE 23 (C10): the fallback is now `#/home`, which is CHROME and therefore matches no
 * entry β€” so this returns `undefined` for an unknown route, and the frame reads "no entry" as
 * "render Home". One behaviour change, stated plainly: `#/deleted_table` used to open the
 * Customer grid and now opens Home. That is the better answer (the reader asked for something
 * that is gone; the landing is where you choose again) and it is the SAME answer an empty hash
 * gets β€” which is what "Home is the default" has to mean in order to be true.
 */
export function resolveRoute(entries: NavEntry[], route: string): NavEntry | undefined {
  const i = entries.findIndex((e) => e.key === route);
  if (i >= 0) {
    const hit = entries[i];
    if (hit.kind !== "group") return hit;
    // A group head: fall through to its first real member β€” the rows that
    // follow it DEEPER, stopping at the next row of its own level or shallower.
    for (const e of entries.slice(i + 1)) {
      if (e.depth <= hit.depth) break;
      if (e.kind !== "group") return e;
    }
  }
  const fallback = defaultRoute(entries);
  return entries.find((e) => e.key === fallback);
}