File size: 247,790 Bytes
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9ca0aa
792ee39
 
 
b80130d
792ee39
 
 
 
 
 
 
2183dbe
 
 
 
 
 
 
a83fcff
1f123e1
 
 
 
 
 
 
 
 
 
c8a9b67
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
1904e77
1f123e1
4b54047
a9ca0aa
a83fcff
1f123e1
 
4b54047
c8a9b67
 
 
 
 
1f123e1
 
 
 
 
 
cfa8541
a83fcff
1f123e1
792ee39
 
 
 
 
39a9177
 
 
 
 
a83fcff
bdac669
 
 
1f123e1
 
 
 
dcd43e2
 
 
 
1f123e1
 
cfa8541
 
 
 
 
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c920df3
1f123e1
c920df3
1f123e1
 
 
 
 
 
dcd43e2
a9ca0aa
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c920df3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
a83fcff
 
 
 
 
 
bdac669
a83fcff
 
 
 
 
 
 
bdac669
 
a83fcff
 
 
 
992a41f
 
 
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
 
 
 
 
a83fcff
 
 
 
 
 
 
bdac669
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
992a41f
 
 
 
 
 
a83fcff
 
 
 
 
e13472e
a83fcff
 
 
 
 
 
 
e13472e
 
a83fcff
 
 
 
 
e13472e
992a41f
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
0ab3e74
 
 
 
 
 
 
 
 
 
 
992a41f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
 
 
 
 
 
 
992a41f
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
 
 
 
a83fcff
 
 
992a41f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
 
 
 
 
 
 
992a41f
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
a83fcff
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
0de30a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
1f123e1
c920df3
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e77cd4
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c920df3
 
1f123e1
 
 
 
 
cfa8541
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
1f123e1
 
 
 
 
 
 
 
 
 
4b54047
cfa8541
 
 
4b54047
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
1f123e1
 
 
 
a9ca0aa
 
4b54047
1f123e1
 
 
 
4b54047
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
1f123e1
 
 
e13472e
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9177
 
 
792ee39
39a9177
792ee39
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa8541
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
792ee39
 
 
 
e9a4c3e
 
 
 
 
 
 
 
 
a83fcff
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9177
 
 
 
 
1f123e1
 
 
 
 
 
39a9177
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
c920df3
 
1f123e1
3ae85d8
 
 
1f123e1
 
 
4b54047
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
 
dcd43e2
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b80130d
 
 
 
9b4b996
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
792ee39
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
c8a9b67
792ee39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
1f123e1
2183dbe
 
 
1f123e1
b80130d
 
 
a9ca0aa
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
79c50b4
 
 
792ee39
 
 
 
 
2183dbe
a9ca0aa
1904e77
 
2183dbe
 
1904e77
2183dbe
1f123e1
 
 
 
 
2183dbe
1f123e1
2183dbe
 
 
 
 
 
1f123e1
2183dbe
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a9b67
 
 
 
 
792ee39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a9b67
792ee39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
dcd43e2
 
f5696cb
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
3ae85d8
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
 
 
 
 
 
 
 
 
1f123e1
4b54047
 
c920df3
4b54047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa8541
 
 
 
 
4b54047
 
c920df3
4b54047
 
 
 
 
 
 
 
1f123e1
 
 
 
 
3ae85d8
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
1f123e1
 
 
 
 
 
c920df3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9ca0aa
 
 
 
 
 
 
 
 
 
 
 
3ae85d8
a9ca0aa
 
 
 
 
 
 
 
 
 
1f123e1
 
cfa8541
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9ca0aa
1f123e1
 
a9ca0aa
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcd43e2
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b4b996
 
 
1f123e1
 
 
 
 
 
 
 
9b4b996
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
1f123e1
bdac669
 
a83fcff
 
 
bdac669
 
 
 
a83fcff
 
bdac669
 
 
 
 
 
 
 
a83fcff
 
 
 
 
 
 
 
 
 
bdac669
 
a83fcff
4b54047
a83fcff
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
39a9177
 
 
1f123e1
bdac669
 
 
 
 
1f123e1
 
f5696cb
 
 
 
 
 
 
b80130d
f5696cb
 
 
a9ca0aa
f5696cb
 
 
 
 
a9ca0aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b80130d
a9ca0aa
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0de30a1
 
 
1f123e1
 
 
 
 
 
 
 
 
9b4b996
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e77cd4
 
1f123e1
 
 
 
 
c920df3
 
a83fcff
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
3331871
1f123e1
 
cfa8541
 
1f123e1
 
 
 
1904e77
 
 
 
1f123e1
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1904e77
 
 
 
2183dbe
 
 
 
 
 
39a9177
 
 
 
 
 
 
 
2183dbe
a9ca0aa
e13472e
f5696cb
 
 
e13472e
f5696cb
 
2183dbe
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9177
 
 
 
 
 
1f123e1
 
 
 
 
b80130d
1f123e1
dcd43e2
1f123e1
 
 
 
 
c8a9b67
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e77cd4
 
 
 
 
 
a9ca0aa
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
1f123e1
e13472e
1f123e1
 
 
 
 
 
 
 
 
 
 
2e77cd4
 
 
 
 
1f123e1
 
 
 
 
 
 
792ee39
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
1f123e1
 
 
 
 
 
 
2e77cd4
 
 
 
 
 
 
 
 
 
 
1f123e1
a83fcff
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
 
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
e9a4c3e
 
 
 
 
 
 
1f123e1
 
 
 
 
 
f5696cb
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
2183dbe
1f123e1
2183dbe
792ee39
 
 
 
f5696cb
 
 
 
 
 
 
 
 
 
 
 
b80130d
1f123e1
 
792ee39
2183dbe
 
 
 
 
 
 
 
1f123e1
 
e13472e
cfa8541
e13472e
cfa8541
e13472e
 
 
 
 
 
 
 
 
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
792ee39
1f123e1
 
 
 
 
 
 
cfa8541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
a83fcff
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792ee39
 
 
 
a83fcff
792ee39
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b80130d
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a9b67
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
dcd43e2
 
 
 
 
 
 
 
bdac669
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa8541
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5696cb
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
9b4b996
4b54047
 
 
9b4b996
 
a9ca0aa
 
 
f5696cb
a9ca0aa
 
 
 
 
9b4b996
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
cfa8541
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcd43e2
1f123e1
 
 
3ae85d8
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
1f123e1
4b54047
c920df3
a83fcff
1f123e1
 
 
 
 
 
 
 
 
 
3ae85d8
 
bdac669
1f123e1
a83fcff
 
1f123e1
 
 
 
 
 
 
 
dcd43e2
1f123e1
 
 
 
 
 
a83fcff
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
a83fcff
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
 
 
 
 
 
 
1f123e1
bdac669
 
 
 
 
 
 
 
 
 
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d60127
1f123e1
 
 
 
 
 
 
 
bdac669
1f123e1
 
 
 
 
 
 
bdac669
1f123e1
 
 
 
 
 
 
 
 
39a9177
 
 
1f123e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
// ---------------------------------------------------------------------------
// 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, useMemo, useRef, useState } from "react";
/* ⭐ W53-T34 / contract C4 β€” the shell's glyphs live in ONE file now. See the tombstone where
   `FlowIcon` used to be drawn, further down. */
import { AgentIcon, DatabaseIcon } from "./icons";
import { OverlayScroll } from "../ui/OverlayScroll";
// ⭐ W53-T35 / C4 β€” the shell's own sheet, imported here the way `NavExtras.tsx` imports
// `navExtras.css`. It carries the one rule that keeps the DATABASE mark out of the folder
// fill (`styles/wave45/data-applications.css` paints every `.cg-folder-mark path` brand
// purple, which is right for a folder and is owner instruction 26's complaint for a
// database). It is scoped by two classes, so it wins on specificity and does not rest on
// import order β€” the sheet it overrides ships in a lazy chunk.
import "./shell.css";
/* β›” `import { createPortal } from "react-dom";` STOOD HERE AND IS DELETED (W41-T32). The database
   flyout was this file's ONLY portal β€” checked by the compiler, not by reading: `tsc -b` named it
   (TS6133) the moment the panel went, which is the unused-locals check doing the remembering
   exactly as `PlusMark`'s tombstone further down predicted it would.
   ⚠ AND `npx tsc --noEmit` DID NOT CATCH IT β€” only `npm run build`'s `tsc -b` did. The two are not
   the same check here; a lane that runs the first and skips the second gets a false green on every
   symbol it orphans. */
import type { MouseEvent as ReactMouseEvent, ReactNode, RefObject } 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 lazy too:
 * only routes that mount a grid need its component chunk. The shell's synchronous cache and
 * scope helpers remain eager because invalidation and alert scope reads must precede navigation
 * and session changes.
 *
 * ⚠ `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"));
// ⭐⭐ WAVE 37 Β· T48 β€” `lazy`, like the twelve surfaces below it. This was the ONE eager import
// left in the shell, and it is the biggest module in the tree. See `App.tsx` for the measurement.
// ⚠ IT JOINS `Lazily`, NOT A BARE `Suspense`: the shared wrapper carries the ErrorBoundary, so a
// chunk that fails to load names the surface it was for instead of blanking the frame.
const CustomerGrid = lazy(() => import("../customer-grid/CustomerGrid"));
import { clearCustomersCache, currentSurfaceScope } from "../customer-grid/apiBridge";
import { OverlayProvider } from "../customer-grid/OverlaySurface";
import { appPathHash, dataPathHash, readDataPath } from "../customer-grid/dataPath";
import type { DataDatabase } from "../customer-grid/dataPath";
import "../styles/wave55/apps.css";
// 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 { AGENTS_CHANGED, API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, VIEW_OPEN_EVENT, WORKSPACE_STALE_EVENT, signal } from "../apiContract";
// Envelope dashboards are conditional routes; their renderer is not needed to paint the shell.
// Locked production build: entry 422.44 -> 393.41 kB (422,447 -> 393,416 bytes on disk).
// The mount keeps PageSurface's heading and spinner visible while its chunk loads.
const PageSurface = lazy(() =>
  import("../pages/PageSurface").then((m) => ({ default: m.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 { APP_ROUTE, ASSISTANT_ROUTE, CONNECTORS_ROUTE, DATA_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, FEEDBACK_ROUTE, HOME_ROUTE, INBOX_ROUTE, NO_SUBSCRIPTION_TENANT, SUBSCRIPTION_ROUTE, USAGE_ROUTE, MAX_NAV_FOLDERS, NAV_MALFORMED_STATUS, NAV_STAYS_EXPANDED_ROUTES, NAV_TIMEOUT_STATUS, agentAddressHash, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchSchema, fetchTableFootprint, postOpened, QUERY_ROUTE, dataAddressHash, readAgentAddress, readDataAddress, resolveRoute, rewrittenHash, routeKeyOf, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, RailSlot, Recent, SchemaField, SchemaPayload } from "./nav";
// ⭐ 2026-08-14 β€” the database frame, extracted so the Query module can wear the SAME one.
// β›” W53-T35 β€” `DbIcon` IS NO LONGER IMPORTED HERE. The Data row wears `icons.tsx::DatabaseIcon`
// (owner instruction 26: the Home page's cylinder is the correct one), and `dbFrame.tsx` keeps
// exporting `DbIcon` for `query/queryParts.tsx`, which still draws the coin stack. Only
// `gridScopeFor` is read from this module now.
import { gridScopeFor } from "./dbFrame";
// W51-T31 β€” the shell's overlays join the ONE Escape stack (C8 / DESIGN.md Β§4). Every
// registration below is gated on that overlay's OWN open flag, never on `true`: the arbiter
// preventDefaults and stops propagation on a claimed Escape, and Escape is also the browser's
// cancel-this-drag key for the rail's folder drag-and-drop.
import { useEscapeClose } from "../ui/useEscapeClose";
import { useApplicationWizardOverlay } from "./useApplicationWizardOverlay";
import { BodyPortal } from "../customer-grid/OverlaySurface";
import { OPEN_APP_TEMPLATE_EVENT } from "../sheet/templates/templatesApi";
import type { TemplateModule } from "../sheet/templates/templatesApi";
/* ⭐ W35-T09 β€” the assistant's EXISTING door for opening an AI-built view: hash + a retry
   ladder, returning a canceller. A second emit here would be a second answer. */
import { openBuiltView } from "../assistant/AssistantPage";
const HomePage = lazy(() => import("../home/HomePage"));
const SheetGalleryPage = lazy(() =>
  import("../home/HomePage").then((m) => ({ default: m.SheetGalleryPage })));
const AgentsGalleryPage = lazy(() =>
  import("../home/HomePage").then((m) => ({ default: m.AgentsGalleryPage })));
const TemplatePicker = lazy(() => import("../home/TemplatePicker"));
const ConnectorsPage = lazy(() => import("../connectors/ConnectorsPage"));
const ExternalAccessPane = lazy(() => import("../settings/ExternalAccessPane"));
const FinanceWorkspace = lazy(() => import("../app/FinanceWorkspace"));
// W63-T06 β€” AI API is chrome, like Connectors and Sheet. It deliberately stays local to the
// shell because this lane cannot widen nav.ts's file fence; unknown hash routes already pass
// through canonicalRoute unchanged and are mounted by an explicit branch below.
const AI_API_ROUTE = "ai-api";
/**
 * ⭐⭐ WAVE 49 Β· T01 (owner rulings R1, R2, R30) β€” THE SHEET MODULE.
 *
 * Built on the CONNECTORS pattern, not the `_BUILDERS` page pattern: a route constant, a lazy
 * page, a rail row. `platform/core/registry.py::REGISTRY` rows are dashboard MODULES, and Data and
 * Connectors are chrome route constants with no row there β€” so Sheet gets none either. β›” AND IT
 * MUST NOT: every provisioned tenant carries a restricted `modules` list (`['analyst','automation']`
 * on all three today) and `/nav` silently OMITS a registry key outside it, so a `registry.py` row
 * would make Sheet invisible in every tenant on the platform while every gate stayed green. That
 * is the trap `nav.ts::INBOX_ROUTE` and `QUERY_ROUTE` are each annotated with by name.
 *
 * ⚠ THE ROUTE CONSTANT LIVES IN `../sheet` RATHER THAN IN `./nav` BESIDE ITS SIBLINGS, because
 * T01's file fence does not include `nav.ts`. Consequence, read rather than assumed: `sheet` is
 * absent from `nav.ts::CHROME_ROUTES`, whose only runtime consumer is `firstDestination` (the
 * LANDING question) β€” and `sheet` is not in `LANDING_PREFERENCE`, so nothing behaves differently.
 * `#/sheet` is reachable because the hash normaliser below rewrites only `LOGIN_ROUTE` and the
 * empty hash, and `resolveRoute` answers an unknown key with `undefined`, which lands on this
 * file's own `route === SHEET_ROUTE` branch. Folding the constant into `CHROME_ROUTES` later is
 * additive and safe; it is recorded in T01's handoff rather than done behind the fence.
 */
import { SHEET_ROUTE } from "../sheet";
const SheetPage = lazy(() => import("../sheet/SheetPage"));
/* ⭐ WAVE 35 Β· T06 (contract C6, wiring W2) β€” the three account surfaces, session B's tree. Lazy
   like every other page here: none of them is on the path to first paint, and all three are behind
   a menu the user has to open. Default exports, as B published them β€” `lazy()` over a NAMED export
   fails at RUNTIME, on click, and only for that one surface (the note at the top of this file). */
const FeedbackPage = lazy(() => import("../account/FeedbackPage"));
const UsagePage = lazy(() => import("../account/UsagePage"));
const SubscriptionPage = lazy(() => import("../account/SubscriptionPage"));
// 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";
// ⚠ EAGER, not `lazy()`, and deliberately β€” same call as `FormPublic` beside it. A published link
// is a stranger's FIRST request; a lazy chunk would cost them a second round trip before anything
// paints, to save a signed-in user bytes they have already paid for. The page imports nothing
// from `customer-grid/**`, so it drags no spreadsheet engine along with it.
import PublishedView from "../publish/PublishedView";
import { financeNavigation, mergeRecents } from "../home/homeModel";
import type { AutomationTile } from "../home/homeModel";
import type { ApplicationTile } from "../home/HomePage";
// ⭐ 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, listVoiceAgents } from "../automation/automationApi";
import { CreateNewRow, 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"));
/**
 * ⭐⭐ 2026-08-14 (owner item 2) β€” THE AI ASSISTANT, UNBOARDED.
 *
 * β›” AND THE `ai-agent` MODULE IS GONE, WHICH IS THE SAME DECISION SEEN FROM THE OTHER SIDE.
 * 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's own note beside that rail row had already reached the same conclusion and declined to
 * act on it (*"that row's destination IS dead … retiring it in favour of this one looks right"*),
 * raising it as ASK C-9. This is the answer to that ask: ONE AI door, and it is this one.
 *
 * ⚠ The `ai_agent` automation ACTION KIND is a different thing and stays β€” it is a STEP inside a
 * flow (`automation_engine.py`), not a module, and `POST /automations/draft` behind it is still
 * mounted and still gated (`api/verify_automation.py::section_w33_ai_agent`).
 */
const AssistantPage = lazy(() => import("../assistant/AssistantPage"));

/**
 * 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.
 */
/** ⭐ WAVE 37 Β· T06 (R7) β€” is `route` a REAL surface this session was not granted?
 *
 *  Returns its LABEL (so the placeholder can name what was knocked on) or `""`.
 *
 *  β›” THE TABLE IS EXPLICIT AND SHORT ON PURPOSE. A generic "any route with no entry" rule would
 *  board every stale bookmark and every hand-typed key, which is precisely what the `!active`
 *  fallback to Home already handles correctly and deliberately. Only a surface that REALLY EXISTS
 *  can be honestly called under construction; anything else is a lie about a feature.
 *  ⚠ The two keys are the REGISTRY's (`registry.py`: `analyst` = "Assistant", `automation` =
 *  "Agents"), not the routes' β€” `#/assistant` is served by the `analyst` grant, and reading the
 *  route name as the grant key is the mismatch this comment exists to prevent.
 *
 *  β›”β›” AND IT MUST READ **BOTH** BUCKETS, WHICH IS THE BUG THIS FUNCTION SHIPPED WITH FOR AN HOUR.
 *  The first version asked `entries` alone. `splitChrome` sends every page with `chrome ===
 *  "utility"` to `utility` and everything else to `entries` β€” and `analyst` is a UTILITY page, which
 *  is why the shell's own `findAnalyst(utility)` exists twenty lines below. So `entries.some(key ===
 *  "analyst")` was ALWAYS false and the Assistant read "Under construction" **for everyone,
 *  administrators included**. It was found by looking at a screenshot taken for a different ticket.
 *  ⭐ THE LESSON IS THE ONE THIS WAVE ALREADY BOOKED TWICE (`NOTE C-14`, amendment A21): reading the
 *  SYMBOL and not the DATA IT RESOLVES AGAINST. `entries` is a true name for a collection that does
 *  not contain what this function needed.
 */
function boardedFor(
  route: string,
  entries: ReadonlyArray<{ key: string }>,
  utility: ReadonlyArray<{ key: string }>,
): string {
  const BOARDED: ReadonlyArray<[string, string, string]> = [
    [ASSISTANT_ROUTE, "analyst", "Assistant"],
    ["automation", "automation", "Agents"],
  ];
  for (const [r, key, label] of BOARDED) {
    if (route === r && !entries.some((e) => e.key === key)
        && !utility.some((e) => e.key === key)) return label;
  }
  return "";
}

function Lazily({ children, surface }: { children: ReactNode; surface: string }) {
  return (
    <ErrorBoundary surface={surface}>
      <Suspense fallback={
        <div className="shell-rail-skeleton is-destination" role="status" aria-label={`Loading ${surface}`}>
          <div className="shell-rail-skeleton-row is-heading" aria-hidden="true">
            <span className="shell-rail-skeleton-mark" />
            <span className="shell-rail-skeleton-bar" />
          </div>
          {Array.from({ length: 6 }, (_, row) => (
            <div className="shell-rail-skeleton-row" key={row} aria-hidden="true">
              {Array.from({ length: 4 }, (_, column) => (
                <span className="shell-rail-skeleton-bar" key={column} />
              ))}
            </div>
          ))}
        </div>
      }>{children}</Suspense>
    </ErrorBoundary>
  );
}

type ApplicationTemplateKind = "route" | "catalog";

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

interface ApplicationTemplate {
  kind: ApplicationTemplateKind;
  label: string;
  applicationType: "route" | "map";
  displayMode: "map";
  fieldRoles: ApplicationTemplateRole[];
  defaultPlacement: { section: "app"; order: number };
}

interface CreatedTemplateApplication {
  id: string;
  name: string;
  type: string;
  templateKind: ApplicationTemplateKind;
  sourceDatabase: string;
  fieldMap: Record<string, string>;
  openTarget?: { database?: string };
}

type WizardLoad<T> =
  | { phase: "idle" }
  | { phase: "loading" }
  | { phase: "ready"; value: T }
  | { phase: "error"; message: string };

function TemplateRouteIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <circle cx="5" cy="6" r="2.2" />
      <circle cx="19" cy="18" r="2.2" />
      <path d="M7.2 6h3.3c2.2 0 2.2 3.3 4.4 3.3h1c2 0 2 3.6 0 3.6h-4.8c-2.1 0-2.1 3.1-4.1 3.1H5" />
    </svg>
  );
}

function TemplateCatalogIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <rect x="3" y="4" width="18" height="16" rx="2" />
      <path d="M3 9h18M9 9v11M15 9v11" />
    </svg>
  );
}

function ApplicationWizard({
  databases,
  initialTemplate = "",
  panelRef,
  onClose,
  onBusyChange,
  onCreated,
}: {
  databases: DataDatabase[];
  initialTemplate?: string;
  panelRef: RefObject<HTMLDivElement>;
  onClose: () => void;
  onBusyChange: (busy: boolean) => void;
  onCreated: (application: CreatedTemplateApplication) => void;
}) {
  const [step, setStep] = useState(0);
  const [templates, setTemplates] = useState<WizardLoad<ApplicationTemplate[]>>({ phase: "loading" });
  const [templateKind, setTemplateKind] = useState<ApplicationTemplateKind | "">(
    initialTemplate === "route" || initialTemplate === "catalog" ? initialTemplate : "");
  const [sourceDatabase, setSourceDatabase] = useState("");
  const [schema, setSchema] = useState<WizardLoad<SchemaPayload>>({ phase: "idle" });
  const [fieldMap, setFieldMap] = useState<Record<string, string>>({});
  const [name, setName] = useState("");
  const [shareEntries, setShareEntries] = useState<ShareEntry[]>([]);
  const [sharePeople, setSharePeople] = useState<SharePerson[]>([]);
  const [shareQuery, setShareQuery] = useState("");
  const [sharePickRole, setSharePickRole] = useState<ShareRole>("view");
  const [shareLoadPhase, setShareLoadPhase] = useState<"idle" | "loading" | "ready">("idle");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const schemaGeneration = useRef(0);

  useEffect(() => {
    const controller = new AbortController();
    setTemplates({ phase: "loading" });
    void fetch(`${API_V1}/nav/application-templates`, {
      credentials: CREDENTIALS,
      signal: controller.signal,
    }).then(async (response) => {
      const body = await response.json().catch(() => ({}));
      if (!response.ok) throw new Error(String(
        body?.detail?.message ?? body?.detail ?? "Application templates could not be loaded.",
      ));
      const offered = Array.isArray(body?.templates)
        ? body.templates.filter((row: unknown): row is ApplicationTemplate => {
            if (!row || typeof row !== "object" || Array.isArray(row)) return false;
            const candidate = row as Partial<ApplicationTemplate>;
            return (candidate.kind === "route" || candidate.kind === "catalog") &&
              Array.isArray(candidate.fieldRoles) && !!candidate.defaultPlacement;
          })
        : [];
      if (!offered.length) throw new Error("No Application templates are available.");
      if (!controller.signal.aborted) {
        setTemplates({ phase: "ready", value: offered });
        setName(offered.find((candidate: ApplicationTemplate) => candidate.kind === initialTemplate)?.label ?? "");
        if (offered.some((candidate: ApplicationTemplate) => candidate.kind === initialTemplate)) setStep(1);
      }
    }).catch((reason: unknown) => {
      if (!controller.signal.aborted) setTemplates({
        phase: "error",
        message: reason instanceof Error ? reason.message : "Application templates could not be loaded.",
      });
    });
    return () => controller.abort();
  }, [initialTemplate]);

  useEffect(() => {
    onBusyChange(busy);
    return () => onBusyChange(false);
  }, [busy, onBusyChange]);

  useEffect(() => {
    const mine = ++schemaGeneration.current;
    if (!sourceDatabase) {
      setSchema({ phase: "idle" });
      return;
    }
    setSchema({ phase: "loading" });
    void fetchSchema(sourceDatabase).then((answer) => {
      if (mine !== schemaGeneration.current) return;
      setSchema(answer
        ? { phase: "ready", value: answer }
        : { phase: "error", message: "The database fields could not be loaded." });
    });
    return () => { schemaGeneration.current += 1; };
  }, [sourceDatabase]);

  useEffect(() => {
    const controller = new AbortController();
    setShareEntries([]);
    setSharePeople([]);
    setShareQuery("");
    setSharePickRole("view");
    if (!sourceDatabase) {
      setShareLoadPhase("idle");
      return () => controller.abort();
    }
    setShareLoadPhase("loading");
    void fetch(`${API_V1}/share/database/${encodeURIComponent(sourceDatabase)}`, {
      credentials: CREDENTIALS,
      signal: controller.signal,
    }).then(async (response) => {
      const body = await response.json().catch(() => ({}));
      if (!controller.signal.aborted) {
        setSharePeople(response.ok ? parseShare(body).people : []);
        setShareLoadPhase("ready");
      }
    }).catch(() => {
      if (!controller.signal.aborted) {
        setSharePeople([]);
        setShareLoadPhase("ready");
      }
    });
    return () => controller.abort();
  }, [sourceDatabase]);

  useApplicationWizardOverlay(panelRef, onClose);

  const shareOptions = addablePeople(sharePeople, shareEntries);
  const shareRecipient = resolveShareRecipient(sharePeople, shareEntries, shareQuery);
  const canAddEveryone = !shareEntries.some((entry) => entry.user === EVERYONE);
  const shareNameOf = (user: string) => user === EVERYONE
    ? EVERYONE_LABEL
    : sharePeople.find((person) => person.user === user)?.name ?? user;
  const template = templates.phase === "ready"
    ? templates.value.find((candidate) => candidate.kind === templateKind) ?? null
    : null;
  const mappedLatitude = fieldMap.latitude ?? "";
  const mappedLongitude = fieldMap.longitude ?? "";
  const mappedAddress = fieldMap.address ?? "";
  const missingRequired = template?.fieldRoles.some(
    (role) => role.required && !String(fieldMap[role.key] ?? "").trim(),
  ) ?? true;
  const coordinatePairError = templateKind === "route" && (
    Boolean(mappedLatitude) !== Boolean(mappedLongitude) ||
    Boolean(mappedLatitude && mappedLongitude && mappedLatitude === mappedLongitude)
  );
  const routeLocationError = templateKind === "route" &&
    !mappedAddress && !mappedLatitude && !mappedLongitude;
  const canContinue = step === 0
    ? !!template
    : step === 1
      ? !!sourceDatabase && schema.phase === "ready"
      : step === 2
        ? !missingRequired && !coordinatePairError && !routeLocationError
        : step === 3
          ? true
          : !!name.trim();

  const chooseTemplate = (candidate: ApplicationTemplate) => {
    setTemplateKind(candidate.kind);
    setName(candidate.label);
    setFieldMap({});
    setError("");
  };

  const createApplication = async () => {
    if (!template || schema.phase !== "ready" || !canContinue || busy) return;
    setBusy(true);
    setError("");
    const mapped = Object.fromEntries(
      Object.entries(fieldMap).filter(([, value]) => String(value).trim()),
    );
    try {
      const response = await fetch(`${API_V1}/nav/applications`, {
        method: "POST",
        credentials: CREDENTIALS,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: name.trim(),
          templateKind: template.kind,
          type: template.applicationType,
          sourceDatabase,
          fieldMap: mapped,
          navPlacement: template.defaultPlacement,
        }),
      });
      const body = await response.json().catch(() => ({}));
      if (!response.ok || !body?.application?.id) {
        throw new Error(String(
          body?.detail?.message ?? body?.detail ?? "The Application was not saved.",
        ));
      }
      if (shareEntries.length > 0) {
        try {
          // β›”β›” FIXED AT THE WAVE-59 COMBINE: this PATCHed `/nav/applications/{id}`, and NO
          // SUCH ROUTE EXISTS -- `routes_nav.py` mounts only `POST /nav/applications`. Every
          // create therefore fell into the catch below and reported "sharing did not save",
          // so W59-T26's done-when ("creating the app persists those grants") could not hold.
          // The reviewed door is `PATCH /applications/{id}` in `routes_assets.py`, which
          // passes the body to `application_registry.mutate` -- and that is the writer that
          // already understands `{share: {mode, users}}`, the exact shape sent below.
          // ⚠ Only api_api's D-48 leg could see this: it is the one check that matches every
          // decidable client fetch path against a route the app actually MOUNTED, it belongs
          // to lane F, and lane E owned neither it nor `routes_nav.py`.
          const shareResponse = await fetch(`${API_V1}/applications/${encodeURIComponent(body.application.id)}`, {
            method: "PATCH",
            credentials: CREDENTIALS,
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              share: shareEntries.some((entry) => entry.user === EVERYONE)
                ? { mode: "tenant", users: [] }
                : { mode: "users", users: shareEntries.map((entry) => entry.user) },
            }),
          });
          await shareResponse.json().catch(() => ({}));
          if (!shareResponse.ok) throw new Error("Sharing did not save.");
        } catch {
          const sharingError = "The app was created, but sharing did not save. You can share it from the App module.";
          setError(sharingError);
          // Creation closes the wizard, so the shell must also carry the partial result.
          window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: sharingError }));
        }
      }
      onCreated(body.application as CreatedTemplateApplication);
    } catch (reason: unknown) {
      setError(reason instanceof Error ? reason.message : "The Application was not saved.");
    } finally {
      setBusy(false);
    }
  };

  const headings = ["Choose a template", "Choose a database", "Map the fields", "Choose who can open it", "Review and create"];
  return (
    <div className="shell-newdb-scrim">
      <div
        ref={panelRef}
        className="shell-newdb app-wizard"
        role="dialog"
        aria-modal="true"
        aria-label="Create application"
      >
        <header className="app-wizard-head">
          <div>
            <p>New Application</p>
            <h2>{headings[step]}</h2>
          </div>
          <button type="button" className="app-wizard-close" aria-label="Close" onClick={onClose} disabled={busy}>
            <svg viewBox="0 0 16 16" aria-hidden="true"><path d="m3.5 3.5 9 9m0-9-9 9" /></svg>
          </button>
        </header>
        <ol className="app-wizard-steps" aria-label="Application setup progress">
          {["Template", "Database", "Fields", "Share", "Review"].map((label, index) => (
            <li key={label} className={index === step ? "is-current" : index < step ? "is-done" : ""}
              aria-current={index === step ? "step" : undefined}>
              <span>{index + 1}</span>{label}
            </li>
          ))}
        </ol>

        <div className="app-wizard-body">
          {step === 0 ? (
            templates.phase === "loading" ? (
              <div className="app-wizard-loading" role="status" aria-label="Loading templates">
                <span /><span />
              </div>
            ) : templates.phase === "error" ? (
              <p className="app-wizard-message is-error" role="alert">{templates.message}</p>
            ) : templates.phase === "ready" ? (
              <div className="app-wizard-template-grid">
                {templates.value.map((candidate) => (
                  <button
                    key={candidate.kind}
                    type="button"
                    className={templateKind === candidate.kind ? "app-wizard-template is-selected" : "app-wizard-template"}
                    aria-pressed={templateKind === candidate.kind}
                    onClick={() => chooseTemplate(candidate)}
                  >
                    <span className="app-wizard-template-icon">
                      {candidate.kind === "route" ? <TemplateRouteIcon /> : <TemplateCatalogIcon />}
                    </span>
                    <span><strong>{candidate.label}</strong><small>
                      {candidate.kind === "route"
                        ? "Plan customer routes from mapped records."
                        : "Browse mapped records as a visual catalog."}
                    </small></span>
                  </button>
                ))}
              </div>
            ) : null
          ) : null}

          {step === 1 ? (
            <label className="app-wizard-field">
              <span>Source database</span>
              <select value={sourceDatabase} onChange={(event) => {
                setSourceDatabase(event.target.value);
                setFieldMap({});
                setError("");
              }}>
                <option value="">Choose a database</option>
                {databases.map((database) => <option key={database.key} value={database.key}>{database.label}</option>)}
              </select>
              {schema.phase === "loading" ? <small role="status">Loading database fields...</small> : null}
              {schema.phase === "error" ? <small className="is-error" role="alert">{schema.message}</small> : null}
            </label>
          ) : null}

          {step === 2 && template && schema.phase === "ready" ? (
            <div className="app-wizard-field-list">
              <p>Map each Application role to a field in {schema.value.label}.</p>
              {template.kind === "route" ? (
                <p>Coordinates are used when present, and you can look up the address for selected records when they are empty.</p>
              ) : null}
              {template.fieldRoles.map((role) => {
                const options = schema.value.fields.filter((field) =>
                  !role.types.length || role.types.includes(field.type.toLowerCase()),
                );
                return (
                  <label className="app-wizard-field" key={role.key}>
                    <span>{role.label}{role.required ? <small>Required</small> : <small>Optional</small>}</span>
                    <select value={fieldMap[role.key] ?? ""} onChange={(event) => {
                      setFieldMap((current) => ({ ...current, [role.key]: event.target.value }));
                      setError("");
                    }}>
                      <option value="">{role.required ? "Choose a field" : "Not mapped"}</option>
                      {options.map((field: SchemaField) => (
                        <option key={field.key} value={field.key}>{field.label}</option>
                      ))}
                    </select>
                  </label>
                );
              })}
              {coordinatePairError ? (
                <p className="app-wizard-message is-error" role="alert">
                  Routing needs both coordinate fields or neither, and they must be different.
                </p>
              ) : null}
              {routeLocationError ? (
                <p className="app-wizard-message is-error" role="alert">
                  Choose both coordinate fields or an address field.
                </p>
              ) : null}
            </div>
          ) : null}

          {step === 3 ? (
            shareLoadPhase === "loading" ? (
              <p className="shell-share-blurb" role="status">Loading people...</p>
            ) : sharePeople.length === 0 ? (
              <p className="shell-share-blurb">Only you can open this app for now. You can share it from the App module later.</p>
            ) : (
              <>
                <div className="shell-share-list">
                  {shareEntries.length === 0 ? (
                    <div className="shell-share-empty">Not shared with anyone yet.</div>
                  ) : null}
                  {shareEntries.map((entry) => (
                    <div className="shell-share-row" key={entry.user}>
                      <span className="shell-share-who">{shareNameOf(entry.user)}</span>
                      <select
                        className="shell-share-select"
                        value={entry.role}
                        disabled={busy}
                        aria-label={`Role for ${shareNameOf(entry.user)}`}
                        onChange={(event) => setShareEntries((current) =>
                          withEntry(current, entry.user, event.target.value as ShareRole))}
                      >
                        {SHARE_ROLES.map((role) => (
                          <option key={role} value={role}>{role === "edit" ? "Can edit" : "Can view"}</option>
                        ))}
                      </select>
                      <button type="button" className="shell-share-revoke" disabled={busy}
                        onClick={() => setShareEntries((current) => withoutEntry(current, entry.user))}>
                        Remove
                      </button>
                    </div>
                  ))}
                </div>
                <div className="shell-share-add">
                  <input
                    className="shell-share-select"
                    type="search"
                    list="app-wizard-share-options"
                    value={shareQuery}
                    disabled={busy}
                    aria-label="Search people to share with"
                    placeholder="Search people"
                    onChange={(event) => setShareQuery(event.target.value)}
                  />
                  <datalist id="app-wizard-share-options">
                    {canAddEveryone ? <option value={EVERYONE_LABEL} /> : null}
                    {shareOptions.map((person) => (
                      <option key={person.user} value={`${person.name} (${person.user})`} />
                    ))}
                  </datalist>
                  <select
                    className="shell-share-select"
                    value={sharePickRole}
                    disabled={busy}
                    aria-label="Role for the person being added"
                    onChange={(event) => setSharePickRole(event.target.value as ShareRole)}
                  >
                    {SHARE_ROLES.map((role) => (
                      <option key={role} value={role}>{role === "edit" ? "Can edit" : "Can view"}</option>
                    ))}
                  </select>
                  <button type="button" className="login-submit shell-share-grant"
                    disabled={busy || !shareRecipient}
                    onClick={() => {
                      if (!shareRecipient) return;
                      setShareEntries((current) => withEntry(current, shareRecipient, sharePickRole));
                      setShareQuery("");
                    }}>
                    Grant access
                  </button>
                </div>
                <p className="shell-share-blurb">Everyone you add can open this app. Only you can change it.</p>
              </>
            )
          ) : null}

          {step === 4 && template ? (
            <div className="app-wizard-review">
              <label className="app-wizard-field">
                <span>Application name</span>
                <input value={name} maxLength={120} onChange={(event) => { setName(event.target.value); setError(""); }} />
              </label>
              <dl>
                <div><dt>Template</dt><dd>{template.label}</dd></div>
                <div><dt>Database</dt><dd>{schema.phase === "ready" ? schema.value.label : sourceDatabase}</dd></div>
                <div><dt>Shared with</dt><dd>{shareEntries.length
                  ? shareEntries.map((entry) => shareNameOf(entry.user)).join(", ")
                  : "Only you"}</dd></div>
                {template.fieldRoles.filter((role) => fieldMap[role.key]).map((role) => (
                  <div key={role.key}><dt>{role.label}</dt><dd>{
                    schema.phase === "ready"
                      ? schema.value.fields.find((field) => field.key === fieldMap[role.key])?.label ?? fieldMap[role.key]
                      : fieldMap[role.key]
                  }</dd></div>
                ))}
              </dl>
              <p className="app-wizard-review-note">This saves an Application definition in App and opens it with the selected database.</p>
            </div>
          ) : null}

          <p className={error ? "app-wizard-message is-error" : "app-wizard-message"} role="alert">
            {error}
          </p>
        </div>

        <footer className="app-wizard-actions">
          <button type="button" className="app-wizard-secondary" onClick={onClose} disabled={busy}>Cancel</button>
          <span />
          {step > 0 ? (
            <button type="button" className="app-wizard-secondary" onClick={() => { setStep((current) => current - 1); setError(""); }} disabled={busy}>Back</button>
          ) : null}
          {step < 4 ? (
            <button type="button" className="login-submit" disabled={!canContinue || busy}
              onClick={() => { setStep((current) => current + 1); setError(""); }}>Continue</button>
          ) : (
            <button type="button" className="login-submit" disabled={!canContinue || busy}
              onClick={() => void createApplication()}>{busy ? "Creating..." : "Create and open"}</button>
          )}
        </footer>
      </div>
    </div>
  );
}

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 { EVERYONE, EVERYONE_LABEL, SHARE_OPEN_EVENT, SHARE_ROLES, addablePeople, parseShare, parseShareRequest, resolveShareRecipient, withEntry, withoutEntry } from "./shareModel";
import type { ShareEntry, SharePerson, ShareRequest, ShareRole } from "./shareModel";
// WAVE 19 R8 β€” the chosen database mark. Read-only across the session fence.
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";

/** HOTFIX 2026-09-24: the same-origin OAuth approval a sign-in interrupted, resumed once. */
function resumeOAuthApproval(): boolean {
  let saved: string | null = null;
  try {
    saved = window.sessionStorage.getItem("aios.oauthReturn");
    window.sessionStorage.removeItem("aios.oauthReturn");
  } catch {
    return false;
  }
  if (!saved) return false;
  try {
    const url = new URL(saved, window.location.origin);
    if (url.origin !== window.location.origin || url.pathname !== "/api/v1/external/oauth/authorize")
      return false;
    window.location.assign(url.href);
    return true;
  } catch {
    return false;
  }
}
/** A stable identity for "no nav yet" β€” see its use below. */
const NO_ENTRIES: NavEntry[] = [];

/* β›”β›” W40-T22 (owner instruction 5, 2026-08-23) β€” `const GRID_CHAT_OPEN_EVENT` STOOD HERE, WITH A
   long argument for the shell→grid "open the chat" channel, AND IT IS DELETED. The owner: *"remove
   [the 'Ask about this data' icon] from the MAIN navigation entirely so it lives only in the
   secondary navigation"*. The twin constant existed for exactly ONE raiser β€” the minimised rail's
   launcher, deleted in the same ticket β€” so the argument it carried (why the literal is typed twice
   rather than imported) is an argument for a control that no longer exists, and leaving it standing
   is how the control comes back.
   ⚠ THE GRID SIDE IS UNTOUCHED AND THAT IS DELIBERATE: `CustomerGrid.tsx` still exports the same
   constant and still listens on it, and `ViewSidebar.tsx`'s `cg-chat-toggle` opens the panel
   directly through `onToggleChat` rather than through the event. The listener is now dormant, not
   broken; removing it is a separate decision and `CustomerGrid.tsx` was outside this ticket.
   ⚠ `verify_wiring.py`'s two W38-T06 rows, which asserted this constant and its click, are deleted
   with it and carry their own tombstone there. */

/* β›”β›” W41-T32 (owner instruction 29, ruling R2) β€” `DBFLY_MAX_H`, `flyoutAt` AND `flyoutFrom`
   STOOD HERE AND ARE DELETED WITH THE PANEL THEY POSITIONED. Owner: *"when a user click on a
   Database (let's rename it to Data), it doesn't pop up a [flyout] of the database, instead it
   should show the list of databases in the second navigation"*. R2 makes the rail a PATH STACK:
   the database list is a rail LEVEL now, a direct child of `.shell-nav`, so it inherits the rail's
   own scroll and needs no anchor, no clamp and no portal. Three exported symbols with zero call
   sites is [[artifact-with-no-importer]]; they go rather than stand as geometry for a control
   nobody can open. Checked before deleting: `grep flyoutAt\|flyoutFrom` over `web/src/**` returns
   this file only β€” no importer anywhere, and no `_test/` leg.
   ⚠ WAVE 23's C10 ARGUMENT WAS RIGHT FOR ITS OWN DESIGN and is worth keeping in view: a panel that
   escapes a scrolling, clipping, 44px-collapsible rail cannot be a descendant of it. This ticket
   does not answer that objection, it removes it β€” a LEVEL replaces the rail's contents instead of
   floating beside them, so there is nothing to escape from. The collapsed rail is handled at the
   click instead (the Data row expands the rail before it drills β€” see its own note).
   β›” AND THREE `verify_home.py` LEGS ASSERT WHAT THIS DELETES β€” see the tombstone at the flyout's
   old site further down for the exact line numbers. They are RETARGET work, not this lane's:
   `aios-web/api/verify_home.py` is a gate, and a gate is off this lane's fence. */

/**
 * 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;
}

/**
 * ⭐⭐ WAVE 33 item 8b (ruling R5, W33-T26) β€” the PUBLISHED VIEW route: `#/v/<token>`.
 *
 * The same construction as `formTokenOf` immediately above, and the same reason: the token is
 * WHITELISTED against `secrets.token_urlsafe`'s alphabet, never sliced out of the hash. Anything
 * else in that position is not a token this product minted, and passing it through would let a
 * crafted hash decide what `PublishedView` puts in a URL. Refusing here drops the frame back into
 * normal routing, where the visitor meets the login page β€” the right answer for a link that is
 * not one of ours.
 *
 * ⚠ `v` RATHER THAN `view`, and it is not brevity for its own sake: `#/view/...` would sit one
 * typo away from the app's own routes, while `v` is a namespace nothing else claims. R5 names
 * this exact shape.
 */
export function publishTokenOf(route: string): string | null {
  const m = /^v\/([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; malformed?: boolean };

type FinanceNav =
  | { phase: "idle" | "loading" | "error" }
  | { phase: "ready"; applications: ApplicationTile[] };

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

/**
 * ⭐⭐ W33-T22 (owner item 1) β€” THE TWO ROWS THE PAYLOAD DECIDES, FOUND IN ONE PLACE.
 *
 * ⚠ Both predicates had exactly one call site, in the render body, and now have two β€” the render
 * and the memory effect below. Written out here so the two cannot answer differently: "is
 * Automation on this rail?" must not be `kind === "native"` in one place and `truthy` in the
 * other, or the remembered rail reserves a slot the render never fills [[one-question-two-normalizers]].
 */
const findAnalyst = (utility: NavPage[]) => utility.find((p) => p.key === "analyst");
const findAutomation = (entries: NavEntry[]) =>
  entries.find((e) => e.key === "automation" && e.kind === "native");

/**
 * ⭐⭐ W33-T22 β€” WHAT THIS ACCOUNT'S RAIL LOOKED LIKE LAST TIME, so first paint need not guess.
 *
 * β›” THE PROBLEM A PLACEHOLDER ALONE DOES NOT SOLVE, and it was found by a reviewer reading the
 * fix rather than by any gate. Holding a slot for a conditional row fixes the common case β€” the
 * row lands and fills the box it was already occupying β€” but for an account that does NOT have
 * the surface, the slot is reserved at first paint and then COLLAPSES when `/nav` says "silent".
 * That is a flash-then-shove, i.e. arguably worse for that user than the bug we set out to fix,
 * and `silent` must keep collapsing: reserving permanent space for a surface the server did not
 * grant would be the hard-coded row this frame refuses to have (see the file header).
 *
 * ⭐ SO THE FIRST PAINT REPRODUCES THE LAST ONE. On every `ready` payload we record which of the
 * two conditional rows this account actually had; on the next load we reserve a slot only for the
 * rows it had. A returning user therefore gets their FINAL rail geometry in the first paint,
 * whichever way it goes, and `/nav` only ever confirms it.
 *
 * ⚠ KEYED BY USERNAME, NOT BY BROWSER. `aios-nav-collapsed` above is a per-BROWSER preference and
 * that is right for it; this is a per-ACCOUNT fact about permissions, and on a shared machine an
 * un-keyed version would paint one person's grants for another. `who` is known at first paint
 * because the shell is released on `/me`, which is the same fact that makes this bug possible.
 *
 * β›” UNKNOWN IS NOT FALSE. A first-ever load has no memory, and the honest answer there is to
 * RESERVE the slot (`pending`), not to assume absence β€” an absent row that then arrives is the
 * original defect. Only a remembered, explicit `false` suppresses the placeholder. Same on a
 * blocked/parse-failed storage: fall back to reserving.
 */
// W33-T75 supersedes the T22 account-memory approach above. The whole rail owns loading, and a
// settled known-absent module collapses completely; only an incomplete response keeps an honest
// unavailable row. The absent marker below has no label, route, focus target, or layout.

/**
 * ⭐⭐ W33-T75 (owner item 1, `reference/ERROR 6.png`) β€” THE RAIL PAINTS ONCE.
 *
 * β›” THE ACCEPTANCE TEST IS NOT "THE SPINNER IS GONE", IT IS "NO ROW IS EVER IN A DIFFERENT
 * STATE FROM ITS SIBLINGS." The owner has reported this four times. Every previous answer kept
 * the same shape β€” five finished rows plus one or two rows wearing a *distinguishable* loading
 * state β€” and shrank the difference: `/nav` went 11.0 s β†’ 26 ms (still two paints, because
 * `:911` makes `entries` `NO_ENTRIES` until `nav.phase === "ready"`, so first paint happens
 * while "does this workspace have Automation / an Analyst?" is unknown at ANY speed); then W31-T11
 * gave Automation a spinner slot; then W33-T22 gave the Assistant one too. `ERROR 6.png` is the
 * result: Home / Query / Inbox / Database / Connectors drawn in ink, **AI assistant and Automation
 * drawn as spinners**, and a sixth spinner below Connectors. Two states in one list is exactly
 * what "the navigation loads separately" describes, and a placeholder that ANNOUNCES itself as
 * pending is a second state however tall it is.
 *
 * β›” SO THE FIX IS AT THE OTHER END: while `/nav` is in flight the rail draws THIS and no rows at
 * all. One skeleton, seven identical bars, nothing claiming to be a destination β€” then the real
 * rail arrives in a single paint. There is no frame in which one row is further along than
 * another, which is the only form of the sentence that cannot come back a fifth time.
 *
 * ⚠ WHAT IT COSTS, STATED RATHER THAN DISCOVERED: Home / Query / Inbox / Database / Connectors
 * are not clickable for the length of the `/nav` round trip, where before they were. That is a
 * real trade and it is the owner's own priority β€” measured, `/nav` is **0.77 s cold on the
 * deployed build and 26 ms warm** (wave 33 close record), so the window is short; and the four
 * waves of reports are about the rail's shape, never about waiting for it. `phase: "error"` and
 * `degraded` are UNCHANGED: they draw the real rows with their unavailable arms, because there
 * the answer has arrived and is bad news, which is a fact worth showing rather than a wait.
 *
 * The sixteen-row skeleton is a deliberate ceiling over the settled rail of nine or ten rows.
 * Finance applications now live as cards inside App and contribute no rail rows.
 * β›” KEEP THIS NUMBER >= THE SETTLED ROW COUNT AND NEVER BELOW IT. A skeleton one bar TALLER than
 * the settled rail is a shrink, which is fine; one bar SHORTER is the appear-from-nowhere shove
 * W33-T22 was written about, arriving by a different door. The two `.shell-nav-sep` hairlines are
 * deliberately NOT counted: they are hidden by the same `is-rail-loading` rule as the rows.
 */
const RAIL_SKELETON_ROWS = 16;

function RailSkeleton() {
  return (
    <div className="shell-rail-skeleton" role="status" aria-label="Loading navigation">
      {Array.from({ length: RAIL_SKELETON_ROWS }, (_, i) => (
        <div className="shell-rail-skeleton-row" key={i} aria-hidden="true">
          <span className="shell-rail-skeleton-mark" />
          <span className="shell-rail-skeleton-bar" />
        </div>
      ))}
    </div>
  );
}

function useHashRoute(): { route: string; hash: 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.
  //
  // β›”β›” W34-T15 β€” `routeKeyOf` REPLACES `.replace(/^#\/?/, "")`, AND THAT IS THE WHOLE TICKET.
  // Lane D found it before it could ship (post D-1): the old expression took 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 would have
  // put the right URL in the address bar and the wrong screen under it, and a gate asserting the
  // redirect's target string would have been green over it.
  const read = () => {
    if (!window.location.hash && window.location.pathname.startsWith("/finance/")) {
      window.history.replaceState(window.history.state, "", `/#${window.location.pathname}${window.location.search}`);
    }
    const hash = rewrittenHash(window.location.hash) ?? window.location.hash;
    if (hash !== window.location.hash) window.history.replaceState(window.history.state, "", hash);
    return { route: canonicalRoute(routeKeyOf(hash)), hash };
  };
  // ⭐⭐ W34-T15 (R14 / C2) β€” `#/query` BECOMES `#/assistant?mode=query`, IN THE ADDRESS BAR.
  //
  // ⚠ A REWRITE, NOT A RESOLVE, and `LEGACY_ROUTES` alone would not do: the merged surface picks
  // which list to show from `?mode=` on the hash, so a translation that never touched the URL
  // would land a Query bookmark on the CHAT list.
  //
  // β›”β›” AND IT IS IN THE INITIALISER RATHER THAN AN EFFECT, WHICH IS NOT A STYLE CHOICE.
  // `AssistantPage` resolves its mode ONCE, in its own `useState` initialiser, by reading
  // `window.location.hash` (`assistant/AssistantPage.tsx::initialMode` β€” the hash wins, else the
  // stored preference). Children initialise AFTER their parent renders and BEFORE any effect
  // runs. So a rewrite in a `useEffect` here would land after the assistant had already read the
  // OLD hash, found no `?mode=`, fallen back to the stored preference and opened the Chat list β€”
  // right URL, wrong screen, and nothing anywhere to say so. Rewriting during this initialiser
  // updates `window.location.hash` synchronously, so the child reads the new one.
  //
  // ⚠ Safe to run twice (React StrictMode does): `rewrittenHash` answers null once the key is
  // `assistant`, so the second call is a no-op. `replace` rather than assignment, so a bookmark
  // redirect does not leave a back-button trap on the hash it came from.
  const [location, setLocation] = useState(read);
  useEffect(() => {
    // The SAME rewrite for a hash typed into the bar mid-session, where there is no child
    // initialiser to race: by then the assistant is mounted and reads `?mode=` on its own.
    const onChange = () => {
      // Data addressing lives in the query string, so two database hashes intentionally share
      // the canonical route `data`. Keep the whole hash in state to make every location a render.
      setLocation(read());
    };
    window.addEventListener("hashchange", onChange);
    return () => window.removeEventListener("hashchange", onChange);
  }, []);
  return location;
}

/** 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. */
/* β›” `SearchIcon` LIVED HERE AND IS DELETED WITH THE QUERY RAIL ROW (wave 34, R14). It was the
   magnifier the owner asked for on 2026-08-14 (*"Change the icon for Query, it should just be a
   magnifying glass icon"*) and the Query row was its ONLY call site β€” `tsc` said so (TS6133) the
   moment that row went, which is the unused-locals check doing the remembering, exactly as
   `PlusMark`'s note one screen down predicted it would.
   ⚠ A COMMENT IN THIS FILE CLAIMED OTHERWISE FOR ABOUT A MINUTE. The first draft of the Query
   deletion asserted that "the flyout's own filter box draws it" and kept the function on that
   basis. It does not, and `tsc` refuted it immediately. Left here because the useful half is the
   habit, not the slip: a claim about who calls a symbol is checkable in one command, so check it
   rather than reason about it. The magnifier is not lost β€” `#/assistant`'s Query mode is where
   that vocabulary lives now. */


/** The retained `is-spark` hook suppresses the parent stroke, so this dotted ring reuses the
 *  row's `currentColor` directly while the shared glyph rule still owns width and round caps. */
function SparkIcon() {
  return (
    <svg className="shell-nav-icon is-spark" viewBox="0 0 16 16" aria-hidden="true">
      <circle cx="8" cy="8" r="5.5" fillOpacity="0" stroke="currentColor" strokeDasharray="1 1.8" />
    </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>
  );
}

/* ⭐ `DbIcon` AND `gridScopeFor` LIVE IN `shell/dbFrame.tsx` (moved there 2026-08-14). They were
   private to this file, and the owner's Query instruction β€” *"the query module should exactly BE
   looking like the database module, COMPLETELY"* β€” made them a SECOND surface's too. `gridScopeFor`
   is not a move but a fix: the registry key and the grid scope are different spellings, and the map
   used to live inline in the native branch below where nothing else could reach it.
   β›” W53-T35 β€” THIS FILE NO LONGER DRAWS `DbIcon`. Owner instruction 26 standardised the database
   mark on the Home page's outline cylinder, so the Data rail row renders
   `shell/icons.tsx::DatabaseIcon` and only `gridScopeFor` is still imported from `dbFrame.tsx`.
   `DbIcon` stays exported there because `query/queryParts.tsx` still mounts it; if that surface is
   standardised too, it points at `icons.tsx` and `dbFrame.tsx`'s copy goes.
   β›” `DbHead` MOVED WITH THEM AND IS NOW DELETED (W36-T51, owner item 7 β€” *"Remove the header for
   database completely"*). Its tombstone, and the list of what must NOT be swept away with it, is in
   `dbFrame.tsx` where it lived. */

/** 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 `DatabaseIcon` 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 36 Β· T50 (owner item 5) β€” THE OTHER FOUR ACCOUNT-MENU MARKS, so the menu is one column
   of icons rather than one gear and a stack of bare text. W35-T06 shipped Feedback, Usage
   and Subscription as rows with no glyph beside `GearIcon`, which left their labels starting 24px
   further left than Settings' β€” the raggedness is what the owner is looking at when item 5 says
   these rows "need their icon".
   ⚠ THEY ARE DEFINED HERE, BESIDE THE GEAR, AND NOT IN `ui/icons.tsx` β€” checked before choosing.
   That module is the shared presentation layer, its glyphs are `viewBox="0 0 24 24"` and it carries
   Download/Check/Alert/Bell/Star only; the account menu's vocabulary is the 16x16 box plus the
   `.shell-menu-icon` class (`fill:none`, `stroke: currentColor`, 1.2, muted). Adding four 16px
   marks to a 24px module would be the drift `ui/icons.tsx`'s own header warns about, from the other
   direction. Same argument `GearIcon`'s note makes: one family, one file.
   β›” NO EMOJIS (owner constant, DESIGN.md) β€” vector paths, `currentColor`, no colour written here. */

/** Feedback: a speech bubble. The row opens a page that asks the reader to SAY something, and a
 *  bubble is the one mark that means "your words"; an envelope would collide with Inbox's. */
function BubbleIcon() {
  return (
    <svg className="shell-menu-icon" viewBox="0 0 16 16" aria-hidden="true">
      <rect x="2.2" y="3.1" width="11.6" height="8.2" rx="1.8" />
      <path d="M5.8 11.3 5 13.7l3.2-2.4" />
    </svg>
  );
}

/** Usage: a PIE β€” a circle with one wedge marked off.
 *
 *  ⚠ NOT a coin, and the PAGE is what decided it: `UsagePage` renders a METER of consumption (its
 *  own comment argues about what a failed read must not look like β€” *"a meter reading zero is the
 *  most reassuring possible lie"*). A coin would promise a balance the surface does not show. A pie
 *  says "this much of it is gone", which is what the page says.
 *
 *  ⭐ AND THE SHAPE WAS CHOSEN BY LOOKING, NOT BY REASONING, because the first one failed the eye.
 *  Six candidates were rendered at 16px in this exact stroke vocabulary and read at true size
 *  (`scratchpad/shots/glyph-candidates.png`):
 *    Β· an ARC-AND-NEEDLE gauge β€” what shipped first, and it reads as a hill or an eyebrow: the
 *      needle touches the arc and the two merge into one stroke at 16px;
 *    Β· a COIN WITH A RIM (two concentric circles) β€” reads as a bullseye, and it is the loudest
 *      mark in the menu;
 *    Β· a COIN STACK β€” that WAS this rail's database mark (`dbFrame.tsx::DbIcon`), and the
 *      argument stands under W53-T35's replacement: the shape is still spent on "database"
 *      (now as `icons.tsx::DatabaseIcon`'s cylinder here, and as `DbIcon` on Query), and one
 *      mark may mean one thing (DESIGN.md Β§4);
 *    Β· a WALLET β€” reads as a battery;
 *    Β· a gauge WITH A HUB β€” better than the first, still optically thin beside the gear.
 *  The pie won on legibility and on weight: a closed circle sits at the same optical weight as
 *  `GearIcon` above it, and nothing else in the client draws one. */
function PieIcon() {
  return (
    <svg className="shell-menu-icon" viewBox="0 0 16 16" aria-hidden="true">
      <circle cx="8" cy="8" r="5.5" />
      <path d="M8 2.5V8l3.9 2.3" />
    </svg>
  );
}

/** Subscription: a card. The row is about what the workspace pays with, and a card with its stripe
 *  is legible at 16px where anything more literal (a receipt, a calendar of renewals) is not. */
function CardIcon() {
  return (
    <svg className="shell-menu-icon" viewBox="0 0 16 16" aria-hidden="true">
      <rect x="1.9" y="4.1" width="12.2" height="7.8" rx="1.4" />
      <path d="M1.9 6.9h12.2" />
    </svg>
  );
}

/** Sign out: a door with the arrow leaving it.
 *  ⚠ IT NEEDED A CSS RULE AS WELL AS A PATH, and that is the trap in adding a mark to this row:
 *  `.shell-menu-item.is-signout` paints the row `--lp-red-deep` while `.shell-menu-icon` sets its
 *  own `color: var(--lp-muted)`, so the glyph would have rendered grey beside red text and read as
 *  a half-broken row. `index.css` gives the signout icon `color: inherit` at rest and on hover. */
function ExitIcon() {
  return (
    <svg className="shell-menu-icon" viewBox="0 0 16 16" aria-hidden="true">
      <path d="M9.4 2.7H4.2a1.4 1.4 0 0 0-1.4 1.4v7.8a1.4 1.4 0 0 0 1.4 1.4h5.2" />
      <path d="M11.3 5.7 13.7 8l-2.4 2.3" />
      <path d="M6.9 8h6.8" />
    </svg>
  );
}

/* β›” `AutoIcon` LIVED HERE AND IS DELETED WITH THE AGENTS HEADER (W35-T32, owner item 2). It was
   the two-node flow glyph the head drew beside the word "Agents"; with the head gone it had no
   call site, and `tsc`'s unused-locals check named it in the same run β€” which is the argument for
   letting the compiler do the remembering rather than a sweep.
   ⚠ THAT SENTENCE IS STALE AND W51-T30 CORRECTS IT RATHER THAN LEAVING IT TO ROT. It read *"NOT
   the same mark as the rail's `RobotIcon`, which SURVIVES and is what owner item 5 asked for. Two
   glyphs, two jobs; only the header's is retired."* The rail's robot is gone too now (R15, wave
   51) and the rail drew `FlowIcon` β€” a two-node flow glyph, which was the SAME FAMILY of mark this
   header one was.
   ⚠ THAT PARAGRAPH IS STALE IN ITS TURN AND W53-T34 CORRECTS IT RATHER THAN LEAVING IT TO ROT:
   `FlowIcon` IS GONE TOO (owner instruction 4), and there is no flow mark anywhere in the shell
   any more. The rail now draws `shell/icons.tsx::AgentIcon`, a square with two eyes.
   β›” THAT IS NOT A LICENCE TO BRING THIS ONE BACK β€” it is the opposite. `AutoIcon` belonged to a
   HEADER that no longer exists, at header geometry, and its family of mark has now been rejected
   by the owner on the rail. Resurrecting it would re-open a settled question with a glyph nobody
   asked for. */

/* ⭐ `BellIcon` LIVED HERE AND IS DELETED (wave 34, R15) β€” AND THAT DELETION CLOSES `D-207`.
   The Inbox row took `MailIcon`, leaving this local copy with no call site. D-207 records that
   `ui/icons.tsx` β€” the file whose own header warns that "a second hand-copy in the shell is the
   drift this module exists to prevent" β€” already carried a second `BellIcon`, and the shell had
   one anyway. Deleting the LOCAL copy and keeping the SHARED one is the right half to keep: the
   shared module is the one another surface can import.
   ⚠ So `ui/icons.tsx::BellIcon` is now the only bell in the client. `W34-T17` verifies that,
   rather than this comment asserting it. */


/** 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 34 R15 β€” Inbox's mark. An envelope.
 *
 *  ⚠ IT REPLACES `BellIcon` ON THAT ROW, and this is a rename of the CONCEPT, not just the glyph.
 *  Owner, 2026-08-16: *"Alerts is called Inbox and it's right below Home"* (R23) β€” there is no
 *  separate Alerts row and there never was; one row has been wearing a bell while the page it
 *  opens is an inbox. A bell says "something happened"; an envelope says "there is mail for you",
 *  which is what the surface actually shows.
 *
 *  β›” THAT PARAGRAPH IS STALE AND W37-T01 CORRECTS IT RATHER THAN LEAVING IT TO ROT. It read
 *  *"`BellIcon` STAYS DEFINED β€” deleting this one while the duplicate survives would leave the copy
 *  as the only bell, which is the wrong half to keep"*. `W34-T17` DID the reconciliation and kept
 *  the opposite half: the local copy is gone (see the deletion note above this file's icons) and
 *  `ui/icons.tsx::BellIcon` is the only bell in the client, which is the SHARED one and therefore
 *  the right half. **D-207 is closed**, verified by grep at wave 37: one `function BellIcon` in the
 *  tree. A comment asserting a duplicate that no longer exists sends the next reader hunting. */
function MailIcon() {
  return (
    <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
      <rect x="2.1" y="3.9" width="11.8" height="8.2" rx="1.3" />
      <path d="M2.6 5.1 8 8.9l5.4-3.8" />
    </svg>
  );
}

/* β›” `FlowIcon` LIVED HERE AND IS GONE TWICE OVER (W53-T34, owner instruction 4). It was the
   two-node flow glyph wave 51 drew for the Agents row, and it has moved AND been redrawn in the
   same edit, so neither half of that is a search anyone should have to run:
     Β· MOVED β€” every shell glyph now lives in `shell/icons.tsx` (contract C4), because the
       database cylinder was being hand-copied across three files and the copy nobody edits is the
       one a reader sees. The mark this row mounts is imported at the top of this file.
     Β· REDRAWN β€” owner instruction 4: *"Agent module icon is still ugly. How about just make it
       square and have two dots in side that looks like an eye."* `shell/icons.tsx::AgentIcon` is
       that square, and its own comment carries why the flow argument lost at 16px.
   β›” AND `RobotIcon`, WHICH `FlowIcon` REPLACED IN WAVE 51 (R15), STAYS DELETED. Two glyphs have
   now been retired from this one row; the next person to dislike the mark should draw a third,
   not resurrect either. `verify_icons.py` fails on a `RobotIcon` in code, by name. */

/** ⭐⭐ WAVE 35 Β· T04 (owner item 5) β€” AN ACTUAL PLUG. Owner: *"change the Icon for the connector to
 *  look like the cable head that you would put in an electrical outlet."*
 *  β›” THE NAME HAS BEEN WRONG SINCE WAVE 23 and that is why nobody noticed: this function is called
 *  `PlugIcon` and drew two links of a CHAIN. Wave 23's own note argued the chain "is exactly what a
 *  connector is", which is a defensible idea and not the one the owner asked for.
 *  Two prongs up, a rounded body, a cord leaving the bottom and turning right. The PRONGS are the
 *  load-bearing part; the cord is what stops it reading as a padlock at 16px.
 *  ⚠ GEOMETRY PUBLISHED BY SESSION B (`ASK B-5`) AND TAKEN VERBATIM, deliberately: `HomePage.tsx::
 *  ConnectIcon` draws the same mark for the Home card that leads here, the two files each keep
 *  their own copy, and agreeing on the paths by hand is the only thing stopping the nav row and its
 *  card from drifting apart again. Change one, change both. */
function PlugIcon() {
  return (
    <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
      <path d="M6.1 5.2V2.1M9.9 5.2V2.1" />
      <path d="M12.1 5.2v3.1a2.7 2.7 0 0 1-2.7 2.7H6.6a2.7 2.7 0 0 1-2.7-2.7V5.2Z" />
      <path d="M8 11v1.6a1.6 1.6 0 0 0 1.6 1.6h1.5" />
    </svg>
  );
}

/** W63-T06 β€” braces around two endpoint dots: an API, distinct from Connectors' physical plug. */
function ApiIcon() {
  return (
    <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
      <path d="M5.2 3.1H3.8a1.7 1.7 0 0 0-1.7 1.7v6.4a1.7 1.7 0 0 0 1.7 1.7h1.4M10.8 3.1h1.4a1.7 1.7 0 0 1 1.7 1.7v6.4a1.7 1.7 0 0 1-1.7 1.7h-1.4" />
      <circle cx="6.4" cy="8" r="1.1" />
      <circle cx="9.6" cy="8" r="1.1" />
    </svg>
  );
}

/** ⭐⭐ WAVE 49 Β· T01 (R1/R2/R30) β€” SHEET. A page ruled into cells: one outlined sheet with two
 *  rules across and two down, which is the shortest mark that reads as a spreadsheet rather than
 *  as a table or a window at 16px. Same 16x16 / `currentColor` / 1.35 vocabulary as every other
 *  rail mark, so it sits in the column without redrawing the row's weight.
 *  ⚠ ITS OWN GLYPH, NOT THE DATABASE CYLINDER (`icons.tsx::DatabaseIcon` since W53-T35; it was
 *  `dbFrame.tsx::DbIcon` when this was written): Sheet stands at the head of the data band and
 *  beside Data, and two rows wearing one mark is how a reader stops believing the marks mean
 *  anything. */
function SheetIcon() {
  return (
    <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
      <rect x="2.3" y="2.7" width="11.4" height="10.6" rx="1.3" />
      <path d="M2.3 6.2h11.4M2.3 9.8h11.4M6.4 2.7v10.6M10.1 2.7v10.6" />
    </svg>
  );
}

/** Tenant Apps: one window with four arranged parts, in the shell's existing stroke register. */
function AppIcon() {
  return (
    <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
      <rect x="2.3" y="2.3" width="11.4" height="11.4" rx="1.7" />
      <path d="M2.3 6.2h11.4M6.2 6.2v7.5M10 6.2v7.5" />
    </svg>
  );
}

/** ⭐ WAVE 35 Β· T05 (owner item 6) β€” Templates. Owner, of Airtable's rail: *"a 'Templates and apps'
 *  section? I want our app to have it too but just call it Templates ... located just above our
 *  User button."* A sheet of cards, which is what a template gallery is: one outlined page with a
 *  second offset behind it. Same 16x16 / `currentColor` / 1.35 vocabulary as every other rail mark,
 *  so it sits in the column without redrawing the row's weight. */
function TemplatesIcon() {
  return (
    <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
      <rect x="2.2" y="4.4" width="8.2" height="9.2" rx="1.3" />
      <path d="M5.6 4.4V3.7a1.3 1.3 0 0 1 1.3-1.3h6a1.3 1.3 0 0 1 1.3 1.3v6a1.3 1.3 0 0 1-1.3 1.3h-.7" />
    </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). */
/** ⭐ W41-T32 (owner instruction 29) β€” the path stack's `<` and `>`.
 *
 *  β›” THE SAME PATH AS `CaretIcon` ABOVE, MIRRORED, and that is the whole design decision. The
 *  rail already owns a chevron in a 12x12 box at this weight; importing a second one β€” or typing
 *  the `β€Ή` character, which is a font's opinion rather than the app's β€” would put two marks in one
 *  rail meaning "there is more this way" (DESIGN Β§4: one mark, one meaning).
 *
 *  ⚠ IT DOES NOT WEAR `.shell-nav-open`, which `CaretIcon` does. That class sits at `opacity: 0`
 *  until its ROW is hovered, which is right for a disclosure hint riding a link and wrong for a
 *  control that has to be findable before the pointer is on it. Its own class carries the same
 *  16px-family stroke vocabulary at full strength.
 */
/** 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);

  // W51-T31 β€” Escape leaves through the shared stack. The local capture listener that used to
  // sit here closed this menu even when a dialog was open on top of it, because every overlay
  // arbitrated for itself and the winner was whichever listener registered last.
  useEscapeClose(open, () => setOpen(false), { container: () => wrap.current });

  useEffect(() => {
    if (!open) return;
    const onDoc = (e: MouseEvent) => {
      if (wrap.current && !wrap.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [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>
          {/* ⭐⭐ WAVE 35 Β· T06 (owner item 13, contract C6) β€” Feedback Β· Usage Β·
              Subscription, *"below settings"* exactly as the owner placed them.
              β›” THE SUBSCRIPTION ROW IS HIDDEN FOR ROYAL IMPORTS **AND** ITS ROUTE IS REFUSED
              (the dispatch, below). C6's second trap is that hiding a row whose route still
              answers is not hiding β€” anyone who types the hash, or follows an old bookmark, walks
              straight in. Both halves read ONE constant, `NO_SUBSCRIPTION_TENANT`, so they cannot
              drift.
              ⚠ Plain `<a href>` rows, not buttons: these are ADDRESSES. A button would make three
              real routes unbookmarkable and un-middle-clickable for no gain, and the frame already
              owns hash routing. */}
          <a
            className="shell-menu-item"
            role="menuitem"
            href={`#/${FEEDBACK_ROUTE}`}
            onClick={() => setOpen(false)}
          >
            <BubbleIcon />
            Feedback
          </a>
          <a
            className="shell-menu-item"
            role="menuitem"
            href={`#/${USAGE_ROUTE}`}
            onClick={() => setOpen(false)}
          >
            <PieIcon />
            Usage
          </a>
          {user.tenant === NO_SUBSCRIPTION_TENANT ? null : (
            <a
              className="shell-menu-item"
              role="menuitem"
              href={`#/${SUBSCRIPTION_ROUTE}`}
              onClick={() => setOpen(false)}
            >
              <CardIcon />
              Subscription
            </a>
          )}
          {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();
            }}
          >
            <ExitIcon />
            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>
  );
}

/** How the rail came to be folded, as persisted in `aios-nav-collapsed`. */
type NavFold = "0" | "1" | "auto";

/** The one key both halves of the fold read and write. */
const NAV_FOLD_KEY = "aios-nav-collapsed";

/**
 * ⭐⭐ WAVE 53 Β· T32 (ruling R1) β€” WHO FOLDED THE RAIL, not merely whether it is folded.
 *
 * The stored value used to be a boolean, and that is exactly why owner instruction 3 had to be
 * written: a rail the GRID folded on a cell click was indistinguishable from a rail the READER
 * folded with the minimize button, so the grid's fold followed you to Home and survived the next
 * app open. Three values keep them apart:
 *   `"0"`    the rail is open.
 *   `"1"`    the reader folded it themselves. A choice, and it holds everywhere, Home included.
 *   `"auto"` the work surface folded it (`NAV_MINIMIZE_EVENT`). Still folded, still remembered,
 *            but it is the surface's fold and it does not outlive that surface.
 *
 * ⚠ `"1"` IS READ BY THE OLD SPELLING TOO, and that is not an accident: every browser that has
 * opened this app before today holds a literal `"1"`, and treating it as an explicit fold is the
 * kinder reading of an unknowable one. Anything that is not `"0"` means folded, so a value this
 * function has never heard of still fails safe as folded rather than silently opening the rail.
 */
function readNavFold(): NavFold {
  try {
    const raw = localStorage.getItem(NAV_FOLD_KEY);
    if (raw === "auto") return "auto";
    return raw === "1" ? "1" : "0";
  } catch {
    // storage can be blocked; the rail then simply starts open, as it does for a new reader
    return "0";
  }
}

function ShellFrame() {
  const [session, setSession] = useState<Session>({ phase: "checking" });
  const [nav, setNav] = useState<Nav>({ phase: "idle" });
  const [financeNav, setFinanceNav] = useState<FinanceNav>({ phase: "idle" });
  const financeNavRequestEpoch = useRef(0);
  // Wave 18 (C3-UT): bumped after "+ New database" so the rail refetches and the new ut_ key
  // appears without a reload. Rename, create and delete paths share the same bumper: the
  // authoritative answer 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 navRequestEpoch = useRef(0);
  const [applicationsEpoch, setApplicationsEpoch] = useState(0);
  const applicationCheckEpoch = useRef(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, hash } = useHashRoute();
  const dataPath = readDataPath(hash);
  // W60 C2: readDataPath deliberately does not parse Sheet's workbook address.
  const sheetQuery = hash.indexOf("?");
  const sheetWorkbookId = route === SHEET_ROUTE && sheetQuery >= 0
    ? (new URLSearchParams(hash.slice(sheetQuery + 1)).get("wb") || "")
    : "";
  const agentAddress = readAgentAddress(hash);
  const agentsGalleryOpen = route === "automation" && !agentAddress.agent && !agentAddress.voice;
  /**
   * ⭐⭐ WAVE 35 Β· T06/T09 (asks B-2 and B-8) β€” OPEN A VIEW INSIDE ITS DATABASE. One handler,
   * passed to BOTH `HomePage` and `StarredPage`, so a starred view opened from Home and the same
   * view opened from Starred cannot behave differently.
   *
   * β›” THE FRAME OWNS THE HASH AND THE LADDER, WHICH IS WHY THIS IS NOT A PROP THE PAGES IMPLEMENT.
   * `CustomerGrid`'s VIEW_OPEN listener drops an event whose view it has not fetched yet and there
   * is NO ACK, so a single emit fired the instant the hash changes is silently discarded on a cold
   * click: the table opens, the view is not selected, and the click "worked".
   *
   * β›” `gridScopeFor`, NEVER THE REGISTRY KEY. The listener compares `detail.topic !== scope`,
   * and a grid's scope is a DIFFERENT SPELLING from its registry key (`customer_data` -> `customer`).
   * A mismatch is dropped in silence β€” the same class of defect as the wave-34 alert-create handler
   * that filed alerts against the wrong topic and answered 200.
   *
   * ⚠ THE LADDER IS LONGER THAN THE INBOX'S, AND THAT IS MEASURED, NOT CAUTIOUS. `OPEN_RETRY_MS`
   * tops out at 2,600 ms; a grid's COLD mount was measured at ~12 s (wave 34, the Query refactor),
   * so the inbox ladder would have every attempt land before the listener exists. A retry ladder is
   * only correct against a measured worst case.
   */
  const VIEW_OPEN_RETRY_MS = [0, 250, 700, 1500, 2600, 5000, 9000, 14000, 21000] as const;
  const openViewInDatabase = useCallback((database: string, viewId: string) => {
    // β›”β›” WAVE 35 QA β€” THIS WROTE `#/db/${database}` AND NOTHING IN THE APP READS A `db/` PREFIX,
    // SO EVERY STARRED-VIEW TILE ON HOME AND ON STARRED WAS A DEAD CLICK. `routeKeyOf` strips only
    // a leading `#/` (`nav.ts`), so the route became the literal `"db/ut_odoo_invoices"`;
    // `resolveRoute` looks that up against entry keys that are BARE (`"ut_odoo_invoices"`), missed,
    // and the shell fell back to Home β€” the URL changed, the screen did not. Reproduced on two
    // different views, held for 30 s+, and confirmed structurally: `"db/"` appeared exactly ONCE
    // in `Shell.tsx` + `nav.ts` + `dbFrame.tsx` combined β€” here, the writer, with no reader
    // anywhere. Every other hash write in this file is `#/${key}` (`:1764`, `:2934`, …); this one
    // invented a second vocabulary for the same thing. [[one-question-two-normalizers]]
    // ⚠ The failure is silent by construction, which is why no gate saw it: a route that does not
    // resolve is the SAME code path as "no route yet", and that path renders Home on purpose.
    // W62-T19 (C6): NO folder is carried here on purpose. C6's own fallback is "the address
    // first, then the opened item's placement", and a view opened in another database belongs to
    // THAT database's placement - carrying the folder the reader happened to be standing in would
    // address a folder this database is not filed in. `verify_grid_ux.py` also pins this line.
    window.location.hash = dataPathHash({ database, view: viewId });
    viewEmitCancel.current?.();
    viewEmitCancel.current = retryEmit(
      () => {
        signal(VIEW_OPEN_EVENT, { topic: gridScopeFor(database), viewId });
      },
      undefined,
      VIEW_OPEN_RETRY_MS
    );
  }, []);
  // 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);
  // ⭐⭐ W33-T26 β€” the published-view token, read the same way and for the same reason the line
  // above gives: two copies of "is this a public route?" is how one of them ends up answering
  // differently. Both feed the SAME auth-bounce exemption and the same pre-session render branch.
  const publishToken = publishTokenOf(route);
  const publicToken = formToken || publishToken;
  // 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>(() => readNavFold() !== "0");
  /**
   * ⭐⭐ W53-T32 (R1) β€” was the fold on screen the SURFACE's or the READER's? A ref, not state,
   * because it is read by the effects below at the moment they run and never by the render: a
   * re-render standing between the fold and the write is precisely what would let the flag and
   * `navCollapsed` disagree about the same fold.
   *
   * ⚠ Seeded from `readNavFold()`, the SAME reader that seeds `navCollapsed` one line above, so
   * the two cannot start out describing different histories. Lazy-initialised (`null` until the
   * first render asks) rather than passed to `useRef` directly, which would re-read storage on
   * every render of the largest component in the app for a value that can only change here.
   */
  const navFoldWasAuto = useRef<boolean | null>(null);
  if (navFoldWasAuto.current === null) navFoldWasAuto.current = readNavFold() === "auto";
  useEffect(() => {
    try {
      // ⚠ The WHO, not just the whether β€” see `readNavFold`. An automatic fold that wrote `"1"`
      // here would be an explicit fold as far as tomorrow's app open could tell.
      localStorage.setItem(NAV_FOLD_KEY, navCollapsed ? (navFoldWasAuto.current ? "auto" : "1") : "0");
    } catch {
      // storage can be blocked; the toggle still works for the session
    }
  }, [navCollapsed]);
  // ── ⭐⭐ W38-T04 (ruling R9): A CELL CLICK ALWAYS FOLDS THE RAIL ───────────────────────────
  //
  // β›” WAVE 34's R1 IS REVOKED. That ruling read owner item 10's fold as a COURTESY a deliberate
  // expand was allowed to decline, and this block used to hold a `railHeldOpen` ref that every
  // expand raised, the explicit fold lowered, and the automatic fold consulted before it set.
  // Wave 38 item 3 overrules it, verbatim: *"Clicking any cell must minimize the main navigation.
  // This was the previous behavior; make sure it is fixed forever."* R9 reads "fixed forever"
  // LITERALLY β€” no held-open state, no preference, no ref may decline the fold, because anything
  // able to decline it is a way for the behaviour to stop being fixed.
  //
  // β›” THE REF WAS DELETED, NOT LEFT INERT, and that is the deliberate half of this edit. A
  // `railHeldOpen` that every expand still raised while nothing read it would compile clean β€” it
  // is WRITTEN, so no unused-local diagnostic ever sees it β€” and would read to the next person as
  // a live rule with a missing consumer, which is an invitation to "repair" the decline back in.
  // A revoked ruling leaves no residue. (`proto/nav-stuck/README.md` keeps R1's original trace;
  // its finding β€” that no expand CONTROL was ever missing β€” is still true and still worth having.)
  //
  // ⚠ WHAT SURVIVES R1 IS THE ONE-DOOR SHAPE, and `verify_ui.py` still enforces it: every expand
  // goes through `expandRail`, every deliberate collapse through `collapseRail`, so a fifth
  // control cannot set `navCollapsed` behind the two named doors. R1's decline is gone; the
  // plumbing that kept its call sites countable is not.
  /** Every deliberate expand goes through here, so a fifth expand door cannot be added quietly. */
  const expandRail = useCallback(() => {
    setNavCollapsed(false);
    navFoldWasAuto.current = false;
  }, []);
  /**
   * ⭐⭐ W53-T33 (owner instruction 6) β€” A RAIL ICON OPENS ITS MODULE **AND** OPENS THE RAIL.
   *
   * Owner: *"When clicking any of the icon under a minimized main navigation ... we should not
   * only open that module, but also unminimized the main navigation. Only when the user click
   * anywhere in the module like it is wired right now should the main navigation be minimized
   * again."* So this is an EXPAND-ONLY handler: it never collapses, and `onNavMinimize` keeps
   * owning the click-into-the-module fold exactly as before.
   *
   * β›” ONE HANDLER, NOT NINE INLINE COPIES, AND IT GOES THROUGH `expandRail` β€” the one door.
   * `verify_ui.py` counts every setter call site and reddens on a third one, which
   * is what stops a rail row from growing its own private expand. Rows that are plain `<a href>`
   * simply add `onClick={expandOnNavClick}`; the two rows that already own an `onClick` call it as
   * their first statement, so navigation and expansion cannot answer differently.
   *
   * ⚠ The `navCollapsed` guard is not decoration: an unguarded `expandRail()` would clear
   * `navFoldWasAuto` on every rail click in the EXPANDED state too, which is the flag the
   * auto-fold logic reads.
   */
  const expandOnNavClick = useCallback(() => {
    if (navCollapsed) expandRail();
  }, [navCollapsed, expandRail]);
  // 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.
  // ⚠ W34-T12 β€” the SELECTOR LIST IS UNTOUCHED, and that is the ticket's named trap: widening it
  // so more clicks expand would trade one outage for another (a collapsed row's icon could no
  // longer be clicked without the rail jumping open under the pointer). Only the setter changed.
  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;
    expandRail();
  }, [expandRail]);

  // ── W41-T32 (owner instruction 29, ruling R2): THE RAIL IS A PATH STACK ────────────────────
  //
  // R2: *"The rail shows ONE level at a time and swaps as you drill: `Data` -> the list of
  // databases -> that database's views and folders."* Owner: *"We go from the main path, and when
  // we click the folder it opens that folder's path, and so the folders from the main path is no
  // longer showing."*
  //
  // ⭐ ONE STATE OBJECT, NOT TWO. The history and the cursor into it are a single fact β€” "where am
  // I, and what have I already clicked to" β€” and holding them as two `useState`s is how a back
  // button ends up pointing into a list that a push already truncated. One object cannot desync
  // with itself [[one-question-two-normalizers]].
  //
  // ⭐ INDEX 0 IS ALWAYS THE ROOT, and that is what makes `<` the way OUT of a level rather than a
  // control that strands you: the level replaces the rail's chrome rows, so with no way back to
  // index 0 there would be no Home, no Inbox and no Connectors on screen at all.
  //
  // W62-T19 / R52 overturns the earlier refusal of a #/data route: Data joins nav.ts::CHROME_ROUTES.
  // A route that joins CHROME_ROUTES must also render. The existing Home/App/Data fallback branch
  // below meets that condition with <HomePage mode="data">; C6's address also carries its folder.
  // Data is one global destination. Its database hierarchy is owned by ViewSidebar, where it can
  // share the same disclosure, keyboard and folder vocabulary as the views it contains.
  /**
   * Leave the levels and show the rail's own rows again.
   *
   * ⚠ THE NAME IS KEPT ON PURPOSE and it is the same call `shell-nav-alerts` makes one screen
   * down: this is a stable hook that `verify_wiring.py` already keys on (the "each create door
   * closes the panel first" pair), the assertion it carries is still TRUE β€” the doors still leave
   * the level before opening their dialog β€” and renaming it buys a reader nothing this comment
   * does not already give them. The `-DbFly` in it names a control that no longer exists; the
   * behaviour it names does.
   * ⚠ THE HISTORY SURVIVES. `at: 0` moves the cursor, it does not truncate: the Data row can then
   * put you back where you were rather than starting the walk again, which is the only reason the
   * root needs no forward button of its own.
   */
  /** A folded rail is always the global rail, never a squeezed database path. */
  const collapseRail = useCallback(() => {
    setNavCollapsed(true);
    // ⭐ W53-T32 (R1) β€” a fold arriving through this door is the READER's until something says
    // otherwise, and the only thing that says otherwise is the `NAV_MINIMIZE_EVENT` handler, on
    // the line straight after its own `collapseRail()`. Clearing it here rather than in the
    // minimize button's own handler keeps the count of `setNavCollapsed` call sites at two.
    navFoldWasAuto.current = false;
  }, []);
  /** Drill into the database list. RESUMES the walk rather than restarting it β€” see `closeDbFly`. */
  /** Drill from the list into ONE database. The row's own `href` does the navigating; this records
   *  where the click went, so `<` and `>` can walk back to it.
   *  ⚠ It TRUNCATES anything ahead of the cursor, which is what a browser's forward button does
   *  after you take a new branch: a forward entry you can no longer reach by going back is a
   *  destination the history is lying about. */
  // ⚠ Declared here and READ inside the Escape 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.

  /**
   * β›” ESCAPE LEAVES THE LEVEL β€” AND MUST NOT WHILE A DRAG IS IN FLIGHT.
   *
   * The guard is wave 23's, carried across because the hazard is the same one wearing new clothes.
   * The level carries the folder drag-and-drop (`NAV_DRAG_TYPE`, the `__root__` drop target,
   * `draggable` rows), and Escape is ALSO the browser's own "cancel this drag" key. Without the
   * ref, one Escape mid-drag cancels the drag AND unmounts the drop target under the cursor: the
   * folder move silently fails and the list the user was arranging vanishes, which reads as a
   * crash. A gate cannot see a drop that never lands, so nothing else would have caught it.
   *
   * ⚠ The wave-23 OUTSIDE-CLICK rule is gone with the panel and is not replaced. A level is part
   * of the rail; clicking the page beside a rail has never dismissed it, and making it do so here
   * would mean a click on the grid could silently throw away the path you had walked.
   */

  // ── 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 ?? ""));
    // 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(SHARE_OPEN_EVENT, onShareOpen);
    return () => {
      window.removeEventListener(UNAUTHORIZED_EVENT, onUnauthorized);
      window.removeEventListener(DATA_ERROR_EVENT, onDataError);
      window.removeEventListener(TOAST_EVENT, onToast);
      window.removeEventListener(SHARE_OPEN_EVENT, onShareOpen);
    };
  }, []);

  // ── ⭐⭐ W53-T32 (ruling R1): THE FOLD IS NOT SUBSCRIBED TO ON A READING SURFACE ─────────
  //
  // Owner instruction 3: *"Never collapse on home or starred UNLESS the user click the minmize
  // navigation button of course. Also apply this for inbox module."*
  //
  // β›” W38-T04 IS UNTOUCHED, AND THAT IS THE WHOLE REASON THIS IS AN EFFECT RATHER THAN A GUARD.
  // R9 says the automatic fold may never be declined, and the handler below still declines
  // nothing: it folds the moment it hears the event, with nothing in front of it. What R1 changes
  // is not what the handler does, it is whether the handler is LISTENING at all. On Home, Starred
  // and Inbox this effect leaves before it subscribes, so no event reaches a handler that could
  // have folded. Leaving one of those routes re-runs the effect and re-attaches the listener, so
  // Data, Sheet and Connectors keep the wave-38 behaviour exactly, cell click for cell click.
  //
  // ⚠ A guard in front of `collapseRail()` would have been the OTHER way to write this, and it
  // is the one wave 38 forbade: `verify_ui.py`'s `W38-T04 unconditional` leg reads the 500
  // characters after the handler's own name and goes red on any `if`, `return`, `&&`, `||` or
  // `localStorage` standing before the fold. The condition belongs to the SUBSCRIPTION, one scope
  // out, which is also the honest place for it: these three pages never had anything to fold for.
  useEffect(() => {
    if (NAV_STAYS_EXPANDED_ROUTES.has(route)) return;
    // ⭐⭐ S64-T05 / R4 REVOKES S63-T07 / R5 FOR THE MAIN RAIL: owner instruction 8 is ASYMMETRIC.
    // The main rail folds on EVERY cell click, with no per-visit memory and no session hold.
    // The SECONDARY rail in `SheetRail.tsx` keeps its once-per-visit fold and its manual hold β€”
    // that is the half R4 preserved. β›” A future guard here is the exact shape W38-T04 / R9 and
    // R4 both forbid: an unconditional handler cannot fold a rail it never hears about.
    // ⭐⭐ W38-T04 (R9) β€” THE AUTOMATIC FOLD IS UNCONDITIONAL, AND THAT IS THE WHOLE RULE.
    // `NAV_MINIMIZE_EVENT` fires from `CustomerGrid` on EVERY cell click and EVERY view switch;
    // this is its only listener, and it folds, every time, with nothing in front of it. W34-T12's
    // `railHeldOpen` guard stood here and is deleted (see the block by `expandRail` for why the
    // ref went with it). β›” ANY early return, condition or stored preference added between this
    // line and the fold re-creates the behaviour owner item 3 asked to be fixed FOREVER β€” and
    // `verify_ui.py`'s `W38-T04 unconditional` leg exists to go red the moment one appears.
    const onNavMinimize = () => {
      collapseRail();
      // ⭐ W53-T32 (R1) β€” AFTER the fold, never before it: this line records that the fold
      // was the surface's rather than the reader's, and a line standing in FRONT of
      // `collapseRail()` is the declining guard R9 revoked. `collapseRail` clears this flag
      // as its own last statement, so the order here is what makes the automatic fold
      // distinguishable from the minimize button pressing the same door one instruction later.
      navFoldWasAuto.current = true;
    };
    window.addEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
    return () => window.removeEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
  }, [collapseRail, route]);

  // ── ⭐⭐ W53-T32 (ruling R1): AN AUTOMATIC FOLD DOES NOT OUTLIVE THE SURFACE THAT MADE IT ──
  //
  // The other half of instruction 3, and the half that is visible on a cold start: *"When user
  // first open the app and they're at home. Make sure the navigation is unminimized."* Not
  // subscribing is not enough on its own, because `navCollapsed` is ONE persisted flag: a rail the
  // grid folded on a Data cell click is still folded when you arrive at Home, and still folded on
  // the next app open, which is the fold owner instruction 3 says must not be there.
  //
  // So the fold is undone at the door, and ONLY the automatic one. `"1"` β€” the reader's own
  // minimize β€” walks straight past this and stays folded on Home, which is the *"UNLESS the user
  // click the minmize navigation button"* clause honoured rather than merely quoted.
  //
  // ⚠ `expandRail` IS THE DOOR, not `setNavCollapsed`. W34-T12's one-door rule survives R9 and is
  // gated, and this is the fourth control to go through it rather than the fifth to go around.
  //
  // β›” THE REF ALONE IS NOT ENOUGH, AND THE CASE THAT PROVES IT IS THE READER'S OWN FOLD. When
  // `collapseRail()` folds a rail that is ALREADY folded β€” the reader minimized it, then clicked a
  // Data cell β€” `navCollapsed` does not change, so the persistence effect never re-runs and storage
  // KEEPS the `"1"` the reader put there, while the handler's next line has already marked the ref
  // automatic. Storage is the record that did not move, which makes it the honest arbiter of who
  // folded the rail currently on screen: an explicit `"1"` is never reopened here, so *"UNLESS the
  // user click the minmize navigation button"* holds across a trip through a work surface too.
  //
  // ⚠ THE REF STAYS IN THE TEST rather than being replaced by the read. A browser with site data
  // blocked answers `"0"` to every `readNavFold()`, and a test on storage alone would then refuse
  // to reopen anything β€” leaving the rail folded on Home for exactly the readers who cannot
  // persist a preference in the first place. Ref says "an automatic fold happened"; storage says
  // "and the reader did not fold it first"; both have to agree before the rail is reopened.
  //
  // ⚠ `localStorage` IS LEGAL HERE and moving this read is what would break the gate, not keeping
  // it. `verify_ui.py`'s `W38-T04 unconditional` leg bans it only in the 500 characters after
  // `const onNavMinimize` and before that handler's own `collapseRail()`. This is a different
  // scope and a different question: not whether to fold, but whether an old fold still speaks for
  // the reader.
  useEffect(() => {
    if (!NAV_STAYS_EXPANDED_ROUTES.has(route)) return;
    if (!navCollapsed || !navFoldWasAuto.current || readNavFold() === "1") return;
    expandRail();
  }, [route, navCollapsed, expandRail]);

  // W60-T37 (R19): App arrivals preserve the reader's rail state.
  // App shares Data's cell-click fold through the NAV_MINIMIZE_EVENT handler above.

  // 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, dataPath?.database]);

  // 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;

  const leaveDeletedApplication = useCallback((database: string, application: string) => {
    const live = readDataPath(window.location.hash);
    if (live?.database !== database || live.application !== application) return;
    viewEmitCancel.current?.();
    // Replace the dead history entry so Back does not become a redirect loop.
    window.history.replaceState(window.history.state, "", "#/app");
    window.dispatchEvent(new HashChangeEvent("hashchange"));
  }, []);

  useEffect(() => {
    const refresh = () => {
      applicationCheckEpoch.current += 1;
      financeNavRequestEpoch.current += 1;
      setApplicationsEpoch((epoch) => epoch + 1);
    };
    const changed = (event: Event) => {
      refresh();
      const deletedId = (event as CustomEvent<{ deletedId?: string }>).detail?.deletedId;
      if (typeof deletedId !== "string" || !deletedId) return;
      const live = readDataPath(window.location.hash);
      if (live?.application === deletedId) leaveDeletedApplication(live.database, deletedId);
      navRequestEpoch.current += 1;
      setNavEpoch((epoch) => epoch + 1);
    };
    const visible = () => { if (document.visibilityState === "visible") refresh(); };
    window.addEventListener("aios:applications-changed", changed);
    window.addEventListener("focus", refresh);
    document.addEventListener("visibilitychange", visible);
    return () => {
      window.removeEventListener("aios:applications-changed", changed);
      window.removeEventListener("focus", refresh);
      document.removeEventListener("visibilitychange", visible);
    };
  }, [leaveDeletedApplication]);

  useEffect(() => {
    const requestEpoch = ++applicationCheckEpoch.current;
    const database = dataPath?.database;
    const application = dataPath?.application;
    if (!who || !database || !application) return;
    const controller = new AbortController();
    void fetch(`${API_V1}/applications?database=${encodeURIComponent(database)}`, {
      credentials: CREDENTIALS,
      signal: controller.signal,
    }).then(async (response) => {
      if (!response.ok) return;
      const body = await response.json();
      if (controller.signal.aborted || requestEpoch !== applicationCheckEpoch.current) return;
      // Failed or malformed reads are unknown, never evidence that an App was deleted.
      if (!Array.isArray(body?.applications)
        || body.applications.some((row: { id?: unknown } | null) => !row || typeof row.id !== "string")) return;
      if (!body.applications.some((row: { id: string }) => row.id === application)) {
        leaveDeletedApplication(database, application);
      }
    }).catch(() => undefined);
    return () => controller.abort();
  }, [who, dataPath?.database, dataPath?.application, applicationsEpoch, leaveDeletedApplication]);

  useEffect(() => {
    const onWorkspaceStale = () => {
      // W63-T29: connector creation/enablement/removal changes both membership and the rows a
      // newly addressable database will read. Drop the client cache before asking `/nav` again;
      // otherwise a re-enabled key can paint the old absence even after its rail row arrives.
      clearCustomersCache();
      setDataError("");
      // Invalidate immediately: an older response can resolve before the next effect cleans up.
      navRequestEpoch.current += 1;
      financeNavRequestEpoch.current += 1;
      setNavEpoch((epoch) => epoch + 1);
    };
    window.addEventListener(WORKSPACE_STALE_EVENT, onWorkspaceStale);
    return () => window.removeEventListener(WORKSPACE_STALE_EVENT, onWorkspaceStale);
  }, []);

  useEffect(() => {
    const requestEpoch = ++navRequestEpoch.current;
    if (who === null) {
      setNav({ phase: "idle" });
      return;
    }
    let dead = false;
    // ⚠ WAVE 19 β€” STALE-WHILE-REFRESH. 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 and
    // "+ 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 || requestEpoch !== navRequestEpoch.current) 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 } : {}),
                    ...(r.status === NAV_MALFORMED_STATUS ? { malformed: true } : {}) });
    });
    return () => {
      dead = true;
    };
  }, [who, navEpoch]);

  // The shell owns the grant-filtered read; App home owns its cards.
  useEffect(() => {
    const requestEpoch = ++financeNavRequestEpoch.current;
    if (who === null) {
      setFinanceNav({ phase: "idle" });
      return;
    }
    const controller = new AbortController();
    setFinanceNav((current) => current.phase === "ready" ? current : { phase: "loading" });
    void fetch(`${API_V1}/nav/applications`, {
      credentials: CREDENTIALS,
      signal: controller.signal,
    }).then(async (response) => {
      if (!response.ok) throw new Error("application_list_failed");
      const body = await response.json();
      if (!Array.isArray(body?.applications)) throw new Error("application_list_invalid");
      if (!controller.signal.aborted && requestEpoch === financeNavRequestEpoch.current) {
        setFinanceNav({ phase: "ready", applications: body.applications });
      }
    }).catch(() => {
      if (!controller.signal.aborted && requestEpoch === financeNavRequestEpoch.current) {
        setFinanceNav({ phase: "error" });
      }
    });
    return () => controller.abort();
  }, [who, navEpoch, applicationsEpoch]);
  const financeApplications = useMemo(
    () => financeNav.phase === "ready" ? financeNavigation(financeNav.applications) : [],
    [financeNav]
  );

  /**
   * ⭐⭐ W33-T22 β€” RECORD THE RAIL THE PAYLOAD JUST DESCRIBED, for the next first paint.
   *
   * ⚠ IT LIVES UP HERE WITH THE OTHER EFFECTS, NOT BESIDE THE ROWS IT IS ABOUT, and that is not
   * a filing preference: the render body below has several early returns (the public form at
   * `<FormPublic/>`, the boot gate at `session.phase === "checking"`, the login page), so a hook
   * written next to the rail would be called on some renders and not others β€” the rules-of-hooks
   * crash, and one that only fires on the public-form route.
   *
   * β›” ONLY `ready` WRITES. An `error` payload knows nothing about this account's grants, and
   * recording "absent" from a failed read would suppress the placeholder on the next load for a
   * row the user actually has [[empty-answer-vs-unfinished-answer]].
   */
  // 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 [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]
  );
  // ── 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 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 });
    },
    [commitPrefs]
  );

  const dbEntries = useMemo(() => databaseEntries(entries), [entries]);
  const dataDatabases = useMemo<DataDatabase[]>(
    () =>
      dbEntries
        .filter((entry) => entry.kind !== "group")
        .map((entry) => ({
          key: entry.key,
          label: entry.label,
          ...(entry.source ? { source: entry.source } : {}),
          ...(entry.sourceGroup ? { source: entry.sourceGroup } : {}),
          ...(entry.managedBy ? { managedBy: entry.managedBy } : {}),
          ...(entry.protected ? { protected: true } : {}),
          ...(entry.locked ? { locked: true } : {}),
          ...(entry.icon ? { icon: entry.icon } : {}),
          ...(navPrefs.placement[entry.key]
            ? { folderId: navPrefs.placement[entry.key] }
            : {}),
          ...(entry.kind === "handoff" && entry.href ? { externalHref: entry.href } : {}),
        })),
    [dbEntries, navPrefs.placement]
  );

  useEffect(() => {
    // A connector disable/delete can invalidate the database named by the current Data address.
    // Wait for the authoritative nav refresh, then replace only the dead database segment so the
    // gallery and any still-valid folder remain reachable without a reload or a dead Back entry.
    if (nav.phase !== "ready" || !dataPath?.database
        || dbEntries.some((entry) => entry.key === dataPath.database)) return;
    const folder = readDataAddress(window.location.hash).folder;
    window.history.replaceState(window.history.state, "", dataAddressHash({ ...(folder ? { folder } : {}) }));
    window.dispatchEvent(new HashChangeEvent("hashchange"));
  }, [nav.phase, dataPath?.database, dbEntries]);

  // ── 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;
      // β›” THE GRID'S OWN SCOPE, NOT THE HASH (2026-08-14). This used to map the route key
      // inline β€” a third copy of `gridScopeFor`, and one the Query module breaks outright:
      // a grid mounted at `#/query` would have filed every alert raised from it against
      // `customer`, because "query" is not a database key and the else-branch is the
      // customer topic. Silently wrong, on a door that answers 200. `currentSurfaceScope()`
      // is the value the emitting grid stamps on all its other events, read back.
      const topic = currentSurfaceScope();
      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;
        }
        // ⭐ W34-T17 (R23) β€” THE COPY NAMES **INBOX**, because that is the row the reader will
        // look for. Owner, 2026-08-16: *"Alerts is called Inbox and it's right below Home."* This
        // sentence used to send them to "Alerts", a surface that no longer has that name anywhere
        // on screen: the rail row says Inbox, the route is `#/inbox`, the page heading says Inbox.
        // A toast is a door with a sign on it, and the sign was pointing at a room that was
        // renamed three waves ago.
        setToast(`Alerting on "${req.label}". New records that enter it appear in your Inbox.`);
        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 (dataPath?.database === key || route === key) window.location.hash = "";
      return { ok: true };
    },
    [dataPath?.database, 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.
    // ⭐⭐ W33-T26 β€” `publicToken`, not `formToken`. Wave 33's published view (`#/v/<token>`) needs
    // BOTH exemptions for exactly the reasons the paragraph above gives about the form, and
    // extending the existing test is the only way they cannot come apart: a second `if` here
    // would be a second answer to "is this route public", and the wave-23 note is about what
    // happens when one of two such answers is forgotten.
    if (publicToken) 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, publicToken]);

  // ── 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[]>([]);
  const [voiceAgents, setVoiceAgents] = useState<AutomationTile[]>([]);
  const [voiceAgentsError, setVoiceAgentsError] = useState("");
  /**
   * ⭐⭐ WAVE 35 Β· T08 (owner item 11, wiring W6) β€” Home's agent tiles stop going stale.
   * The frame fetches these tiles; `AutomationSurface` is props-free by contract and fetches its
   * own list, so nothing told the frame when a delete happened inside the module. It listens now.
   * ⚠ A SEPARATE EPOCH FROM `navEpoch` ON PURPOSE: bumping `navEpoch` would re-fetch `/nav`, a
   * whole-document read of a 28.6 MB store (D-175/D-185), to refresh a list of tiles.
   * ⚠ The DATABASE half of item 11 needed no change and that was CHECKED, not assumed:
   * `removeDatabase` already bumps `navEpoch`, and this effect already depends on it.
   */
  const [agentsEpoch, setAgentsEpoch] = useState(0);
  useEffect(() => {
    const onChanged = () => setAgentsEpoch((e) => e + 1);
    window.addEventListener(AGENTS_CHANGED, onChanged);
    return () => window.removeEventListener(AGENTS_CHANGED, onChanged);
  }, []);
  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, agentsEpoch]);

  useEffect(() => {
    if (who === null) {
      setVoiceAgents([]);
      setVoiceAgentsError("");
      return;
    }
    if (!agentsGalleryOpen) return;
    // W60-T39 scout correction: AutomationList excludes voice by design. Reuse the existing
    // permission-aware voice reader only for this gallery; Home keeps its original list/read.
    const ac = new AbortController();
    let dead = false;
    setVoiceAgentsError("");
    void listVoiceAgents(ac.signal).then((r) => {
      if (dead) return;
      setVoiceAgents((r.voiceAgents || []).map((a) => ({
        id: a.automationId,
        name: a.displayName,
        // The surface's status formatter is private; keep raw connection enums off tiles.
        sub: "Voice",
      })));
    }).catch(() => {
      if (!dead) setVoiceAgentsError("Voice agents could not be loaded. Reload to retry.");
    });
    return () => {
      dead = true;
      ac.abort();
    };
  }, [who, agentsGalleryOpen, agentsEpoch]);

  // 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 =
      (dataPath ? entries.find((entry) => entry.key === dataPath.database) : undefined) ??
      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, dataPath?.database]);

  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.
  /** Templates, Home and App all open this one creation flow. The narrow state keeps unrelated
   * overlays from drifting into the Application wizard. */
  const [assistOpen, setAssistOpen] = useState<false | "templates">(false);
  const [templateModule, setTemplateModule] = useState<TemplateModule | null>(null);
  const [appTemplate, setAppTemplate] = useState("");
  const appWizardRef = useRef<HTMLDivElement>(null);
  const appWizardBusy = useRef(false);
  const openApplicationWizard = useCallback(() => {
    setTemplateModule(route === SHEET_ROUTE ? "sheet" : route === DATA_ROUTE ? "data" : "app");
  }, [route]);
  const chooseAppTemplate = useCallback((key: string) => {
    setAppTemplate(key);
    setAssistOpen("templates");
  }, []);
  useEffect(() => {
    const open = (event: Event) => {
      const key: unknown = (event as CustomEvent).detail;
      if (key === "route" || key === "catalog") chooseAppTemplate(key);
    };
    window.addEventListener(OPEN_APP_TEMPLATE_EVENT, open);
    return () => window.removeEventListener(OPEN_APP_TEMPLATE_EVENT, open);
  }, [chooseAppTemplate]);
  const closeApplicationWizard = useCallback(() => {
    if (appWizardBusy.current) return;
    setAssistOpen(false);
  }, []);
  const setApplicationWizardBusy = useCallback((busy: boolean) => {
    appWizardBusy.current = busy;
  }, []);
  const launchCreatedApplication = useCallback((application: CreatedTemplateApplication) => {
    appWizardBusy.current = false;
    setAssistOpen(false);
    setTemplateModule(null);
    setNewDb(null);
    const database = application.openTarget?.database || application.sourceDatabase;
    window.location.hash = appPathHash({ database, application: application.id });
  }, []);
  // (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;
  // ApplicationWizard joins the shared overlay layer itself so focus trap, restoration and
  // Escape ordering are one contract. The older database dialog still needs this direct claim.
  // β›” The busy guard is the same one the scrim keeps: a create already in flight is not
  // cancellable, so Escape must leave the dialog standing rather than orphan the request.
  useEscapeClose(newDb !== null, () => setNewDb((cur) => (cur && cur.busy ? cur : null)));
  const openNewDb = useCallback((mode: "blank" | "template") => {
    if (mode === "template") {
      // Keep an existing New database dialog underneath so Escape restores its opener.
      setTemplateModule("data");
      return;
    }
    setNewDb({ mode, name: "", busy: false, err: "" });
  }, []);
  const selectDatabase = useCallback((key: string, preserveRoute = false) => {
    // W57-T26 (C6) - preserving a route means keeping the address the reader is standing on,
    // application id and all. Dropping the id would leave a bare grid wearing the App route,
    // which is the state this ticket exists to remove. An App is bound to one database, so a
    // switch to any other database honestly leaves it.
    const current = readDataPath();
    const stays = preserveRoute && !!current?.application && current.database === key;
    // W62-T19 (C6): the switched-to database brings its OWN placement, so no folder rides along.
    window.location.hash = stays
      ? appPathHash({ database: key, application: current.application })
      : dataPathHash({ database: key });
  }, []);
  // W57-T26 (instruction 25): the grid switches databases inside the module already open.
  const selectDatabaseInRoute = useCallback(
    (key: string) => selectDatabase(key, route === APP_ROUTE),
    [route, selectDatabase]
  );
  const renderDatabaseActions = useCallback(
    (database: DataDatabase): ReactNode => {
      const entry = dbEntries.find((candidate) => candidate.key === database.key);
      if (!entry || entry.depth !== 0 || entry.protected || entry.managedBy === "loopable") {
        return null;
      }
      return (
        <RowMenu
          entryLabel={entry.label}
          canSchema
          onSchema={() => setSchemaFor(entry.key)}
          canRename={!!entry.manage && entry.key.startsWith("ut_")}
          onRename={(name) => void commitNavMeta(entry.key, { name })}
          {...(entry.key.startsWith("ut_")
            ? {
                onShare: () =>
                  setShareFor({ kind: "database", id: entry.key, label: entry.label }),
              }
            : {})}
          canDelete={!!entry.canDelete}
          onLoadFootprint={() => fetchTableFootprint(entry.key)}
          onDelete={() => removeDatabase(entry.key)}
        />
      );
    },
    [commitNavMeta, dbEntries, removeDatabase]
  );
  const databaseCreateControl = useMemo(
    () => (
      <CreateNewRow
        collapsed={false}
        onExpand={expandRail}
        onCreateFolder={createFolder}
        onNewDatabase={() => openNewDb("blank")}
        onFromTemplate={() => openNewDb("template")}
        canFolder={entries.length > 0}
      />
    ),
    [createFolder, entries.length, expandRail, openNewDb]
  );
  /*
   * β›” `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);
          // W62-T19 (C6): a database created just now is filed nowhere, so it addresses no folder.
          window.location.hash = dataPathHash({ database: 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} />;
  }

  // ⭐⭐ W33-T26 (item 8b, R5) β€” THE PUBLISHED VIEW, on the same seam and by the same argument as
  // the form above: this branch adds no new public SURFACE. The SPA bundle is already served
  // unauthenticated, so `#/v/<token>` has always loaded for free; what this adds is a client
  // route that renders something there instead of the login page. The genuinely public half is
  // the server's (`routes_publish.py` β€” one uniform 403, constant-time compare, a streamed body
  // bound, a per-IP sliding window).
  // ⚠ It returns BEFORE the boot gate below, so a stranger never sees the shell's brand card
  // flash while `/me` decides they are nobody.
  if (publishToken) {
    return <PublishedView token={publishToken} />;
  }

  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) => {
          // HOTFIX 2026-09-24: an AI app's OAuth approval sent a signed-out visitor here
          // (`routes_external.py::_login_bounce`). Go back to that approval, and only to it.
          if (resumeOAuthApproval()) return;
          // 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 =
    (dataPath ? entries.find((entry) => entry.key === dataPath.database) : undefined) ??
    resolveRoute(entries, route);
  const utility = nav.phase === "ready" ? nav.utility : NO_UTILITY;
  const analyst = findAnalyst(utility);
  // ── 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 = findAutomation(entries);
  /**
   * ⭐⭐ 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.)
   */
  /**
   * ⭐⭐ W33-T22 (owner item 1, "I ask you fix this in multiple different waves already") β€”
   * THE RULE ABOVE IS NOW A FUNCTION, BECAUSE IT HAD TO APPLY TO A SECOND ROW.
   *
   * β›” THE MECHANISM IS A RENDER GATE, NOT A DURATION, and that is why two shipped LATENCY fixes
   * did not touch the symptom. `/nav` was 11.0 s (wave 30) and is 26 ms (wave 32) β€” the rail still
   * painted twice, because `:1437` releases the shell as soon as `/me` resolves and `:911` makes
   * `entries` `NO_ENTRIES` until `nav.phase === "ready"`. First paint therefore happens while the
   * answer to "does this workspace have Automation / an Analyst?" is still unknown, at ANY speed.
   *
   * β›” TWO SYMPTOMS, ONE CAUSE, and the second one is what the owner's words actually describe.
   * W31-T11 gave AUTOMATION the four-state slot below, so that row stopped vanishing. It left
   * the AI-assistant row at `{analyst ? … : null}` with NO placeholder β€” and that row is ABOVE
   * Query / Inbox / Automation / Database / **Connectors**. So when `/nav` landed it INJECTED a
   * ~34 px row and pushed all five down a beat after first paint. Connectors (`:1765`) has no
   * gate of any kind and cannot arrive late: it MOVES. "Automation and Connection module still
   * loads separately" is one late row and one shoved row, from the same missing placeholder.
   *
   * ⚠ ONE FUNCTION, TWO CALLERS, ON PURPOSE. The four states were a hand-written ternary chain
   * on one row; a second copy is how the two rows start disagreeing about what `degraded` means
   * [[one-question-two-normalizers]]. `present` is the ONLY per-row input.
   *
   * ⭐⭐ W33-T75 SUPERSEDES BOTH, AND DELETES THE `pending` STATE ENTIRELY. See `RailSkeleton`:
   * while `/nav` is in flight this rail draws NO rows, so there is no in-flight row state left
   * to name. What remains is what the ANSWER says β€” the row, an `unavailable` arm when the
   * answer was bad, and `absent` when the answer was "this workspace does not have it". `absent`
   * contributes no rail geometry; the visible settled slots decide group separators below.
   *
   * β›” `railLoading` IS THE SAME PREDICATE, WRITTEN ONCE. It is what the rail renders the
   * skeleton on AND what makes the slot function unreachable, so the two cannot come to disagree
   * about when the nav is settled [[one-question-two-normalizers]].
   */
  // Finance paints only App cards, so its read must not delay the rail.
  const railLoading = nav.phase === "loading" || nav.phase === "idle";
  const navFailureMessage = nav.phase !== "error"
    ? ""
    : nav.timedOut
      ? "Navigation took too long to load. Try again."
      : nav.malformed
        ? "Navigation data could not be read. Try again."
        : "Navigation unavailable. Try again.";
  const railSlot = (present: boolean): RailSlot =>
    present
      ? "row"
      : nav.phase === "error"
        ? "unavailable"
        : nav.phase === "ready" && (nav.degraded?.length ?? 0) > 0
          ? "unavailable"
          : "absent";
  const automationSlot: RailSlot = railSlot(!!automation);
  const analystSlot: RailSlot = railSlot(!!analyst);
  const financeAppKey = /^#\/finance\/([^/?#]+)/.exec(hash)?.[1];
  const financeCurrent = Boolean(financeAppKey);
  // 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.
  // 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);

  // ── W41-T32 (R2) β€” WHERE THE RAIL IS, DERIVED FROM THE ONE STATE THAT KNOWS ────────────────
  //
  // β›” `dbAt` IS A DERIVED CONST NOW, NOT STATE, AND THE NAME IS KEPT ON PURPOSE. It used to be
  // the flyout's anchor rect (`null` = shut); it is now "the rail is standing inside a level".
  // Two things follow from keeping the name, and both are the reason:
  //   Β· the Data row's `is-active` expression below is UNCHANGED, so `verify_ui.py`'s W35-T03 leg
  //     β€” the one that caught this row lighting up only while a panel was open β€” still asserts
  //     exactly what it was written to assert, against a rail that now works differently;
  //   Β· a second boolean for "is a level open" beside the cursor that already answers it is how
  //     the two come to disagree [[one-question-two-normalizers]]. There is one answer, computed
  //     from `rail.at`, and everything reads it.
  /**
   * Walk the click history. `<` at the FIRST level lands on the root, which is what puts Home and
   * Connectors back on screen β€” a level replaces the rail's rows, so this is the way out, not a
   * convenience.
   *
   * ⚠ A `db` step RE-NAVIGATES, because that is what the entry MEANS. The owner asked to *"go to
   * the previous path"*, and for a database the path IS the open surface; a back button that
   * changed the rail while leaving the grid on another table would be showing a path nobody is
   * standing on.
   * ⚠ A plain function, not a `useCallback`: it reads `rail` from this render and every click
   * gets a fresh one, so there is no stale-cursor window between two human clicks β€” and a hook
   * here would have to be declared 900 lines up, away from the thing it walks.
   */
  /** The level's own name, and the only header a level gets (DESIGN Β§2: a short plain noun). */
  /**
   * The topbar path segment that read `Loopable / <database>` is GONE, by owner instruction 3 of
   * wave 51: the header is the logo and the word Loopable, nothing else. Its const, its JSX and
   * its rules in `styles/wave41/rail-nav.css` are deleted rather than hidden, and
   * `verify_shell_rail.py` greps `Shell.tsx`, `index.css` and `rail-nav.css` for the removed class
   * name expecting zero, so the segment cannot creep back as dead code.
   * β›” `dbAt` BELOW IS NOT PART OF THAT REMOVAL and must not be swept up with it: the Data row's
   * `is-active` expression, its `aria-current`, the flyout click guard and `verify_ui.py`'s
   * W35-T03 leg all read it.
   */
  const dbAt = !!active && dataDatabases.some((database) => database.key === active.key);
  /** An App instance resolves through its database so the existing grid can render, but the route
   * key remains the one rail authority. Without this guard Data and App both claim the same click.
   * W57-T26 (C6) reads this as the App-route authority; the existing first term already makes it
   * false unconditionally on the App route. */
  const dataRailCurrent = route !== APP_ROUTE &&
    (route === DATA_ROUTE
      || dbAt || (!!active && dbEntries.some((entry) => entry.key === active.key)));

  return (
    <div className="shell-root">
      {/* ⭐⭐ WAVE 35 Β· T01 + T02 (owner item 1, ruling R1, contract C1) β€” THE ONE PERSISTENT TOP
          STRIP. Owner: the "III" icon *"needs to be positioned on the edge of the left side of the
          navigation instead of the edge of the right side ... the Loopable logo will be to the
          right of the 'III' icon, aligned left as well."*
          R1 chose a strip on EVERY module over one scoped to four, precisely so this cluster never
          moves: it is a child of `.shell-root` and a SIBLING of the rail-and-content row, so it
          spans the whole window and Database and Connectors keep their own header BELOW it.
          β›” THE ORDER IS THE CONTRACT, NOT A PREFERENCE. C1: toggle FIRST, brand SECOND, both hard
          left. `web_ui`'s W35-T01 leg asserts exactly that with an NC that swaps them.
          β›”β›” AND THIS IS WHERE THE WAY BACK LIVES NOW. Wave-20 R9 made the LOGO the way out of a
          collapsed rail, because `index.css` hid `.shell-rail-toggle` while collapsed β€” so moving
          the logo out of the rail without moving the toggle too would have left a collapsed rail
          with NO way to reopen it. Resolved by construction rather than by a new rule: the toggle
          is no longer inside `.shell-side`, so `.shell-side.is-collapsed .shell-rail-toggle` can
          no longer match it, and that dead rule is deleted rather than left to look load-bearing.
          The toggle is therefore present and labelled in BOTH states, and the collapsed rail also
          keeps its background-click (`expandOnBlank`). */}
      <header className="shell-topbar">
        <button
          type="button"
          className="shell-topbar-toggle"
          aria-label={navCollapsed ? "Expand navigation" : "Minimize navigation"}
          aria-expanded={!navCollapsed}
          title={navCollapsed ? "Expand navigation" : "Minimize navigation"}
          onClick={navCollapsed ? expandRail : collapseRail}
        >
          <RailToggleIcon />
        </button>
        {/* ⭐ W51-T29 (owner instruction 3) β€” THE LOCKUP IS THE LOGO AND `Loopable`, NOTHING ELSE.
            W41-T32 had hung a path segment naming the open database beside the mark; instruction 3
            of wave 51 removed it, so this element has exactly ONE child and `verify_shell_rail.py`
            asserts that, with a control that adds a sibling and goes red.
            β›” `Brand` IS SHARED with the login card and `StarredPage`'s `Mark`, so the removal
            happened HERE and nothing inside that component was touched. */}
        <div className="shell-topbar-brand">
          <Brand size={26} className="shell-brand" />
        </div>
      </header>
      <div className="shell-frame">
      <OverlayScroll element="aside"
        className={"shell-side" + (navCollapsed ? " is-collapsed" : "")}
        style={{ position: "relative" }}
        // 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}
      >
        {/* S64-T06 / R8 (owner instruction 7, 2026-09-21) β€” D-405'S ABSOLUTE HAIRLINE
            STOOD HERE AND IS DELETED. Owner: *"Why in the hell is Home under main Navigation
            separate from Inbox / Assistant, remove the line that separate the button."*
            It continued the shared rail-head-height band line across `.shell-side`, without
            taking up space. W38-T05 made Home the rail's topmost row, but this line stayed at
            the old head's height: measured y = 87 against Home 52..86 and Inbox 86..120, so it
            painted a full-width line between Home and Inbox despite their flush row boxes.
            THE ACCEPTED TRADE: on Data and Agents, `.cg-views-top` / `.auto-rail-top` still draw
            their own band, which now begins at the rail's right edge instead of crossing it.
            On Sheet and Home there was never anything to its right to join, which is where
            the owner was looking. Home, Inbox and Assistant remain one unbroken group; the
            `shell-nav-sep` below Assistant still closes that group.
            RESTORING THIS LINE RE-CREATES THE DEFECT IN INSTRUCTION 7. A future "the rails'
            lines do not meet" fix belongs in the CONTENT pane's band, never in `.shell-side`. */}
        {/* β›”β›” WAVE 38 Β· T05 (owner instruction 2) β€” `<div className="shell-side-head" aria-hidden />`
            STOOD HERE AND IS DELETED, WITH ITS RULE IN `index.css`. Owner: *"Move the 'Home' button
            into the empty space above it, and every other module button upward, so there is no
            awkward gap."* That empty space was this element: an `aria-hidden` spacer holding
            `--lp-rail-head-h`, so `<nav>` β€” and Home as its first row β€” opened a full header below
            the top strip. `<nav>` is now `.shell-side`'s first child, Home is the rail's topmost
            row, and every row below rises by the same one head, because they are literal
            source-order siblings and nothing else about them moved.
            ⚠ IT WAS NOT A LEFTOVER, AND THE COMMENT THAT STOOD HERE WAS RIGHT: it aligned this
            rail's first row with the content pane's first band. The tombstone on `.shell-side-head`
            in `index.css` carries the cost that was accepted and the alternative that was rejected.
            The short version is that the band it aligned with (`.cg-views-top`, `.auto-rail-top`)
            exists only on grid and Agents surfaces, so on Home β€” where the owner is looking β€” it
            aligned with nothing at all.
            ⚠ NOTHING ELSE IN THE RAIL KEYED ON IT, checked rather than assumed: neither `index.css`
            nor `shell/navExtras.css` carries a `.shell-side >`, `:first-child` or `:nth-child` rule
            into `.shell-side`, so `<nav>` becoming the first child changes no other selector's
            match. `verify_ui.py`'s `W38-T05 no-rail-head` leg keeps the element from coming back. */}
        {/* The narrow rail is one global destination list. Data opens a database through its own
            row; it does not replace Home, Inbox, or Connectors with a second rail level. The only
            navigation-wide visibility state is `is-rail-loading`, whose direct-child rule hides
            every row behind one skeleton while `/nav` is unresolved.
            Keep the rows direct children: the loading selector deliberately reaches every row,
            and a wrapper would let part of the rail paint ahead of the skeleton. */}
        <nav className={"shell-nav" + (railLoading ? " is-rail-loading" : "")}>
          {/* ⭐⭐ W33-T75 β€” THE ONE IN-FLIGHT STATE. `is-rail-loading` hides every sibling below
              (`navExtras.css`), so a row cannot paint ahead of its neighbours. Rendering the rows
              and hiding them β€” rather than not rendering them β€” is deliberate: the flyout portal,
              the tooltips and the account menu all hang off this subtree, and unmounting them for
              the length of a fetch would tear down state that has nothing to do with the nav. */}
          {railLoading ? <RailSkeleton /> : null}
          {/* β›”β›” W40-T22 (owner instruction 5, 2026-08-23) β€” WAVE 38 Β· T06's CHAT LAUNCHER STOOD
              HERE β€” a `navCollapsed`-only `<button>` wearing the `shell-rail-chat` class β€” AND IS
              DELETED, WITH ITS RULE IN `index.css` AND ITS TWO `verify_wiring.py` ROWS. Owner:
              *"remove it from the MAIN navigation entirely so it lives only in the secondary
              navigation"*.
              ⚠ IT WAS NOT A LEFTOVER AND THE COMMENT THAT STOOD HERE ARGUED WELL FOR IT: two doors
              onto one panel, the collapsed rail's and the views rail's, wearing one glyph. The owner
              has ruled that one door is right and it is the views rail's (`ViewSidebar.tsx`'s
              `cg-chat-toggle`), which sits beside the data the chat is about instead of on a frame
              that is often looking at no grid at all. That also settles what the argument here never
              could: collapsed, this control sat under the rail's own divider (`ERROR 9.png`), and a
              control with nowhere clean to sit in the one state it exists in is a control in the
              wrong rail.
              β›” DO NOT RESTORE IT AS A SECOND DOOR. `signal()`, `tipEnter`/`tipLeave` and
              `navCollapsed` all survive here for other rows; what is gone is the launcher, its
              `GRID_CHAT_OPEN_EVENT` twin (tombstoned at the top of this file) and nothing else. */}
          {/* ⭐ 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}`}
            onClick={expandOnNavClick}
            onMouseEnter={navCollapsed ? tipEnter("Home") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
          >
            <HomeIcon />
            <span className="shell-nav-label">Home</span>
          </a>

          {/* ⭐⭐ WAVE 34 R15 + R23 β€” INBOX MOVED UP, directly under Home, and took a MAIL icon.
              Owner, 2026-08-16: *"Home/Inbox (change the inbox logo to a mail icon) then a subtle
              line separation. Then Assistant / Agents"* and, correcting the planner minutes later,
              *"Alerts is called Inbox and it's right below Home"*.
              ⚠ THAT SECOND SENTENCE KILLED A PLANNED SEVENTH ROW. The wave's first draft read the
              rail as having BOTH an Alerts row and an Inbox row and scheduled work to keep them
              ordered. There is only one row, and it has been wearing a bell while the page it opens
              is an inbox β€” which is why the class is still `shell-nav-alerts` while the label,
              the route and now the glyph all say Inbox. The class stays for one reason only: it is
              a stable hook that `verify_wiring` and the collapsed-rail rules already key on, and
              renaming it buys nothing a reader of this comment does not already have. */}
          <a
            className={"shell-nav-item shell-nav-alerts" + (route === INBOX_ROUTE ? " is-active" : "")}
            href={`#/${INBOX_ROUTE}`}
            onClick={expandOnNavClick}
            onMouseEnter={navCollapsed ? tipEnter("Inbox") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
          >
            <MailIcon />
            <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>

          {/* The Analyst slot closes the first rail group: Home / Inbox / Assistant.
              (app.py:8166 pins "AI assistant" over the nav tree, same label,
              now represented here by the dotted ring). 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 ? (
            /* ⭐⭐ 2026-08-14 (owner item 2) β€” THE DOOR IS OPEN. Owner: *"you can unblock user
               from accessing the AI assistant, in staging only so that we can see if the prompt
               to query data works."* It used to open `setAssistOpen("assistant")` β€” an
               under-construction note for the Streamlit Analyst that was DELETED at EXIT-6, so
               the row led to an apology for a surface that is never coming back.
               β›” STILL A `<button>`, NOT AN `<a>`, and that is deliberate rather than lazy. This
               visible row's box is W33-T22 β€” the owner's own layout-jump report β€” and its
               ready/unavailable arms stay the same 34 px. A known-absent grant is intentionally
               outside layout; `<a>` and `<button>` do measure identically here (wave 19 R11's
               reset, measured on staging v12), so this is belt not braces: changing the element
               is a risk with no return when a hash write does the same job. */
            <button
              type="button"
              className={
                "shell-nav-item shell-nav-assist" +
                (route === ASSISTANT_ROUTE ? " is-active" : "")
              }
              onClick={() => {
                expandOnNavClick();
                window.location.hash = `#/${ASSISTANT_ROUTE}`;
              }}
              onMouseEnter={navCollapsed ? tipEnter("Assistant") : undefined}
              onMouseLeave={navCollapsed ? tipLeave : undefined}
            >
              <SparkIcon />
              <span className="shell-nav-label">Assistant</span>
            </button>
          ) : analystSlot === "unavailable" ? (
            /* β›” The payload never came, or came back `degraded`. Silence here is a claim that this
               workspace has no assistant, and we do not know that β€” same argument as W31-T11's
               unavailable arm one row below, same `title`, same quiet dot. */
            <div
              className="shell-nav-item shell-nav-assist is-unavailable"
              title={
                nav.phase === "error"
                  ? navFailureMessage
                  : "This list could not be loaded in full. Reload to retry."
              }
            >
              <SparkIcon />
              <span className="shell-nav-label shell-nav-label--muted">Assistant</span>
              <span className="shell-nav-note-dot" aria-hidden="true" />
            </div>
          ) : (
            /* `absent` has zero visual and accessibility geometry. The direct child remains a
               stable rail-markup identity for the whole-rail loading contract, but it is not an
               entry, a focus target, or an invisible spacer. */
            <div
              className="shell-nav-item shell-nav-assist is-rail-skeleton"
              aria-hidden="true"
              hidden
              style={{ display: "none" }}
            />
          )}

          {/* WAVE 55 instruction 2: the first group is complete even when Assistant is absent.
              Home and Inbox remain real rows, so this boundary is stable rather than permission
              dependent. */}
          <div className="shell-nav-sep" role="none" />

          {/* β›” THE "AI agent" ROW WAS HERE AND IS DELETED (owner, 2026-08-14): *"AI assistant
              module IS AI agent module. So no need to separate it like that."* Wave 33's own note
              on this row had already argued the collapse and deferred it as ASK C-9 because
              W33-T22's done-when named the seven rail rows; the owner has now ruled, so the set
              goes back to those seven. `verify_wiring.py` asserts the absence rather than merely
              dropping the check that asserted the presence β€” a deleted check is
              [[gate-can-report-green-on-nothing]]. */}

          {/* β›”β›” THE QUERY ROW WAS HERE AND IS DELETED (WAVE 34 R14). Owner, 2026-08-16: *"I want
              to combine the AI assistant module AND the Query module… just above '+ New chat' I
              want you to have an easily accessible toggle between Chat/Query."*
              Query did not lose its surface β€” it lost its RAIL ROW, because a toggle inside the
              assistant is now the way in. `#/query` still resolves and redirects (`W34-T15`), so
              every existing bookmark and every `openBuiltView` hand-off keeps working.
              ⚠ THIS COMMENT ASSERTED SOMETHING FALSE FOR ABOUT A MINUTE, and the correction is
              kept because the habit is the useful part. It read *"`SearchIcon` survives as a
              symbol: the flyout's own filter box draws it"* β€” it does not, and `tsc` (TS6133) said
              so on the very next run. The function was deleted in the same edit; its tombstone is
              where it used to live, one screen up. **A claim about who calls a symbol is
              answerable in one command, so ask the compiler rather than reasoning about it.**
              Found again at the close-out dead-code sweep, which greps every deleted symbol and
              reads each survivor: this one was a stale CLAIM rather than a live caller. */}

          {/* WAVE 56 instruction 20: Sheet starts the application-building group and remains an
              unconditional chrome destination. It is followed by Data, App and Agents so the
              fixed module band matches the owner's reading order without rewriting any route.
              The gate reads rendered JSX with comments removed, so this note cannot satisfy the order.

              β›” AN `<a>` LIKE CONNECTORS, UNCONDITIONAL, AND BOTH HALVES MATTER. A `<button>` would
              be the Data affordance's shape (it opens a panel over a server-sent list); Sheet is a
              destination with a hash, so it is a link a person can bookmark, middle-click and see
              in the status bar. And it is NOT wrapped in a ternary: `verify_wiring`'s rail scan
              marks a row CONDITIONAL when the characters before its `<` are `? (`, and every
              conditional row must then carry an inert `is-rail-skeleton` twin so a known-absent
              surface cannot collapse and displace the rows below it. Sheet is granted to everyone
              β€” it is chrome, like Connectors β€” so it has nothing to be absent about. */}
          <a
            className={
              "shell-nav-item shell-nav-sheet" +
              (route === SHEET_ROUTE ? " is-active" : "")
            }
            href={`#/${SHEET_ROUTE}`}
            onClick={expandOnNavClick}
            onMouseEnter={navCollapsed ? tipEnter("Sheet") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
          >
            <SheetIcon />
            <span className="shell-nav-label">Sheet</span>
          </a>

          {/* ⭐ 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.
              W57-T27 (R9) now makes this button a route to Data's landing state. The same granted
              dataDatabases list feeds the landing and the secondary rail, answering R7's concern
              about a hard-coded page. The reader chooses a database; this click no longer opens
              the first database or the creation dialog when the list is empty. */}
          <button
            type="button"
            // β›”β›” WAVE 35 QA β€” `dbAt` ALONE IS THE FLYOUT ANCHOR, NOT THE CURRENT SURFACE, AND
            // THAT MADE W35-T03 FALSE ON THE ONE ROW A PERSON SPENDS MOST OF THEIR DAY IN.
            // Measured on the deployed build: standing on "Odoo customers", `.shell-nav-db` read
            // exactly `shell-nav-item shell-nav-db` β€” every rail row painted identically plain,
            // nothing marking Database as current. It lit up only while the flyout was manually
            // REOPENED, which is a click the ticket's "at a glance" does not allow for. Six of the
            // seven rows in that clause were right; this one was gated on the wrong fact.
            // ⭐ THE FLYOUT'S OWN ROWS ALREADY HAD THE RIGHT ANSWER (`active.key === item.key`,
            // below) β€” the button was the only thing in the rail reading a different question.
            // So this asks the SAME question the rows ask: is the resolved route one of the
            // databases this flyout lists? [[one-evaluator-per-question]]
            className={"shell-nav-item shell-nav-db" + (dataRailCurrent ? " is-active" : "")}
            aria-current={dataRailCurrent ? "page" : undefined}
            onMouseEnter={navCollapsed ? tipEnter("Data") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
            onClick={() => {
              // W53-T33 β€” was `if (navCollapsed) expandRail();`. Same behaviour, one owner: this
              // row was the ONLY one that already expanded, and instruction 6 makes that rule the
              // whole rail's, so the rule lives in `expandOnNavClick` rather than here.
              expandOnNavClick();
              // W57-T26 (C6) recorded: inside an App the Data row HOLDS the current App address,
              // application id included, rather than rewriting it as a Data address for the
              // same database. That rewrite is what turned an open App into Data mode.
              // W57-T27 (R9) supersedes that App branch: R9 is unconditional, so Data reaches
              // its top level from an App too. It never converts the open App into a Data view
              // of the App's own database, which was instruction 9's complaint.
              // W57-T27 (R9, instruction 10): the screenshot harness measured a route-only guard
              // swallowing the Data click from #/data?database=customer_data, leaving the grid
              // visible instead of the landing. `routeKeyOf` drops the query, so the landing and
              // every addressed database share the Data route key. On that route, only having
              // no database addressed honestly means "already at Data's top level".
              if (route === DATA_ROUTE && !dataPath?.database) return;
              window.location.hash = dataAddressHash({});
            }}
          >
            <DatabaseIcon />
            {/* ⭐⭐ W41-T32 (R2) β€” "Database" BECOMES "Data". Owner instruction 29, in passing:
                *"when a user click on a Database (let's rename it to Data)"*.
                β›” THE LABEL ONLY. The route key, the class `shell-nav-db` and every selector that
                keys on it are UNCHANGED β€” a key change would need a `nav.ts::LEGACY_ROUTES` row
                or a stored nav preference orphans, and `.claude/skills/deploy/scripts/verify_live.py`
                drives this row by that exact class. Checked before renaming: no gate in the
                battery asserts the WORD, and no `_test/` leg contains it. */}
            <span className="shell-nav-label">Data</span>
          </button>

          <a
            className={"shell-nav-item shell-nav-app" + (route === APP_ROUTE && !financeCurrent ? " is-active" : "")}
            href={`#/${APP_ROUTE}`}
            aria-current={route === APP_ROUTE && !financeCurrent ? "page" : undefined}
            onClick={expandOnNavClick}
            onMouseEnter={navCollapsed ? tipEnter("App") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
          >
            <AppIcon />
            <span className="shell-nav-label">App</span>
          </a>

          {/* Agents stays permission-aware after App. Its label still comes from the server
              registry when present; moving all three arms together prevents a missing grant from
              changing the module band's order or spacing. */}
          {automation ? (
            <a
              className={
                "shell-nav-item shell-nav-auto" +
                (active && active.key === automation.key ? " is-active" : "")
              }
              href={automation.href}
              onClick={expandOnNavClick}
              onMouseEnter={navCollapsed ? tipEnter(automation.label) : undefined}
              onMouseLeave={navCollapsed ? tipLeave : undefined}
            >
              <AgentIcon />
              <span className="shell-nav-label">{automation.label}</span>
            </a>
          ) : automationSlot === "unavailable" ? (
            <div
              className="shell-nav-item shell-nav-auto is-unavailable"
              title={
                nav.phase === "error"
                  ? navFailureMessage
                  : "This list could not be loaded in full. Reload to retry."
              }
            >
              <AgentIcon />
              <span className="shell-nav-label shell-nav-label--muted">Agents</span>
              <span className="shell-nav-note-dot" aria-hidden="true" />
            </div>
          ) : (
            <div
              className="shell-nav-item shell-nav-auto is-rail-skeleton"
              aria-hidden="true"
              hidden
              style={{ display: "none" }}
            />
          )}

          <div className="shell-nav-sep" role="none" />

          {/* ⭐ 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}`}
            onClick={expandOnNavClick}
            onMouseEnter={navCollapsed ? tipEnter("Connectors") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
          >
            <PlugIcon />
            <span className="shell-nav-label">Connectors</span>
          </a>

          <a
            className={
              "shell-nav-item shell-nav-ai-api" +
              (route === AI_API_ROUTE ? " is-active" : "")
            }
            href={`#/${AI_API_ROUTE}`}
            aria-current={route === AI_API_ROUTE ? "page" : undefined}
            onClick={expandOnNavClick}
            onMouseEnter={navCollapsed ? tipEnter("AI API") : undefined}
            onMouseLeave={navCollapsed ? tipLeave : undefined}
          >
            <ApiIcon />
            <span className="shell-nav-label">AI API</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. */}

          {/* W33-T75: loading is represented only by the two row-local slots above. A separate
              nav-level spinner here sat beneath Connectors and looked like a late eighth row. */}
          {/* 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">
              {navFailureMessage}
            </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>

          {/* ⭐⭐ WAVE 35 Β· T05 (owner item 6) β€” TEMPLATES, DIRECTLY ABOVE THE USER BUTTON.
            It opens the same Application wizard as Home and App, so the three entry points share
            one template, database and field-mapping contract.
            β›” A SIBLING OF `.shell-side-bottom`, NOT A CHILD, and that is behavioural rather than
            cosmetic: that band carries an `onClickCapture` which, while collapsed, swallows the
            click and expands the rail instead (the account POPOVER cannot fit in a 56px strip).
            Nesting this inside it would make Templates unreachable in one click whenever the rail
            is folded β€” the account row's compromise applied to a row that has no popover and does
            not need it.
            ⚠ The tip is the trap the ticket names: collapsed, `.shell-nav-label` folds to zero
            width, so without `tipEnter` this becomes an unlabelled glyph like every other rail row
            would. */}
        <button
          type="button"
          // β›”β›” IT FOLLOWS THE RAIL'S LOADING STATE, AND A SCREENSHOT IS THE ONLY THING THAT
          // CATCHES THIS. `.shell-nav.is-rail-loading > *:not(.shell-rail-skeleton)` hides every
          // real nav row while `/nav` is in flight (W33-T75), but this row is a SIBLING of
          // `.shell-nav`, so that rule cannot reach it: the first build painted "Templates" in ink
          // beneath six skeleton bars. That is two visibly different row states in one list, which
          // is owner item 1 verbatim β€” the complaint that took four waves and four "fixes" to
          // settle, and whose acceptance test is "THE RAIL PAINTS ONCE", never "the spinner is
          // gone". [[a-rail-must-paint-once]]
          className={"shell-nav-item shell-nav-templates" + (railLoading ? " is-rail-hidden" : "")}
          onClick={() => {
            // W53-T33 β€” instruction 6 says "any of the icon". Templates opens an OVERLAY rather
            // than a route, and the rail expanding behind it is what every other row now does.
            expandOnNavClick();
            openApplicationWizard();
          }}
          onMouseEnter={navCollapsed ? tipEnter("Templates") : undefined}
          onMouseLeave={navCollapsed ? tipLeave : undefined}
        >
          <TemplatesIcon />
          <span className="shell-nav-label">Templates</span>
        </button>

        <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();
                  expandRail();
                }
              : undefined
          }
          onMouseEnter={navCollapsed ? tipEnter(session.user.name) : undefined}
          onMouseLeave={navCollapsed ? tipLeave : undefined}
        >
          <AccountMenu
            user={session.user}
            utility={utility}
            onSignOut={signOut}
            onSettings={setSettings}
          />
        </div>
      </OverlayScroll>

      {/* 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.
          <Suspense key={active.key} fallback={
            <div className="pg-state">
              <h1>{active.label}</h1>
              <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" />
            </div>
          }>
            <PageSurface key={active.key} pageKey={active.key} label={active.label} />
          </Suspense>
        ) : 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.
          /* ⭐⭐ WAVE 35 Β· T32 (owner item 2, ask D-1) β€” THE AGENTS HEAD IS GONE; THE FRAME STAYS.
              Owner: *"Let's remove that header for Agent completely."* Agents opens straight onto
              its surface, the way Assistant does.
              β›” THE EDIT IS HERE, NOT IN `AutomationSurface.tsx`, and D found that: T32's `files:`
              and `how:` both said the surface "mounts `shell-db-frame` + `DbHead`", but the surface
              renders no head at all β€” this branch does. Written as the PRD says and nobody would
              have owned the edit. Recorded as amendment A3.
              β›” THE HEAD, NOT THE FRAME. `.shell-db-frame` is the rail-and-content GEOMETRY and
              `.shell-auto-host` is the `flex: 1 1 auto; min-height: 0` link the surface's
              `height: 100%` needs; dropping either collapses the box. Wave-23 C13's argument for
              ONE title system is not revoked β€” it still holds for every real DATABASE, which is
              what `DbHead` is for. Agents is a MODULE, and a module titles itself or not at all. */
          /* β›” THE TWO `key`s ARE LOAD-BEARING, AND THEY WERE PAID FOR. Both arms render a
             `<Lazily>` at the SAME position with the same props, so React reconciles them as one
             instance and the ErrorBoundary inside it KEEPS ITS ERROR STATE across the switch:
             once an open agent threw, walking Back to the gallery repainted the crash card, not
             the gallery, until a reload. Measured on a frame, 2026-09-14 β€” the gallery never
             came back. Distinct keys make them two instances, so a crash in one cannot hold the
             other hostage. */
          agentAddress.agent || agentAddress.voice ? (
            <div className="shell-db-frame">
              <div className="shell-auto-host">
                {/* USER-VISIBLE: ErrorBoundary renders "{surface} could not be shown" (T40, QA) */}
                <Lazily key="agents-surface" surface="Agents"><AutomationSurface /></Lazily>
              </div>
            </div>
          ) : (
            <Lazily key="agents-gallery" surface="Agents">
              <AgentsGalleryPage
                initialStarredOnly={window.location.hash.includes("filter=starred")}
                entries={dbEntries}
                recents={recents}
                folders={navPrefs.folders}
                folderPlacement={navPrefs.placement}
                onSaveFolders={navPrefs !== EMPTY_NAV_PREFS ? (folders, placement) => commitPrefs({ folders, placement }) : undefined}
                automations={autoTiles}
                voiceAgents={voiceAgents}
                agentsError={voiceAgentsError}
                onTemplates={openApplicationWizard}
                onNewDatabase={() => openNewDb("blank")}
                onConnectors={() => { window.location.hash = `#/${CONNECTORS_ROUTE}`; }}
                onOpenAutomation={(autoId) => {
                  window.location.hash = agentAddressHash("agent", autoId);
                }}
                onOpenView={openViewInDatabase}
                onOpenQuery={(qid) => {
                  viewEmitCancel.current = openBuiltView(qid);
                }}
              />
            </Lazily>
          )
        ) : financeAppKey ? (
          <Lazily surface="Finance"><FinanceWorkspace key={financeAppKey} appKey={financeAppKey} /></Lazily>
        ) : 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.
          /* ⭐⭐ WAVE 36 Β· T51 (owner item 7) β€” AND THE HEADER IS GONE FROM THIS BRANCH. Owner:
              *"Remove the header for database completely. its a waste of white space. User should
              be able to tell what database they are in just by seeing the first Unique ID field.
              its ok."* That last sentence is the whole argument and it is why the deletion is safe
              HERE and not everywhere: a database grid's first column IS its identity, on screen,
              in every row. Wave-20 R8's "one title system" was right that the two surfaces needed
              the SAME answer; the owner has now given a different one.
              β›” THE FRAME STAYS, THE HEAD GOES β€” the same distinction W35-T32 drew for Agents six
              comments up. `.shell-db-frame` is the rail-and-content GEOMETRY; dropping it collapses
              the box. Only the 44px title band is reclaimed, and the grid takes it: `.shell-grid-
              host` is `height: 100%` inside a column that now has one fewer fixed row.
              ⚠ `.shell-side-head` WAS CHECKED HERE AND FOUND LIVE. W38-T05 HAS SINCE DELETED IT,
              and this line is corrected rather than left standing, because a comment asserting the
              liveness of an element that no longer exists is the precise failure the "checked
              rather than assumed" habit was adopted to prevent. β›” THE REASONING WAS SOUND AND ITS
              CONCLUSION STILL HOLDS FOR T51: the band aligned with the VIEWS rail's head, not with
              the database title, so nothing T51 did orphaned it. What retired it was owner
              instruction 2 of wave 38 β€” the rail's empty top band IS the "awkward gap" β€” which is a
              later and unrelated ruling. Its tombstone in `index.css` carries the full argument.
              β›” `DbHead` ITSELF SURVIVES UNTIL W36-T67 LANDS. `query/QueryPage.tsx:138` still mounts
              it and that file is session D's fence β€” a component cannot be deleted while another
              fence imports it, which is why T51 is blocked-by T67 rather than the reverse. */
          // W57-T26 (R3): the App route wears its own class on the shared frame. It is the hook
          // the secondary-rail removal needs and it adds no styling on its own.
          // β›” THE DATABASE-MANAGEMENT PROPS BELOW STAY UNCONDITIONAL. Making them route-aware
          // was tried and reverted the same hour: `verify_wiring.py`'s W44 seam leg pins the
          // literal `renderDatabaseActions={renderDatabaseActions}` and
          // `databaseCreateControl={databaseCreateControl}` at this mount, so a ternary there
          // goes red on a wave-44 contract this ticket never meant to touch. R3 removes the
          // whole secondary rail, which takes those controls with it; withdrawing them one by
          // one while the rail still stands is a half-measure that buys nothing.
          <div className={"shell-db-frame" + (route === APP_ROUTE ? " is-app-frame" : "")}>
            <div className="shell-grid-host">
              <OverlayProvider>
                {/* ⭐ 2026-08-14 β€” `gridScopeFor` (shell/dbFrame.tsx), not the inline ternary that
                    stood here. Identical answers; the difference is that the Query module needs
                    the SAME map, and the two spellings (registry key vs grid scope) fail SILENTLY
                    when they diverge β€” `CustomerGrid`'s VIEW_OPEN listener drops an event whose
                    `topic` is the other one. [[one-question-two-normalizers]] */}
                <Lazily surface={active.label || "Database"}>
                  <CustomerGrid
                    // An App owns transient presentation state. Data keeps its persistent grid
                    // across database switches; crossing into or out of an App starts a new owner.
                    key={dataPath?.application ? `application:${dataPath.database}:${dataPath.application}` : "workspace"}
                    scope={gridScopeFor(active.key)}
                    dataPath={dataPath?.database === active.key ? dataPath : undefined}
                    databases={dataDatabases}
                    activeDatabaseKey={active.key}
                    databaseFolders={navPrefs.folders}
                    onSelectDatabase={selectDatabaseInRoute}
                    onDatabaseMove={movePage}
                    onDatabaseFolderRename={renameFolder}
                    onDatabaseFolderDelete={deleteFolder}
                    renderDatabaseActions={renderDatabaseActions}
                    databaseCreateControl={databaseCreateControl}
                  />
                </Lazily>
              </OverlayProvider>
            </div>
          </div>
        ) : active ? (
          <StranglerPage entry={active} />
        ) : route === FEEDBACK_ROUTE ? (
          // ⭐⭐ WAVE 35 Β· T06 (owner item 13, R8, contract C6, wiring W2) β€” the three account
          // surfaces. All three take NO props, on purpose and per B's published contract: Usage
          // reads everything from `GET /usage`, Feedback's confirmation is inline, and
          // Subscription must not hide itself (two places deciding one thing is how they disagree).
          // β›” `tsc` CANNOT ENFORCE THESE THREE MOUNTS, precisely because the components take no
          // props β€” so the `verify_wiring` W2 row is the only wall between "the page exists" and
          // "the page is reachable". Wave 23 shipped THREE finished routers with no mount line,
          // 404-dead behind entirely green gates. [[reachable-is-not-the-same-as-built]]
          <Lazily surface="Feedback"><FeedbackPage /></Lazily>
        ) : route === USAGE_ROUTE ? (
          <Lazily surface="Usage"><UsagePage /></Lazily>
        ) : route === SUBSCRIPTION_ROUTE ? (
          // β›” C6's SECOND HALF, and the whole reason the row's absence is not enough: a hidden
          // menu row whose route still answers is not hidden. Anyone who types the hash or follows
          // an old bookmark walks in. Same constant as the menu, so the two cannot disagree.
          session.user.tenant === NO_SUBSCRIPTION_TENANT ? (
            <div className="shell-placeholder">
              <h1>Not available</h1>
              <p>This workspace does not have a subscription page.</p>
            </div>
          ) : (
            <Lazily surface="Subscription"><SubscriptionPage /></Lazily>
          )
        ) : route === SHEET_ROUTE ? (
          // ⭐⭐ WAVE 49 Β· T01 (rulings R1, R2, R30) β€” THE SHEET MODULE'S DOOR.
          //
          // β›” THE PAGE TAKES NO PROPS, so `tsc` cannot prove this branch exists β€” a prop-less
          // component cannot be forgotten INTO a type error, which is exactly how wave 23 shipped
          // three finished routers with no mount line, 404-dead behind entirely green gates. The
          // wall is `verify_wiring`'s W49-W1 rows, and they assert the LAZY IMPORT and THIS BRANCH
          // rather than a display string: that gate's header records a false green where deleted
          // JSX text survived in a comment. [[reachable-is-not-the-same-as-built]]
          //
          // ⚠ `Lazily`, not a bare `Suspense`, like every other split surface here: the shared
          // wrapper carries the ErrorBoundary, so a chunk that fails to load names the surface it
          // was for instead of blanking the frame.
          /* The keys are here for the reason the Agents branch records below: two `<Lazily>`
             elements at one position are ONE ErrorBoundary instance, so a crash inside the
             workbook would keep painting over the gallery after Back. */
          sheetWorkbookId ? (
            <Lazily key="sheet-workbook" surface="Sheet"><SheetPage /></Lazily>
          ) : (
            <Lazily key="sheet-gallery" surface="Sheets">
              <SheetGalleryPage
                initialStarredOnly={window.location.hash.includes("filter=starred")}
                entries={dbEntries}
                recents={recents}
                folders={navPrefs.folders}
                folderPlacement={navPrefs.placement}
                onSaveFolders={navPrefs !== EMPTY_NAV_PREFS ? (folders, placement) => commitPrefs({ folders, placement }) : undefined}
                automations={autoTiles}
                onTemplates={openApplicationWizard}
                onNewDatabase={() => openNewDb("blank")}
                onConnectors={() => { window.location.hash = `#/${CONNECTORS_ROUTE}`; }}
                onOpenAutomation={(autoId) => {
                  window.location.hash = agentAddressHash("agent", autoId);
                  signal(AUTOMATION_OPEN_EVENT, { autoId });
                }}
                onOpenView={openViewInDatabase}
                onOpenQuery={(qid) => {
                  viewEmitCancel.current = openBuiltView(qid);
                }}
              />
            </Lazily>
          )
        ) : 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 === AI_API_ROUTE ? (
          <div className="shell-home">
            <Lazily surface="AI API"><ExternalAccessPane /></Lazily>
          </div>
        ) : 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 = agentAddressHash("agent", dest.autoId);
                  signal(AUTOMATION_OPEN_EVENT, { autoId: dest.autoId, tab: dest.tab });
                  return;
                }
                if (dest.surface === "map") {
                  window.location.hash = "#/customer";
                  window.setTimeout(() => signal("aios:route-open", { routeId: dest.routeId }), 0);
                  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>
        ) : boardedFor(route, entries, utility) ? (
          // ⭐⭐ WAVE 37 Β· T06 (owner item 8, ruling R7) β€” THE BOARDED SURFACE, DECIDED BY THE GRANT.
          //
          // β›” R7 REFUSES A HARDCODED `is_admin` BRANCH, and the refusal is the design rather than a
          // style note: `perm_scope.may_access` already opens with `if perms.is_admin(user): return
          // True`, so a second admin rule beside it would be two gates that can disagree about one
          // question [[two-gates-can-assert-opposite-things]]. This reads the GRANT the server
          // already applied β€” `entries` IS `/nav`'s page list, i.e. the set the server decided this
          // session may see β€” so re-granting one account restores the surface with no code change,
          // which is R7's "reversible per account" in the literal sense.
          //
          // β›” WHY IT IS NEEDED AT ALL, given the server already refuses: `#/assistant` is a CHROME
          // route (`nav.ts::CHROME_ROUTES`), so it renders for ANY session regardless of the grant,
          // and the page's own calls then 403 β€” a non-admin deep-linking it met a working-looking
          // surface whose every request failed. Agents is the mirror image: `resolveRoute` returns
          // no entry, so it fell through to HOME, silently. **Neither is an error and neither is a
          // blank; both are worse, because they look like the link is broken rather than boarded.**
          //
          // ⚠ IT SITS ABOVE THE ROUTE BRANCHES ON PURPOSE. Below them it would be unreachable for
          // the assistant (a chrome route matches first) and below `!active` it would be
          // unreachable for Agents (Home matches first) β€” the two failure shapes it exists to fix.
          <Lazily surface="Under construction">
            <div className="acct-page">
              <h1 className="acct-title">{boardedFor(route, entries, utility)}</h1>
              <p className="acct-sub">
                Under construction. This area is being built and is not available on your account
                yet. An administrator can turn it on for you in Settings, under Manage users.
              </p>
            </div>
          </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>
        ) : route === ASSISTANT_ROUTE ? (
          // ⭐⭐ 2026-08-14 (owner item 2) β€” THE AI ASSISTANT, where the question is asked.
          //
          // β›” `granted` IS REQUIRED HERE FOR THE SAME REASON IT IS ON `QueryPage` ABOVE, and it
          // is now the more load-bearing of the two: this is the surface that NAMES a database to
          // the model. It is the nav's own entries β€” the set the server decided this session may
          // see β€” so *"a chrome route renders nothing the server did not already grant"* stays
          // true by construction, and the build door re-checks with the same wall regardless.
          <Lazily surface="Assistant"><AssistantPage granted={entries} /></Lazily>
        ) : nav.phase === "ready" ? (
          // W58-T02: bare Data reuses Home's database projection, cards and layout controls.
          // The mode omits creation and other Home sections; App keeps its own directory.
          // Home remains the fallback for empty, stale and unknown hashes.
          // ⭐ 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={route === APP_ROUTE ? "App" : route === DATA_ROUTE ? "Data" : "Home"}>
            <HomePage
              mode={route === APP_ROUTE ? "app" : route === DATA_ROUTE ? "data" : "home"}
              financeApplications={financeApplications}
              initialStarredOnly={window.location.hash.includes("filter=starred")}
              // ⭐ `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}
              folders={navPrefs.folders}
              folderPlacement={navPrefs.placement}
              onSaveFolders={navPrefs !== EMPTY_NAV_PREFS ? (folders, placement) => commitPrefs({ folders, placement }) : undefined}
              automations={autoTiles}
              // Home's Templates card and App's Create new button share this wizard door.
              onTemplates={openApplicationWizard}
              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 = agentAddressHash("agent", autoId);
                signal(AUTOMATION_OPEN_EVENT, { autoId });
              }}
              /* ⭐ W35-T16 (ask B-8) β€” the SAME handler `StarredPage` gets, deliberately: a starred
                 view opened from Home and the same view opened from Starred must not behave
                 differently, and two copies of "route then ask" is how they would. */
              onOpenView={openViewInDatabase}
              onOpenQuery={(qid) => {
                viewEmitCancel.current = openBuiltView(qid);
              }}
            />
          </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>Navigation unavailable</h1>
            <p>{navFailureMessage}</p>
            <button
              className="login-submit shell-retry"
              type="button"
              onClick={() => setNavEpoch((epoch) => epoch + 1)}
            >
              Try again
            </button>
          </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>
      </div>{/* /.shell-frame β€” C1's rail-and-content row, beneath the top strip */}

      {/* 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. */}
      {templateModule ? (
        <Lazily surface="Templates">
          <TemplatePicker initialModule={templateModule} onClose={() => setTemplateModule(null)}
            onApplication={chooseAppTemplate}
            onCreated={(address) => { setTemplateModule(null); setNewDb(null); window.location.hash = address; }} />
        </Lazily>
      ) : null}
      {assistOpen ? (
        <BodyPortal>
          <div style={{ position: "relative", zIndex: "var(--cg-z-overlay)" }}>
            <ApplicationWizard
              databases={dataDatabases}
              initialTemplate={appTemplate}
              panelRef={appWizardRef}
              onClose={closeApplicationWizard}
              onBusyChange={setApplicationWizardBusy}
              onCreated={launchCreatedApplication}
            />
          </div>
        </BodyPortal>
      ) : 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={() => openNewDb("template")}
              >
                <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>
            {(
              <>
                <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 })}
                  // W51-T31 β€” Escape is NOT handled here any more. The dialog's
                  // `useEscapeClose` entry claims the key in the capture phase and stops it, so
                  // a branch here would be dead code that reads as the live one.
                  onKeyDown={(e) => {
                    if (e.key === "Enter") void createDb();
                  }}
                />
                {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}
          /* ⭐ W33-T27 β€” the DATABASE a shared VIEW belongs to, which the publish control needs
             and the share request never carried. The emitter's value wins when it sends one
             (`CustomerGrid` is another lane's file this wave); otherwise the OPEN SURFACE's key,
             which is the same table by construction β€” a view's share dialog can only be opened
             from inside that view. ⚠ A non-view share passes nothing and the panel does not
             render, which is the same absence a non-publishable view produces. */
          topic={shareFor.topic || (active ? active.key : "")}
          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>
  );
}