File size: 353,456 Bytes
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
 
 
 
 
 
 
 
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
 
 
 
 
 
 
 
 
 
 
 
 
 
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcdb685
 
 
 
e1b3e71
 
 
 
 
 
 
 
 
 
 
 
 
609fb78
 
 
 
 
 
 
e1b3e71
 
 
 
 
 
 
 
 
 
 
 
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609fb78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609fb78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcdb685
 
609fb78
 
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609fb78
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
 
 
 
 
 
 
 
 
 
 
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b3e71
 
 
 
 
 
 
051f280
 
 
 
 
 
 
 
 
 
e1b3e71
 
 
 
 
 
 
 
 
 
 
 
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
import {
  memo,
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { DataEditor, GridCellKind } from "@glideapps/glide-data-grid";
import type {
  CellClickedEventArgs,
  DataEditorRef,
  EditableGridCell,
  GridKeyEventArgs,
  GridMouseEventArgs,
  GridSelection,
  DrawHeaderCallback,
  HeaderClickedEventArgs,
  Item,
  Rectangle,
  Theme,
} from "@glideapps/glide-data-grid";
import "@glideapps/glide-data-grid/dist/index.css";

import { useCustomerData } from "./useCustomerData";
import type { SurfaceScope } from "./apiBridge";
// ⭐ WAVE 30 Β· W30-T42 (contract C2) β€” the WINDOWED grid's arithmetic, pure and node-run in
// `verify_grid_ux.py`, because every one of these decisions is taken inside a callback where
// only its own source text could otherwise be checked.
import { WINDOW_ROWS } from "./apiBridge";
import {
  EMPTY_WINDOW_PREDICATE, limitSummary, nextWindowOffset, windowedCapabilityNote,
  windowedFoldNote, windowPredicateKey,
} from "./counts";
import { defaultViewConfig, useGridColumns } from "./useGridColumns";
import { activeMeasureRuleIds, pendingMeasures, runPipeline, sliceForDisplay,
  unresolvedConditions, useVisibleRows } from "./useVisibleRows";
import { computeAggs } from "./aggregations";
import type { CohortSets } from "./useVisibleRows";
import type { MeasureSets } from "./useVisibleRows";
import { useGetCellContent } from "./useGetCellContent";
import { useGridSelection } from "./useGridSelection";
import Toolbar from "./Toolbar";
import JsonViewer from "./JsonViewer";
import RecordDetail from "./RecordDetail";
import ViewSidebar from "./ViewSidebar";
import ColumnMenu from "./ColumnMenu";
import type { ColumnMenuState } from "./ColumnMenu";
import { HEADER_ICONS } from "./iconShapes";
import { emitHostEvent, eventId } from "./hostBridge";
// ⭐ WAVE 27 item 21 (R14) β€” which of this table's views carry an alert. The SERVER's
// list is the only answer; the rail's alert door is a one-way create.
import { fetchAlerts } from "../alerts/alertsApi";
import { NAV_MINIMIZE_EVENT, ROWS_STALE_EVENT, TOAST_EVENT, VIEW_OPEN_EVENT,
  WORKSPACE_STALE_EVENT, signal }
  from "../apiContract";
import type { ViewOpenDetail } from "../apiContract";
import { addTableField, addTableRow, deleteTableField, deleteTableRow, fetchLinkTargets,
  fetchRollupSources, patchTableField } from "./apiBridge";
import type { LinkTarget, RollupSourceOffer } from "./apiBridge";
import SelectFromFile from "./SelectFromFile";
import ImportDialog from "./ImportDialog";
import { FormInterface } from "./FormInterface";
import type { FormSpec } from "./FormInterface";
// Owner item 16 / R4 / C-UNDO β€” the stack and every inverse. Pure, so a node gate can run it.
import { describe, directed, popRedo, popUndo, pushUndo, stackFor } from "./undoStack";
import type { CellChange, UndoBook, UndoEntry, UndoRow, UndoValue } from "./undoStack";
import { exportFilename, runExport, triggerDownload } from "./export";
import type { ExportFormat } from "./export";
// owner item 3 (2026-08-03) β€” a time-series view exports its SHEET, not the rows under it.
import { buildTsCsv, tsSheetToTable } from "./timeSeriesData";
import type { TsSheet } from "./timeSeriesData";
import { echoReemit, reconcileEchoView } from "./viewEcho";
import { pruneStamps, reconcileFields } from "./optimism";
import { applyViewOrder, newFolderId, pruneFolderStamps, reconcileFolders,
  resolveFolderId } from "./folders";
import type { FolderStamps } from "./folders";
// ⭐ WAVE 27 item 22 β€” the cells the active view's filter forces on a record added under it.
import { filterSeedValues } from "./filterSeed";
import { adoptNewFields, adoptNewViews, pruneTombstones, seedLocalViews, stampTombstone }
  from "./liveWorkspace";
import type { Tombstones } from "./liveWorkspace";
import type { GridFolder, ViewPermissions } from "./types";
import type { FieldStamps } from "./optimism";
import { evalFormula, orderFormulas, parseFormula } from "./formulaEngine";
import type { FormulaAst } from "./formulaEngine";
import { CalendarView, KanbanView, ListView, ModeSwitch } from "./viewModes";
import { SwipeView } from "./SwipeView";
import type { SwipeSpec } from "./SwipeView";
// The chart engine lives in `viz/` since EXIT wave 2 (W2-5/Y3) β€” the grid is now
// one of its two callers, the Y1 page envelope being the other.
import { DashboardView } from "../viz/DashboardView";
import { cleanCharts } from "../viz/chartData";
import type { ChartSpec } from "../viz/chartData";
import { MapView } from "./MapView";
/* ═══ W18-C CATALOG ═══ (owner item 4, contract C6) */
import { CatalogView } from "./CatalogView";
import { CATALOG_CODE_FIELD } from "./catalogData";
import type { CatalogSpec } from "./types";
/* ═══ end W18-C CATALOG ═══ */
import { lightTheme, STATUS_ROW_THEME, HOVER_ROW_THEME, HOVER_NEUTRAL,
  ACTIVE_ROW_NEUTRAL, CUSTOM_FIELD_MARK } from "./theme";
import { avatarInitials, formatDisplay, imageCellRenderer, ratingCellRenderer, setAvatarRepaint,
  userCellRenderer } from "./cells";
import { optionTint, pickTint } from "./choiceColors";
import {
  EMPTY_GRID_COPY_PROVENANCE,
  markGridCopy,
  observeCopyEvent,
  planFieldPaste,
  pasteRowCount,
} from "./clipboard";
import { cellTipText, expandButtonRect, GROUP_HEADER_FONT, GROUP_LABEL_PAD, headerMarkLayout,
  headerMarkSizes, tipLeft } from "./overlayPlacement";
import { AnchoredOverlay, BodyPortal, useOverlayLayer } from "./OverlaySurface";
import type { AnchorRect } from "./OverlaySurface";
import { StarIcon } from "./Stars";
import { ALL_VIEW_ID, MAX_CALENDAR_METRICS, allViewName,
  MAX_FROZEN, choiceOptions, choiceVocabulary, clampFrozenCount, cleanDisplay, formulaOf,
  topicForScope,
  isDateFamilyType, isFilterGroup, isGroupableField, isMachineOwned,
  isDerivedLink, isUserSchemaField, TOTAL_GROUP_KEY,
  isNumericFieldType,
  machineFoundRows, reFindConsequences,
  isPickType, mayEditField,
  isModeFrozen, isUndeletableView, mayEditView, mayToggleViewLock,
  measureColumnIndex, ratingMax, ruleColumnKeys,
  tableMode, uniqueDisplayName } from "./types";
import type {
  DisplayMode,
  DisplaySpec,
  Field,
  HostEvent,
  FieldScope,
  FieldType,
  FilterNode,
  FilterRule,
  Row,
  RowHeightMode,
  SavedView,
  ViewConfig,
} from "./types";
// Item 7 (C-TS). Default-exported because it is a leaf VIEW like MapView, and because RECORD
// imports the same default for the record-detail Insights tab (C-EMBED).
import TimeSeriesPanel from "./TimeSeriesPanel";
import type { WindowSpec } from "./windows";
import { windowLabel } from "./windows";

const ROW_PX: Record<RowHeightMode, number> = { short: 28, medium: 34, tall: 48 };

/**

 * Wave-14 R7 β€” **a button label is ONE LINE.** Every button row in this file is a flex row with

 * no width reservation, so on a narrow grid box the items shrink and their labels wrap:

 * "Remove from cohort" becomes two lines, the row grows, and the bar stops being a bar. It only

 * happens below a width no fixed-size screenshot is taken at, which is why it survived.

 *

 * ⚠ Applied INLINE rather than on `.cg-btn`, where it belongs: `index.css` is PANEL's fence this

 * wave. A mailbox line asks them to hoist it onto `.cg-btn` globally β€” after which this is

 * redundant, and harmless, because it says exactly the same thing.

 */
const ONE_LINE = { whiteSpace: "nowrap" } as const;

/**

 * How many VISIBLE columns glide freezes. Module-level and used twice on purpose (item 15): the

 * `freezeColumns` prop and the group bar's label fit must read ONE answer, because the label is

 * clipped to exactly this strip and a second copy of the clamp would let the two disagree by a

 * column β€” which shows up as a label cut early for no visible reason.

 */
function frozenCountOf(config: ViewConfig): number {
  return Math.min(MAX_FROZEN, Math.max(1, config.frozenCount ?? 1));
}
/* WAVE 21 item 3 (R6): the id and the NAME both moved to `types.ts` β€” the id because a second

   copy of a pinned literal is the drift class this repo gates against, the name because it is

   now topic-derived and the host mints the same string. */

/**

 * owner item 2 (2026-08-03) β€” the measure-cell skeleton's pulse, and its ceiling.

 *

 * 140ms against the 4-step colour ramp is a ~0.6s cycle: a wait, not a strobe. The ceiling is

 * ~60s, after which the cells fall back to ordinary blanks β€” a measure that has not resolved in

 * a minute is not "still loading", and a shimmer that never ends promises a number that is not

 * coming. Shared constant so the two are read in one place rather than tuned apart.

 */
const PULSE_MS = 140;
const PULSE_MAX_TICKS = Math.round(60_000 / PULSE_MS);
/** Referentially stable, so the fallback does not change `getCellContent`'s identity per render

 *  and repaint the canvas forever. */
const NO_PENDING_KEYS: ReadonlySet<string> = new Set<string>();

/**

 * I2 β€” measure a cell's text in GLIDE'S OWN font, so "is this cut off?" is a fact rather than

 * a character-count guess (a guess is wrong in both directions: "IIIII" is narrow, "WWWWW" is

 * wide, and being wrong means either a missing tip or a tip over text you can already read).

 * One lazily-built offscreen context for the whole module β€” `measureText` is cheap, but

 * creating a canvas per mouse-move would not be.

 */
let _tipCtx: CanvasRenderingContext2D | null | undefined;
function measureCellText(text: string): number {
  if (_tipCtx === undefined) {
    _tipCtx = document.createElement("canvas").getContext("2d");
    // glide's default `baseFontStyle` is 13px; the family comes from our own theme.
    if (_tipCtx) _tipCtx.font = `13px ${lightTheme.fontFamily ?? "Inter, sans-serif"}`;
  }
  return _tipCtx ? _tipCtx.measureText(text).width : 0;
}
/**

 * Item 15 β€” the GROUP BAR's measurer, and it is a SECOND context on purpose.

 *

 * `measureCellText` above is set to plain "13px", which is right for ordinary cells and WRONG for

 * a group bar: that row carries `baseFontStyle: GROUP_HEADER_FONT` (semibold), and glide paints a

 * cell with the merged theme's font. Measuring the fit with the lighter weight under-truncates

 * and the label overflows into the frozen strip's hard clip β€” the exact failure `fitGroupLabel`

 * exists to prevent. Font string built from the SAME constant the cell's themeOverride uses, so

 * the two cannot drift.

 */
let _groupCtx: CanvasRenderingContext2D | null | undefined;
function measureGroupText(text: string): number {
  if (_groupCtx === undefined) {
    _groupCtx = document.createElement("canvas").getContext("2d");
    if (_groupCtx)
      _groupCtx.font = `${GROUP_HEADER_FONT} ${lightTheme.fontFamily ?? "Inter, sans-serif"}`;
  }
  return _groupCtx ? _groupCtx.measureText(text).width : 0;
}
/**

 * Owner item 8 (2026-07-27): the first render shows this many rows; "See more" reveals the rest.

 * A DISPLAY cap only β€” the pipeline still runs over the whole book, the toolbar count is still

 * the full matched count, and the cap is stated beside the control that lifts it, which is what

 * keeps [[no-unverifiable-aggregates]] satisfied: nothing is silently truncated.

 */
const DISPLAY_PAGE = 50;
const DISPLAY_STEP = 250;

/* ═══════════════════════════════════════════════════════════════════════════════════════════

   ═══ W18-B VOID ═══ (wave 18, owner item 1b) β€” the two constants the void geometry needs

   that belong to the BROWSER and to GLIDE rather than to us. Both are mirrors, and both say

   here what they are mirroring, because a mirror that does not name its original is how the

   two copies stop agreeing.

   ═══════════════════════════════════════════════════════════════════════════════════════════ */

/** The header band. `headerHeight={36}` at the DataEditor mount is the original.

 *  Not `+ groupHeaderHeight`: glide adds that only when `enableGroups` is on, which it turns on

 *  when a COLUMN carries a `group` β€” `useGridColumns` never sets one (scrolling-data-grid.js:13). */
const HEADER_PX = 36;

/** glide's own row-marker width ladder, `data-editor.js:103`, verbatim.

 *

 *  ⚠ It is passed BACK to glide as `rowMarkerWidth` rather than merely predicted here. The

 *  marker column is part of the content width the void's left edge is measured from, so a

 *  four-pixel disagreement between what glide draws and what we compute is a four-pixel seam of

 *  white against the tint β€” visible, and invisible to every gate. Pinning makes the two the same

 *  number by construction; mirroring the ladder (rather than pinning one constant) is what keeps

 *  the pin from changing the marker column's width on tables of more than 100 rows. */
function rowMarkerPx(rows: number): number {
  return rows > 10_000 ? 48 : rows > 1000 ? 44 : rows > 100 ? 36 : 32;
}

/** The scrollbar gutter this browser steals from a scrollable box, measured once.

 *

 *  β›” WHY THE VOID HAS TO KNOW. The void rectangles sit ON TOP of glide's scroller, so a

 *  rectangle drawn to the box's own edge paints over the scrollbar and hides it. The two cases

 *  are CROSSED, which is the part that is easy to get backwards: the BOTTOM void has to stop

 *  short when the columns overflow (a horizontal scrollbar), and the RIGHT void has to stop

 *  short when the rows overflow (a vertical one). Both happen in ordinary use β€” twelve columns

 *  filtered to five rows is exactly the owner's case.

 *

 *  0 on overlay-scrollbar platforms (macOS, touch), which is correct: nothing is stolen there. */
let scrollbarGutterPx: number | null = null;
function scrollbarGutter(): number {
  if (scrollbarGutterPx !== null) return scrollbarGutterPx;
  if (typeof document === "undefined") return 0;
  const probe = document.createElement("div");
  probe.style.cssText =
    "position:absolute;top:-9999px;width:100px;height:100px;overflow:scroll";
  document.body.append(probe);
  scrollbarGutterPx = probe.offsetWidth - probe.clientWidth;
  probe.remove();
  return scrollbarGutterPx;
}
/* ═══ end W18-B VOID (module scope) ═══ */

interface LocalWorkspace {
  fields: Field[];
  views: SavedView[];
  activeViewId: string;
  /** When this copy was written (browser clock β€” same-machine freshness only,

   *  never date semantics). Absent on copies from before the echo reconcile. */
  savedAt?: number;
  /** Wave-6 item 3c β€” per-key freshness for this browser's own field-def

   *  writes (edits + tombstones), consumed by reconcileFields at init. */
  fieldStamps?: FieldStamps;
  /** BUG-1 (wave 11) β€” viewId β†’ the filter tree already pushed back to the host, so the

   *  echo re-emit happens once per user edit rather than once per remount. NOT a timestamp:

   *  `savedAt` beside it is rewritten on every init, so any time-based bound is refreshed by

   *  the remount it is meant to bound. See viewEcho.echoReemit. */
  reemitted?: Record<string, string>;
  /** 2026-08-04 β€” viewId β†’ when THIS browser deleted it. The views half of the tombstone

   *  rule fields and folders already had, needed the moment the rail adopts host views

   *  after mount (liveWorkspace.ts). Persisted, not a ref, because a remount inside the

   *  echo window would otherwise re-adopt a view the user deleted a second ago. */
  viewTombstones?: Tombstones;
  /** D-19 (wave 20) β€” viewId β†’ when THIS browser last WROTE it. The counterpart of the

   *  tombstones above: they stop a deleted view coming back, this stops a just-created one

   *  being dropped by the host-list rule at init, before its upsert has round-tripped.

   *  Same window, same prune, same browser-clock caveat. */
  viewWrites?: Tombstones;
}

function sameConfig(a: ViewConfig, b: ViewConfig): boolean {
  return JSON.stringify(a) === JSON.stringify(b);
}

function normalizeConfig(config: Partial<ViewConfig> | undefined, fields: Field[]): ViewConfig {
  const base = defaultViewConfig(fields);
  return {
    ...base,
    ...config,
    filters: Array.isArray(config?.filters) ? config.filters : [],
    // Legacy views persisted a flat rule array with an implicit AND β€” anything
    // other than an explicit "or" normalizes to "and", so old views are unchanged.
    filterConj: config?.filterConj === "or" ? "or" : "and",
    sorts: Array.isArray(config?.sorts) ? config.sorts : [],
    order: Array.isArray(config?.order) && config.order.length ? config.order : base.order,
    visible:
      Array.isArray(config?.visible) && config.visible.length
        ? config.visible
        : base.visible,
    widths: config?.widths && typeof config.widths === "object" ? config.widths : {},
    memberPids: Array.isArray(config?.memberPids) ? config.memberPids : [],
    // Wave-6 items 10/11. Both normalize junk to ABSENT (grid / 1 frozen), so
    // a legacy view is byte-identical to itself after a round trip. W13 (C4 as
    // amended): cleanDisplay keeps grid-carried field picks.
    display: cleanDisplay(config?.display),
    frozenCount: clampFrozenCount(config?.frozenCount),
  };
}

/**

 * The pinned system view, as this browser mints it when no host copy has arrived.

 *

 * WAVE 21 item 3 (R6) β€” the NAME is the scope's now (`allViewName`), not the literal "All

 * customers" this minted on every topic including `ut_*` databases of anything at all. The

 * ID is unchanged and deliberately so (see `ALL_VIEW_ID`).

 */
function allRecordsView(fields: Field[], scope: string): SavedView {
  return {
    id: ALL_VIEW_ID,
    name: allViewName(scope),
    kind: "system",
    locked: true,
    config: defaultViewConfig(fields),
  };
}

function readLocal(storageKey: string): LocalWorkspace | null {
  try {
    const raw = localStorage.getItem(`aios-grid:${storageKey}`);
    return raw ? (JSON.parse(raw) as LocalWorkspace) : null;
  } catch {
    return null;
  }
}

function writeLocal(storageKey: string, value: LocalWorkspace): void {
  try {
    localStorage.setItem(`aios-grid:${storageKey}`, JSON.stringify(value));
  } catch {
    // Storage can be blocked in hardened/opaque iframes. The host bridge remains durable.
  }
}

function nextViewId(): string {
  return `view_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
}

/** A multiselect cell's SET, out of its comma-joined string (the `multi` contract). */
function splitMulti(v: string): string[] {
  return v
    .split(",")
    .map((s) => s.trim())
    .filter((s) => s !== "");
}

/** Wave-5 item 3 β€” does any leaf of the filter tree name this column?

 *

 *  ⚠ Wave-20 item 2 RETARGETED the note that stood here ("measure leaves carry measure keys,

 *  which are never field keys, so they cannot false-positive"). True about false POSITIVES,

 *  and precisely why it was a false NEGATIVE: a measure column's own condition names the

 *  MEASURE, so this answered "not filtered" for a column the user had visibly filtered, and

 *  the menu never offered "Don't filter by this field" on it. Both doors now go through

 *  `ruleColumnKeys` β€” the same resolution the tint uses, so the menu and the colour can never

 *  disagree about which columns a filter is about. */
function treeNamesField(

  nodes: FilterNode[],

  key: string,

  measureCols: Map<string, string[]>

): boolean {
  for (const n of nodes) {
    if (isFilterGroup(n)) {
      if (treeNamesField(n.children, key, measureCols)) return true;
    } else if (ruleColumnKeys(n as FilterRule, measureCols).includes(key)) return true;
  }
  return false;
}

/** Wave-5 item 3 β€” "Don't filter by this field": drop every leaf naming the column, prune

 *  groups that end up empty. Returns new arrays throughout (the config is state). */
function dropFieldFromTree(

  nodes: FilterNode[],

  key: string,

  measureCols: Map<string, string[]>

): FilterNode[] {
  const out: FilterNode[] = [];
  for (const n of nodes) {
    if (isFilterGroup(n)) {
      const children = dropFieldFromTree(n.children, key, measureCols);
      if (children.length) out.push({ ...n, children });
    } else if (!ruleColumnKeys(n as FilterRule, measureCols).includes(key)) {
      out.push(n);
    }
  }
  return out;
}

// The header sprite map moved to iconShapes.ts (wave-8 I20/I21) β€” it is data +
// SVG-source builders with no React in it, which is what lets verify_icons.py
// import it under node and assert the (i) actually contrasts.

function slugify(label: string): string {
  return (
    label
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "_")
      .replace(/^_|_$/g, "")
      .slice(0, 28) || "field"
  );
}

interface FieldBuildExtra {
  formula?: string;
  max?: number;
  scope?: FieldScope;
  label?: string;
  colorCodeOptions?: boolean;
  optionColors?: Record<string, string>;
  /**

   * ⭐⭐ 2026-08-09 β€” THE RELATIONAL BAGS, WHICH THIS INTERFACE USED TO DROP ON THE FLOOR.

   *

   * `ColumnMenu.FieldConfigExtra` has carried them since 2026-08-07 and `extraFor` builds a

   * complete bag; this type β€” the receiving end of the same `extra` argument β€” never declared

   * either key, so `buildOverlayField` could not copy what it could not see. The measured result

   * on nurilab: a column stored as

   *   `{key:'custom_video_views_90j26', label:'Video Views', type:'rollup', source:'overlay'}`

   * with NO bag, in one user's workspace stratum, which `compute_relation_cells` never reads.

   * Named, configured, rendering, and permanently blank β€” the owner's *"the Rollup doesn't

   * work"*. β›” Both halves were needed: this type, and the `createField` route below.

   */
  link?: Record<string, unknown>;
  rollup?: Record<string, unknown>;
  /** Item 15 (C-RENAME) β€” the option renames this save carries, by row identity. Consumed by

   *  `retypeField` (which emits `choice_rename`) and ignored by every create path: a field

   *  being CREATED has no values to migrate. */
  renames?: { from: string; to: string }[];
}

/**

 * One constructor for a user-created field, shared by "insert field" and Change-field's

 * "New field" half (wave-2 item 5) so the two doors cannot drift. A `multiselect` carries its

 * declared options AND `multi: true` β€” the cell is a comma-joined SET, and the flag is what the

 * grouping contract keys on (belt to the type-derived brace in groupRows).

 *

 * Wave-5: `formula` and `created_time` are built in the HOST's OWN emission shape (source

 * 'odoo' + derived β€” aios_grid.READONLY_CUSTOM_TYPES), so the optimistic local def and the

 * next payload's echo are byte-identical and nothing restyles on the round trip. `rating`

 * carries top-level `max`, `formula` carries top-level `formula` (the ~20:20 contract

 * amendment: options stays the select-family list). Wave-6 item 6: both types are now

 * `filterable: true` β€” the host flipped its emission, and conditions on them evaluate in the

 * client engine over computedRows (this table's counts are client-mode; a windowed table's

 * columns come from the semantic model, so the SQL engine never sees these types).

 */
/**

 * ⭐⭐ 2026-08-09 (owner ruling) β€” DOES THE PRE-SET LOCK CLOSE THIS COLUMN'S SCHEMA?

 *

 * Owner: *"No rollup field should be uneditable, everything is custom and changeable always."*

 * A ROLLUP holds no data of its own β€” it is a question asked of other rows, re-askable at any

 * time, and re-asking it costs nothing because the answer is recomputed from the authoritative

 * store on the next pass. `preset` still closes every column that HOLDS something: retyping a

 * pre-set `followers` column would strand real measurements in a column that can no longer read

 * them.

 *

 * β›” THE CLIENT MIRROR OF `core.user_tables.preset_editable`, and `verify_rollup_editor.py`

 * holds the two in step. This check has THREE enforcement points (here, `may_edit_field`, and

 * `routes_tables._field_or_refuse`'s sentence); a client that kept hiding the editor while the

 * route allowed the PATCH would read as "you fixed nothing", which is the failure mode a fix in

 * one of three places always wears.

 */
function isSchemaLocked(field: Field): boolean {
  return field.automation?.preset === true && field.type !== "rollup";
}

function buildOverlayField(

  label: string,

  type: FieldType,

  options?: string[],

  extra?: FieldBuildExtra

): Field {
  const key = `custom_${slugify(label)}_${Math.random().toString(36).slice(2, 7)}`;
  if (type === "formula" || type === "created_time") {
    return {
      key,
      label,
      type,
      source: "odoo",
      derived: true,
      filterable: true,
      default: true,
      custom: true,
      ...(type === "formula"
        ? { agg: "sum", ...(extra?.formula ? { formula: extra.formula } : {}) }
        : {}),
    };
  }
  return {
    key,
    label,
    type,
    source: "overlay",
    default: true,
    custom: true,
    agg: ["currency", "int"].includes(type) ? "sum" : undefined,
    // The relational bags ride the local definition too, so the optimistic field and the
    // server's echo describe the same column. Without them the grid held a bagless twin of a
    // field the store had configured, and `mayEditField`/`isDerivedLink` read the twin.
    ...(extra?.link ? { link: extra.link as Field["link"] } : {}),
    ...(extra?.rollup ? { rollup: extra.rollup as Field["rollup"] } : {}),
    ...((type === "select" || type === "multiselect") && options?.length ? { options } : {}),
    ...((type === "select" || type === "multiselect")
      ? {
          colorCodeOptions: extra?.colorCodeOptions !== false,
          ...(extra?.optionColors && Object.keys(extra.optionColors).length
            ? { optionColors: extra.optionColors }
            : {}),
        }
      : {}),
    ...(type === "multiselect" ? { multi: true } : {}),
    ...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
  };
}

/** The surface this grid draws. `cohort` is the same table over hand-curated SETS β€” the server

 *  confirms it by stamping `workspace.cohortMode`, which is the only thing the body below reads.

 *

 *  MEMOIZED (owner item 1, 2026-07-31): the shell re-renders on every chrome state flip β€” nav

 *  collapse, toast, settings β€” and an unmemoized grid re-rendered its whole 3,400-line tree

 *  each time. Measured cost: 200ms-5s of main-thread block, which ate the 240ms rail-fold

 *  transition whole (the fold froze, then SNAPPED β€” the exact "static" the owner named). The

 *  props surface is one stable string, so memo makes chrome state changes free; the grid still

 *  re-renders for its own state (edits, resize) and remounts on route change via `key`. */
interface CustomerGridProps {
  scope?: SurfaceScope;
  /** Read-only Grid view embedded in a linked-record modal. It keeps the standard

   * filter/sort/search toolbar while withdrawing schema and row mutations. */
  embedded?: boolean;
  /** Exact linked pids to project from the target database. */
  embeddedRecordIds?: readonly number[];
  /** Selection mode used by an editable ordinary-Link modal. */
  embeddedSelectable?: boolean;
  embeddedSelectedIds?: readonly number[];
  onEmbeddedSelectionChange?: (recordIds: number[]) => void;
}

interface LinkGridModalProps {
  label: string;
  table: SurfaceScope;
  recordIds: readonly number[];
  editable?: boolean;
  single?: boolean;
  onSave?: (recordIds: number[]) => void;
  onClose: () => void;
}

function LinkGridModal({ label, table, recordIds, editable = false, single = false,

  onSave, onClose }: LinkGridModalProps) {
  const panelRef = useRef<HTMLDivElement>(null);
  const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
  const changeSelectedIds = useCallback((ids: number[]) => {
    const next = single ? ids.slice(-1) : ids;
    setSelectedIds((current) =>
      current.join(",") === next.join(",") ? current : next
    );
  }, [single]);
  useOverlayLayer({
    panelRef,
    onDismiss: onClose,
    dismissOnOutside: true,
    initialFocus: "[data-overlay-autofocus]",
    trapFocus: true,
  });
  return (
    <BodyPortal>

      <div className="cg-record-backdrop">

        <section

          className="cg-link-grid-modal"

          ref={panelRef}

          role="dialog"

          aria-modal="true"

          aria-label={label}

          data-overlay-kind="linked-record-grid"

          tabIndex={-1}

        >

          <header className="cg-link-grid-head">

            <div>

              <div className="cg-link-grid-title">{label}</div>

              <div className="cg-link-grid-sub">

                {(editable ? selectedIds.length : recordIds.length).toLocaleString()} linked{

                  single ? " (one allowed)" : ""

                } {(editable ? selectedIds.length : recordIds.length) === 1 ? "record" : "records"}

              </div>

            </div>

            <button

              type="button"

              className="cg-icon-btn"

              aria-label="Close linked records"

              data-overlay-autofocus

              onClick={onClose}

            >

              Γ—

            </button>

          </header>

          <div className="cg-link-grid-body">

            <CustomerGrid

              scope={table}

              embedded

              embeddedRecordIds={editable ? undefined : recordIds}

              embeddedSelectable={editable}

              embeddedSelectedIds={selectedIds}

              onEmbeddedSelectionChange={changeSelectedIds}

            />

          </div>

          {editable ? (

            <footer className="cg-link-grid-foot">

              <button type="button" className="cg-btn" onClick={onClose}>Cancel</button>

              <button

                type="button"

                className="cg-btn cg-btn--primary"

                onClick={() => { onSave?.(selectedIds); onClose(); }}

              >

                Save links

              </button>

            </footer>

          ) : null}

        </section>

      </div>

    </BodyPortal>
  );
}

function CustomerGrid({

  scope = "customer",

  embedded = false,

  embeddedRecordIds,

  embeddedSelectable = false,

  embeddedSelectedIds = [],

  onEmbeddedSelectionChange,

}: CustomerGridProps = {}) {
  // Wave 16 C-TOPIC: which TABLE this tree is drawing, derived from the one scope prop.
  const topic = topicForScope(scope);
  const {
    fields: payloadFields,
    rawRows: fetchedRows,
    payload,
    loading,
    overlayEdits,
    setOverlayEdits,
    patchOverlay,
    requestWindow,
  } = useCustomerData(scope, {
    bindSurface: !embedded,
    includeWorkspace: !embedded,
    writable: !embedded,
  });
  const embeddedIdsKey = embeddedRecordIds?.join(",") ?? "";
  /**

   * ⭐ WAVE 27 Β· OWNER ITEM 2 (contract C2) β€” **ROWS THIS BROWSER JUST CREATED**, held locally

   * until the server's own copy comes back.

   *

   * β›” THE OWNER'S WORDS: *"adding a new record visually takes too long, I need to be able to

   * spam it."* The old path awaited the POST, then fired `ROWS_STALE_EVENT` and re-read the

   * WHOLE table β€” so every "+" cost a round trip plus a full refetch before anything moved, and

   * pressing it five times queued five full refetches of a table that grew by five rows.

   *

   * ⚠ ADD-ONLY AND SELF-PRUNING, which is `liveWorkspace.ts`'s discipline applied to rows: a

   * pending row is merged in only while the fetched payload does NOT carry its pid, and the

   * effect below drops it the moment the server's copy arrives. There is no third state and no

   * merge of values β€” the server's row wins outright, because by then it IS this row.

   */
  const [pendingRows, setPendingRows] = useState<Row[]>([]);
  const rawRows = useMemo(() => {
    const base = embeddedRecordIds
      ? fetchedRows.filter((row) => new Set(embeddedRecordIds).has(row.pid))
      : fetchedRows;
    if (!pendingRows.length) return base;
    const known = new Set(base.map((r) => r.pid));
    const extra = pendingRows.filter((r) => !known.has(r.pid));
    return extra.length ? [...base, ...extra] : base;
    // The scalar key keeps this stable when a caller reconstructs the same id list.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetchedRows, embeddedIdsKey, pendingRows]);
  useEffect(() => {
    // ⚠ PRUNED AGAINST THE FETCHED PAYLOAD, not against `rawRows` β€” `rawRows` contains the
    // pending rows, so it can never report that one has been absorbed. Pruning against the
    // memo's own output is the loop that keeps a placeholder alive forever.
    if (!pendingRows.length) return;
    const known = new Set(fetchedRows.map((r) => r.pid));
    if (!pendingRows.some((r) => known.has(r.pid))) return;
    setPendingRows((cur) => cur.filter((r) => !known.has(r.pid)));
  }, [fetchedRows, pendingRows]);
  /**

   * The rows as of the last render, for callbacks that must not be rebuilt per payload.

   * `appendRow` reads it to mint the next row id the way the server does (`max + 1`); putting

   * `rawRows` in that callback's dependency list would give the trailing "+" a new identity on

   * every refetch, which is a re-render of the grid for a value only used at click time.

   */
  const rowsRef = useRef<Row[]>(rawRows);
  rowsRef.current = rawRows;
  /**

   * ⭐ WAVE 27 Β· ITEM 2 β€” THE NEXT ROW ID, ADVANCED SYNCHRONOUSLY AT MINT TIME.

   *

   * β›” A RENDER-TIME SNAPSHOT IS NOT ENOUGH FOR THE GESTURE THIS ITEM IS ABOUT. `rowsRef.current`

   * is assigned during RENDER, so two "+" presses that land before React commits the first

   * `setPendingRows` both read the same list and both mint the same id. The owner's words were

   * *"I need to be able to spam it"* β€” that IS the failing case, and the damage is not a

   * duplicate row: `minted` is the identity key the failure and re-anchor branches filter and

   * map on, so ONE refused write would withdraw BOTH rows and one taken id would rewrite both.

   *

   * ⚠ SEEDED FROM THE ROWS ON EVERY MINT, then advanced: `Math.max(seen, storeMax) + 1`. Reading

   * the store's max each time is what keeps the client in step after a refetch brings rows in

   * from elsewhere; the ref is what stops a burst from colliding with itself in between.

   */
  const nextRidRef = useRef(0);
  const mintRid = useCallback(() => {
    const storeMax = rowsRef.current.reduce((m, r) => Math.max(m, r.pid), 0);
    nextRidRef.current = Math.max(nextRidRef.current, storeMax) + 1;
    return nextRidRef.current;
  }, []);
  /**

   * Withdraw rows this browser is still holding locally, because they have been DELETED.

   *

   * β›” THE PRUNE EFFECT CANNOT DO THIS AND THAT IS THE WHOLE BUG IT FIXES. Pruning is "the

   * server's payload now CONTAINS this row, so drop my copy" β€” a deleted row will never appear

   * in a payload again, so a pending row that is deleted before its first refetch stays merged

   * into `rawRows` for the life of the mount. Add a record, press Ctrl+Z, and the row sits there

   * looking undeleted while the store has already lost it.

   * ⚠ CALLED AT EVERY `deleteTableRow` SITE (the selection delete and undo's `rowDelete`

   * inverse), because those are the only two doors that remove a row β€” and the undo one is

   * exactly the path that produces a still-pending victim.

   */
  const withdrawPending = useCallback((rids: (string | number)[]) => {
    if (!rids.length) return;
    const gone = new Set(rids.map((r) => Number(r)));
    setPendingRows((cur) => (cur.some((r) => gone.has(r.pid))
      ? cur.filter((r) => !gone.has(r.pid))
      : cur));
  }, []);
  /**

   * ⭐ WAVE 27 Β· OWNER ITEM 21 / RULING R14 β€” WHICH VIEWS ON THIS TABLE CARRY AN ALERT.

   *

   * β›” THE SERVER'S LIST IS THE ONLY ANSWER. The rail's "Alert me about new records…" is a

   * one-way CREATE (it emits an event the shell turns into a POST) and nothing in the grid

   * hears the outcome β€” a `no_filter` refusal is a real answer, so an optimistic local set

   * would paint a badge on a view that has no alert. `GET /alerts` is the state.

   *

   * ⚠ RE-READ ON FOCUS, the same idiom the shell's own inbox uses. An alert created or deleted

   * in another surface (the Alerts pane owns the delete door) reaches this rail on the next

   * focus rather than instantly; the alternative was for the grid to guess at the outcome of a

   * request another component made.

   * ⚠ EMBEDDED GRIDS DO NOT ASK. A linked-record grid inside a modal is not a table anyone

   * alerts on, and a second fetch per relation cell would be a workspace read per click.

   */
  const [alerted, setAlerted] = useState<string[]>([]);
  useEffect(() => {
    if (embedded) return;
    let live = true;
    const pull = () => {
      void fetchAlerts().then((r) => {
        if (!live || !r.ok) return;      // a failed read leaves the badges as they were
        setAlerted(r.value.filter((a) => a.topic === scope).map((a) => a.viewId));
      });
    };
    pull();
    window.addEventListener("focus", pull);
    return () => {
      live = false;
      window.removeEventListener("focus", pull);
    };
  }, [embedded, scope]);

  const [fields, setFields] = useState<Field[]>([]);
  const [views, setViews] = useState<SavedView[]>([]);
  const [activeViewId, setActiveViewId] = useState(ALL_VIEW_ID);
  const [config, setConfig] = useState<ViewConfig>(() => defaultViewConfig([]));
  const [workspaceReady, setWorkspaceReady] = useState(false);
  const [saveState, setSaveState] = useState<"saved" | "saving">("saved");
  const [search, setSearch] = useState("");
  const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
  const [hoverRow, setHoverRow] = useState<number | undefined>(undefined);
  /**

   * Owner item 19 β€” the hover-only Expand button: which record it opens and where it sits, in

   * VIEWPORT coordinates (glide's `getBounds` space, the same one `.cg-header-tip` uses).

   *

   * A real DOM button rather than a mark painted into the canvas, and that is the whole design:

   * a drawn affordance needs a second hit-test that drifts out of step with the drawing, and

   * neither `tsc` nor a screenshot can see the drift β€” the button is painted, and clicking it

   * does nothing ([[ui-invisible-to-assertions]]). An element IS its own hit test.

   */
  const [expandAt, setExpandAt] = useState<
    { pid: number; x: number; y: number; size: number } | null
  >(null);
  const [detailPid, setDetailPid] = useState<number | null>(null);
  const [columnMenu, setColumnMenu] = useState<ColumnMenuState | null>(null);
  /** Open choice list for a `select` / `user` cell β€” see onCellClicked. */
  const [picker, setPicker] = useState<{
    pid: number;
    fieldKey: string;
    anchor: AnchorRect;
  } | null>(null);
  /** Owner item 5 (2026-07-31) β€” closing a picker RETURNS FOCUS TO THE GRID, so Enter keeps

   *  navigating (pick β†’ Enter β†’ next record) instead of stranding focus on a dead overlay. */
  const closePicker = useCallback(() => {
    setPicker(null);
    requestAnimationFrame(() => gridRef.current?.focus());
  }, []);
  /** ⭐ Wave-23 C7 β€” which `json` cell the big viewer is open on. NOT anchored like the picker

   *  above: a document is not a choice list, so it opens as a centred modal (the record drawer's

   *  surface) rather than a popover the size of the cell it came from. */
  const [jsonAt, setJsonAt] = useState<{ pid: number; fieldKey: string } | null>(null);
  const closeJson = useCallback(() => {
    setJsonAt(null);
    requestAnimationFrame(() => gridRef.current?.focus());
  }, []);
  /** A relation opens as the target database's real Grid view, projected to the linked ids.

   * This is intentionally distinct from JsonViewer: filters, sorts, search, column visibility,

   * and the standard cell renderers all remain available inside the large modal. */
  const [linkAt, setLinkAt] = useState<{ pid: number; fieldKey: string } | null>(null);
  const closeLink = useCallback(() => {
    setLinkAt(null);
    requestAnimationFrame(() => gridRef.current?.focus());
  }, []);
  /** WAVE 21 item 11 (R10) β€” is "Select records from a list" open? Opened from the view

   *  rail's "…" and closed by the dialog; the SELECTION it produces outlives it. */
  const [selectFromFile, setSelectFromFile] = useState(false);
  const [importOpen, setImportOpen] = useState(false);
  /** The selection bar's "Add to cohort" popover (owner item 2's purpose for the checkboxes). */
  const [selAddOpen, setSelAddOpen] = useState(false);
  const [selListName, setSelListName] = useState("");
  const selAddRef = useRef<HTMLButtonElement>(null);
  /** Owner item 9 (wave 20) β€” its counterpart: "Remove from cohort…", in ORDINARY views. */
  const [selRemoveOpen, setSelRemoveOpen] = useState(false);
  const selRemoveRef = useRef<HTMLButtonElement>(null);
  /** Owner item 4 / C-ADDROW β€” the pid the trailing "+" just created, so the cursor can land on

   *  it once the re-read actually brings it back (the row does not exist locally before that). */
  const [newRowPid, setNewRowPid] = useState<number | null>(null);
  /**

   * ⭐ WARN-THEN-ALLOW on delete (owner, 2026-08-06) β€” the SIGNATURE of the selection currently

   * armed, or `""`.

   *

   * A signature and not a boolean, deliberately: it is the pid list itself, so changing the

   * selection DISARMS automatically. A boolean would stay true while you re-selected, and the

   * second Delete would then destroy a set nobody had been warned about β€” which is worse than no

   * warning at all, because the warning is what made it feel checked.

   */
  const [delArmed, setDelArmed] = useState("");
  /** Wave-2 item 2c β€” cohort mode: the active cohort and the "+ Add customers" picker. Picks

   *  ACCUMULATE across searches (search, tick, search again, confirm once). */
  const [activeCohortId, setActiveCohortId] = useState<string | null>(null);
  const [addCustOpen, setAddCustOpen] = useState(false);
  const [addCustQuery, setAddCustQuery] = useState("");
  const [addCustPicked, setAddCustPicked] = useState<Set<number>>(new Set());
  const addCustRef = useRef<HTMLButtonElement>(null);
  /** Wave-5 item 1 β€” "Filter by this field": a monotonic signal the Toolbar consumes (it

   *  appends the seeded condition and opens the builder). Wave-6 item 6c: a MEASURE-carrying

   *  column seeds the equivalent measure condition instead (same measure key + window). */
  const [filterSeed, setFilterSeed] = useState<
    | { key?: string; measure?: { key: string; window: WindowSpec }; n: number }
    | null
  >(null);
  /** Wave-6 item 4 β€” the header-row "+" (insert at end): anchors the create-only menu. */
  const [plusMenu, setPlusMenu] = useState<AnchorRect | null>(null);
  /**

   * Wave-6 item 3c β€” per-key freshness of this browser's own field-def writes, persisted with

   * the workspace copy and consumed by reconcileFields at init. A ref, not state: stamps ride

   * along with the setFields that caused them; nothing renders from a stamp.

   */
  const fieldStampsRef = useRef<{ edited: Record<string, number>; deleted: Record<string, number> }>(
    { edited: {}, deleted: {} }
  );
  /** Wave-5 item 6 β€” the header description tip. Floated, pointer-events:none β€” a tooltip

   *  that can receive the pointer swallows the NEXT click ([[ui-invisible-to-assertions]]). */
  const [headerTip, setHeaderTip] = useState<{ text: string; x: number; y: number } | null>(
    null
  );
  /** Wave-9 I2 β€” the CELL tip: hovering a cell whose text is cut off reveals it in full.

   *  Same contract as the header tip above (floated, pointer-events:none, aria-hidden) for

   *  the same reason β€” a tooltip that can receive the pointer swallows the NEXT click, which

   *  this surface has already paid for once ([[ui-invisible-to-assertions]]). */
  const [cellTip, setCellTip] = useState<{ text: string; x: number; y: number } | null>(null);

  /** BUG-1 β€” viewId β†’ the filter tree we have already pushed back to the host. Persisted with

   *  the local workspace because the remount it guards against destroys any ref. */
  const reemittedRef = useRef<Record<string, string>>({});
  /** 2026-08-04 β€” views THIS browser deleted, by id. Read by the live adopt below AND by

   *  init, so the mount path and the after-mount path answer "was this deleted here?" the

   *  same way. Persisted with the local workspace for the same reason `reemitted` is. */
  const viewTombstonesRef = useRef<Tombstones>({});
  /** D-19 β€” viewId β†’ when this browser last wrote it (see LocalWorkspace.viewWrites). */
  const viewWritesRef = useRef<Tombstones>({});
  const initializedKey = useRef<string | null>(null);
  const saveTimer = useRef<number | null>(null);
  const gridRef = useRef<DataEditorRef>(null);
  const gridBoxRef = useRef<HTMLDivElement>(null);
  /** Internal clipboard provenance. The browser exposes pasted text, not its source column;

   *  recording the grid's own copy keeps cross-field paste fail-closed without blocking

   *  ordinary external text pasted into an editable field. */
  const copyProvenanceRef = useRef(EMPTY_GRID_COPY_PROVENANCE);
  useEffect(() => {
    const onCopy = () => {
      // The native copy event follows our grid key event. Preserve that provenance once;
      // every later copy (address bar, another app surface, another input) invalidates it.
      copyProvenanceRef.current = observeCopyEvent(copyProvenanceRef.current, Date.now());
    };
    const onWindowBlur = () => {
      copyProvenanceRef.current = EMPTY_GRID_COPY_PROVENANCE;
    };
    document.addEventListener("copy", onCopy, true);
    window.addEventListener("blur", onWindowBlur);
    return () => {
      document.removeEventListener("copy", onCopy, true);
      window.removeEventListener("blur", onWindowBlur);
    };
  }, []);
  const [gridSize, setGridSize] = useState({ width: 800, height: 600 });

  /**

   * β›” WAVE 21 item 3 (3c) β€” THE FALLBACK KEY IS THE SCOPE'S, and the literal it replaces is

   * the cross-table bleed the owner reported as "RI fields on a new database".

   *

   * MEASURED, not theorised. `fetchWorkspace` collapses 403 / 5xx / network / unreadable into

   * one silent `null` β€” deliberately, because the workspace is an ENHANCEMENT of the table and

   * an older host simply does not serve one. But `null` also meant "no `storageKey`", and the

   * fallback was the LITERAL `"customer-grid-standalone"` β€” ONE localStorage bucket for every

   * scope this component can be mounted at. So on a tenant whose `/workspace` 403s for `ut_*`

   * (routes_grid gated the route on `module_gate("customer_data")` β€” C4 fixes that half), the

   * FIRST user table to be opened writes its views and custom fields into that bucket and the

   * SECOND one reads them back as its own. Two databases with nothing to do with each other,

   * sharing a schema, with no error anywhere.

   *

   * Scoping the key makes that structurally impossible: a bucket belongs to one surface, so

   * the worst a failed workspace read can now do is show THIS table its own last-known local

   * copy. The prefix marks it as the local-only stratum β€” a key the server never issues, so it

   * can never collide with a real `storageKey` (those are `<key>_table_workspace`-shaped).

   *

   * ⚠ Existing browsers lose the contents of the old shared bucket. That is the point: every

   * byte in it is a workspace some other surface persisted, and there is no way to tell whose.

   */
  const storageKey = payload?.workspace?.storageKey ?? `local:${scope}`;

  // Initialize once per permission/data scope. Host state wins; local state
  // fills only missing objects and keeps the standalone path useful.
  useEffect(() => {
    if (!payload || payloadFields.length === 0 || initializedKey.current === storageKey) return;
    const local = embedded ? null : readLocal(storageKey);
    // Item 3c: the def half of the no-blip layer. A RECENT local stamp beats a
    // lagged host echo (rename survives, retype holds, a delete stays deleted);
    // a caught-up echo returns host objects byte-identical (see optimism.ts).
    const stamps = pruneStamps(local?.fieldStamps, Date.now());
    fieldStampsRef.current = {
      edited: { ...(stamps.edited ?? {}) },
      deleted: { ...(stamps.deleted ?? {}) },
    };
    const initialFields = reconcileFields(
      payloadFields,
      local?.fields ?? [],
      stamps,
      Date.now(),
      payload.workspace != null
    );
    const hostViews = embedded ? [] : payload.workspace?.views ?? [];
    const byId = new Map<string, SavedView>();
    byId.set(ALL_VIEW_ID, allRecordsView(initialFields, scope));
    // D-19 β€” the HOST'S LIST DECIDES WHICH VIEWS EXIST. A local copy the host no longer
    // names is a ghost (deleted elsewhere, share revoked, store moved) and is dropped here,
    // guarded by this browser's own recent writes so an optimistic create survives.
    viewWritesRef.current = pruneTombstones(local?.viewWrites, Date.now());
    for (const view of seedLocalViews(local?.views ?? [], hostViews, viewWritesRef.current,
                                      Date.now(), payload.workspace != null))
      byId.set(view.id, view);
    // Host state wins β€” EXCEPT when it is a lagged echo of this browser's own
    // in-flight edit, where taking it would turn a just-completed measure rule
    // valueless: inactive, no pending marker, whole-book count. A rerun replaces
    // the iframe, so this init runs after every host round trip; the reconcile
    // is what keeps a rule with a typed rhs PENDING rather than inactive across
    // that remount (see viewEcho.ts).
    //
    // BUG-1 (wave 11) β€” which views carry a FILTER TREE the host copy does not have, and have
    // not already been told about. `echoReemit` owns both guards (see viewEcho.ts): identity
    // alone would also fire on a display-only reconcile, and a time-based bound cannot work
    // because the local-workspace effect below restamps `savedAt` on every init.
    const reemit = new Map<string, string>();
    // 2026-08-04 β€” the views tombstone map, seeded from the persisted copy so a remount
    // INSIDE the echo window cannot walk back a view this browser just deleted. Init had
    // no such guard before (fields and folders both did), which was survivable only while
    // every host round trip was itself a remount.
    const tombstones = pruneTombstones(local?.viewTombstones, Date.now());
    viewTombstonesRef.current = tombstones;
    for (const view of hostViews) {
      // Both doors, the `reconcileFields` rule: a tombstone drops the host copy AND any
      // local copy, so a delete that raced localStorage cannot re-enter through either.
      if (tombstones[view.id] !== undefined) {
        byId.delete(view.id);
        continue;
      }
      const merged = reconcileEchoView(
        view, byId.get(view.id), local?.savedAt, Date.now()
      );
      const key = echoReemit(merged, view, local?.reemitted?.[view.id]);
      if (key !== null) reemit.set(view.id, key);
      byId.set(view.id, merged);
    }
    const initialViews = [...byId.values()].map((view) => ({
      ...view,
      config: normalizeConfig(view.config, initialFields),
    }));
    const requested =
      local?.activeViewId ?? payload.workspace?.activeViewId ?? ALL_VIEW_ID;
    const active = initialViews.find((view) => view.id === requested) ?? initialViews[0];
    setFields(initialFields);
    setViews(initialViews);
    setActiveViewId(active.id);
    setConfig(active.config);
    setWorkspaceReady(true);
    initializedKey.current = storageKey;

    /**

     * BUG-1 (wave 11) β€” TELL THE HOST. The reconcile above was right about the state and silent

     * about the consequence: it restored a rule this browser completed and the host copy does

     * not have, and then nothing sent it. The autosave effect cannot: init seeds `views` AND

     * `config` from the same reconciled object, so `sameConfig` reports "saved" and no upsert

     * is ever emitted. The rule stays ACTIVE client-side, PENDING forever, and unknown to

     * `_cl_resolve_measures` β€” which is exactly W11-HOST's live trace, a pending view carrying

     * no measure rule at all while the saved-view path resolves correctly.

     *

     * ⚠ THIS TERMINATES, and NOT because the host will store what we send. It might not: a

     * measure key outside this user's BU offer is stripped by `clean_filter_tree`, so the host

     * copy never gains the rule and `lagged` stays true forever. Termination comes from the

     * IDEMPOTENCE KEY β€” the filter tree itself, persisted per view β€” so we tell the host about

     * a given tree exactly once and only speak again when the USER edits the conditions.

     * ⚠ A ref cannot hold that: the remount this exists to survive destroys it. It rides in

     * localStorage beside the views, and `writeLocal` below carries it forward.

     *

     * Emitted from the NORMALIZED copy (`initialViews`), never from the raw host view: that is

     * the config the client is actually filtering with, and sending anything else would ask the

     * host to resolve a question nobody on screen is asking.

     */
    if (!embedded && reemit.size > 0) {
      const stamped = { ...(local?.reemitted ?? {}) };
      for (const view of initialViews) {
        const key = reemit.get(view.id);
        if (key === undefined) continue;
        viewWritesRef.current = stampTombstone(viewWritesRef.current, view.id,
                                               Date.now());
        viewWritesRef.current = stampTombstone(viewWritesRef.current, view.id, Date.now());
    emitHostEvent({ id: eventId("view"), type: "view_upsert", view });
        stamped[view.id] = key;
      }
      reemittedRef.current = stamped;
    } else {
      reemittedRef.current = { ...(local?.reemitted ?? {}) };
    }
  }, [payload, payloadFields, storageKey, embedded, scope]);

  useEffect(() => {
    if (!workspaceReady || embedded) return;
    writeLocal(storageKey, {
      fields,
      views,
      activeViewId,
      savedAt: Date.now(),
      fieldStamps: pruneStamps(fieldStampsRef.current, Date.now()),
      // BUG-1 β€” carried forward, never recomputed here. Dropping it would restore the loop:
      // the next init would find no record of what it already told the host and say it again.
      reemitted: reemittedRef.current,
      // Pruned on the way out, like every other stamp map here: the persisted blob is a
      // recent window, never an archive of everything this tab ever deleted.
      viewTombstones: pruneTombstones(viewTombstonesRef.current, Date.now()),
      // D-19's other half β€” without persisting these, a reload inside the echo window would
      // drop a view this browser created seconds ago.
      viewWrites: pruneTombstones(viewWritesRef.current, Date.now()),
    });
  }, [workspaceReady, storageKey, fields, views, activeViewId, embedded]);

  /**

   * ⭐ THE LIVE WORKSPACE (owner report, 2026-08-04) β€” what has APPEARED since we mounted.

   *

   * The init effect above runs ONCE per mount (`initializedKey`), which under Streamlit was

   * indistinguishable from "once per host round trip" because a rerun replaces the iframe.

   * The standalone shell has no rerun: this component stays mounted until `key={active.key}`

   * changes in Shell.tsx β€” switching modules. So a cohort created here reached the store,

   * came back in the very next `/workspace` re-read, sat in `payload.workspace.views`, and

   * never reached the rail. That is the owner's report, exactly: it appears after you visit

   * another module and come back, because that is the only thing that remounts this tree.

   *

   * ⚠ FIELDS FIRST, AND THE ORDER IS LOAD-BEARING. `fields_from_workspace(ws,

   * cohorts=bool(cohort_lists))` emits the derived "Locked views" column only once a cohort

   * EXISTS β€” so a user's FIRST cohort changes the field contract in the same payload that

   * carries the new view. The adopted views are normalized against `nextFields`, not against

   * the `fields` state (which React has not committed yet), or a projected `config.order`

   * naming the new column would be normalized against a list that does not have it.

   *

   * ⚠ Add-only, tombstoned, and identity-stable β€” see liveWorkspace.ts for why each of those

   * is a correctness property rather than a nicety.

   */
  const hostWorkspaceViews = payload?.workspace?.views;
  useEffect(() => {
    if (!workspaceReady || embedded) return;
    const now = Date.now();
    const nextFields = adoptNewFields(
      fields, payloadFields, fieldStampsRef.current.deleted, now
    );
    if (nextFields !== fields) setFields(nextFields);
    setViews((current) =>
      adoptNewViews(current, hostWorkspaceViews, viewTombstonesRef.current, now,
                    (config) => normalizeConfig(config, nextFields))
    );
  }, [workspaceReady, hostWorkspaceViews, payloadFields, fields, embedded]);

  /** Item 3c β€” stamp a def write / a delete. Pruned at every touch so the persisted blob

   *  stays a recent window, never an archive. */
  const stampFieldEdit = useCallback((key: string) => {
    const s = pruneStamps(fieldStampsRef.current, Date.now());
    fieldStampsRef.current = {
      edited: { ...(s.edited ?? {}), [key]: Date.now() },
      deleted: { ...(s.deleted ?? {}) },
    };
  }, []);
  const stampFieldDelete = useCallback((key: string) => {
    const s = pruneStamps(fieldStampsRef.current, Date.now());
    const edited = { ...(s.edited ?? {}) };
    delete edited[key];
    fieldStampsRef.current = {
      edited,
      deleted: { ...(s.deleted ?? {}), [key]: Date.now() },
    };
  }, []);

  const updateConfig = useCallback(
    (next: ViewConfig) => {
      if (next.groupBy !== config.groupBy) setCollapsed(new Set());
      setConfig(next);
    },
    [config.groupBy]
  );

  const {
    visibleCols,
    fieldByKey,
    order,
    visible,
    lockedKey,
    onColumnResize,
    onColumnMoved,
    onColumnProposeMove,
    setColumnVisible,
    insertColumn,
  } = useGridColumns(fields, config, updateConfig);

  /**

   * ⭐ Wave-20 owner item 4 (ruling R8, contract C-ADDROW) β€” **THE GHOST ROW.**

   *

   * A trailing "+" row at the bottom of the grid, the way Airtable grows a table, replacing the

   * "Add record" button that used to sit in the shell's header bar (S4 deleted it this wave).

   *

   * β›” USER DATABASES ONLY. A connector's rows are read-synced from Odoo; a "+" there could only

   * refuse, and R8 names that a fake affordance. The test is the SCOPE (`ut_*`), which is also

   * the only scope with a rows endpoint to POST to β€” so the affordance and the capability come

   * from the same fact rather than from two lists that can drift.

   *

   * ⚠ THE ROW IS NOT ADDED LOCALLY. `rawRows` is the server's answer, and a client-invented row

   * would have no rid, no defaults and no place in anyone else's copy. The POST clears the rows

   * cache and fires `ROWS_STALE_EVENT`, `useCustomerData` re-reads, and the row arrives with the

   * id the store gave it. The cursor then follows it (`newRowPid` + the effect below) β€” which is

   * why the pid is remembered instead of glide's `"bottom"` being returned here: at the moment

   * this resolves, the appended row does not exist yet, so "bottom" would land on the last OLD

   * row.

   */
  const isUserTable = !embedded && scope.startsWith("ut_");
  const recordsMutable = payload?.recordsMutable !== false;
  const canMutateRecords = isUserTable && recordsMutable;
  /**

   * ⭐ 2026-08-07 β€” the databases a `link` column may point at, fetched when the column menu

   * OPENS rather than on every render of the grid.

   *

   * ⚠ ON DEMAND IS THE WHOLE DESIGN. `GET /tables` walks every table in the tenant and returns

   * their full field lists; hanging that off the grid's mount would put a workspace-wide read

   * behind every page view for a picker almost nobody opens. The column menu is the only surface

   * that needs it, so it is the surface that asks.

   * ⚠ The list is left standing once fetched β€” a database created in another tab mid-session is

   * a staleness a menu re-open corrects, and re-fetching per open would spend the same read

   * repeatedly for a list that changes about once a week.

   */
  const [linkTargets, setLinkTargets] = useState<LinkTarget[]>([]);
  useEffect(() => {
    // β›”β›” 2026-08-09 β€” `plusMenu` TOO, AND THAT OMISSION WAS THE WHOLE BUG. Owner: *"I am not
    // able to see Choose Column for Post rows link"*. There are TWO doors into this editor β€”
    // a column's own menu (`columnMenu`) and the "+" Add-field button (`plusMenu`) β€” and this
    // effect knew about one. Via "+", `linkTargets` stayed `[]`, so `target` never resolved and
    // the rollup Column picker held nothing but its placeholder, permanently. Editing an
    // EXISTING column worked, which is what made it look like a rollup bug rather than a fetch
    // that never fired. MEASURED on the live app: 5 selects rendered, "Column to roll up" with
    // exactly 1 option while `GET /tables` returns `ut_ig_posts` with 22 fields.
    // ⚠ A picker that is EMPTY and a picker whose data never loaded look identical, which is
    // why this survived: both render "Choose a column…" over nothing.
    if ((!columnMenu && !plusMenu) || linkTargets.length) return;
    let live = true;
    void fetchLinkTargets().then((t) => {
      if (live) setLinkTargets(t);
    });
    return () => {
      live = false;
    };
  }, [columnMenu, plusMenu, linkTargets.length]);
  /**

   * ⭐⭐ 2026-08-09 β€” the READ-THROUGH rollup's offer, fetched on the same terms as the link

   * targets above: only when the column menu opens, and once per session.

   *

   * ⚠ THE GUARD IS A SEPARATE `asked` FLAG, NOT `topics.length`. An empty offer is the CORRECT

   * and common answer (a tenant with nothing connected), so guarding on the length would re-ask

   * on every single menu open for exactly the workspaces where the answer can never change β€”

   * the one case the "fetch once" rule exists for.

   */
  const [rollupSourceOffer, setRollupSourceOffer] =
    useState<RollupSourceOffer>({ topics: [], windows: [] });
  const rollupOfferAsked = useRef(false);
  useEffect(() => {
    // β›” SAME TWO DOORS as the link targets above. This one is less visible because an empty
    // offer is the correct answer for a tenant with nothing connected β€” so a source offer that
    // never loaded is indistinguishable from one that is legitimately empty, and the mode switch
    // simply never appears. Fixing only the link half would have left that asymmetry in place.
    if ((!columnMenu && !plusMenu) || rollupOfferAsked.current) return;
    rollupOfferAsked.current = true;
    let live = true;
    void fetchRollupSources().then((o) => {
      if (live) setRollupSourceOffer(o);
    });
    return () => {
      live = false;
    };
  }, [columnMenu, plusMenu]);
  /**

   * ⭐ WAVE 27 Β· OWNER ITEM 22 β€” the values the ACTIVE VIEW forces on a new record.

   *

   * β›” THE DEFECT: "+" posted `{values: {}}` on every view, so a record added while a filter was

   * on was created, was real, and was invisible β€” the button read as broken and the row the user

   * then typed into did not exist as far as they could see. `filterSeed.ts` owns the derivation

   * and its whole design is how much it REFUSES to derive (negations, ranges, `or` branches,

   * contradictions, machine columns β€” each with its reason at the clause).

   *

   * ⚠ ONE FUNCTION, TWO CALLERS, deliberately: item 2's optimistic add must insert the row

   * carrying these same cells, or the row it paints locally fails the filter it was added under

   * and disappears on the next read β€” the exact blip C2 exists to prevent.

   */
  const seedValues = useCallback(
    () => filterSeedValues(config.filters, config.filterConj, fields, payload?.viewer),
    [config.filters, config.filterConj, fields, payload?.viewer]
  );
  /**

   * ⭐ WAVE 27 Β· OWNER ITEM 2 (contract C2) β€” the "+" paints its row NOW.

   *

   * β›” THE ID IS MINTED THE WAY THE SERVER MINTS IT β€” `max(numeric row id) + 1`, which is

   * `core.user_tables.add_row`'s own rule β€” and then POSTed as `{rid, values}` through the door

   * the undo path already opened (C-ADDROW). That is what makes the optimism honest rather than

   * hopeful: on the overwhelmingly common single-writer path the server stores exactly the id

   * this browser drew, so the row on screen and the row in the store are the same record from

   * the first frame.

   *

   * ⚠ AND WHEN THEY ARE NOT, IT RE-ANCHORS. Two people adding at once means the second POST

   * finds the id taken; `add_row` falls back to `max+1` and ANSWERS with what it actually wrote

   * (its own note says so), so the local row is re-keyed to the returned pid. Assuming the

   * requested id came back is the one way this could leave a row on screen that no longer

   * matches anything in the store.

   *

   * β›” NO `ROWS_STALE_EVENT` ON THE HAPPY PATH. That event re-reads the whole table, which is

   * the cost item 2 exists to remove β€” and re-reading would also un-paint the row for the

   * duration of the fetch, which is the NO-BLIP law's exact subject. The pending row is pruned

   * by the effect above when a payload that already contains it arrives, from whatever cause.

   *

   * ⚠ THE NARROW RACE, STATED: a cell PATCHed within the POST's round trip could reach the

   * server before the row exists. The window is now ~20ms (A moved the relation refresh off

   * this path), it needs a keystroke inside it, and the PATCH's failure is a rolled-back

   * overlay edit rather than lost data β€” the alternative, blocking the paint until the POST

   * resolves, is the defect being fixed.

   */
  const appendRow = useCallback(async (): Promise<undefined> => {
    if (!canMutateRecords) return undefined;
    const seeded = seedValues();
    const minted = mintRid();
    const optimistic: Row = { ...seeded, pid: minted };
    setPendingRows((cur) => [...cur, optimistic]);
    setNewRowPid(minted);
    const made = await addTableRow(scope, seeded, minted);
    if (!made) {
      // `addTableRow` already said WHY, in the server's own words (a row cap, a refused profile
      // cell, an unreachable host). The row is withdrawn rather than left standing: a row that
      // survives its own failed write is the lie this whole path has to avoid.
      setPendingRows((cur) => cur.filter((r) => r.pid !== minted));
      setNewRowPid(null);
      return undefined;
    }
    if (made.pid !== minted) {
      setPendingRows((cur) =>
        cur.map((r) => (r.pid === minted ? { ...r, pid: made.pid } : r))
      );
      setNewRowPid(made.pid);
    }
    // R4 β€” the append is undoable: Ctrl+Z deletes the row it just created, and a redo restores
    // it under the SAME rid (the server's `{rid}` passthrough, C-ADDROW).
    // β›” ITEM 22 MOVED THIS LINE. It read `values: {}` with a comment saying "an empty new record
    // carries no values" β€” true until this wave, and now false: a row added on a filtered view is
    // born holding the cells that filter forces. `redo` replays `r.values` verbatim
    // (`:1569`), so leaving the literal would have made Ctrl+Z β†’ Ctrl+Y restore the row under the
    // right id with its seeded cells silently dropped β€” [[undo-capture-before-the-write]] in its
    // quietest form, since the id and the row count would both be right.
    undoBook.current[scope] = pushUndo(stackFor(undoBook.current, scope), {
      kind: "rowAdd", table: scope, rows: [{ rid: made.rid, values: seeded }],
    });
    // β›” NO `signal(ROWS_STALE_EVENT)` HERE ANY MORE (item 2 / C2). It re-read the whole table
    // on every "+", which is the whole cost the owner reported β€” and every OTHER caller of it
    // still fires, so a row created by an automation, another tab or an undo still arrives.
    // The one thing that used to depend on this refetch was the cursor landing on the new row,
    // and the row is now on screen before the POST resolves, so it lands immediately.
    // `undefined` is returned rather than glide's "bottom": "bottom" is resolved against the
    // rows glide knew about when the gesture started, which is the row BEFORE this one.
    return undefined;
  }, [canMutateRecords, scope, seedValues, mintRid]);

  /* wave20 item 2 β€” measure key + window -> the columns that display it. Built ONCE per field

     list and handed to every consumer of "which column is this rule about", so the tint

     (`columnTones`, inside the hook above) and the column menu's filter doors resolve a

     measure condition the same way. See `types.ruleColumnKeys`. */
  const measureCols = useMemo(() => measureColumnIndex(fields), [fields]);

  // Airtable behavior: configuration changes to the active view autosave.
  useEffect(() => {
    if (!workspaceReady || embedded) return;
    const active = views.find((view) => view.id === activeViewId);
    if (!active || sameConfig(active.config, config)) {
      setSaveState("saved");
      return;
    }
    setSaveState("saving");
    if (saveTimer.current !== null) window.clearTimeout(saveTimer.current);
    saveTimer.current = window.setTimeout(() => {
      const updated = { ...active, config };
      setViews((current) =>
        current.map((view) => (view.id === updated.id ? updated : view))
      );
      viewWritesRef.current = stampTombstone(viewWritesRef.current, updated.id,
                                             Date.now());
      emitHostEvent({ id: eventId("view"), type: "view_upsert", view: updated });
      setSaveState("saved");
      saveTimer.current = null;
    }, 420);
    return () => {
      if (saveTimer.current !== null) window.clearTimeout(saveTimer.current);
    };
  }, [workspaceReady, activeViewId, config, views, embedded]);

  // Numeric dimensions force a glide relayout when either the component frame
  // or Streamlit's main column changes width (notably sidebar collapse).
  useLayoutEffect(() => {
    const element = gridBoxRef.current;
    if (!element) return;
    const measure = () => {
      const rect = element.getBoundingClientRect();
      if (rect.width > 0 && rect.height > 0) {
        setGridSize({
          width: Math.floor(rect.width),
          height: Math.floor(rect.height),
        });
      }
    };
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(element);
    window.addEventListener("resize", measure);
    return () => {
      observer.disconnect();
      window.removeEventListener("resize", measure);
    };
  }, [workspaceReady]);

  // CG-3: one mode per table, decided by whether the payload is a window. See types.ts
  // `TableMode` for why both engines running at once is the failure this prevents.
  const mode = tableMode(payload?.counts);
  const serverWindowed = mode === "server-windowed";
  // Owner items 4+6 β€” the Cohort page's grid renders without the Views sidebar.
  const hideViews = embedded || payload?.workspace?.hideViews === true;
  // Wave-6 item 10 β€” how this view displays. A WINDOWED table is always the grid: list/
  // calendar/kanban compute over the whole matched set, and one page is not it (CG-3's rule,
  // the same reason grouping is off there).
  const displaySpec = cleanDisplay(config.display);
  const displayMode: DisplayMode = serverWindowed ? "grid" : displaySpec?.mode ?? "grid";

  // ═══════════════════════════════════════════════════════════════════════════════════════
  // ⭐⭐ WAVE 30 Β· W30-T42 (contract C2) β€” PAGING A READ-THROUGH GRID.
  // ═══════════════════════════════════════════════════════════════════════════════════════
  //
  // The client engine is already refused in this mode (`useVisibleRows` passes rows straight
  // through), which is C2's "F may render no client-side predicate over a windowed grid". That
  // clause on its own would leave a filter chip INERT: the user narrows 32,826 orders, nothing
  // filters, and the count keeps reading 32,826 β€” honest about the scope and silent about the
  // question. So the predicate has to reach the evaluator that CAN answer it, which is SQL.
  //
  // β›” THE SAVED VIEW'S OWN OBJECTS GO ON THE WIRE, UNTRANSLATED (see `windowRowsPath`).
  const windowPredicate = useMemo(
    () => windowPredicateKey(config.filters, config.filterConj, config.sorts, search),
    [config.filters, config.filterConj, config.sorts, search]
  );
  const windowRequest = useCallback(
    (offset: number) => ({
      offset,
      limit: WINDOW_ROWS,
      filters: config.filters,
      filterConj: config.filterConj,
      sorts: config.sorts,
      search,
    }),
    [config.filters, config.filterConj, config.sorts, search]
  );
  const sentPredicate = useRef<string | null>(null);
  useEffect(() => {
    if (!serverWindowed) {
      sentPredicate.current = null;
      return;
    }
    if (sentPredicate.current === windowPredicate) return;
    // ⚠ THE FIRST WINDOW WENT OUT WITH NO QUERY ARGS AT ALL β€” `config` is this component's own
    // state, seeded from a workspace call that had not landed when the rows request left. So a
    // view carrying no filter, no sort and no search has ALREADY been answered, and firing here
    // would spend a round trip to receive the bytes on screen. Any other predicate is a real
    // question and goes out. One function owns both the key and the empty case, so "no
    // predicate" cannot be spelled two ways.
    if (sentPredicate.current === null && windowPredicate === EMPTY_WINDOW_PREDICATE) {
      sentPredicate.current = windowPredicate;
      return;
    }
    sentPredicate.current = windowPredicate;
    requestWindow(windowRequest(0));
  }, [serverWindowed, windowPredicate, windowRequest, requestWindow]);

  /**

   * The scroll β†’ next window. glide reports the visible RECTANGLE; `nextWindowOffset` decides.

   *

   * ⚠ `counts.shown` IS THE LOADED COUNT, not `rawRows.length`. They are the same number today

   * and would stop being one the moment anything layers a row in that the server did not send

   * (`pendingRows` does exactly that on editable tables) β€” and the offset this produces is a

   * promise to the server about where our contiguous run ends. It has to come from the merge

   * that built the run.

   */
  const onVisibleRegionChanged = useCallback(
    (range: Rectangle) => {
      if (!serverWindowed) return;
      const offset = nextWindowOffset({
        lastVisibleRow: range.y + range.height,
        loaded: payload?.counts?.shown ?? 0,
        matched: payload?.counts?.matched ?? 0,
        limit: WINDOW_ROWS,
      });
      if (offset !== null) requestWindow(windowRequest(offset));
    },
    [serverWindowed, payload?.counts?.shown, payload?.counts?.matched, requestWindow,
     windowRequest]
  );

  // CG-8 β€” measure conditions, answered by the host as `{ruleId: pid[]}`. Converted to Sets
  // once here rather than per row: the pipeline runs this over every row of the book.
  //
  // ⚠ REPLACED, not merged. Merging looks like the safer choice β€” "hold the previous result"
  // is the design β€” but it holds it FOREVER: the host omits a rule's id when it could not
  // resolve it (a warming store, a scope change mid-flight), and a merged map keeps yesterday's
  // answer under today's question with `pendingMeasures` reporting zero, so the marker never
  // shows. That is the widening sin wearing a confident count.
  //
  // Holding the previous result across a LOCAL edit does not need the merge and never did: the
  // memo is keyed on `payload.measureSets` identity, which does not change while the user is
  // typing, so the ref already carries the last answers through to the next payload. Merge and
  // replace therefore differ only in the dangerous case.
  const measures = useMemo(() => payload?.measures ?? [], [payload?.measures]);
  const measureSetsRef = useRef<MeasureSets>({});
  const measureSets = useMemo(() => {
    const incoming = payload?.measureSets;
    if (incoming) {
      const next: MeasureSets = {};
      for (const [ruleId, pids] of Object.entries(incoming)) next[ruleId] = new Set(pids);
      measureSetsRef.current = next;
    }
    return measureSetsRef.current;
  }, [payload?.measureSets]);
  const pendingMeasureCount = useMemo(
    () => pendingMeasures(config.filters, measureSets),
    [config.filters, measureSets]
  );
  // BUG-1 (wave 11) β€” the two key sets, published for the handshake. See the `.cg-shell`
  // attributes below for why they are DOM attributes and not console logs.
  const measureRuleKeys = useMemo(
    () => activeMeasureRuleIds(config.filters).join(","),
    [config.filters]
  );
  const measureSetKeys = useMemo(() => Object.keys(measureSets).join(","), [measureSets]);

  // Owner item 5. Cohort membership rides `workspace.lists`, the same array the "Add to list"
  // picker already reads, so the names offered and the sets tested come from one place. A
  // cohort with no `pids` is a target you can add to but cannot filter on; the engine treats it
  // as unanswerable (matches nothing) rather than absent (matches everything).
  const lists = useMemo(() => payload?.workspace?.lists ?? [], [payload?.workspace?.lists]);
  /* wave17 R1 / C-LOCKV β€” `railCohortId` is gone. It held the TRANSIENT lock the retired

     Cohorts section applied on click: a lock that lived in component state and was never

     persisted. A locked view now carries its own `config.cohortLock`, so SELECTING the view

     is the lock and the saved config is the only source. One mechanism, and it survives a

     reload β€” which the transient one never did. */
  const cohortSets = useMemo(() => {
    const out: CohortSets = {};
    for (const l of lists) if (l.pids) out[l.id] = new Set(l.pids);
    return out;
  }, [lists]);
  // The TENANT'S today. Never `new Date()`: a browser a day ahead of the server would resolve
  // "the past month" to a different month than the host summed, and the count would deny the
  // rows with nothing erroring.
  const today = payload?.today;
  // Wave-5 item 1 β€” who is looking (host-computed). ONE editability verdict for every edit
  // door (cells, pickers, drawer): types.mayEditField β€” stratum + read-only-by-nature +
  // permissions vs the viewer, fail-closed on restricted fields when the viewer is unknown.
  const viewer = payload?.viewer;
  const canEditField = useCallback(
    (f: Field): boolean => !embedded && recordsMutable && mayEditField(f, viewer),
    [embedded, recordsMutable, viewer]
  );
  const unresolvedCount = useMemo(
    () => unresolvedConditions(config.filters, { cohortSets, today }),
    [config.filters, cohortSets, today]
  );

  // Wave-5 items 9/11 β€” CLIENT-COMPUTED cells, injected AT their field keys so the whole
  // pipeline (filter/search/sort/group), the cells and the drawer read them like any other
  // value. Formulas parse ONCE per definition change (never per row); evaluation reads the
  // row WITH this session's overlay edits layered, so editing a referenced field recomputes
  // live. A formula that does not parse, or errors on a row, yields BLANK β€” never a wrong
  // number (formulaEngine.ts). `created_time` copies the row's `_created`.
  // 2026-07-31 (owner item 2): formulas may reference OTHER formulas now, so parse order is
  // TOPOLOGICAL (orderFormulas) β€” a formula runs after the formulas it reads, cycle members
  // never run (blank, never a stale number), and each row's results feed the next formula
  // through a per-row scope.
  const formulaAsts = useMemo(() => {
    const sources = new Map<string, string>();
    for (const f of fields) {
      if (f.type !== "formula") continue;
      const src = formulaOf(f);
      if (src) sources.set(f.key, src);
    }
    const { order, cyclic } = orderFormulas(sources);
    const out: { key: string; ast: FormulaAst }[] = [];
    for (const key of order) {
      if (cyclic.has(key)) continue;
      const p = parseFormula(sources.get(key)!);
      if (p.ok) out.push({ key, ast: p.ast });
    }
    return out;
  }, [fields]);
  const createdTimeKeys = useMemo(
    () => fields.filter((f) => f.type === "created_time").map((f) => f.key),
    [fields]
  );
  const computedRows = useMemo(() => {
    if (formulaAsts.length === 0 && createdTimeKeys.length === 0) return rawRows;
    const env = { today: payload?.today };
    return rawRows.map((r) => {
      const edits = overlayEdits[r.pid];
      const scope: Row = edits ? { ...r, ...edits } : { ...r };
      const out: Row = { ...r };
      for (const k of createdTimeKeys) {
        out[k] = (r._created as string | undefined) ?? null;
        scope[k] = out[k];
      }
      for (const { key, ast } of formulaAsts) {
        const v = evalFormula(ast, (k) => scope[k], env);
        out[key] = v;
        scope[key] = v; // later formulas read this one's result β€” the topo order above
      }
      return out;
    });
  }, [rawRows, overlayEdits, formulaAsts, createdTimeKeys, payload?.today]);

  // Wave-2 item 2c β€” COHORT MODE (the Cohort page). The host serves the WHOLE pool (rows +
  // derived values over the pool); the ACTIVE cohort scopes the table to its pids CLIENT-side.
  const cohortMode = payload?.workspace?.cohortMode === true;
  useEffect(() => {
    if (!cohortMode) return;
    if (activeCohortId && lists.some((l) => l.id === activeCohortId)) return;
    setActiveCohortId(lists[0]?.id ?? null);
  }, [cohortMode, lists, activeCohortId]);
  const activeCohort = cohortMode
    ? lists.find((l) => l.id === activeCohortId) ?? null
    : null;
  const cohortMemberSet = useMemo(
    () => new Set(activeCohort?.pids ?? []),
    [activeCohort]
  );
  // The FIXED subset is the scope. A cohort with no membership shows nothing β€” falling back to
  // the whole pool would put 1,500 rows under a rail entry that says 12, which is the widening
  // sin wearing a sidebar. Everything downstream (pipeline, counts, selection, detail) runs
  // over this scope, so the toolbar count is the cohort's matched count by construction.
  const scopedRows = useMemo(
    () =>
      cohortMode
        ? computedRows.filter((r) => cohortMemberSet.has(r.pid))
        : computedRows,
    [cohortMode, computedRows, cohortMemberSet]
  );

  const { visibleRows, pidToIndex } = useVisibleRows(
    scopedRows,
    fields,
    config.filters,
    search,
    config.sorts,
    // grouping a WINDOW would headline a page's count/subtotals as the group's
    serverWindowed ? null : config.groupBy,
    collapsed,
    config.memberPids,
    config.filterConj,
    serverWindowed,
    measureSets,
    cohortSets,
    today,
    // Item 12 (C-LOCK) β€” the 14th positional, RECORD's engine input. The lock intersects
    // FIRST, so everything downstream (conditions, memberPids, the ranking domain) operates
    // inside the cohort. Absent = today's behaviour exactly.
    // wave17 R1 / C-LOCKV: the view's SAVED lock is now the only source. A locked view is a
    // saved view whose `config.cohortLock` names its own id, so opening it IS applying the
    // lock β€” the wave-15 transient rail pick that used to outrank this is gone with its rail.
    config.cohortLock
  );

  // Owner item 8 β€” the DISPLAY cap. The pipeline above still ran over the whole book (counts,
  // "Add to list" and selection-by-pid all depend on that); only what glide PAINTS is sliced.
  // pidToIndex is rebuilt over the slice because every index consumer (selection, detail
  // navigation, hover) is positional against what is actually on screen.
  const [displayCap, setDisplayCap] = useState(DISPLAY_PAGE);
  /**

   * β›” W30-T42 β€” NO CLIENT CAP ON A WINDOWED TABLE, AND THE TWO CAPS WOULD HAVE FOUGHT.

   *

   * The display cap exists because the whole-book path holds every row and glide should not be

   * asked to lay out 33,000 of them at once. In `server-windowed` mode the WINDOW is already

   * that bound β€” one page of `WINDOW_ROWS` β€” so a second cap on top would stop the grid 50 rows

   * in, under a "Showing first 50 of 200" bar, while the toolbar says "showing 200 of 32,826".

   * Two truncation stories about one table, neither of them wrong, together a lie.

   *

   * β›” AND IT WOULD HAVE BROKEN THE PAGING OUTRIGHT: the scroll decision reads how far down the

   * LOADED rows the viewport reaches, and a capped grid can never scroll past the cap, so the

   * end of the window would be unreachable and the next window never requested.

   */
  const capped = !serverWindowed && visibleRows.length > displayCap;
  /**

   * ⭐⭐ WAVE-29 T33 (owner item 17) β€” THE TOTALS ROW, and the cap fix it forced.

   *

   * β›” THE SUMMARY IS OVER ALL M MATCHED ROWS, NEVER THE N PAINTED. The pipeline above already

   * ran over the whole book; only what glide paints is sliced. A total computed from the slice

   * would silently describe the first `DISPLAY_PAGE` records while sitting under a bar that says

   * "Showing first N of M" β€” an answer to a question nobody asked, wearing the right label.

   *

   * β›” AND THE SLICE ITSELF WAS ALREADY WRONG FOR GROUPS. `visibleRows` is FLATTENED (header,

   * rows, footer, header, …), so a straight `slice(0, cap)` could cut a group between its last

   * row and its footer β€” the subtotal simply vanished, for the groups furthest down, with no

   * marker of any kind. `sliceForDisplay` counts DATA rows toward the cap and keeps the

   * structural rows of every group it admits, so a group is whole or absent.

   */
  const totalsAggs = useMemo(
    () => computeAggs(
      visibleRows.flatMap((vr) => (vr.kind === "data" ? [vr.record] : [])),
      fields
    ),
    [visibleRows, fields]
  );
  /**

   * ⭐⭐ WAVE 30 Β· W30-T42 (contract C2 / the ticket's own named trap) β€” THE TOTALS ROW OVER A

   * WINDOW IS DISCLOSED, NOT DELETED.

   *

   * β›” THE TRAP. `totalsAggs` folds `visibleRows`, which in `server-windowed` mode is exactly the

   * rows this browser has loaded. Painted in the table's footer with no denominator, "the sum of

   * whatever happens to be in memory" wears the sum of 32,826 orders β€” a fabricated aggregate,

   * the thing [[no-unverifiable-aggregates]] exists to forbid. Grouping is refused in this mode

   * for the same reason (a group header over a window subtotals the PAGE while claiming to

   * describe the group), and that refusal stays: a group is a claim about a SET, and the client

   * cannot see the set.

   *

   * β›” BUT ABSENT IS NOT ONE OF THE TWO HONEST STATES. T42's done-when offers exactly two β€”

   * "reads from the server" or "says plainly that it covers the loaded window" β€” and the wire

   * carries no aggregates (`rows/total/totalUnfiltered/offset/limit/limits`), so the second one

   * is the one available. The fold is CORRECT for a question nobody asked; naming the question

   * is what makes it honest, and the loaded rows are on screen and scrollable, so the number

   * still drills to rows. The disclosure is `windowedFoldNote`, and it is bound to `showTotals`

   * by ONE memo below rather than by two conditions that could drift apart β€” a totals row over a

   * window with its sentence missing is the whole defect back again.

   */
  const showTotals = useMemo(
    () => !config.groupBy && Object.keys(totalsAggs).length > 0,
    [config.groupBy, totalsAggs]
  );
  /** The denominator sentence β€” non-null EXACTLY when a totals row is painted over a window that

   *  does not hold the whole matched set. Null on a whole-book table (the total is total) and on

   *  a window that happens to hold everything (`windowedFoldNote` refuses to invent a

   *  truncation that is not there). */
  const foldNote = useMemo(
    () =>
      serverWindowed && showTotals
        ? windowedFoldNote(payload?.counts?.shown ?? 0, payload?.counts?.matched ?? 0)
        : null,
    [serverWindowed, showTotals, payload?.counts?.shown, payload?.counts?.matched]
  );
  /** R6's SECOND SENTENCE, on the client side of the wire: the limits D's route DECLARED on this

   *  response. Received and painted nothing = the limit is silent again, one layer further out. */
  // ⭐ W32-T03: `counts` rides along so the clamped-window clause can say "Showing 5,000 of
  // 963,783 rows" rather than naming the server's own word for what was limited. Optional on the
  // callee, so the sentence degrades to its cause rather than to silence when a payload has none.
  const limitNote = useMemo(
    () => limitSummary(payload?.limits, payload?.counts),
    [payload?.limits, payload?.counts]
  );
  /**

   * β›” AND THE LIMIT NOBODY DECLARED, WHICH IS THE ONE A PERSON ACTUALLY NOTICES. Nine controls

   * this component gates on `serverWindowed` vanish the moment a grid becomes a window β€” export,

   * cohorts, folders, grouping, the four alternative views, select-from-file, alert badges β€” all

   * of which were working on this grid the day before, because the whole table used to be in the

   * browser. Every refusal is right on its own; a screen where eight buttons quietly disappear

   * is not. See `windowedCapabilityNote` for the list and why it is not a guess.

   */
  const capabilityNote = useMemo(
    () => (serverWindowed ? windowedCapabilityNote(payload?.counts?.matched ?? 0) : null),
    [serverWindowed, payload?.counts?.matched]
  );
  const displayRows = useMemo(() => {
    const shown = capped ? sliceForDisplay(visibleRows, displayCap) : visibleRows;
    // ⚠ APPENDED AFTER THE SLICE, so the cap can never eat the totals row itself β€” and it is the
    // LAST row, which is what `freezeTrailingRows={1}` pins.
    return showTotals
      ? [...shown,
         { kind: "group-footer" as const, groupKey: TOTAL_GROUP_KEY, aggs: totalsAggs }]
      : shown;
  }, [capped, visibleRows, displayCap, showTotals, totalsAggs]);
  const displayPidToIndex = useMemo(() => {
    if (!capped) return pidToIndex;
    const m = new Map<number, number>();
    displayRows.forEach((vr, i) => {
      if (vr.kind === "data" && !m.has(vr.record.pid)) m.set(vr.record.pid, i);
    });
    return m;
  }, [capped, displayRows, pidToIndex]);

  // C-AVATAR (wave-14 item 11) β€” profile photos, absent until HOST serves them. The tick is the
  // async half: `cells.setAvatarRepaint` fires it when an Image finishes decoding, and it is a
  // dep of `getCellContent`, which is the only thing glide watches. See useGetCellContent.
  const [avatarTick, setAvatarTick] = useState(0);
  useEffect(() => {
    setAvatarRepaint(() => setAvatarTick((t) => t + 1));
    return () => setAvatarRepaint(undefined);
  }, []);
  const userAvatars = payload?.workspace?.userAvatars;
  /**

   * Item 15 β€” the frozen strip's usable width, which is what a GROUP BAR's label is clipped to

   * now that the first column is pinned in every mode. `null` when nothing is grouped (no bar to

   * clip) β€” see `fitGroupLabel` for why the clip exists and why the count outranks the name.

   */
  const groupLabelSpace = useMemo(() => {
    if (!config.groupBy) return null;
    const n = Math.min(frozenCountOf(config), visibleCols.length);
    let px = 0;
    // `GridColumn` is a union β€” only its SIZED member declares `width`, and `useGridColumns`
    // always builds that one. Narrowed rather than asserted so an auto-sized column (which we
    // do not create) would read 0 and simply not be counted, instead of throwing in a memo.
    for (let i = 0; i < n; i += 1)
      px += (visibleCols[i] as { width?: number } | undefined)?.width ?? 0;
    return Math.max(0, px - GROUP_LABEL_PAD);
  }, [config, visibleCols]);
  /**

   * ⭐ owner item 2 (2026-08-03) β€” WHICH MEASURE COLUMNS ARE STILL BEING CALCULATED.

   *

   * A measure column's numbers are resolved by the server (one aggregate over the whole book)

   * and reach the browser on the workspace re-read that follows the create β€” seconds later.

   * In between, the column is on screen with nothing in it, which the owner correctly read as

   * an error rather than as a wait.

   *

   * β›” `editRequestId` IS THE TEST, and it is the honest one. It is set optimistically at the

   * moment the create is emitted and cleared by `reconcileFields` when the host's own copy of

   * that field comes back β€” and the host's copy travels in the SAME `/workspace` response as

   * `derived`, which is where the values are. So the flag is true across exactly the window

   * where the column exists and its numbers do not, and false the instant they land.

   *

   * The alternative β€” "no value anywhere in the column" β€” cannot tell a pending column from

   * one that permanently failed to resolve (a BU-scoped caller on a company-level measure,

   * say), and would spin forever on the second. This one resolves either way: when the echo

   * arrives with no values, the flag clears and the cells go honestly blank.

   */
  const pendingMeasureKeys = useMemo(() => {
    const out = new Set<string>();
    for (const f of fields)
      if (f.editRequestId && f.key.startsWith("measure_")) out.add(f.key);
    return out;
  }, [fields]);
  /**

   * The skeleton's pulse. A canvas cell cannot hold a CSS animation, so the motion is repaints:

   * this counter is a dependency of `getCellContent`, which is the only thing glide watches.

   *

   * ⚠ IT RUNS ONLY WHILE SOMETHING IS PENDING, and the effect's own guard is what stops it β€”

   * an interval left running would repaint the whole canvas ~7Γ—/s forever, on every grid, to

   * animate nothing. 140ms Γ— the 4-step ramp is a ~0.6s cycle: a wait, not a strobe.

   */
  const [pulse, setPulse] = useState(0);
  /**

   * β›” AND IT GIVES UP. A skeleton that never resolves is worse than the blank it replaced: a

   * blank cell is at least honest about having no number, while a permanent shimmer promises

   * one that is never coming.

   *

   * The window it guards is narrow but real. `editRequestId` clears when `reconcileFields` takes

   * the host's copy β€” and that function has a branch (`hostAuthoritative: false`, i.e. a payload

   * with no workspace) whose `{...local, ...host}` spread would PRESERVE the flag forever. Today

   * that branch cannot be reached with a measure column on screen (measures are offered through

   * the workspace, so a payload without one cannot have produced this field), which is an

   * argument about the current call graph and not a property of the code. This bound holds

   * whether or not the argument stays true, and it costs one boolean.

   */
  const [pendingGaveUp, setPendingGaveUp] = useState(false);
  useEffect(() => {
    setPendingGaveUp(false);
    if (pendingMeasureKeys.size === 0) return;
    let n = 0;
    const id = window.setInterval(() => {
      n += 1;
      if (n > PULSE_MAX_TICKS) {
        window.clearInterval(id);
        setPendingGaveUp(true);      // fall back to ordinary blank cells
        return;
      }
      setPulse((p) => p + 1);
    }, PULSE_MS);
    return () => window.clearInterval(id);
  }, [pendingMeasureKeys]);
  const activePendingKeys = pendingGaveUp ? NO_PENDING_KEYS : pendingMeasureKeys;
  const getCellContent = useGetCellContent(
    displayRows,
    visibleCols,
    fieldByKey,
    overlayEdits,
    canEditField,
    userAvatars,
    avatarTick,
    groupLabelSpace,
    measureGroupText,
    activePendingKeys,
    pulse
  );
  const { gridSelection, selectedPids, onGridSelectionChange, selectPids, togglePid,
          setActiveCell, clearSelection } =
    useGridSelection(
      displayRows,
      displayPidToIndex,
      visibleCols.length,
      embeddedSelectable ? embeddedSelectedIds : []
    );
  const embeddedSelectedKey = embeddedSelectedIds.join(",");
  const selectedPidKey = [...selectedPids].join(",");
  useEffect(() => {
    if (!embeddedSelectable) return;
    if (selectedPidKey !== embeddedSelectedKey)
      selectPids(embeddedSelectedIds as number[], "replace");
  }, [embeddedSelectable, embeddedSelectedKey, embeddedSelectedIds, selectedPidKey, selectPids]);
  useEffect(() => {
    if (!embeddedSelectable) return;
    onEmbeddedSelectionChange?.([...selectedPids]);
  }, [embeddedSelectable, onEmbeddedSelectionChange, selectedPids]);
  /* ════════════════════════ owner item 16 / R4 / C-UNDO ════════════════════════

     THE RECORDING LAYER. `undoStack.ts` owns the stack and every inverse; this owns the one

     thing it cannot: reading the value a cell held BEFORE the write, which only exists at the

     call site. Everything below funnels through `patchAndRecord` / `patchManyAndRecord`, so a

     write path that forgets to record is a write path that does not reach the store either.



     ⚠ A REF, NOT STATE. Nothing on screen depends on the stack in v1 (no undo button), so

     keeping it in state would repaint the grid on every keystroke of a paste for no pixels.

     Per SCOPE (a Ctrl+Z on the Customer grid must never rewrite a user table's cell) and per

     tab (nothing persists it β€” a stack restored into a session that did not make those edits

     would undo somebody else's work). */
  const undoBook = useRef<UndoBook>({});
  const applyingUndo = useRef(false);

  /** The value a cell holds RIGHT NOW: the overlay stratum wins over the payload row, exactly

   *  as `useGetCellContent` renders it β€” so what undo restores is what was on screen. */
  const rowByPid = useMemo(() => {
    const map = new Map<number, Row>();
    for (const r of rawRows) map.set(r.pid, r);
    return map;
  }, [rawRows]);
  const currentValue = useCallback(
    (pid: number, key: string): UndoValue => {
      const edited = overlayEdits[pid]?.[key];
      const raw = edited !== undefined ? edited : rowByPid.get(pid)?.[key];
      return raw == null ? null : (raw as UndoValue);
    },
    [overlayEdits, rowByPid]
  );

  const recordCells = useCallback(
    (changes: CellChange[], label: string) => {
      if (applyingUndo.current || changes.length === 0) return;
      undoBook.current[scope] = pushUndo(stackFor(undoBook.current, scope), {
        kind: "cells", label, changes,
      });
    },
    [scope]
  );

  /** ONE cell write, recorded. Every editor, picker and drag goes through this. */
  const patchAndRecord = useCallback(
    (pid: number, updates: Partial<Row>, label = "an edit") => {
      const changes: CellChange[] = Object.entries(updates).map(([key, value]) => ({
        pid, key,
        before: currentValue(pid, key),
        after: (value ?? null) as UndoValue,
      }));
      patchOverlay(pid, updates);
      recordCells(changes, label);
    },
    [currentValue, patchOverlay, recordCells]
  );

  /** MANY cells, ONE stack entry β€” a paste and a bulk clear are each one user action (R4). */
  const patchManyAndRecord = useCallback(
    (writes: { pid: number; updates: Partial<Row> }[], label: string) => {
      const changes: CellChange[] = [];
      for (const w of writes)
        for (const [key, value] of Object.entries(w.updates))
          changes.push({
            pid: w.pid, key,
            before: currentValue(w.pid, key),
            after: (value ?? null) as UndoValue,
          });
      for (const w of writes) patchOverlay(w.pid, w.updates);
      recordCells(changes, label);
    },
    [currentValue, patchOverlay, recordCells]
  );

  /**

   * Apply one stack entry in one direction. The INVERSE lives in `undoStack.directed` β€” this

   * only knows how to WRITE each op, and it writes through the same doors the user does

   * (`patchOverlay`, the rows endpoint), so an undone edit is persisted exactly like the edit

   * was. Nothing here is optimistic-only: a Ctrl+Z that reverted the screen and not the store

   * would come back on the next reload.

   */
  const applyEntry = useCallback(
    async (entry: UndoEntry, dir: "back" | "forward") => {
      const op = directed(entry, dir);
      if (op.kind === "cells") {
        const byPid = new Map<number, Partial<Row>>();
        for (const c of op.changes) {
          const at = byPid.get(c.pid) ?? {};
          at[c.key] = (c.after ?? "") as Row[string];
          byPid.set(c.pid, at);
        }
        applyingUndo.current = true;
        try {
          for (const [pid, updates] of byPid) patchOverlay(pid, updates);
        } finally {
          applyingUndo.current = false;
        }
      } else if (op.kind === "rowAdd") {
        // Restore under the OLD id where the store still has it free; the server answers with
        // what it actually wrote and the re-read is what puts the rows back on screen.
        //
        // ⚠ SEQUENTIAL, not `Promise.all`. `add_row` picks `max(id)+1` when the requested id is
        // taken, and it reads the store to do it β€” firing ten restores concurrently is ten
        // readers racing one counter, which is how two rows end up sharing an id.
        let any = false;
        let moved = 0;
        for (const r of op.rows) {
          const made = await addTableRow(op.table, r.values as Record<string, unknown>, r.rid);
          any = any || !!made;                   // a refusal already said why, in the server's words
          // ⚠ THE ID IS PART OF WHAT IS BEING UNDONE, and `add_row` falls back to `max(id)+1`
          // when the one it was asked for is no longer free β€” which happens if anything created
          // a row in the gap. The restore is still the right thing to do, but it is no longer
          // the SAME record to anything that named the old id (a cohort, a comment, a filter),
          // and a redo would then look for an id that is not there. Said out loud rather than
          // discovered later.
          if (made && String(made.rid) !== String(r.rid)) moved += 1;
        }
        if (!any) return;
        if (moved)
          signal(
            TOAST_EVENT,
            `${moved} restored record${moved === 1 ? "" : "s"} came back under a new id β€” ` +
              `something had taken the original while it was gone.`
          );
        signal(ROWS_STALE_EVENT);
      } else if (op.kind === "rowDelete") {
        let any = false;
        for (const r of op.rows) any = (await deleteTableRow(op.table, r.rid)) || any;
        if (!any) return;
        // ⭐ ITEM 2 β€” the row may still be one of THIS browser's pending copies (add, then
        // Ctrl+Z). A deleted row never reappears in a payload, so the prune effect can never
        // absorb it and it would sit on screen looking undeleted. See `withdrawPending`.
        withdrawPending(op.rows.map((r) => r.rid));
        signal(ROWS_STALE_EVENT);
      } else if (op.kind === "choiceRename") {
        // Item 15 β€” the inverse mapping. The host rewrites the values and the saved views that
        // name them, exactly as it did on the way out; `directed` already turned the pairs
        // around, so this emits what it is given.
        emitHostEvent({
          id: eventId("choicerename"),
          type: "choice_rename",
          key: op.fieldKey,
          renames: op.renames,
        });
      }
      signal(TOAST_EVENT, describe(entry, dir));
    },
    [patchOverlay, withdrawPending]
  );

  /**

   * Ctrl+Z / Ctrl+Shift+Z (and Ctrl+Y, which is the same request on Windows).

   *

   * ⚠ ON `window`, IN CAPTURE, and it steps aside for real text fields. The grid is a canvas β€”

   * glide's key handling only fires while the canvas has focus, so a Ctrl+Z after clicking the

   * toolbar would do nothing, which is exactly the "sometimes it works" the owner would report

   * next. But an <input> with a cursor in it has its OWN undo that belongs to the browser, and

   * stealing that would be worse than not having ours: the search box, the rename field and

   * glide's own cell editor are all inputs, so `activeElement` decides.

   *

   * Nothing to undo says so out loud rather than silently ignoring the key β€” an undo that

   * appears to do nothing is indistinguishable from one that is broken.

   */
  useEffect(() => {
    const onKey = (event: KeyboardEvent) => {
      if (!(event.ctrlKey || event.metaKey) || event.altKey) return;
      const key = event.key.toLowerCase();
      if (key !== "z" && key !== "y") return;
      const el = document.activeElement as HTMLElement | null;
      if (el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable))
        return;
      const forward = key === "y" || event.shiftKey;
      event.preventDefault();
      const book = undoBook.current;
      const state = stackFor(book, scope);
      const { state: next, entry } = forward ? popRedo(state) : popUndo(state);
      if (!entry) {
        signal(TOAST_EVENT, forward ? "Nothing to redo." : "Nothing to undo.");
        return;
      }
      book[scope] = next;
      void applyEntry(entry, forward ? "forward" : "back");
    };
    window.addEventListener("keydown", onKey, true);
    return () => window.removeEventListener("keydown", onKey, true);
  }, [scope, applyEntry]);


  /**

   * R4 β€” **BULK BACKSPACE/DELETE IS ONE ACTION.** glide's own delete walks the selection and

   * calls `onCellEdited` per cell, which would put forty entries on the stack for one keypress;

   * returning `false` takes the whole operation over so it lands as one.

   *

   * ⚠ PRESETS ARE NEVER ATTEMPTED (the contract says so, and it is also the only honest

   * behaviour): `canEditField` is the same verdict the editor and the paste path use, so a

   * selection spanning read-only columns clears the editable ones and leaves the rest exactly

   * as they were β€” rather than firing writes the server will refuse one by one.

   */
  /**

   * ⭐ 2026-08-06 (owner) β€” DELETE RECORDS, with Ctrl+Z.

   *

   * Owner, verbatim: *"I should always be able to delete records that I created myself manually

   * (not from automation), because right now it only shows 'Add to cohort'… make sure I can use

   * 'Delete/Backspace' to delete the record and use Ctrl Z if i want to undo."*

   *

   * Everything under this was already built and had no door: `DELETE /tables/{key}/rows/{rid}`,

   * `deleteTableRow`, and `undoStack`'s `rowDelete` β€” whose inverse (`rowAdd` under the SAME rid)

   * is exactly "put it back". The only missing piece was something that calls them.

   *

   * β›” THE VALUES ARE CAPTURED BEFORE THE DELETE, and this is the line the whole feature rests on.

   * `deleteTableRow` answers a boolean; it does not hand the row back. Push the undo entry after

   * the round trip and there is nothing left to read, so Ctrl+Z would faithfully restore an EMPTY

   * row under the right id β€” a silent data loss wearing the costume of a working undo.

   *

   * ⚠ ONE ENTRY FOR THE WHOLE GESTURE (R4's "bulk Backspace = ONE grouped stack entry"), which is

   * why `UndoEntry` carries a row LIST now. Ten rows deleted must be one Ctrl+Z, not ten.

   *

   * ⚠ NO CONFIRM DIALOG, deliberately. The owner named Ctrl+Z as the safety net in the same

   * sentence as the delete; a modal on top of a working undo is friction that teaches people to

   * dismiss modals.

   */
  const deleteRecords = useCallback(
    async (pids: number[]): Promise<boolean> => {
      if (!canMutateRecords || !pids.length) return false;
      // The row as it stands NOW, straight off the rendered records β€” the same values the
      // reader can see, so a restore puts back what they watched disappear.
      const byPid = new Map<number, Row>();
      for (const vr of displayRows)
        if (vr.kind === "data") byPid.set(vr.record.pid, vr.record);
      const captured: UndoRow[] = [];
      /*

       * β›” A SKIPPED ROW IS COUNTED AND NAMED, never dropped quietly ([[no-unverifiable-aggregates]]).

       * `displayRows` is FILTERED and CAPPED, and the selection is not: Select-from-file matches

       * on a value and can tick pids the current view does not render β€” `fileSelect` has a whole

       * bucket for exactly that ("not in this view"). Capturing only what is on screen and

       * `continue`ing past the rest would delete two rows and report three, which is the silent-cap

       * defect in the one place it is least forgivable.

       *

       * REFUSED WHOLE rather than partially applied: a delete that half-happened leaves the reader

       * reconciling a count against a table, and the fix (scroll or clear the filter, then select

       * again) is one sentence away.

       */
      const offscreen: number[] = [];
      for (const pid of pids) {
        const rec = byPid.get(pid);
        if (!rec) {
          offscreen.push(pid);
          continue;
        }
        const values: Record<string, UndoValue> = {};
        for (const f of fields) {
          const v = rec[f.key];
          if (v !== undefined && v !== null && v !== "")
            values[f.key] = v as UndoValue;
        }
        captured.push({ rid: pid, values });
      }
      if (offscreen.length) {
        signal(
          TOAST_EVENT,
          `Nothing was deleted β€” ${offscreen.length} of the ${pids.length} selected ` +
            `record${pids.length === 1 ? " is" : "s are"} not shown in this view. Clear the ` +
            `filter (or scroll them into view) and select again.`
        );
        return false;
      }
      if (!captured.length) return false;

      /*

       * ⭐ WARN THEN ALLOW (owner ruling, 2026-08-06) β€” the arm fires ONLY where something is

       * actually at stake, so deleting your own scratch rows stays one keypress.

       *

       * β›” THE PREDICATE IS "WHAT WOULD BE LOST", NOT "WHO CREATED THIS". There is no stored

       * creator on a row, and deriving one from a stage column would flip meaning as the

       * automation runs. But the question the warning answers is a different and answerable one:

       * *has an automation written to this row* β€” because that is exactly what a re-find cannot

       * give back. MEASURED in `run_discover_instagram`: the seen-before test reads the rows

       * CURRENTLY IN THE TABLE, so a deleted candidate returns as NEW β€” `found_count` back to 1,

       * `first_found` re-stamped, and its stage reset to Review. Deleting a candidate somebody

       * had already judged throws that judgement away.

       *

       * ⚠ This paragraph used to name a "Declined" stage. WAVE 26 / R6 DELETED THE BOARD'S

       * BUILT-IN TERMINALS β€” the lanes are whatever the user defined now β€” so the warning names

       * the mechanism (the stage resets to Review) and no longer a stage that does not ship.

       */
      /**

       * ⭐⭐ WAVE-29 T23 (owner item 2b) β€” **THE QUESTION IS AUTHORSHIP, AND IT HAS AN ANSWER.**

       *

       * The note above this used to argue there is no stored creator on a row, so the warning

       * asked "has a machine written here" instead. There IS one: `automation_engine` stamps

       * `created_by` ("Found by") on every candidate row it discovers, and `add_row` stamps

       * nothing β€” so the two authors are distinguishable, and `machineFoundRows` (types.ts) is

       * that distinction. Everything the old predicate got wrong followed from asking the

       * answerable-but-different question: every preset column is machine-tagged, a hand-added

       * row is born holding materialised rollups, and the STAGE cell a human drives was

       * force-included β€” so pressing "+" and then Delete produced a loud warning about losing

       * an automation's work on a row the person had just made themselves.

       *

       * ⚠ The wave-27 note that lived here (`stageField` survives the stage deletion, so a

       * legacy stage column stays read-only) is about the READ-ONLY readers β€” `isMachineWritten`

       * / `mayEditField` in types.ts, which are untouched. It never described this predicate; the

       * risk test is the one place where including the stage column is the defect rather than the

       * protection.

       *

       * β›” AND THE SENTENCE IS BUILT FROM THE COLUMNS THIS TABLE HAS. It used to name first-found,

       * times-found and a stage reset unconditionally while all three live in `CANDIDATE_FIELDS`

       * β€” so on a user-named IG Profile database it named the loss of three columns that are not

       * there. `reFindConsequences` reads the field list.

       */
      const riskyIds = new Set(machineFoundRows(fields, captured));
      const risky = captured.filter((r) => riskyIds.has(r.rid));
      const sig = captured.map((r) => r.rid).join(",");
      if (risky.length && delArmed !== sig) {
        setDelArmed(sig);
        const losses = reFindConsequences(fields);
        const one = risky.length === 1;
        signal(
          TOAST_EVENT,
          `${risky.length} of these ${one ? "records was" : "records were"} FOUND by an ` +
            `automation. Deleting ${one ? "it" : "them"} is not undone by a re-find` +
            (losses.length
              ? `: ${losses.join(", ")} β€” so a card somebody had already moved on comes back ` +
                `undecided`
              : ` β€” ${one ? "it" : "they"} would come back as a new record with no history`) +
            `. Press Delete again (or click again) to confirm.`
        );
        return false;
      }
      setDelArmed("");
      // SEQUENTIAL, matching the restore path: the store is one document and ten concurrent
      // read-modify-writes against it is how a delete silently misses a row.
      const gone: UndoRow[] = [];
      for (const r of captured)
        if (await deleteTableRow(scope, r.rid)) gone.push(r);
      if (!gone.length) {
        signal(TOAST_EVENT, "Nothing was deleted β€” the server refused.");
        return false;
      }
      undoBook.current[scope] = pushUndo(stackFor(undoBook.current, scope), {
        kind: "rowDelete", table: scope, rows: gone,
      });
      // ⭐ ITEM 2 β€” same reason as the undo path: a row added and then deleted in one session
      // is still a PENDING copy here, and no future payload will ever prune it.
      withdrawPending(gone.map((r) => r.rid));
      clearSelection();
      signal(ROWS_STALE_EVENT);
      // ⚠ THE CONSEQUENCE IS NAMED IN FULL, and the first version of this sentence undersold it.
      // It said only that a matching record "will return", which is true and reassuring and
      // leaves out the part that actually costs something.
      //
      // MEASURED in `run_discover_instagram`: the seen-before test is built from the rows
      // CURRENTLY IN THE TABLE (`seen` comes from `existing2`). A deleted profile is therefore
      // not "seen again" on the next run β€” it is NEW. `found_count` resets to 1, `first_found`
      // is re-stamped, and the stage goes back to Review, because a new candidate's card starts
      // at the human gate. So deleting a candidate somebody had already moved out of Review puts
      // it back there undecided β€” the human judgement is the thing the re-find cannot give back.
      // (W26/R6 deleted the board's built-in terminals, so there is no named stage to cite here.)
      //
      // (The follower SNAPSHOT history is safe either way β€” it lives in the platform master keyed
      // by handle, a different store, which only `purge_handle` touches.)
      // Same survival, same reason as `machineKeys` above (item 12 / R3, B's ASK ->C): the flag
      // is no longer WRITTEN, and a table that has not been migrated yet still carries it.
      const fedByAutomation = fields.some((f) => f.automation?.stageField);
      signal(
        TOAST_EVENT,
        `Deleted ${gone.length} record${gone.length === 1 ? "" : "s"}. Ctrl+Z to undo.` +
          (fedByAutomation
            ? " If this automation finds one again it comes back as a NEW candidate β€” first-found" +
              " and times-found reset, and its stage back to Review. Undo keeps all of that."
            : "")
      );
      return true;
    },
    [canMutateRecords, displayRows, fields, scope, clearSelection, delArmed,
     withdrawPending]
  );

  const onGridDelete = useCallback(
    (sel: GridSelection): boolean => {
      /*

       * ⭐ 2026-08-06 (owner) β€” A ROW SELECTION + Delete/Backspace DELETES THE RECORDS.

       *

       * Checking rows and pressing Delete used to CLEAR every editable cell in them, which on the

       * owner's Instagram table now clears nothing at all: every column but one is machine-written

       * and refuses the write. So the key appeared to do nothing, which is what they reported.

       *

       * ⚠ ROWS ONLY, AND ONLY WHEN NO **MULTI-CELL** RANGE IS DRAWN. Checking rows is an explicit

       * gesture about RECORDS; DRAGGING a range is a gesture about CELLS, and a Delete that

       * destroyed records because some rows happened to be checked would feel unrecoverable even

       * with an undo behind it. When both are present, the narrower reading (clear the cells) wins.

       *

       * β›” A SINGLE ACTIVE CELL IS NOT A RANGE, and the first version of this got it wrong.

       * `sel.current.range` is ALWAYS set when a cell is merely focused β€” a 1Γ—1 rect β€” so

       * `!sel.current?.range` meant the feature worked only if you had never clicked a cell.

       * Caught by driving it live rather than by the gate: click a cell, then check a row, then

       * press Delete, and the key silently went back to clearing cells. The gesture the rule is

       * actually about is a DRAG, which is width or height greater than one.

       */
      const dragged = !!sel.current
        && (sel.current.range.width > 1 || sel.current.range.height > 1);
      if (canMutateRecords && sel.rows.length > 0 && !dragged) {
        const pids: number[] = [];
        for (const rowIndex of sel.rows) {
          const vr = displayRows[rowIndex];
          if (vr && vr.kind === "data") pids.push(vr.record.pid);
        }
        // β›” `true`, NOT `false`, WHEN THIS BRANCH DOES NOT DO THE WORK β€” the scar the comment at
        // the bottom of this handler already records, pointed at a second case. `false` cancels
        // glide's own delete, so bailing with it would leave Delete doing nothing at all on a
        // selection this branch declined. `deleteRecords` is async and the keypress cannot wait
        // for it, so the branch commits here and reports the outcome through its own toast.
        if (!pids.length) return true;
        void deleteRecords(pids);
        return false;
      }
      const byPid = new Map<number, Partial<Row>>();
      const clear = (rowIndex: number, colIndex: number) => {
        const vr = displayRows[rowIndex];
        if (!vr || vr.kind !== "data") return;
        const column = visibleCols[colIndex];
        const field = column ? fieldByKey.get(column.id!) : undefined;
        if (!field || !canEditField(field)) return;
        const at = byPid.get(vr.record.pid) ?? {};
        at[field.key] = "";
        byPid.set(vr.record.pid, at);
      };
      for (const rowIndex of sel.rows)
        for (let c = 0; c < visibleCols.length; c++) clear(rowIndex, c);
      const range = sel.current?.range;
      if (range)
        for (let y = range.y; y < range.y + range.height; y++)
          for (let x = range.x; x < range.x + range.width; x++) clear(y, x);
      const writes = [...byPid.entries()].map(([pid, updates]) => ({ pid, updates }));
      if (!writes.length) return true;
      patchManyAndRecord(writes, "clearing cells");
      // ⚠ `false` ONLY WHEN THIS ACTUALLY DID THE WORK. Returning it unconditionally cancels
      // glide's own delete for cases this handler does not cover β€” a COLUMN selection, which
      // glide deletes from `toDelete.columns` and the loops above never look at β€” so Delete
      // would silently clear nothing. Handing the keypress back when there is nothing to
      // group is strictly safer than swallowing it: the per-cell path still refuses read-only
      // fields (`onCellEdited`'s own `canEditField`), it just does not arrive as one entry.
      return false;
    },
    [canMutateRecords, deleteRecords, displayRows, visibleCols, fieldByKey, canEditField,
     patchManyAndRecord]
  );

  /**

   * Owner item 4 / C-ADDROW β€” the cursor FOLLOWS the appended row, once it exists.

   *

   * The append is a server round trip, so at click time there is nothing to focus; this waits

   * for the re-read to bring the pid back and then lands the active cell on its first column,

   * scrolled into view. `newRowPid` is cleared either way β€” a row the re-read never produced

   * (a refused write, a filter that excludes it) must not leave a cursor waiting forever.

   */
  useEffect(() => {
    if (newRowPid === null) return;
    const index = displayPidToIndex.get(newRowPid);
    if (index === undefined) return;
    setActiveCell(0, index);
    gridRef.current?.scrollTo(0, index, "vertical", 0, 0, { vAlign: "center" });
    setNewRowPid(null);
  }, [newRowPid, displayPidToIndex, setActiveCell]);

  /** Owner item 23 β€” the fields in the view's column order, for the Hide-fields panel. Built

   *  from `order` (already reconciled by useGridColumns) rather than from `config.order` so the

   *  panel and the grid can never disagree about which fields exist or where they sit. */
  const orderedFields = useMemo(
    () => order.map((key) => fieldByKey.get(key)).filter((f): f is Field => !!f),
    [order, fieldByKey]
  );
  /** Owner item 17 β€” the row of the ACTIVE cell, i.e. what the last click highlighted. Read off

   *  `gridSelection` rather than tracked separately so keyboard navigation moves the wash too;

   *  `useGridSelection` already guards this index against a grid that shrank this render. */
  const activeRow = gridSelection.current?.cell[1];

  const statusValues = useMemo(() => {
    const map: Record<string, string[]> = {};
    for (const field of fields) {
      // A `user`'s people come from the HOST, never from the rows β€” an assignee nobody has been
      // given yet is still assignable.
      if (field.type === "user") {
        map[field.key] = payload?.userOptions ?? [];
        continue;
      }
      // ⭐ Owner item 24 β€” every other choice column goes through ONE rule (`choiceVocabulary`):
      // the DECLARED list when the field has one, the values seen in the data when it does not.
      // This used to branch on the type, which sent `stock_bucket` β€” a `select` whose vocabulary
      // is computed server-side and declares no `options` β€” down the declared path to an empty
      // list, and an empty supplied list WINS in the filter panel. See the function's own note;
      // it is pure so the gate can run it, which nothing inside this file can be.
      if (field.type === "select" || field.type === "multiselect" || field.type === "status")
        map[field.key] = choiceVocabulary(field, rawRows);
    }
    return map;
  }, [fields, rawRows, payload?.userOptions]);

  const rowPx = ROW_PX[config.rowHeightMode];
  // DISTINCT customers, not painted data rows. Grouping a MULTI field (Cohorts) puts the same
  // customer under every group it belongs to, so counting rows would report more records than
  // there are customers β€” a number nobody could reconcile against the book. `pidToIndex` is
  // first-wins per pid, so its size IS the distinct count, and it equals the row count for every
  // non-multi grouping and for no grouping at all.
  //
  // ⚠ The FULL pipeline's map, never the display slice's: the toolbar count must state what the
  // view MATCHES. What is painted is the "Showing first N" bar's job (owner item 8).
  const recordCount = pidToIndex.size;
  const shownRecords = displayPidToIndex.size;
  /* wave17 GRID β€” item 2 / owner R5. The whole-table row band is GONE, and with it the

     `bandTone` / `bandMask` pair that used to sit here: the winning control's tone, and the

     alternating-row mask built from the DATA-ROW ORDINAL so group headers could not flip the

     stripe at a boundary. What follows is now three row states, not four.

     β›” wave-29 R8 (2026-08-11) β€” R5 also kept an involved-COLUMN cell wash; that is now gone too,

     so `COLUMN_TONE_THEME` carries HEADER keys only. This callback and `cells.AUTOMATION_TINT`

     are therefore the ONLY writers of a body `bgCell` on this canvas: a sorted or filtered column

     can no longer layer anything over a status wash, which is exactly what R8 asked for. */
  const getRowThemeOverride = useCallback(
    (row: number): Partial<Theme> | undefined => {
      const visibleRow = displayRows[row];
      if (!visibleRow || visibleRow.kind !== "data") return undefined;
      // Owner item 17 β€” the row holding the ACTIVE cell stays washed after the pointer moves
      // on. Ordered AFTER hover on purpose: the pointer is the more immediate signal, and a
      // hovered-and-active row reading as merely active would make hover look broken.
      if (row === hoverRow) {
        if (!config.colorBy) return HOVER_NEUTRAL;
        return (
          HOVER_ROW_THEME[String(visibleRow.record[config.colorBy] ?? "").toLowerCase()] ??
          HOVER_NEUTRAL
        );
      }
      // A colour-by wash already marks this row with meaning the user chose; overlaying the
      // active tint on top would blend two hues into a third that means neither. There, glide's
      // accent ring is the active marker and this stays out of the way.
      if (!config.colorBy) {
        if (row === activeRow) return ACTIVE_ROW_NEUTRAL;
        return undefined;
      }
      return STATUS_ROW_THEME[
        String(visibleRow.record[config.colorBy] ?? "").toLowerCase()
      ];
    },
    [displayRows, config.colorBy, hoverRow, activeRow]
  );
  const onItemHovered = useCallback(
    (args: GridMouseEventArgs) => {
      const row = args.kind === "cell" ? args.location[1] : undefined;
      setHoverRow((previous) => (previous === row ? previous : row));
      // Owner item 19 β€” the hover-only Expand. Placed from glide's OWN bounds for the primary
      // cell of this row, so freeze, horizontal scroll and row-height mode are handled by the
      // component that owns them rather than re-derived here.
      //
      // ⚠ Only ever CLEARED from here for a different row, never for "the pointer left the
      // canvas". Moving the pointer ONTO the button leaves the canvas, so clearing on
      // out-of-bounds would unmount the control between the mouse arriving and the click
      // landing β€” an affordance that vanishes exactly when you reach for it, and one that
      // every assertion still sees because it exists in every state except the one that
      // matters. `.cg-grid-box`'s own onMouseLeave is what dismisses it.
      const vrow = row !== undefined ? displayRows[row] : undefined;
      if (args.kind === "cell" && vrow?.kind === "data" && row !== undefined) {
        const pid = vrow.record.pid;
        const b = gridRef.current?.getBounds(0, row);
        // Clamped to the grid's own box. ⚠ RETARGETED wave-14 item 15: this used to say "with a
        // grouping active `freezeColumns` is 0, so the primary column scrolls away". It no
        // longer does β€” the first column is now frozen in EVERY mode. The clamp stays because
        // its other half is still live: glide's bounds are VIEWPORT coordinates, so a row
        // scrolled under the header or past the bottom still reports a rect outside the grid,
        // and a `position: fixed` button with no clamp would paint over the chrome on a row
        // nobody can see. The horizontal legs are now defence in depth (a column drag, a box
        // narrower than the frozen strip) rather than the everyday case.
        const at = b
          ? expandButtonRect(b, gridBoxRef.current?.getBoundingClientRect())
          : null;
        // Recomputed EVERY move, not memoised on the pid: a scroll can leave the pointer over
        // the same record at a new y, and a button that keeps the pid but not the position
        // floats over the wrong row. Referential stability is preserved by comparing values,
        // which is the cheap half β€” `getBounds` is arithmetic over glide's own layout.
        setExpandAt((prev) =>
          !at
            ? null
            : prev && prev.pid === pid && prev.x === at.x && prev.y === at.y
              ? prev
              : { pid, x: at.x, y: at.y, size: at.size }
        );
      }
      // Wave-5 item 6 β€” hovering a header whose field carries a description floats the text
      // under the header. The tip element is pointer-events:none and aria-hidden: it can
      // NEVER become the click target, which is the tooltip trap this page has already paid
      // for once ([[ui-invisible-to-assertions]]).
      if (args.kind === "header") {
        const colDef = visibleCols[args.location[0]];
        const field = colDef ? fieldByKey.get(colDef.id!) : undefined;
        const note = field ? field.note || field.description : undefined;
        // Owner item 16 β€” a title the fit SHORTENED must still be readable somewhere, and the
        // tip is where. `colDef.title !== field.label` IS the truncation test: `fitHeaderTitle`
        // returns the label by identity when it fits, so this asks the renderer what it did
        // rather than re-running the measurement and hoping the two agree.
        const cut = !!field && !!colDef && colDef.title !== field.label;
        const text = cut && field ? (note ? `${field.label} β€” ${note}` : field.label) : note;
        const bounds = args.bounds;
        if (text && bounds) {
          setHeaderTip((prev) =>
            prev && prev.text === text && prev.x === bounds.x
              ? prev
              : { text, x: bounds.x, y: bounds.y + bounds.height + 4 }
          );
          return;
        }
      }
      setHeaderTip((prev) => (prev === null ? prev : null));

      // I2 β€” the cell half. Only text that is genuinely CUT OFF gets a tip: a tooltip on
      // every cell just repeats what is already legible and covers the row under it.
      // Truncation is MEASURED with glide's own font rather than guessed from a character
      // count, which is what makes "e.g. a Note" work and a short currency cell stay quiet.
      if (args.kind === "cell" && row !== undefined) {
        const vr = displayRows[row];
        const cellCol = visibleCols[args.location[0]];
        // Group headers and footers carry no cell text of their own β€” a tip over the group
        // bar would repeat the label glide has already drawn across it.
        if (vr?.kind === "data" && cellCol) {
          const field = fieldByKey.get(cellCol.id!);
          const text = field ? formatDisplay(field, vr.record[field.key]) : "";
          const bounds = args.bounds;
          const tip = bounds ? cellTipText(text, measureCellText(text), bounds.width) : null;
          if (tip && bounds) {
            const x = tipLeft(bounds.x, window.innerWidth, measureCellText(tip) + 20);
            const y = bounds.y + bounds.height + 4;
            setCellTip((prev) =>
              prev && prev.text === tip && prev.x === x && prev.y === y
                ? prev
                : { text: tip, x, y }
            );
            return;
          }
        }
      }
      setCellTip((prev) => (prev === null ? prev : null));
    },
    [visibleCols, fieldByKey, displayRows]
  );
  const rowHeight = useMemo(
    () =>
      config.groupBy
        ? (row: number) => (displayRows[row]?.kind === "group-header" ? 32 : rowPx)
        : rowPx,
    [config.groupBy, rowPx, displayRows]
  );

  /* ═══ W18-B VOID ═══ (wave 18, owner item 1b) β€” WHERE THE TABLE ENDS, in canvas pixels.

     Consumed by the two `.cg-grid-void` rectangles at the DataEditor mount; see the CSS region

     of the same name for why the void is painted in the DOM rather than in the glide theme.



     ⭐ THE PROPERTY THAT MAKES THIS ARITHMETIC AND NOT SCROLL-TRACKING, and the reason there is

     no `onVisibleRegionChanged` handler anywhere near it: **a void can only exist in an axis the

     content does not overflow.** glide's scroll extent is EXACTLY the content β€” `scrollWidth =

     nonGrowWidth (+ overscrollX)`, `scrollHeight = header + rows (+ overscrollY)`, and we pass

     neither overscroll prop (scrolling-data-grid.js:12-24) β€” so at maximum scroll the last

     row/column lands flush on the client edge. Wherever there is something to paint, the scroll

     offset in that axis is 0 and cannot become anything else. The rectangles therefore depend on

     the columns, the rows and the box, and on nothing that moves while the user drags.



     Every column carries an explicit `width` (`useGridColumns` sets `config.widths[key] ??

     DEFAULT_WIDTH`) and none carries `grow`, so glide's column sizer passes them through

     untouched and this sum is the width it actually lays out. */
  const gridVoid = useMemo(() => {
    const gutter = scrollbarGutter();
    let colsPx = rowMarkerPx(displayRows.length);
    for (const c of visibleCols) colsPx += (c as { width?: number }).width ?? 0;
    let rowsPx = HEADER_PX;
    if (typeof rowHeight === "number") rowsPx += displayRows.length * rowHeight;
    else for (let i = 0; i < displayRows.length; i++) rowsPx += rowHeight(i);
    // ⚠ Owner item 4 β€” THE GHOST ROW IS PART OF THE TABLE, and this line is what makes it
    // visible. glide draws its trailing row AFTER the last data row, but `displayRows` (our
    // rows) does not contain it, so the void started exactly where the ghost row does and
    // painted flat #F6F8FC straight over it. The "+" was still clickable the whole time
    // (`.cg-grid-void` is `pointer-events: none`), which is the worst version of this bug:
    // the gate went green on an affordance nobody could see. Found by READING THE SCREENSHOT
    // ([[ui-invisible-to-assertions]], [[finalize-visual-review-sop]]).
    if (canMutateRecords)
      rowsPx += typeof rowHeight === "number" ? rowHeight : rowHeight(displayRows.length);

    /* Fit is tested against the client box the OTHER axis's scrollbar leaves behind β€” the same

       `clientWidth`/`clientHeight` glide's own scroll handler reads (infinite-scroller.js:

       110-116), so this branch and glide's cannot disagree about whether a bar is there. The

       two `if`s resolve the circularity in the only direction it can run: a bar in one axis can

       CREATE one in the other, but two bars can never un-create each other. */
    let vBar = rowsPx > gridSize.height;
    let hBar = colsPx > gridSize.width;
    if (vBar && !hBar) hBar = colsPx > gridSize.width - gutter;
    if (hBar && !vBar) vBar = rowsPx > gridSize.height - gutter;
    const clientW = gridSize.width - (vBar ? gutter : 0);
    const clientH = gridSize.height - (hBar ? gutter : 0);

    /* `null` = the content reaches that edge, so there is no void and no rectangle. The

       comparison is strict: a table ending exactly on the edge has nothing past it. */
    return {
      clientW,
      clientH,
      below: rowsPx < clientH ? rowsPx : null,
      right: colsPx < clientW ? colsPx : null,
    };
  }, [visibleCols, displayRows, rowHeight, gridSize, canMutateRecords]);
  /* ═══ end W18-B VOID (geometry) ═══ */

  // The record drawer resolves positions against what the MODE paints: the display slice for
  // grid/list (the cap is real there), the FULL pipeline for calendar/kanban/map (a month, a
  // stack or a pin reaches past the cap by design β€” a drawer that refused those pids would
  // close itself on a card the user can plainly see).
  // ⭐ WAVE-27 item 8 (C3) β€” `swipe` belongs here for calendar/kanban/map's own reason: the deck
  // is derived from `modeDataRows` (the FULL pipeline), so a card past the display cap is one
  // the user can plainly see, and a drawer that refused its pid would close itself on open.
  const fullSetMode =
    displayMode === "calendar" || displayMode === "kanban" || displayMode === "map" ||
    displayMode === "swipe";
  const detailRows = fullSetMode ? visibleRows : displayRows;
  const detailIdxMap = fullSetMode ? pidToIndex : displayPidToIndex;
  const detailIndex = detailPid !== null ? detailIdxMap.get(detailPid) : undefined;
  useEffect(() => {
    if (detailPid !== null && detailIndex === undefined) setDetailPid(null);
  }, [detailPid, detailIndex]);
  const detailRecord = useMemo<Row | null>(() => {
    if (detailIndex === undefined) return null;
    const row = detailRows[detailIndex];
    if (!row || row.kind !== "data") return null;
    return overlayEdits[row.record.pid]
      ? { ...row.record, ...overlayEdits[row.record.pid] }
      : row.record;
  }, [detailIndex, detailRows, overlayEdits]);
  const dataPosition = useMemo(() => {
    if (detailIndex === undefined) return 0;
    return detailRows
      .slice(0, detailIndex + 1)
      .filter((row) => row.kind === "data").length;
  }, [detailIndex, detailRows]);
  const neighborExists = useCallback(
    (delta: -1 | 1) => {
      if (detailIndex === undefined) return false;
      for (
        let index = detailIndex + delta;
        index >= 0 && index < detailRows.length;
        index += delta
      )
        if (detailRows[index]?.kind === "data") return true;
      return false;
    },
    [detailIndex, detailRows]
  );
  const go = useCallback(
    (delta: -1 | 1) => {
      if (detailIndex === undefined) return;
      for (
        let index = detailIndex + delta;
        index >= 0 && index < detailRows.length;
        index += delta
      ) {
        const row = detailRows[index];
        if (row?.kind !== "data") continue;
        setDetailPid(row.record.pid);
        if (displayMode === "grid")
          gridRef.current?.scrollTo(0, index, "vertical", 0, 0, { vAlign: "center" });
        return;
      }
    },
    [detailIndex, detailRows, displayMode]
  );

  /**

   * Wave-9 I3 β€” the description "(i)", drawn RIGHT-ALIGNED and vertically centred with the

   * field name.

   *

   * ⚠ This is the header-draw alternative, taken because glide's `overlayIcon` PROVABLY

   * cannot do it: `drawHeaderInner` paints an overlay at a hard-coded `drawX + 9` /

   * `(height - 18) / 2 + 6` β€” a badge on the bottom-right corner of the TYPE mark at the far

   * LEFT of the header β€” and no prop moves it. `drawHeader` is glide's supported escape

   * hatch: it hands over the ctx, the rect, the menu bounds and the sprite manager, plus a

   * `drawContent()` that runs its own rendering first. So glide still draws the header it

   * always drew (type mark, title, menu); only the (i) is ours, and `overlayIcon` is no

   * longer set on any column.

   *

   * The geometry is `infoMarkRect()` in overlayPlacement.ts, so "right-aligned and centred"

   * is asserted numerically by a gate rather than judged from one screenshot at one width.

   */
  const drawGridHeader = useCallback<DrawHeaderCallback>(
    (args, drawContent) => {
      const field = args.column.id ? fieldByKey.get(args.column.id) : undefined;
      // ⚠⚠ WAVE-14 ITEM 2 β€” THE ONE LINE THAT MAKES AN INVOLVED HEADER BOLD, and it is not a
      // font setting anywhere near where you would look for one.
      //
      // glide's `drawGridHeaders` does, verbatim:
      //     if (theme !== outerTheme) ctx.font = theme.baseFontFull;   // :38-40
      // i.e. the moment a column carries ANY `themeOverride` its header title is painted in the
      // CELL font ("13px") instead of the header font ("600 13px"). That is why the owner's
      // filtered/sorted/grouped headers had already lost their weight β€” nothing in our code
      // asked for it, and setting `headerFontStyle` on the involved theme alone would have
      // changed precisely nothing, because glide never reads it on that path. Re-asserting the
      // MERGED theme's header font on the ctx here is what puts it back, for every column,
      // uniformly: on a column with no override this is a no-op (glide set the same value at
      // :21), and glide's own save/restore around each column stops it leaking to the next.
      //
      // Built from `headerFontStyle` + `fontFamily` rather than reading `headerFontFull`,
      // which is real at runtime but is declared on `FullTheme`, not the public `Theme` the
      // callback is typed with β€” same string, no cast, and it is exactly how
      // `mergeAndRealizeTheme` composes it.
      //
      // Bonus fix, worth knowing: `drawHeaderInner` passes `theme.headerFontFull` to
      // `getMiddleCenterBias`, which measures with the CURRENT ctx font but CACHES under the
      // string it was handed. Before this line, an overridden column measured its baseline bias
      // in the 13px font and filed it under the "600 13px" key, so whichever column drew first
      // decided the vertical centring for all of them.
      args.ctx.font = `${args.theme.headerFontStyle} ${args.theme.fontFamily}`;
      drawContent();
      if (!field) return;
      const hasInfo = !!(field.note || field.description);
      // ⭐ OWNER ITEM 4 (2026-08-06): *"why is the Field still have the Dot at the header to
      // mark its a custom editable field?"* Because the predicate was `source === "overlay"`
      // alone β€” true of columns a person added BESIDE the Odoo ones, and true of literally
      // every column in a `ut_*` database, including the ones an automation spawns and fills.
      // So on the owner's Instagram table the dot marked all 23 columns as "yours", which is
      // both meaningless (it never varies) and wrong (they are not yours to edit).
      const isCustom = field.source === "overlay" && !isMachineOwned(field);
      // ONE layout for both marks, from the same `headerMarkSizes` order `useGridColumns` used
      // to reserve the label's room β€” so the number of marks drawn and the number reserved for
      // cannot disagree. null = the column is too narrow to carry them without covering its own
      // label, and then NOTHING is drawn (all-or-nothing; see headerMarkLayout).
      const marks = headerMarkLayout(
        args.rect,
        args.menuBounds.width,
        headerMarkSizes(hasInfo, isCustom)
      );
      if (!marks) return;
      let slot = 0;
      if (hasInfo) {
        const at = marks[slot++];
        args.spriteManager.drawSprite(
          "aiosInfo",
          "normal",
          args.ctx,
          at.x,
          at.y,
          at.size,
          args.theme
        );
      }
      if (isCustom) {
        // Wave-14 item 1 / R11 β€” the user-created-field marker that REPLACES the yellow header
        // wash. A muted dot: quiet enough to ignore while reading, present enough to answer
        // "which of these columns are mine?" at a glance. Never a background β€” the owner killed
        // the wash, and a paler wash would have been the same answer in a lower voice.
        const at = marks[slot++];
        const ctx = args.ctx;
        ctx.save();
        ctx.beginPath();
        ctx.arc(at.x + at.size / 2, at.y + at.size / 2, at.size / 2, 0, Math.PI * 2);
        ctx.fillStyle = CUSTOM_FIELD_MARK;
        ctx.fill();
        ctx.restore();
      }
    },
    [fieldByKey]
  );

  const onCellClicked = useCallback(
    (cell: Item, event: CellClickedEventArgs) => {
      const row = displayRows[cell[1]];
      if (!row) return;
      // Owner item 10: clicking into the cells is "I am working now" β€” the frame folds its
      // navigation rail to the slim strip (a no-op in the embed; the shell listens).
      signal(NAV_MINIMIZE_EVENT);
      if (row.kind === "group-header") {
        event.preventDefault();
        setCollapsed((current) => {
          const next = new Set(current);
          if (next.has(row.groupKey)) next.delete(row.groupKey);
          else next.add(row.groupKey);
          return next;
        });
        return;
      }
      const column = visibleCols[cell[0]];
      const field = column ? fieldByKey.get(column.id!) : undefined;
      // A picked field (select / assignee) opens its choices where the cell is. It cannot use
      // glide's text overlay β€” a free-text editor on a constrained column is how you end up
      // with "Done", "done" and "DONE" as three different values β€” and glide's own dropdown
      // cell lives in a package we have deliberately not added, so this reuses the same
      // AnchoredOverlay the column and view menus already use. Wave-5: a RATING cell rides
      // the same picker surface (its choices are 1..max stars); both doors respect the
      // permissions verdict.
      if (row.kind === "data" && field && canEditField(field)
          && (isPickType(field.type) || field.type === "rating")) {
        event.preventDefault();
        // Item 6 (2026-07-31) β€” the click also LANDS the active cell here (preventDefault
        // stops glide from committing it), so pick β†’ Enter walks on down the column exactly
        // like a typed edit does.
        setActiveCell(cell[0], cell[1]);
        const b = event.bounds;
        setPicker({
          pid: row.record.pid,
          fieldKey: field.key,
          anchor: {
            left: b.x, top: b.y, right: b.x + b.width, bottom: b.y + b.height,
            width: b.width, height: b.height,
          },
        });
        return;
      }
      // A linked-record cell is a doorway to the target database, not an opaque id list.
      // The large modal mounts the same Grid surface over exactly these pids, so its standard
      // search, Filters, Sort, Fields, and column menus keep working for every database kind.
      if (row.kind === "data" && field?.type === "link" && field.link?.table) {
        if (field.link.table.startsWith("ut_")) {
          event.preventDefault();
          setActiveCell(cell[0], cell[1]);
          setLinkAt({ pid: row.record.pid, fieldKey: field.key });
          return;
        }
      }
      // ⭐ Wave-23 C7 β€” a JSON cell opens the big viewer. It is the ONLY door: the cell carries
      // `allowOverlay:false`, because glide's overlay is a one-line box and one keystroke in the
      // wrong place inside a 32 KB document turns a well-formed payload into an unparseable one,
      // saved. Opened for EVERY reader (a document you may not edit is still one you must be
      // able to read) β€” the viewer takes `onSave` only when the permission verdict allows it,
      // and the host's write wall is the real one either way.
      if (row.kind === "data" && field?.type === "json") {
        event.preventDefault();
        setActiveCell(cell[0], cell[1]);
        setJsonAt({ pid: row.record.pid, fieldKey: field.key });
        return;
      }
      // Wave-5 item 11 β€” a URL cell opens its link on click (scheme-guarded: http/https only,
      // a bare domain gets https://). Editing stays with glide's overlay (Enter/double-click).
      if (row.kind === "data" && field?.type === "url") {
        const raw = String(
          overlayEdits[row.record.pid]?.[field.key] ?? row.record[field.key] ?? ""
        ).trim();
        if (raw) {
          const href = /^https?:\/\//i.test(raw)
            ? raw
            : /^[\w-]+(\.[\w-]+)+/.test(raw)
              ? `https://${raw}`
              : null;
          if (href) {
            event.preventDefault();
            window.open(href, "_blank", "noopener");
            return;
          }
        }
      }
      // Owner item 6 (2026-07-31) β€” CLICKING THE CUSTOMER TICKS THE CHECKBOX. The row marker
      // is a ~32px strip; the identity cell is the widest, most natural target on the row, so
      // a click there toggles the same pid-anchored set the markers write ("more surface area
      // to select individual customers into a Cohort"). No preventDefault: glide still commits
      // the cell highlight below, so reading across the row keeps working.
      if (row.kind === "data" && field && field.key === lockedKey) {
        togglePid(row.record.pid);
      }
      // Owner item 17 β€” A SINGLE CLICK HIGHLIGHTS. It used to open the record panel from here,
      // which meant a user could not select a cell, read across a row, or copy a value without
      // a drawer landing over the table. The highlight is glide's own doing: this handler
      // returns without `preventDefault`, so the click commits `gridSelection.current`, the
      // accent ring lands on the cell and `getRowThemeOverride` washes the row
      // (ACTIVE_ROW_NEUTRAL). Nothing is drawn here.
      //
      // ⚠ SHIPPED WITH ITEM 19, never alone. Deleting this line is what removes the ONLY way to
      // open a record; the hover Expand button below is its replacement, and half of this
      // change is a table whose records cannot be opened at all.
    },
    [displayRows, visibleCols, fieldByKey, canEditField, overlayEdits, lockedKey, togglePid,
     setActiveCell]
  );
  /**

   * Double-click / Enter. KEPT as a door to the record on purpose (owner item 17 names the

   * SINGLE click, and it is the single click that was in the way).

   *

   * Removing it too would leave the record reachable only by pointer β€” the hover affordance

   * cannot be reached from the keyboard at all β€” so a keyboard user would lose the panel

   * outright. glide routes Enter on an EDITABLE cell to its overlay editor before this fires,

   * so the two doors do not collide: this is the activation path for the read-only columns,

   * which is most of the table.

   */
  const onCellActivated = useCallback(
    (cell: Item) => {
      const row = displayRows[cell[1]];
      const column = visibleCols[cell[0]];
      const field = column ? fieldByKey.get(column.id!) : undefined;
      if (row?.kind === "data" && field?.source !== "overlay")
        setDetailPid(row.record.pid);
    },
    [displayRows, visibleCols, fieldByKey]
  );
  const onCellEdited = useCallback(
    (cell: Item, value: EditableGridCell) => {
      const row = displayRows[cell[1]];
      const column = visibleCols[cell[0]];
      const field = column ? fieldByKey.get(column.id!) : undefined;
      if (!row || row.kind !== "data" || !field || !canEditField(field)) return;
      // Wave-5 item 11 β€” a checkbox toggles straight through glide's BooleanCell (no overlay
      // editor); the overlay store keeps its '1'-or-empty contract.
      if (value.kind === GridCellKind.Boolean && field.type === "checkbox") {
        patchAndRecord(row.record.pid, { [field.key]: value.data ? "1" : "" }, "a tick");
        return;
      }
      if (value.kind === GridCellKind.Uri) {
        patchAndRecord(row.record.pid, { [field.key]: value.data ?? "" }, "an edit");
        return;
      }
      if (value.kind === GridCellKind.Text || value.kind === GridCellKind.Number) {
        patchAndRecord(row.record.pid, { [field.key]: value.data }, "an edit");
      }
    },
    [displayRows, visibleCols, fieldByKey, patchAndRecord, canEditField]
  );
  const validateCell = useCallback(
    (cell: Item): boolean => {
      const row = displayRows[cell[1]];
      const column = visibleCols[cell[0]];
      const field = column ? fieldByKey.get(column.id!) : undefined;
      // ONE verdict (types.mayEditField): stratum + read-only-by-nature + permissions. The
      // picked types and rating never take glide's text overlay β€” their pickers are the door.
      return (
        !!row &&
        row.kind === "data" &&
        !!field &&
        canEditField(field) &&
        !isPickType(field.type) &&
        field.type !== "rating" &&
        field.type !== "status"
      );
    },
    [displayRows, visibleCols, fieldByKey, canEditField]
  );
  const onGridPaste = useCallback(
    (target: Item, values: readonly (readonly string[])[]): boolean => {
      const column = visibleCols[target[0]];
      const field = column ? fieldByKey.get(column.id!) : undefined;
      if (!field) return false;
      // ⭐ Wave-15 item 3 (R8) β€” THE SELECTION DECIDES HOW FAR THE PASTE REACHES. Until now the
      // targets were walked down from the anchor for exactly `values.length` rows, so a
      // fifty-row selection and a one-cell clipboard wrote ONE row: the selection was painted
      // and obeyed by nothing. `pasteRowCount` is the whole rule and it is pure, so the gate
      // can drive it β€” this handler cannot be reached by any node test in the repo.
      const rowCount = pasteRowCount(values.length, gridSelection.current?.range,
                                     { col: target[0], row: target[1] });
      const targetPids = Array.from({ length: rowCount }, (_, offset) => {
        const row = displayRows[target[1] + offset];
        return row?.kind === "data" ? row.record.pid : null;
      });
      const patches = planFieldPaste({
        field,
        sourceFieldKey: copyProvenanceRef.current.fieldKey,
        editable: canEditField(field),
        values,
        targetPids,
        allowedChoices: statusValues[field.key] ?? choiceOptions(field),
      });
      if (!patches) return false;
      // R4 β€” ONE stack entry for the whole paste. Cell by cell would put forty entries on the
      // stack for one Ctrl+V, and undoing a paste one cell at a time is not undoing a paste.
      patchManyAndRecord(
        patches.map((patch) => ({ pid: patch.pid, updates: { [field.key]: patch.value } })),
        "a paste"
      );
      // We handled the write ourselves. Returning false tells glide not to run its cell
      // renderers' generic paste path (Bubble/rating renderers cannot enforce this contract).
      return false;
    },
    [visibleCols, fieldByKey, canEditField, statusValues, displayRows, patchManyAndRecord,
     gridSelection.current]
  );

  const openHeaderMenu = useCallback(
    (column: number, bounds: Rectangle) => {
      if (embedded) return;
      const definition = visibleCols[column];
      if (!definition?.id) return;
      setColumnMenu({
        fieldKey: definition.id,
        anchor: {
          left: bounds.x,
          top: bounds.y,
          right: bounds.x + bounds.width,
          bottom: bounds.y + bounds.height,
          width: bounds.width,
          height: bounds.height,
        },
      });
    },
    [embedded, visibleCols]
  );
  const onHeaderClicked = useCallback(
    (column: number, event: HeaderClickedEventArgs) => {
      if (event.isEdge) return;
      event.preventDefault();
      openHeaderMenu(column, event.bounds);
    },
    [openHeaderMenu]
  );
  const onGridKeyDown = useCallback(
    (event: GridKeyEventArgs) => {
      if (
        event.key.toLowerCase() === "c" &&
        (event.ctrlKey || event.metaKey) &&
        !event.altKey
      ) {
        const range = gridSelection.current?.range;
        const source = range?.width === 1 ? visibleCols[range.x] : undefined;
        copyProvenanceRef.current = markGridCopy(source?.id ?? null, Date.now());
        // Do not prevent default: glide still owns serialization and the OS clipboard write.
        return;
      }
      // Owner item 5 (2026-07-31) β€” EXCEL-GRADE ENTER. When no editor is open (an open overlay
      // editor swallows its own keys before the canvas sees them), Enter moves the active cell
      // DOWN one record and Shift+Enter moves UP β€” never opening the record drawer, which is
      // what made keyboard runs down a column "really clunky". Glide's own overlay editor
      // already commits-and-moves-down on Enter, so typing β†’ Enter β†’ typing flows like Excel;
      // this handles the BETWEEN-edits half. Group headers are skipped in the direction of
      // travel. The drawer stays reachable by double-click and the hover Expand button.
      if (event.key === "Enter" && !event.ctrlKey && !event.metaKey && !event.altKey) {
        const cur = gridSelection.current?.cell;
        if (cur) {
          event.preventDefault();
          event.stopPropagation();
          event.cancel();
          // Owner item 6 (2026-07-31) β€” Enter on a PICKED cell (select / multi select /
          // assignee / rating) opens its picker: the keyboard door the mouse click already
          // had. glide's text overlay cannot serve these types (validateCell refuses them),
          // so without this the keyboard run down a column dead-ends at every picked field.
          // Shift+Enter stays pure navigation, so walking UP past picked cells still works.
          const curRow = displayRows[cur[1]];
          const curColumn = visibleCols[cur[0]];
          const curField = curColumn ? fieldByKey.get(curColumn.id!) : undefined;
          if (
            !event.shiftKey &&
            curRow?.kind === "data" &&
            curField &&
            canEditField(curField) &&
            (isPickType(curField.type) || curField.type === "rating")
          ) {
            const b = gridRef.current?.getBounds(cur[0], cur[1]);
            if (b) {
              setPicker({
                pid: curRow.record.pid,
                fieldKey: curField.key,
                anchor: {
                  left: b.x, top: b.y, right: b.x + b.width, bottom: b.y + b.height,
                  width: b.width, height: b.height,
                },
              });
              return;
            }
          }
          const dir = event.shiftKey ? -1 : 1;
          let row = cur[1] + dir;
          while (row >= 0 && row < displayRows.length && displayRows[row]?.kind !== "data")
            row += dir;
          if (row >= 0 && row < displayRows.length) {
            setActiveCell(cur[0], row);
            gridRef.current?.scrollTo(cur[0], row, "vertical", 0, 0);
          }
          return;
        }
      }
      const contextMenu =
        event.key === "ContextMenu" || (event.key === "F10" && event.shiftKey);
      // DataEditor exposes public controlled selection without the row marker,
      // while GridKeyEventArgs.location comes from its internal grid and still
      // includes that marker at column zero.
      const eventColumn =
        event.location && event.location[0] > 0
          ? event.location[0] - 1
          : undefined;
      const column = gridSelection.current?.cell[0] ?? eventColumn;
      if (!contextMenu || column === undefined || !event.bounds) return;
      const gridBounds = gridBoxRef.current?.getBoundingClientRect();
      const headerTop = gridBounds?.top ?? event.bounds.y;
      event.preventDefault();
      event.stopPropagation();
      event.cancel();
      openHeaderMenu(column, {
        x: event.bounds.x,
        y: headerTop,
        width: event.bounds.width,
        height: 36,
      });
    },
    [gridSelection.current, openHeaderMenu, displayRows, setActiveCell,
     visibleCols, fieldByKey, canEditField]
  );

  const persistView = useCallback((view: SavedView) => {
    setViews((current) => {
      const found = current.some((item) => item.id === view.id);
      return found
        ? current.map((item) => (item.id === view.id ? view : item))
        : [...current, view];
    });
    emitHostEvent({ id: eventId("view"), type: "view_upsert", view });
  }, []);

  /**

   * Item 12 (C-LOCK) β€” set or clear a view's cohort lock, from the rail's menu.

   *

   * Works on ANY view, not only the active one, which is why it goes through `persistView`

   * rather than `updateConfig`: the rail's menu opens on whichever row you clicked. When the

   * target IS the active view, the live `config` must move too, or the table keeps showing the

   * old row set until the next select and the lock reads as ignored.

   *

   * Clearing DELETES the key rather than storing null β€” the no-churn rule every other optional

   * config member follows, and the shape `_clean_display`'s sibling validator expects.

   */
  const onViewCohortLock = useCallback(
    (viewId: string, cohortId: string | null) => {
      const target = views.find((v) => v.id === viewId);
      if (!target) return;
      const nextConfig = { ...target.config };
      if (cohortId) nextConfig.cohortLock = cohortId;
      else delete (nextConfig as Record<string, unknown>).cohortLock;
      persistView({ ...target, config: nextConfig });
      if (viewId === activeViewId) {
        setConfig((live) => {
          const next = { ...live };
          if (cohortId) next.cohortLock = cohortId;
          else delete (next as Record<string, unknown>).cohortLock;
          return next;
        });
      }
    },
    [views, activeViewId, persistView]
  );

  const selectView = useCallback(
    (id: string) => {
      const current = views.find((view) => view.id === activeViewId);
      if (current && !sameConfig(current.config, config))
        persistView({ ...current, config });
      const next = views.find((view) => view.id === id);
      if (!next) return;
      setActiveViewId(id);
      setConfig(normalizeConfig(next.config, fields));
      setCollapsed(new Set());
      setSearch("");
      setDetailPid(null);
      setDisplayCap(DISPLAY_PAGE);
      // Owner item 3 (2026-07-31): tell the host WHERE THE USER IS, so a fresh browser (no
      // localStorage copy) resumes on this view instead of the system default. Presentation
      // state β€” the host stores the id and the read side re-validates it.
      emitHostEvent({ id: eventId("view"), type: "view_select", viewId: id });
      // Owner item 10: opening a view is "I am working now" β€” the frame folds its nav rail.
      signal(NAV_MINIMIZE_EVENT);
    },
    [views, activeViewId, config, persistView, fields]
  );

  /**

   * A-S4-3 (item 25) β€” a notification's click-through. The SHELL routes to the table and fires

   * this; the GRID owns view selection, so neither learns the other's state.

   *

   * β›” IGNORE, NEVER THROW, when the view is not ours: an alert can outlive the view it watches

   * (deleted, or a share revoked), and a reader who can no longer see it must simply land on the

   * table. `selectView` already returns early on an unknown id; the topic check stops one grid

   * reacting to another's alert when both are mounted.

   */
  useEffect(() => {
    const onOpen = (e: Event) => {
      const detail = (e as CustomEvent<ViewOpenDetail>).detail;
      if (!detail || detail.topic !== scope) return;
      if (!views.some((v) => v.id === detail.viewId)) return;
      selectView(detail.viewId);
    };
    window.addEventListener(VIEW_OPEN_EVENT, onOpen);
    return () => window.removeEventListener(VIEW_OPEN_EVENT, onOpen);
  }, [scope, views, selectView]);
  const createView = useCallback(
    (name: string, mode: DisplayMode, permissions: ViewPermissions) => {
      const acceptedName = uniqueDisplayName(name, views.map((view) => view.name));
      /**

       * ⭐⭐ WAVE 27 Β· OWNER ITEM 9 / RULING R4 β€” **A NEW VIEW IS BLANK. ALL OF IT.**

       *

       * β›” THIS REVERSES THE WAVE-26 COMMENT THAT STOOD HERE, so the reversal is stated rather

       * than quietly applied. That comment dropped `cohortLock` from the spread and defended

       * keeping the rest: *"their inheritance is a FEATURE (build a view, branch off it)

       * precisely because it is visible"*. The owner disagrees, in as many words β€” R4:

       * **"New views ALWAYS start blank β€” no filters/sorts inherited from anything."** The

       * branch-off use it defended gets its own door later (Duplicate view); it is not what the

       * "+" button means, and the wave-26 fix was the right diagnosis of the wrong scope β€” one

       * member of the spread was invisible, but ALL of them arrived unasked.

       *

       * β›” AND `defaultViewConfig` IS THE BLANK, not a literal assembled here. It is the same

       * function the grid's own initial state and the cohort door already use, so "blank" has

       * ONE definition in this file ([[one-evaluator-per-question]]); a second literal beside it

       * would be a place for the two to disagree the day a `ViewConfig` member is added β€” and

       * the one that got added last wave is exactly what caused this bug.

       *

       * WHAT STOPS CARRYING, enumerated because a reader deserves the list and not just the

       * ruling: `filters` + `filterConj`, `sorts`, `groupBy`, `colorBy`, `rowHeightMode`,

       * `order`/`visible` (hidden columns), `widths`, `memberPids`, `frozenCount` and

       * `cohortLock`. `order`/`visible` come back from the FIELD list's own default visibility,

       * which is why `fields` replaces `config` in the dependency list below.

       *

       * ⚠ THE DISPLAY REFS GO TOO, and that is the one deliberate loss. W13's carry rule kept

       * the calendar's date field / kanban's stack field / map's lat-lon across a mode switch so

       * Grid→Map→Grid→Map did not re-ask; a NEW view is not a mode switch, and inheriting the

       * previous view's stack field is inheritance of exactly the kind R4 names. A ref-less

       * kanban asks which field to stack by, which is the honest state for a view born empty.

       * `cleanDisplay` still collapses a ref-less GRID to absent, so picking "Grid" produces the

       * byte-identical shape every pre-wave-9 view has (no churn).

       */
      const nextConfig: ViewConfig = {
        ...defaultViewConfig(fields),
        display: cleanDisplay({ mode }),
      };
      const view: SavedView = {
        id: nextViewId(),
        name: acceptedName,
        kind: "custom",
        config: nextConfig,
        // I17 (C4) β€” sent EXPLICITLY. Absent on create means 'personal' host-side, so a user
        // who chose "Collaborative" would silently get the opposite. `createdBy` is NOT sent:
        // the host stamps it and ignores whatever the browser claims.
        permissions,
      };
      persistView(view);
      setActiveViewId(view.id);
      // The LIVE config has to move too, not just the stored one. Without this the view is
      // created as a Calendar and the user keeps staring at the Grid until they switch views
      // and back β€” the mode would be real in the store and invisible on screen.
      setConfig(nextConfig);
      setSaveState("saved");
    },
    // `fields`, not `config` (R4): the blank is derived from the COLUMNS, and reading the live
    // config here at all is what item 9 deletes.
    [fields, persistView, views]
  );
  const renameView = useCallback(
    (id: string, name: string) => {
      const view = views.find((item) => item.id === id);
      if (view) {
        const acceptedName = uniqueDisplayName(
          name,
          views.filter((item) => item.id !== id).map((item) => item.name)
        );
        persistView({ ...view, name: acceptedName });
      }
    },
    [views, persistView]
  );
  /**

   * I12 (contract C3) β€” freeze/unfreeze a view's DISPLAY MODE.

   *

   * The client re-checks the actor before emitting even though the menu entry is already

   * gated: an event can be replayed, and "hidden in the client" has never been a permission.

   * The host checks it again and that check is the wall β€” this one only keeps the client from

   * showing a change that will not survive the round trip.

   */
  /**

   * ⭐⭐ WAVE 32 Β· T24 (owner item 17, ruling R5, contract C4) β€” MARK / UNMARK IMPORTANT.

   *

   * β›” NO PERMISSION TEST OF ITS OWN, unlike `toggleViewLock` above, and that is the ruling

   * rather than an omission: R5's mark is a legibility flag ("keep this number in front of me"),

   * not a lock over anybody's rows. `persistView` already refuses a view this caller may not

   * write, which is the wall that matters.

   *

   * ⚠ `important` is written EXPLICITLY as a boolean, never by deleting the key. The server's

   * allowlist reads `cfg.get('important') is True`, so an unmark has to ARRIVE as `false`; a

   * client that dropped the key on unmark would leave the stored `true` untouched and produce a

   * mark that can be set and never cleared.

   */
  const toggleViewImportant = useCallback(
    (id: string, important: boolean) => {
      const view = views.find((item) => item.id === id);
      if (!view) return;
      persistView({ ...view, config: { ...view.config, important } });
    },
    [views, persistView]
  );
  const toggleViewLock = useCallback(
    (id: string, locked: boolean) => {
      const view = views.find((item) => item.id === id);
      if (!view || !mayToggleViewLock(view, viewer)) return;
      persistView({ ...view, locked });
    },
    [views, persistView, viewer]
  );
  // The list description. Template lists ship with prose seeded by the host, but it is
  // the USER's text once they touch it β€” including clearing it. An empty string is
  // persisted as an empty string (never coerced back to the seed), because the host
  // resolves a saved view OVER its template, so "" is how you delete a description.
  const setViewNote = useCallback(
    (id: string, note: string) => {
      const view = views.find((item) => item.id === id);
      if (view) persistView({ ...view, note: note.slice(0, 2000) });
    },
    [views, persistView]
  );
  const duplicateView = useCallback(
    (id: string) => {
      const source = views.find((view) => view.id === id);
      if (!source) return;
      const copy: SavedView = {
        ...source,
        id: nextViewId(),
        name: uniqueDisplayName(
          `${source.name} copy`,
          views.map((view) => view.name)
        ),
        kind: "custom",
        locked: false,
        // I17 (C4) β€” a COPY IS THE DUPLICATOR'S OWN, PERSONAL view. Ruled, not inherited:
        //  - inheriting a 'users' grant would silently re-share the copy with a list the
        //    person making it never chose;
        //  - Duplicate is also the escape hatch for someone who may NOT edit the original,
        //    and 'personal' + the host's fresh createdBy stamp is exactly "mine to work in".
        permissions: { edit: "personal" },
        // Never echo the SOURCE's creator: the host stamps and ignores what the browser
        // sends, but sending someone else's name is a laundering attempt on its face.
        createdBy: undefined,
        config: { ...source.config },
      };
      persistView(copy);
      setActiveViewId(copy.id);
      setConfig(copy.config);
    },
    [views, persistView]
  );
  const deleteView = useCallback(
    (id: string) => {
      const view = views.find((item) => item.id === id);
      // ⚠ This gate used to read `view.locked`, and the menu entry above it did too. C3
      // redefines `locked` as "the DISPLAY MODE is frozen" on ANY view, so leaving the gate
      // here would make a user-frozen Kanban undeletable in the client while the host would
      // delete it happily (app.py refuses only `all-customers`, by id). The MENU is just the
      // door β€” this is the gate, and both had to move.
      // C4 rides alongside: you may not delete a view you may not edit.
      if (!view || isUndeletableView(view) || !mayEditView(view, viewer)) return;
      // 2026-08-04 β€” STAMP BEFORE THE EMIT, the writeLocal-before-emit order every other
      // optimistic path here uses. The live adopt below re-reads `payload.workspace.views`
      // on every echo, and the queue sends ONE batch at a time β€” so an echo answering an
      // EARLIER batch still lists this view, and without the tombstone the row would come
      // back and (since that merge never removes) stay back. See liveWorkspace.ts.
      viewTombstonesRef.current = stampTombstone(viewTombstonesRef.current, id, Date.now());
      setViews((current) => current.filter((item) => item.id !== id));
      emitHostEvent({ id: eventId("view-delete"), type: "view_delete", viewId: id });
      if (activeViewId === id) {
        const all = views.find((item) => item.id === ALL_VIEW_ID) ?? allRecordsView(fields, scope);
        setActiveViewId(all.id);
        setConfig(all.config);
      }
    },
    [views, activeViewId, fields, viewer, scope]
  );

  /**

   * Wave-6 item 7 β€” PER-COHORT view state. Each cohort keeps its own view under the stable id

   * `cohort:<cohortId>`; a cohort with no saved view opens CLEAN (defaultViewConfig β€” no sort,

   * no filters), which is exactly what "first created" means. The view is added LOCALLY on

   * first open and emitted only when the user actually edits it (the autosave effect already

   * compares configs), so "absent = clean" stays true in the store β€” opening every cohort

   * once must not write a store full of empty views.

   */
  useEffect(() => {
    if (!cohortMode || !workspaceReady || !activeCohortId) return;
    const vid = `cohort:${activeCohortId}`;
    if (activeViewId === vid) return;
    const outgoing = views.find((view) => view.id === activeViewId);
    if (outgoing && !sameConfig(outgoing.config, config))
      persistView({ ...outgoing, config });
    const existing = views.find((view) => view.id === vid);
    const view: SavedView = existing ?? {
      id: vid,
      name: lists.find((l) => l.id === activeCohortId)?.name ?? "Cohort",
      kind: "custom",
      config: defaultViewConfig(fields),
    };
    if (!existing) setViews((current) => [...current, view]);
    setActiveViewId(vid);
    setConfig(normalizeConfig(view.config, fields));
    setCollapsed(new Set());
    setSearch("");
  }, [cohortMode, workspaceReady, activeCohortId, activeViewId, views, config,
      fields, lists, persistView]);

  /**

   * "Add to list" (owner item 6). Runs the SAME engine over the named view's config to learn

   * which customers it matches, then hands those pids to the host.

   *

   * ⚠ Deliberately re-runs the pipeline for THAT view rather than using what is on screen: the

   * menu is available on every view, not only the active one, and "add the rows I can see" would

   * quietly mean something different depending on which view happened to be open.

   *

   * ⚠ Refuses on a windowed table. There the client holds ONE PAGE, so "the customers this view

   * matches" is a question it cannot answer β€” it would add the 200 rows it happens to hold and

   * report success. Silence would be worse than the refusal (CG-3, no-unverifiable-aggregates).

   *

   * ⚠ Refuses for the SAME reason when this view has a measure condition with no answer yet

   * (CG-8). A pending condition matches nothing, so the cohort would be built from a filter that

   * is currently narrower than the one the user is reading β€” and a cohort is a FIXED set, so

   * that wrong membership would persist long after the answer arrived.

   */
  /**

   * ⭐ WAVE 27 Β· OWNER ITEM 21 / RULING R14 β€” HOW MANY RECORDS EACH ALERTED VIEW MATCHES.

   *

   * β›” ONE EVALUATOR, AND IT IS `runPipeline` RATHER THAN `matchFilterTree`. The question is

   * "how many records does this VIEW show", and a view is more than its condition list: a

   * `cohortLock` narrows before anything else, `memberPids` are pinned in regardless, and a

   * RANK leaf ("top 10") is only answerable against the domain the other conditions leave.

   * `matchFilterTree` answers a different question β€” "does this ROW match this tree" β€” and

   * using it here would report the whole book for a locked view and nonsense for a ranked one.

   * `addToList` below already reaches for the pipeline for the same reason

   * ([[one-evaluator-per-question]]); this is the same call with the same inputs.

   *

   * β›” THREE CASES WHERE THERE IS NO HONEST NUMBER, and each is ABSENT rather than zero:

   *   Β· a WINDOWED table β€” the client engine is skipped by design (CG-3), so a count here

   *     would be the size of one PAGE wearing the label of a scope;

   *   Β· an unresolved MEASURE condition β€” the server has not answered it yet, so the view

   *     matches nothing *yet*, and rendering `0` would state a fact nobody has established;

   *   Β· a view the rail no longer holds β€” an alert outlives its view.

   * A missing key means no badge (the prop's own contract), which is the correct rendering of

   * "not known" and is distinguishable from `0`, which is a real and interesting answer.

   *

   * ⚠ MEMOISED ON THE ALERTED SET, not on `views`: this walks the whole book once per alerted

   * view, and on a table with no alerts it does nothing at all.

   */
  /**

   * ⭐⭐ WAVE 32 Β· T24 (R5/C4) β€” THE BADGE'S SOURCE SET GAINS THE MARKED VIEWS.

   *

   * β›” THE SAME MACHINE, NOT A SECOND ONE. Wave 27 already computes a live matching count for

   * every ALERTED view and paints it as a red pill; R5 asks for exactly that number on a view

   * the user marked. Building a parallel counter would give one rail two ideas of "how many

   * records match this view", and they would drift the first time the pipeline changed.

   * β›” AND IT ADDS NO QUERY β€” R8's whole subject is that `/nav` is too slow. This folds over

   * `computedRows`, which the grid already holds; the memo below still walks the book once per

   * counted view, and on a table with neither an alert nor a mark it does nothing at all.

   */
  const importantIds = useMemo(
    () => views.filter((v) => v.config?.important === true).map((v) => v.id),
    [views]
  );
  // ⚠ DEDUPED: a view that is BOTH alerted and marked must be counted once, or the memo walks
  // the whole book twice for one number.
  const countedIds = useMemo(
    () => Array.from(new Set([...alerted, ...importantIds])),
    [alerted, importantIds]
  );
  const alertedKey = countedIds.join(",");
  const alertCounts = useMemo(() => {
    const out: Record<string, number> = {};
    if (serverWindowed || !countedIds.length) return out;
    for (const id of countedIds) {
      const view = views.find((v) => v.id === id);
      if (!view) continue;
      if (pendingMeasures(view.config.filters, measureSets) > 0) continue;
      const { pidToIndex } = runPipeline({
        rawRows: computedRows,
        fields,
        filters: view.config.filters,
        search: "",
        sorts: [],
        groupBy: null,
        collapsed: new Set<string>(),
        memberPids: view.config.memberPids,
        filterConj: view.config.filterConj ?? "and",
        measureSets,
        cohortSets,
        cohortLock: view.config.cohortLock,
        today,
      });
      // DISTINCT records, which is what `pidToIndex` is β€” a grouped pipeline can list one
      // record under several headings and `visibleRows.length` would then count it twice.
      out[id] = pidToIndex.size;
    }
    return out;
    // `alertedKey` is the scalar identity of the list; `alerted` itself is a fresh array on
    // every fetch even when the answer has not changed.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [alertedKey, views, computedRows, fields, measureSets, cohortSets, today, serverWindowed]);

  const addToList = useCallback(
    (viewId: string, cohortId: string, name: string) => {
      if (serverWindowed) return;
      const view = views.find((v) => v.id === viewId);
      if (!view) return;
      if (pendingMeasures(view.config.filters, measureSets) > 0) return;
      const { visibleRows: matched } = runPipeline({
        rawRows: computedRows,
        fields,
        filters: view.config.filters,
        search: "",
        sorts: view.config.sorts,
        groupBy: null,
        collapsed: new Set<string>(),
        memberPids: view.config.memberPids,
        filterConj: view.config.filterConj ?? "and",
        measureSets,
        cohortSets,
        today,
      });
      const pids = matched
        .filter((r): r is { kind: "data"; record: Row } => r.kind === "data")
        .map((r) => r.record.pid);
      emitHostEvent({
        id: eventId("addlist"),
        type: "add_to_list",
        viewId,
        cohortId,
        name,
        pids,
      });
    },
    [views, computedRows, fields, serverWindowed, measureSets, cohortSets, today]
  );

  // ---------------------------------------------------------------- I11c (C4)
  // Folders for the Views rail. The MODEL (echo reconcile, tombstones, dangling
  // refs) lives in folders.ts and is gated by verify_folders.py; this is only the
  // wiring: stamps for what this browser just did, and the five events.
  const [folderStamps, setFolderStamps] = useState<FolderStamps>({});
  /**

   * Folders THIS browser just created, held until the host echo returns them.

   *

   * ⚠ Without these, `reconcileFolders` was being called with the host list as

   * BOTH arguments, which makes its optimistic-create branch unreachable: a

   * folder absent from `host` is equally absent from `local`. The function was

   * right and the wiring was wrong, so "+ New folder" painted nothing until the

   * round trip landed β€” seconds, on a cold container, with the user clicking

   * again. The gate passed because it called reconcileFolders with two DIFFERENT

   * arrays; it now also calls it the way this component does.

   */
  const [localFolders, setLocalFolders] = useState<GridFolder[]>([]);
  const workspaceFolders = payload?.workspace?.folders;
  const folders = useMemo(
    () => reconcileFolders(workspaceFolders, localFolders, folderStamps, Date.now()),
    [workspaceFolders, localFolders, folderStamps]
  );
  const folderIdOf = useCallback(
    (viewId: string) =>
      resolveFolderId(
        viewId,
        views.find((v) => v.id === viewId)?.folderId ?? null,
        folders,
        folderStamps,
        Date.now()
      ),
    [views, folders, folderStamps]
  );
  const stampFolder = useCallback((patch: (prev: FolderStamps) => FolderStamps) => {
    setFolderStamps((prev) => pruneFolderStamps(patch(prev), Date.now()));
  }, []);

  /* wave17 R1 / C-LOCKV β€” the COHORT FOLDER surface is gone. `folders['cohorts']` merged

     into `folders['views']` in the host's one-shot migration and `cohortFolders` is no longer

     emitted at all, so `reconcileFolders` here would have been reconciling an absent list

     against nothing forever. A locked view files into an ORDINARY folder now, which is what R1

     means by "native folders". */

  /**

   * C4 as AMENDED β€” the folder-level bulk add's PREVIEW. Deliberately re-runs the

   * engine per contained view, exactly as `addToList` does, and carries the SAME

   * two refusals as named skips rather than dropping them silently: a union that

   * quietly omits two views is a wrong cohort that looks right, and a cohort is a

   * FIXED set, so it stays wrong ([[no-unverifiable-aggregates]]).

   */
  const folderAddPreview = useCallback(
    (folderId: string) => {
      const pids = new Set<number>();
      const skipped: { name: string; why: string }[] = [];
      let counted = 0;
      for (const view of views) {
        if (folderIdOf(view.id) !== folderId) continue;
        if (serverWindowed) {
          skipped.push({ name: view.name, why: "this table loads one page at a time" });
          continue;
        }
        if (pendingMeasures(view.config.filters, measureSets) > 0) {
          // C-NAME (item 9) β€” user-facing, so it says "metric" like every other surface.
          skipped.push({ name: view.name, why: "a metric condition has no answer yet" });
          continue;
        }
        counted += 1;
        const { visibleRows: matched } = runPipeline({
          rawRows: computedRows,
          fields,
          filters: view.config.filters,
          search: "",
          sorts: view.config.sorts,
          groupBy: null,
          collapsed: new Set<string>(),
          memberPids: view.config.memberPids,
          filterConj: view.config.filterConj ?? "and",
          measureSets,
          cohortSets,
          today,
        });
        for (const r of matched) if (r.kind === "data") pids.add(r.record.pid);
      }
      return { pids: [...pids], counted, skipped };
    },
    [views, folderIdOf, serverWindowed, computedRows, fields, measureSets, cohortSets, today]
  );

  const folderAddToList = useCallback(
    (folderId: string, cohortId: string, name: string) => {
      const { pids } = folderAddPreview(folderId);
      if (!pids.length) return;
      // ONE emit with the deduped union, through the SAME guarded event a single
      // view's "Add to cohort" uses β€” so the host validates both identically.
      emitHostEvent({
        id: eventId("addlist"),
        type: "add_to_list",
        viewId: "",
        cohortId,
        name,
        pids,
      });
    },
    [folderAddPreview]
  );

  /**

   * Wave-7 item W2 (contract C2) β€” export "the current view", CLIENT-side. The same

   * engine run addToList uses (that is the point: the file says exactly what the count

   * says), over the same pool the named surface scopes to.

   *

   * ⚠ Same two refusals as addToList, for the same reasons: a server-windowed table

   * holds ONE PAGE (the client cannot answer "the view's matches"), and a view with a

   * PENDING measure condition currently matches nothing β€” an export taken then would be

   * an empty/narrower file wearing the view's name. Both windows self-resolve; the

   * refusal is silent no-op for one round trip.

   */
  const exportRows = useCallback(
    (name: string, cfg: ViewConfig, poolRows: Row[], format: ExportFormat) => {
      if (serverWindowed) return;
      if (pendingMeasures(cfg.filters, measureSets) > 0) return;
      const { visibleRows: matched } = runPipeline({
        rawRows: poolRows,
        fields,
        filters: cfg.filters,
        search: "",
        sorts: cfg.sorts,
        groupBy: null,
        collapsed: new Set<string>(),
        memberPids: cfg.memberPids,
        filterConj: cfg.filterConj ?? "and",
        measureSets,
        cohortSets,
        today,
      });
      const records = matched
        .filter((r): r is { kind: "data"; record: Row } => r.kind === "data")
        .map((r) =>
          overlayEdits[r.record.pid]
            ? { ...r.record, ...overlayEdits[r.record.pid] }
            : r.record
        );
      // Columns = the view's VISIBLE fields in display order (the reconciled order:
      // every key present, config order first β€” the same shape useGridColumns paints).
      const inOrder = new Set(cfg.order);
      const keys = [
        ...cfg.order,
        ...fields.map((f) => f.key).filter((k) => !inOrder.has(k)),
      ];
      const vis = new Set(cfg.visible);
      const cols = keys
        .filter((k) => vis.has(k))
        .map((k) => fieldByKey.get(k))
        .filter((f): f is Field => !!f);
      runExport(format, name, today, cols, records);
    },
    [serverWindowed, fields, fieldByKey, measureSets, cohortSets, today, overlayEdits]
  );

  /**

   * ⭐ owner item 3 (2026-08-03) β€” THE SHEET THE TIME-SERIES VIEW IS SHOWING, published by the

   * panel. A ref rather than state on purpose: nothing renders from it, and setting state on

   * every sheet rebuild would re-render the whole grid to feed a menu nobody has opened yet.

   */
  const tsSheetRef = useRef<TsSheet | null>(null);
  const onTsSheet = useCallback((s: TsSheet) => { tsSheetRef.current = s; }, []);
  /** The same channel for a SUMMARY calendar β€” the other mode whose content is not its rows.

   *  `null` is CalendarView saying "records mode, export the rows" (see its note). */
  const calSheetRef = useRef<{ fields: Field[]; rows: Row[] } | null>(null);
  const onCalSheet = useCallback(
    (s: { fields: Field[]; rows: Row[] } | null) => { calSheetRef.current = s; },
    []
  );

  /**

   * W2 β€” the view menu's Export (Customer page): the named view over the whole pool.

   *

   * ⭐ owner item 3 (2026-08-03) β€” AND IT EXPORTS WHAT THE VIEW SHOWS. Every mode used to

   * export the same thing: the matched customer rows. For grid / list / kanban / calendar /

   * map / chart that is right β€” those modes ARRANGE rows, so the rows are what they show, and

   * a calendar's dates and a kanban's lanes are columns already in the file.

   *

   * TWO modes are not arrangements of rows, and both were wrong in the direction that matters:

   *

   *   Β· `timeseries` β€” metric ROWS over period COLUMNS. Exporting it handed you a customer list

   *     that shares none of its numbers. It exports the SHEET.

   *   Β· `calendar` IN SUMMARY MODE β€” metric values per DAY (C-DISP item 4). Same problem, and

   *     the owner named this one by hand. A calendar in RECORDS mode is genuinely an

   *     arrangement of rows, so it keeps the row export; `CalendarView` says which it is by

   *     publishing a sheet or publishing null.

   *

   * ⚠ ONLY FOR THE ACTIVE VIEW, and this is a real limit, not an oversight. Both sheets are

   * built by the mounted view β€” the time series from a server round trip, the calendar from the

   * month on screen. A view sitting unopened in the rail has neither, and this component cannot

   * conjure one without fetching it. So that case SAYS SO and downloads nothing: the

   * alternative is silently handing over the customer rows under that view's name, which is the

   * exact substitution this branch exists to stop.

   */
  const exportViewData = useCallback(
    (viewId: string, format: ExportFormat) => {
      const view = views.find((v) => v.id === viewId);
      if (!view) return;
      const cfg = normalizeConfig(view.config, fields);
      const spec = cleanDisplay(cfg.display);
      const isActive = viewId === activeViewId;
      const refuse = (what: string) =>
        signal(
          TOAST_EVENT,
          `Open "${view.name}" first: ${what} is exported from what it draws on screen.`
        );

      if (spec?.mode === "timeseries") {
        const sheet = isActive ? tsSheetRef.current : null;
        if (!sheet) return refuse("a time series");
        if (sheet.empty) {
          signal(TOAST_EVENT,
                 `"${view.name}" has no metrics on its sheet yet β€” add one, then export.`);
          return;
        }
        if (format === "csv") {
          // The gated builder (verify_timeseries), kept as THE csv path so the file the owner
          // downloads is the one the gate proves β€” footnotes, grouped thousands and all.
          triggerDownload(
            exportFilename(view.name, today, format),
            new Blob(["ο»Ώ" + buildTsCsv(sheet)], { type: "text/csv;charset=utf-8" })
          );
        } else {
          const { fields: tf, rows: tr } = tsSheetToTable(sheet);
          runExport(format, view.name, today, tf, tr);
        }
        return;
      }

      /* ═══ W18-C CATALOG ═══ A catalog is the THIRD mode that is not an arrangement of rows,

         and it is the furthest from one: its pages are authored content, and its product codes

         are a fraction of the pool in an order the user chose. Handing over the matched rows

         under a catalogue's name would be the same substitution the two branches around this

         one exist to stop. It exports as a PDF, through the browser's own print dialog (R10),

         so this branch refuses the file and names the door that works. */
      if (spec?.mode === "catalog") {
        signal(
          TOAST_EVENT,
          `"${view.name}" is a catalog β€” open it and use Print to save it as a PDF. ` +
            `A spreadsheet of its products is not what it draws.`
        );
        return;
      }
      /* ═══ end W18-C CATALOG ═══ */

      if (spec?.mode === "calendar" && spec.calendarMode === "summary") {
        const sheet = isActive ? calSheetRef.current : null;
        if (!sheet) return refuse("a calendar summary");
        runExport(format, view.name, today, sheet.fields, sheet.rows);
        return;
      }

      exportRows(view.name, cfg, computedRows, format);
    },
    [views, fields, computedRows, exportRows, activeViewId, today]
  );

  /**

   * The selection bar's "Add to locked view": exactly the CHECKED customers, not a view's

   * matches.

   * Same guarded `add_to_list` event β€” the host intersects the pids with the caller's pool

   * either way, so a hand-picked set and a view's match set ride one validation path.

   */
  const addSelectionToList = useCallback(
    (cohortId: string, name: string) => {
      const pids = [...selectedPids];
      if (!pids.length || serverWindowed) return;
      emitHostEvent({
        id: eventId("addlist"),
        type: "add_to_list",
        viewId: activeViewId,
        cohortId,
        name,
        pids,
      });
      setSelAddOpen(false);
      setSelListName("");
      clearSelection();
    },
    [selectedPids, serverWindowed, activeViewId, clearSelection]
  );

  // Item 3c: the local write is the RENDERED truth (the def half of the no-blip contract) β€”
  // stamped so a lagged echo cannot claw it back at the next remount. Item 9c: `scope` rides
  // the EVENT at create time only; the def itself carries `scope: 'cohort'` so the echo is
  // byte-stable ('global' stays absent β€” the host normalizes them to one shape).
  const scopeChoice = payload?.workspace?.scopeChoice === true;
  /**

   * Item 12 (C-LOCK) β€” the Filter banner's copy for a cohort-locked view.

   *

   * `undefined` when the view is not locked. When it IS locked but the set is not in `lists`,

   * this returns an EMPTY object: the banner must still appear (the reader is looking at a

   * narrowed table and deserves to know why), but with no name and no count, because a set we

   * were given no membership for is a set we must not describe. RECORD's banner reads that

   * absence and says "locked to a set you cannot see".

   *

   * The count is the cohort's OWN size, not the number of rows on screen β€” the conditions

   * narrow within the lock, so the two differ and the banner is stating the lock.

   */
  /**

   * ⭐ wave17 R1 / C-LOCKV β€” the lock in force, which is now simply the ACTIVE VIEW's.

   *

   * Wave 15 had two sources: a saved `config.cohortLock` and an ephemeral pick from the Cohorts

   * rail that outranked it while held. The second existed only because a projected cohort was

   * not a saved view, so opening one could not be allowed to write anything. Under R1 it IS a

   * saved view, so selecting it applies its own stored lock through the ordinary view path β€”

   * one source, and it survives a reload, which the transient one never did.

   */
  const effectiveCohortLock = config.cohortLock;
  /* wave17 R1 / C-LOCKV β€” `cohortRows` and the whole `cohortRail` projection are GONE. They

     turned `lists` into rail rows for a section that no longer exists; the host projects each

     cohort into `views` instead, so the rail renders them through the same path as every other

     view and there is nothing left to project. `lists` still arrives and is still load-bearing

     β€” it is the MEMBERSHIP channel that feeds `cohortSets`, which is what the lock resolves

     against. Its absence would blank every locked view, so it is not "unused". */
  const cohortLockChip = useMemo(() => {
    const id = effectiveCohortLock;
    if (!id) return undefined;
    const set = lists.find((l) => l.id === id);
    if (!set) return {};
    return { name: set.name, count: set.pids?.length ?? 0 };
  }, [effectiveCohortLock, lists]);
  // (Setting/clearing the lock lives in `onViewCohortLock` above β€” the rail's menu operates on
  // whichever view you clicked, not necessarily the active one, so it goes through
  // `persistView` and only touches the live `config` when the two are the same view.)
  /**

   * Item 5 / contract C-LAYOUT β€” this user's record-detail field order, for RECORD's

   * `RecordDetail` (they asked for exactly these two props in the wave mailbox).

   *

   * Read straight off the workspace stratum the host echoes, and emitted back as the

   * `record_layout` event HOST landed. Deliberately NOT reconciled or optimistically merged

   * here: the event returns False host-side (an autosave hot path like `view_upsert`), so

   * there is no rerun to race, and `RecordDetail` holds the live order while a drag is in

   * flight. Nothing else in the grid reads it β€” the order is the MODAL's, never the grid's

   * `config.order`.

   */
  const recordLayout = payload?.workspace?.recordLayout?.order;
  const onRecordLayout = useCallback((order: string[]) => {
    emitHostEvent({ id: eventId("rlayout"), type: "record_layout", order });
  }, []);
  const saveField = useCallback(
    (field: Field, scope?: FieldScope) => {
      const requestId = eventId("field");
      const accepted: Field = {
        ...field,
        label: uniqueDisplayName(
          field.label,
          fields.filter((item) => item.key !== field.key).map((item) => item.label)
        ),
        editRequestId: requestId,
      };
      delete accepted.labelCorrectedFrom;
      delete accepted.labelCorrectionId;
      stampFieldEdit(accepted.key);
      setFields((current) =>
        current.some((item) => item.key === accepted.key)
          ? current.map((item) => (item.key === accepted.key ? accepted : item))
          : [...current, accepted]
      );
      emitHostEvent({
        id: requestId,
        type: "field_upsert",
        field: accepted,
        ...(scope ? { scope } : {}),
      });
    },
    [stampFieldEdit, fields]
  );
  const createField = useCallback(
    (

      label: string,

      type: FieldType,

      anchorKey: string | null,

      side: "left" | "right" | "end",

      options?: string[],

      measureSpec?: { key: string; window: WindowSpec },

      extra?: FieldBuildExtra

    ) => {
      /**

       * ⚠ RENAMED FROM `scope` (wave 21, item 7). It used to SHADOW the component's own

       * `scope` prop β€” the surface this grid is drawing β€” with a completely different

       * thing: a FIELD's storage stratum (`'cohort'` or nothing). Two unrelated meanings

       * under one word, in a function that now has to speak to a per-table endpoint.

       * Caught by `tsc` only because `FieldScope` and `SurfaceScope` happen to be

       * incompatible unions; had either been a bare `string`, the C2 call below would have

       * POSTed to `/tables/undefined/fields` and read as a server bug.

       */
      const fieldScope = scopeChoice ? extra?.scope : undefined;
      const scoped = fieldScope === "cohort" ? ({ scope: "cohort" } as const) : {};
      // Owner item 7 β€” a FORMULA-MEASURE column. `measure_` prefixed, source:'odoo' (read-only
      // at both ends), derived (values arrive from the host per render), filterable:false (the
      // replacement is the measure CONDITION with the same measure+window β€” the governed path).
      // The first render after creation shows blank cells for exactly one round trip: the host
      // persists the field, then computes the values into the next payload.
      if (measureSpec) {
        const field: Field = {
          key: `measure_${slugify(label)}_${Math.random().toString(36).slice(2, 7)}`,
          label,
          type,
          source: "odoo",
          default: true,
          custom: true,
          derived: true,
          filterable: false,
          agg: ["currency", "int"].includes(type) ? "sum" : undefined,
          measure: measureSpec,
          ...scoped,
        };
        saveField(field, fieldScope);
        insertColumn(field.key, anchorKey, side);
        return;
      }
      const field = { ...buildOverlayField(label, type, options, extra), ...scoped };
      /**

       * ⭐ WAVE 21 item 7 (contract C2) β€” AN AUTOMATION COLUMN ON A USER DATABASE GOES TO

       * THE DEFINITION, not to this user's overlay stratum.

       *

       * The automation editor's column picker reads `user_tables` (the definition); every

       * grid-created column went to `<key>_table_workspace` (the per-user overlay). So the

       * picker was empty by construction: the user made the column, then could not find it

       * in the automation they made it for. C2 routes exactly this one kind through

       * `POST /tables/{key}/fields`, and the ROUTE is the wall β€” `_field_or_refuse` allows

       * only the creator or an admin, which is the same answer the grid would have got.

       *

       * ⚠ NARROW ON PURPOSE, twice over: `type === "automation"` AND a `ut_` scope. The

       * connector surfaces have no such endpoint (their schema is their source's), and

       * every other kind keeps the overlay path this wave β€” moving all of them changes who

       * can SEE a column, which is a behaviour change three surfaces would feel and is

       * booked as debt rather than smuggled in here.

       *

       * ⚠ AND IT IS ASYNC, where every other create is optimistic. There is no local

       * insert first: the server re-slugs the key and can refuse outright (it 400s until

       * `UT_FIELD_TYPES` learns `automation` β€” C2's other half, A's), and a column shown

       * under a key the store never took is one that vanishes on the next read with no

       * explanation. The wait is one round trip; the alternative is a lie.

       */
      /**

       * ⭐⭐ 2026-08-09 β€” THE RELATIONAL PAIR JOINS THAT ROUTE, and for a stronger reason than

       * `automation` had. The note above says every other kind "keeps the overlay path this

       * wave", weighing it as a question of who can SEE a column. For `link` and `rollup` it is

       * not a visibility trade-off at all: their cells are computed SERVER-side by

       * `compute_relation_cells`, which walks `user_tables` definitions. A rollup parked in a

       * per-user overlay is invisible to the only code that could ever fill it, so it is not a

       * narrower feature β€” it is a column that cannot work, in any account, ever.

       *

       * β›” AND THE BAG TRAVELS. `_clean_field` returns None for a bagless `link`/`rollup`, so

       * sending `{key,label,type}` here would trade a silent blank column for a loud 400. The

       * bag is on `extra`; `field` already carries it (see `FieldBuildExtra`).

       */
      /**

       * ⭐⭐ 2026-08-10 β€” `formula` JOINS THE SAME ROUTE, on the visibility argument the note

       * above weighs and the relational note declines to use.

       *

       * For `link`/`rollup` visibility was not the point (their cells are computed by something

       * that reads the definition). For a formula it IS the whole point, and the trade-off falls

       * the other way from wave 21's read of it: a `ut_*` database is a SHARED database β€” the

       * owner builds a column on "IG profile" and expects the four people looking at that

       * database to see it. In the overlay stratum only its creator ever does. Measured on

       * nurilab: `Trimmed reel views`, the trimmed-average column the whole rollup chain exists

       * to produce, was visible to exactly one account.

       *

       * β›” THE VALUES STILL DO NOT MOVE, and this must not be sold as more than it is. A formula

       * is computed in this browser (`computedRows`) from the row's other cells and is stored

       * nowhere; what became shared is the EXPRESSION. An automation, a rollup and an export

       * still cannot read this column. Sharing the definition is not materialising the number.

       *

       * ⚠ `agg: "sum"` rides along so the totals row behaves identically to the overlay path

       * (`buildOverlayField` stamps it) β€” a column that stops totalling because of which door

       * created it is [[gate-answers-the-wrong-question]] wearing a create route.

       */
      /**

       * ⭐⭐ WAVE-29 T22 (owner item 2a) β€” **EVERY grid-created column on a `ut_*` database goes

       * to the DEFINITION.** The three notes above widened this set one kind at a time

       * (`automation`, then `link`/`rollup`, then `formula`), each ending by asking whoever needed

       * a fifth to come back here and decide. This is that decision, and it goes to ALL of them

       * rather than to `select` alone, because the defect the owner reported is not about select:

       *

       * β›” **ON A `ut_` SCOPE THERE IS NO PER-USER CELL STRATUM LEFT TO WRITE TO.** Every accepted

       * cell edit is routed to `user_tables.patch_cells` β€” the shared DEFINITION rows

       * (`grid_events.py:1979-1984`) β€” while both `ut_` row doors project rows through the

       * definition's own field keys (`routes_tables.scoped_pool:176`, `user_tables.add_row:678`).

       * So a column living only in `<table>_table_workspace` accepts a value, stores it under a

       * key the projection does not know, and reads back BLANK. **The write is not lost; the read

       * cannot see it** β€” which is why the server reports the write as accepted and the cell is

       * empty after any refetch. That is item 2a, and it applied to `text`, `int`, `date`, `user`,

       * `image` and `checkbox` exactly as much as to `select`. The owner reported the one they

       * happened to build.

       *

       * β›” **`created_time` is the ONE exclusion, and it is the SERVER's, not a preference:**

       * `UT_FIELD_TYPES` does not contain it, so this POST would 400 (measured β€” CREATABLE_TYPES

       * minus UT_FIELD_TYPES is exactly `{created_time}`). It keeps the overlay path, where it is

       * harmless: it is `derived`, so it has no cell of its own to lose.

       *

       * ⚠ **The body is a PROJECTION of the field the constructor already built**, not a

       * per-kind list of keys. The old spelling enumerated what each kind needed, which is how

       * `options` came to be missing for the kind that needed it most β€” a select POSTed without

       * its options is degraded to `text` on read (`aios_grid.py:664-668`). `buildOverlayField`

       * decides the shape; this sends what it decided, so a new kind cannot arrive half-described.

       * (`_clean_field` ignores what it does not know, so `custom`/`derived`/`multi` staying

       * client-side costs nothing; `max` on a `rating` is the one key it drops β€” booked, not lost.)

       */
      if (isUserTable && type !== "created_time") {
        void addTableField(scope, {
          key: field.key,
          label: field.label,
          type,
          ...(field.options?.length ? { options: field.options } : {}),
          ...(field.colorCodeOptions !== undefined
            ? { colorCodeOptions: field.colorCodeOptions }
            : {}),
          ...(field.optionColors ? { optionColors: field.optionColors } : {}),
          ...(extra?.link ? { link: extra.link } : {}),
          ...(extra?.rollup ? { rollup: extra.rollup } : {}),
          ...(type === "formula" && extra?.formula ? { formula: extra.formula } : {}),
          ...(field.agg ? { agg: field.agg } : {}),
        }).then((made) => {
          if (!made) return;                       // the bridge has already said why
          setFields((current) =>
            current.some((f) => f.key === made.key) ? current : [...current, made]
          );
          insertColumn(made.key, anchorKey, side);
          /**

           * β›”β›” 2026-08-10 β€” THE WORKSPACE RE-READ USED TO FIRE HERE AND IT ATE THE LINE ABOVE.

           *

           * `insertColumn` adds the new key to the view's `visible` set and autosaves that config;

           * `signal(WORKSPACE_STALE_EVENT)` refetches `/workspace`, whose views carry the SERVER's

           * config β€” the one written a moment before the insert. The refetch won, every time, so

           * a column created into the shared definition was **stored correctly and rendered

           * nowhere**: present in the payload, present in `order` (which is re-derived from the

           * field list), and absent from `visible`. MEASURED on live nurilab across all four

           * views after migrating `Trimmed reel views`; it has been true for `link`, `rollup` and

           * `automation` since that route was widened on 2026-08-09.

           *

           * β›” AND THE COMMENT IT REPLACES WAS THE REASON NOBODY LOOKED. It claimed the signal is

           * "what makes the column survive a reload rather than living only in this browser's

           * state" β€” but the SERVER already stored the field; the 201 is what makes it survive.

           * The signal only refreshed a payload whose field list `setFields` had just updated by

           * hand, and `addTableField` already drops the rows cache. It bought nothing and cost

           * the one piece of state the create had just written.

           *

           * ⚠ The delete and reconfigure paths keep their signals: those change VALUES other

           * columns fold (a dropped link takes its reciprocal and every rollup over it), and

           * neither writes view config in the same breath, so neither has this race.

           */
        });
        return;
      }
      saveField(field, fieldScope);
      insertColumn(field.key, anchorKey, side);
    },
    [insertColumn, saveField, scopeChoice, isUserTable, scope]
  );

  /**

   * ⭐⭐ 2026-08-07 (D-79's last half) β€” turn a text column into THE profile column.

   *

   * The write goes to the DEFINITION (`PATCH /tables/{key}/fields/{fkey}`), never to this

   * user's overlay stratum, for the reason wave 25's amendment C3-A1 records: the automation

   * engine reads `t['rows']`/`t['fields']`, so a flag parked in one person's overlay is a flag

   * the enrich step can never see. Same door, same reasoning, as the automation column above.

   *

   * ⚠ `profile: null` CLEARS it β€” `_clean_field` treats an explicit null as "take the flag off"

   * rather than "leave it alone", which is what lets a column be un-marked without deleting it.

   */
  const setProfileFlag = useCallback(
    (key: string, on: boolean) => {
      if (!isUserTable) return;
      void patchTableField(scope, key, {
        profile: on ? { source: "instagram" } : null,
      }).then((made) => {
        if (!made) return;                          // the bridge has already said why
        setFields((current) => current.map((f) => (f.key === made.key ? made : f)));
        signal(WORKSPACE_STALE_EVENT);
      });
    },
    [isUserTable, scope]
  );

  /**

   * ⭐⭐ 2026-08-09 (owner) β€” RECONFIGURE a `link`/`rollup` column, in the SHARED definition.

   *

   * Owner: *"even when i click edit field for rollup, it doesn't actually show me the

   * configuration"* and *"No rollup field should be uneditable."* Both land here: the Edit pane

   * now renders the bag, and this is where its Save goes.

   *

   * β›” NOT `saveField`, and not `retypeField`. Those write the per-user overlay stratum, which is

   * precisely the defect this change exists to close β€” `compute_relation_cells` reads

   * `user_tables`, so a bag parked in one person's workspace can never be computed by anything.

   * ⚠ ASYNC with no optimistic insert, like the automation create: the server re-cleans the bag

   * and can refuse the whole field (`_clean_rollup` returns None for, say, a `limit` with no

   * `sortBy`), and showing a configuration the store never took is the lie the wait avoids.

   * The cells arrive on the next read β€” a rollup is recomputed server-side, never in the browser.

   */
  const setFieldConfig = useCallback(
    (key: string, patch: {

      label?: string; link?: unknown; rollup?: unknown; formula?: string; agg?: string;

    }) => {
      if (!isUserTable) return;
      void patchTableField(scope, key, patch as Record<string, unknown>).then((made) => {
        if (!made) return;                          // the bridge has already said why
        setFields((current) => current.map((f) => (f.key === made.key ? made : f)));
        // The definition changed, so the wire's field list did too β€” and a rollup's VALUES are
        // recomputed host-side on this write, so the ROWS are a beat stale as well. The bridge
        // drops its rows cache for this table (it owns that map); these two ask for a re-read.
        signal(WORKSPACE_STALE_EVENT);
        signal(ROWS_STALE_EVENT);
      });
    },
    [isUserTable, scope]
  );

  /**

   * Owner item 9 β€” "Change field": the clicked column starts showing another field, in place.

   * The new field takes the old one's slot in `order`; the old field is HIDDEN, not lost β€” it

   * stays in Fields and can be swapped back. The locked primary column is the row identity and

   * cannot be changed away (ColumnMenu never offers it the control).

   */
  const changeField = useCallback(
    (oldKey: string, newKey: string) => {
      if (oldKey === lockedKey || oldKey === newKey) return;
      if (!fieldByKey.has(newKey)) return;
      // The RECONCILED order (every key present, locked first), so the splice is well-defined
      // even for a fresh view whose config.order is still the default.
      const withoutNew = order.filter((k) => k !== newKey);
      const at = withoutNew.indexOf(oldKey);
      if (at < 0) return;
      withoutNew.splice(at, 0, newKey);
      const nextVisible = new Set(visible);
      nextVisible.delete(oldKey);
      nextVisible.add(newKey);
      updateConfig({ ...config, order: withoutNew, visible: [...nextVisible] });
    },
    [config, updateConfig, order, visible, fieldByKey, lockedKey]
  );

  /**

   * Delete a USER-CREATED column outright (owner gap closed 2026-07-27). Only the created

   * strata qualify β€” `custom_` overlay fields and `measure_` formula columns, both marked

   * `custom` β€” so a base field can never leave the schema from here (Hide is its only exit).

   * The definition leaves local state, the ACTIVE view's config is scrubbed (order / visible /

   * widths / sorts / group / color), and the host removes it from the workspace store β€” other

   * views self-heal on their next autosave, the rule every stale colId already rides.

   * Two emits leave in one burst (field_delete + the config autosave); the event-log value

   * slot exists for exactly this.

   */
  const deleteField = useCallback(
    (key: string) => {
      const f = fieldByKey.get(key);
      if (!f?.custom || key === lockedKey) return;
      setFields((current) => current.filter((item) => item.key !== key));
      const nextWidths = { ...(config.widths ?? {}) };
      delete nextWidths[key];
      updateConfig({
        ...config,
        order: order.filter((k) => k !== key),
        visible: [...visible].filter((k) => k !== key),
        widths: nextWidths,
        sorts: (config.sorts ?? []).filter((s) => s.colId !== key),
        groupBy: config.groupBy === key ? null : config.groupBy,
        colorBy: config.colorBy === key ? null : config.colorBy,
      });
      stampFieldDelete(key);
      emitHostEvent({ id: eventId("fielddel"), type: "field_delete", key });
    },
    [config, updateConfig, order, visible, fieldByKey, lockedKey, stampFieldDelete]
  );

  /**

   * ⭐⭐ 2026-08-10 β€” DELETE A COLUMN FROM A USER DATABASE'S SHARED DEFINITION.

   *

   * `deleteField` above writes the per-user overlay: it emits `field_delete`, which

   * `grid_events` gates on the `custom_`/`measure_` prefix and applies to

   * `<table>_table_workspace`. A definition column has a `custom_` key too, so that event is

   * ACCEPTED and scrubs a bucket the definition never reads β€” the column disappears for one

   * paint and is back on the next fetch. That is why this is a different function rather than a

   * branch: two stores, two truths, and the wrong one succeeds quietly.

   *

   * ⚠ SERVER FIRST, THEN THE SCREEN. `_field_or_refuse` can say no (a pre-set column, a

   * non-creator, the last remaining column), and the bridge has already shown its sentence β€”

   * removing the column optimistically would leave the user looking at a grid that disagrees

   * with the store until they reload.

   * ⚠ The VIEW config is scrubbed on the same terms as the overlay delete; a stale `colId` in

   * another view self-heals on its next autosave, the rule every other delete rides.

   */
  const deleteDefinitionField = useCallback(
    (key: string) => {
      if (!isUserTable || key === lockedKey) return;
      void deleteTableField(scope, key).then((ok) => {
        if (!ok) return;                            // the bridge has already said why
        setFields((current) => current.filter((item) => item.key !== key));
        const nextWidths = { ...(config.widths ?? {}) };
        delete nextWidths[key];
        updateConfig({
          ...config,
          order: order.filter((k) => k !== key),
          visible: [...visible].filter((k) => k !== key),
          widths: nextWidths,
          sorts: (config.sorts ?? []).filter((s) => s.colId !== key),
          groupBy: config.groupBy === key ? null : config.groupBy,
          colorBy: config.colorBy === key ? null : config.colorBy,
        });
        signal(WORKSPACE_STALE_EVENT);
        signal(ROWS_STALE_EVENT);
      });
    },
    [isUserTable, scope, lockedKey, config, updateConfig, order, visible]
  );

  /**

   * Change-field's "New field" half (wave-2 item 5): build the overlay field, then swap it into

   * the clicked column's slot β€” one motion, two emits (field_upsert + the config autosave),

   * which is exactly the burst the event-log value slot exists for.

   */
  const createAndSwapField = useCallback(
    (

      oldKey: string,

      label: string,

      type: FieldType,

      options?: string[],

      extra?: FieldBuildExtra

    ) => {
      const scope = scopeChoice ? extra?.scope : undefined;
      const field = {
        ...buildOverlayField(label, type, options, extra),
        ...(scope === "cohort" ? ({ scope: "cohort" } as const) : {}),
      };
      saveField(field, scope);
      changeField(oldKey, field.key);
    },
    [saveField, changeField, scopeChoice]
  );

  /**

   * Wave-6 item 2 β€” Change field on a CREATED (`custom_`) field retypes THAT field in place:

   * `field_upsert` with the SAME key and the new type/options; the host rebuilds the def and

   * keeps createdBy/scope (this optimistic def carries them too, so the echo is byte-stable).

   * Values are never converted β€” cells re-render per the new type, unreadable values show

   * blank (Airtable behavior, disclosed in the pane). A display `format` survives only within

   * its own family (number→number); anything else would be junk the host drops anyway.

   */
  const retypeField = useCallback(
    (

      key: string,

      type: FieldType,

      options?: string[],

      // `label` (owner item 8): rename+retype leave the Edit pane as ONE upsert β€” two

      // sequential emits would each read the stale def and revert the other.

      extra?: FieldBuildExtra

    ) => {
      const old = fieldByKey.get(key);
      /**

       * ⭐⭐ WAVE-29 T27 β€” the same widening as the pane above, and it is load-bearing rather

       * than cosmetic: supplying `onRetype` while this function still bailed would render a

       * Field-type picker that silently does nothing, which is worse than the missing control

       * the owner reported.

       *

       * ⭐ AND IT IS ALSO T24's SECOND HALF. Option colours have a validator now, but the EDIT

       * path for them is this function: on a `ut_*` database the field lives in the shared

       * DEFINITION, so `saveField` (this user's overlay stratum) would fork the column into a

       * private copy of itself and the colours would never reach the door that stores them.

       */
      if (!old || !isUserSchemaField(old, isUserTable)) return;
      if (type === "formula" || type === "created_time") return; // a different stratum
      const numberFam = (t: FieldType) => t === "int" || t === "currency";
      const keepFormat =
        old.format && ((numberFam(old.type) && numberFam(type)) || old.type === type);
      const next: Field = {
        key,
        label: extra?.label?.trim() || old.label,
        type,
        source: "overlay",
        default: old.default,
        custom: true,
        agg: ["currency", "int"].includes(type) ? "sum" : undefined,
        ...(old.note ? { note: old.note } : {}),
        ...(old.description ? { description: old.description } : {}),
        ...(old.scope ? { scope: old.scope } : {}),
        ...(old.createdBy ? { createdBy: old.createdBy } : {}),
        ...(old.permissions ? { permissions: old.permissions } : {}),
        ...(keepFormat ? { format: old.format } : {}),
        ...((type === "select" || type === "multiselect") && options?.length
          ? { options }
          : {}),
        ...((type === "select" || type === "multiselect")
          ? {
              colorCodeOptions: extra?.colorCodeOptions !== false,
              ...(extra?.optionColors && Object.keys(extra.optionColors).length
                ? { optionColors: extra.optionColors }
                : {}),
            }
          : {}),
        ...(type === "multiselect" ? { multi: true } : {}),
        ...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
      };
      if (isUserTable && !old.custom) {
        /* THE DEFINITION DOOR. `patch_field` merges the body through the same `_clean_field` the

           create used, so the type, the options, the colours and a rating's max all land in the

           one validator β€” and the SERVER's echo replaces the local field, exactly as the create

           path does, because it re-cleans what it was given and may refuse. */
        void patchTableField(scope, key, {
          label: next.label,
          type,
          ...(next.options ? { options: next.options } : {}),
          ...(next.optionColors ? { optionColors: next.optionColors } : {}),
          ...(next.colorCodeOptions !== undefined
            ? { colorCodeOptions: next.colorCodeOptions }
            : {}),
          ...(next.max !== undefined ? { max: next.max } : {}),
          ...(next.agg ? { agg: next.agg } : {}),
          ...(next.format ? { format: next.format } : {}),
        }).then((made) => {
          if (!made) return;                        // the bridge has already said why
          setFields((current) => current.map((f) => (f.key === made.key ? made : f)));
          signal(WORKSPACE_STALE_EVENT);
          signal(ROWS_STALE_EVENT);
        });
      } else {
        saveField(next);
      }
      /* ⭐ Owner item 15 / C-RENAME β€” the VALUES follow the definition.

         BESIDE the upsert, never instead of it, and AFTER it: the def is written optimistically

         here, while the rename is a host-side migration over overlay values and saved views. The

         order matters if the host processes the batch in order β€” the list must already offer

         "Navy" before any cell is moved onto it. */
      const renames = extra?.renames?.filter((r) => r.from && r.to && r.from !== r.to) ?? [];
      if (renames.length) {
        emitHostEvent({ id: eventId("choicerename"), type: "choice_rename", key, renames });
        // R4 β€” and it is undoable: Ctrl+Z emits the mapping turned around. The declared LIST is
        // restored by the same inverse (the host rewrites values and views back), so undo does
        // not need to re-send the definition.
        undoBook.current[scope] = pushUndo(stackFor(undoBook.current, scope), {
          kind: "choiceRename", fieldKey: key, renames,
        });
      }
    },
    // ⚠ `isUserTable` is in the list because T27 made this function BRANCH on it. A callback that
    // closed over a stale `isUserTable` would route a definition retype to the overlay on the
    // first render after a scope change β€” the exact defect this ticket removes, reintroduced by
    // a memo rather than by a predicate.
    [fieldByKey, saveField, scope, isUserTable]
  );

  /**

   * Wave-5 item 1 β€” Duplicate field. The CLIENT generates the destination key (same stratum

   * prefix as the source β€” the ~20:20 contract amendment), emits `field_duplicate`, and slots

   * an optimistic clone right of its source SYNCHRONOUSLY. The host validates the prefix

   * pair, stamps createdBy (the clone's creator is the duplicator β€” the local copy drops the

   * source's), and copies overlay VALUES for `custom_` sources; those values arrive with the

   * next payload, so the clone's cells are blank for exactly one round trip.

   */
  const duplicateField = useCallback(
    (source: Field) => {
      const prefix = source.key.startsWith("measure_") ? "measure_" : "custom_";
      const label = uniqueDisplayName(
        `${source.label} copy`,
        fields.map((field) => field.label)
      );
      const key = `${prefix}${slugify(label)}_${Math.random().toString(36).slice(2, 7)}`;
      const requestId = eventId("fielddup");
      const clone: Field = { ...source, key, label, editRequestId: requestId };
      delete clone.createdBy;
      delete clone.permissions;
      delete clone.labelCorrectedFrom;
      delete clone.labelCorrectionId;
      stampFieldEdit(key);
      setFields((current) => [...current, clone]);
      emitHostEvent({
        id: requestId,
        type: "field_duplicate",
        sourceKey: source.key,
        key,
        label,
        // Item 9c: a duplicate INHERITS its source's scope (cohort clone stays cohort-only;
        // a global source stays global = absent). Only meaningful on the cohort page.
        ...(scopeChoice && source.scope === "cohort" ? { scope: "cohort" as const } : {}),
      });
      insertColumn(key, source.key, "right");
    },
    [insertColumn, scopeChoice, stampFieldEdit, fields]
  );

  /**

   * Wave-2 item 8c β€” change the PERIOD of a measure-carrying column (user-created `measure_*`

   * and the pre-set measure fields alike). The header auto-renames to

   * `<Measure> Β· <window label>` ONLY while it still reads as the auto-name for the CURRENT

   * window β€” a user's own title is never overwritten. Values arrive recomputed from the host on

   * the next payload; the ordinary `field_upsert` is the whole protocol.

   */
  const changeMeasurePeriod = useCallback(
    (key: string, window: WindowSpec) => {
      const f = fieldByKey.get(key);
      if (!f?.measure) return;
      const m = measures.find((item) => item.key === f.measure?.key);
      const oldAuto = m ? `${m.label} Β· ${windowLabel(f.measure.window)}` : null;
      const label =
        m && oldAuto && f.label === oldAuto
          ? `${m.label} Β· ${windowLabel(window)}`
          : f.label;
      saveField({ ...f, label, measure: { ...f.measure, window } });
    },
    [fieldByKey, measures, saveField]
  );

  /* wave17 R1 β€” `selectCohort`, `renameCohort`, `deleteCohort` and `exportCohortData` are

     gone. Every one of them was called ONLY by `CohortSidebar`, and every one now has a

     better-governed twin: the Views rail renames and deletes a locked view through the

     ordinary view path, and the HOST routes those to `cohort_mod.rename` / `.delete` on a

     projected id (C-LOCKV guards b and c). One name, one lifecycle, one set of events. */

  /**

   * Cohort mode β€” the selection bar's "Remove from cohort" (contract event `cohort_remove`).

   * The pids are intersected with the cohort's membership client-side as a courtesy; the host

   * re-validates ownership and pool anyway (a pid from the browser is untrusted input).

   */
  const removeSelectionFromCohort = useCallback(() => {
    if (!activeCohortId) return;
    const pids = [...selectedPids].filter((p) => cohortMemberSet.has(p));
    if (!pids.length) return;
    emitHostEvent({
      id: eventId("cohortrm"),
      type: "cohort_remove",
      cohortId: activeCohortId,
      pids,
    });
    clearSelection();
  }, [activeCohortId, selectedPids, cohortMemberSet, clearSelection]);


  /**

   * ⭐ Wave-20 owner item 9 β€” **REMOVE FROM A COHORT WITHOUT BEING INSIDE IT.**

   *

   * "Remove from cohort" existed only under `cohortMode` (you had to open the locked view

   * first), while "Add to cohort" worked from any view. So the two halves of the same idea

   * lived on different screens: you could put a customer in a cohort from wherever you found

   * them, and then had to go looking for the cohort to take them out again.

   *

   * SAME EVENT, same host validation as the cohort-mode button β€” `cohort_remove` with the pids

   * intersected client-side as a courtesy. What is new is only WHICH cohort: the picker names

   * it, instead of it being implied by the page you are standing on.

   */
  const removeSelectionFromList = useCallback(
    (cohortId: string) => {
      const members = cohortSets[cohortId];
      if (!members) return;
      const pids = [...selectedPids].filter((p) => members.has(p));
      if (!pids.length) return;
      emitHostEvent({ id: eventId("cohortrm"), type: "cohort_remove", cohortId, pids });
      setSelRemoveOpen(false);
      clearSelection();
    },
    [cohortSets, selectedPids, clearSelection]
  );

  /**

   * The cohorts the checked rows can actually be removed FROM: those holding at least one of

   * them, and only where this viewer may edit the projected view.

   *

   * ⚠ A cohort holding NONE of the checked rows is not offered. Airtable's rule and the one R8

   * states for the ghost row: an affordance that can only refuse is a fake affordance β€” and

   * here it would be worse than that, because "Remove from Q3 plan" that removes nothing looks

   * exactly like a write that failed.

   *

   * The edit test is the COURTESY half (`mayEditView`, like every other client-side permission

   * check on this surface); the host re-validates ownership and pool on the event regardless.

   * A cohort with no projected view is still offered β€” the host owns that verdict, and hiding

   * it here would silently drop sets the reader can see in their own rail.

   */
  const removableLists = useMemo(() => {
    if (cohortMode || selectedPids.size === 0) return [];
    const out: { id: string; name: string; hits: number }[] = [];
    for (const l of lists) {
      const members = cohortSets[l.id];
      if (!members) continue;
      let hits = 0;
      for (const pid of selectedPids) if (members.has(pid)) hits += 1;
      if (!hits) continue;
      const projected = views.find((v) => v.id === l.id);
      if (projected && !mayEditView(projected, viewer)) continue;
      out.push({ id: l.id, name: l.name, hits });
    }
    return out;
  }, [cohortMode, selectedPids, lists, cohortSets, views, viewer]);

  /** Cohort mode β€” confirm the "+ Add customers" picker (contract event `cohort_add`). */
  const addCustomersToCohort = useCallback(() => {
    if (!activeCohortId || addCustPicked.size === 0) return;
    emitHostEvent({
      id: eventId("cohortadd"),
      type: "cohort_add",
      cohortId: activeCohortId,
      pids: [...addCustPicked],
    });
    setAddCustPicked(new Set());
    setAddCustQuery("");
    setAddCustOpen(false);
  }, [activeCohortId, addCustPicked]);

  /**

   * The picker's candidates: the POOL minus the cohort's current members, narrowed by the

   * search. The pool's own order is kept (it leads with the biggest customers, which is the

   * useful default for "who am I adding").

   */
  const addCandidates = useMemo(() => {
    if (!addCustOpen) return [];
    const q = addCustQuery.trim().toLowerCase();
    const out: { pid: number; name: string }[] = [];
    for (const r of rawRows) {
      if (cohortMemberSet.has(r.pid)) continue;
      const name = String(r[lockedKey] ?? "");
      if (q && !name.toLowerCase().includes(q)) continue;
      out.push({ pid: r.pid, name });
    }
    return out;
  }, [addCustOpen, addCustQuery, rawRows, cohortMemberSet, lockedKey]);

  /**

   * Wave-6 item 11c β€” PIN. "Pin up to this field" freezes every visible column through the

   * clicked one; when the field sits past the clamp (8), it is REORDERED into the frozen

   * prefix first (the contract's wording). Pinning the identity column reads as "just the

   * identity" = the legacy 1, stored as ABSENT.

   *

   * ⚠ CORRECTED wave-14 item 15. This used to read "Grouped mode paints frozenCount 0 (spans

   * break under freezing)". **Spans do not break under freezing** β€” glide splits them

   * (`getSpanBounds` β†’ `[frozenRect, contentRect]`) and draws the row's contents from the frozen

   * half. What IS true, and is the real cost of the pin, is that those contents are then clipped

   * to the frozen strip's width; `fitGroupLabel` is what makes that clip honest. The clamp is

   * gone: `freezeColumns` is `frozenN` in every mode.

   */
  const visibleKeys = useMemo(
    () => order.filter((key) => visible.has(key)),
    [order, visible]
  );
  const frozenN = frozenCountOf(config);
  const pinFieldTo = useCallback(
    (key: string) => {
      const index = visibleKeys.indexOf(key);
      if (index < 0) return;
      if (index < MAX_FROZEN) {
        updateConfig({ ...config, frozenCount: clampFrozenCount(index + 1) });
        return;
      }
      const moved = visibleKeys.filter((k) => k !== key);
      moved.splice(MAX_FROZEN - 1, 0, key);
      let cursor = 0;
      const nextOrder = order.map((k) => (visible.has(k) ? moved[cursor++] : k));
      updateConfig({ ...config, order: nextOrder, frozenCount: MAX_FROZEN });
    },
    [visibleKeys, order, visible, config, updateConfig]
  );
  const unpinFields = useCallback(
    () => updateConfig({ ...config, frozenCount: undefined }),
    [config, updateConfig]
  );

  // Wave-6 item 10 β€” display-mode plumbing. W13 (contract C4 as AMENDED 2026-07-28):
  // `config.display` is the ONE home for the field picks, so leaving a mode must NOT
  // wipe them β€” returning to grid keeps the refs in the draft (mode 'grid' + refs;
  // cleanDisplay's carry), which is what lets the next Kanban/Calendar restore the
  // chosen field instead of feeding the select its default. A view that never picked
  // stays byte-identical (ref-less grid normalizes to absent, the legacy rule).
  const setDisplayMode = useCallback(
    (m: DisplayMode) => {
      // I12 (C3) β€” a locked view's MODE is frozen. The switcher is already hidden for one,
      // so reaching here means something other than the switcher asked; refuse rather than
      // trust the UI. (The host refuses too β€” this only stops the local state diverging from
      // what the host will store, which would look like a working change that never saved.)
      // (Resolved from `views` here rather than the `activeView` binding below β€” this
      // callback is declared above it.)
      const av = views.find((v) => v.id === activeViewId);
      if (av && isModeFrozen(av)) return;
      const spec = cleanDisplay(config.display);
      if (m === "grid") {
        updateConfig({
          ...config,
          display: spec ? cleanDisplay({ ...spec, mode: "grid" }) : undefined,
        });
        return;
      }
      updateConfig({ ...config, display: { ...(spec ?? {}), mode: m } });
    },
    [config, updateConfig, views, activeViewId]
  );
  // C4 (amended): the pick is written INTO display and the selects are FED from the
  // view def (`display.<field>`), never from component state that dies on unmount.
  const setDisplayField = useCallback(
    (k: "dateField" | "stackField" | "colorField" | "sizeField", key: string) => {
      const spec = cleanDisplay(config.display);
      if (!spec) return;
      // Wave-8 I3/I5: colour/size are OPTIONAL encodings, so "" is a real choice
      // (none) and must delete the ref rather than store an empty key that no
      // field can ever match.
      const next = { ...spec, [k]: key };
      if (!key) delete (next as Record<string, unknown>)[k];
      updateConfig({ ...config, display: next });
    },
    [config, updateConfig]
  );
  /**

   * Item 3 (C-DISP) β€” the kanban card clamp.

   *

   * ⚠ `undefined` DELETES the key rather than storing `true`. Absent means clamped, so a

   * stored `true` would be the default wearing a second name β€” and the host's `_clean_display`

   * accepts the literal `false` only, so a `true` would be dropped on save and the toggle

   * would look like it does not persist. Delete-to-default keeps both ends agreeing.

   */
  const setKanbanClamp = useCallback(
    (next: false | undefined) => {
      const spec = cleanDisplay(config.display);
      if (!spec) return;
      const display = { ...spec };
      if (next === false) display.kanbanClamp = false;
      else delete (display as Record<string, unknown>).kanbanClamp;
      updateConfig({ ...config, display });
    },
    [config, updateConfig]
  );
  /**

   * ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) β€” the swipe BINDING.

   *

   * ⚠ `undefined` DELETES the key, for `setKanbanClamp`'s reason one step further on. A swipe

   * binding is a single three-part thing (field + two options); both engines' `_clean_display`

   * DROP a half-binding rather than storing it, so writing one back would look like a save that

   * silently did not persist. Absent IS the unconfigured state.

   */
  const setSwipeSpec = useCallback(
    (next: SwipeSpec | undefined) => {
      const spec = cleanDisplay(config.display);
      if (!spec) return;
      const display = { ...spec };
      if (next) display.swipe = next;
      else delete (display as Record<string, unknown>).swipe;
      updateConfig({ ...config, display });
    },
    [config, updateConfig]
  );
  /**

   * ⭐⭐ WAVE-29 C4 / T29 (owner R7) β€” the FORM spec's writer, shaped exactly like `setSwipeSpec`

   * above it: `null` DELETES the key rather than storing an empty object, because "this view has

   * no form" and "this view has a form with nothing in it" are different states and only one of

   * them should survive a reload. `_clean_display` drops an empty bag anyway, so storing one

   * would make clearing a form look like it did not save.

   */
  const setFormSpec = useCallback(
    (next: FormSpec | null) => {
      const spec = cleanDisplay(config.display);
      if (!spec) return;
      const display = { ...spec };
      if (next) display.form = next;
      else delete (display as Record<string, unknown>).form;
      updateConfig({ ...config, display });
    },
    [config, updateConfig]
  );
  /**

   * Item 4 (C-DISP) β€” the per-day totals. An EMPTY list deletes the key rather than storing

   * `[]`: the always-on Records count is what an absent list means, so `[]` would be that

   * state wearing a second name β€” and `_clean_display` drops an empty array anyway, which

   * would make un-picking the last metric look like it did not save.

   */
  const setCalendarMetrics = useCallback(
    (next: { id: string; field: string; agg: string }[]) => {
      const spec = cleanDisplay(config.display);
      if (!spec) return;
      const display = { ...spec };
      const capped = next.slice(0, MAX_CALENDAR_METRICS);
      if (capped.length) display.calendarMetrics = capped;
      else delete (display as Record<string, unknown>).calendarMetrics;
      updateConfig({ ...config, display });
    },
    [config, updateConfig]
  );
  /** Item 4 (C-DISP) β€” records vs summaries. `records` is the default, so it deletes the key. */
  const setCalendarMode = useCallback(
    (next: "records" | "summary") => {
      const spec = cleanDisplay(config.display);
      if (!spec) return;
      const display = { ...spec };
      if (next === "summary") display.calendarMode = "summary";
      else delete (display as Record<string, unknown>).calendarMode;
      updateConfig({ ...config, display });
    },
    [config, updateConfig]
  );
  // The calendar's date field: the view's pick when it is still a real date-family field,
  // else `last_order`, else the first date-family field. The kanban's stack field: status or
  // single-select ONLY (a multiselect card in two columns at once is a count lie β€” contract).
  const dateFieldChoices = useMemo(
    () => fields.filter((f) => isDateFamilyType(f.type)),
    [fields]
  );
  const stackFieldChoices = useMemo(
    () => fields.filter((f) => f.type === "status" || f.type === "select"),
    [fields]
  );
  const pickBy = (want: string | undefined, choices: Field[], preferred?: string): Field | undefined => {
    const wanted = want ? choices.find((f) => f.key === want) : undefined;
    if (wanted) return wanted;
    const pref = preferred ? choices.find((f) => f.key === preferred) : undefined;
    return pref ?? choices[0];
  };
  // W13 (C4 as amended): the VIEW DEF's display feeds the pickers β€” the refs survive
  // every mode switch via cleanDisplay's grid carry. pickBy already falls back to the
  // default when the stored key no longer names an offerable field (a dropped ref).
  // I3/I5 β€” the map's encodings. Deliberately NOT resolved through `pickBy`:
  // that helper falls back to the first choice, which is right for the calendar
  // (a calendar must have a date) and wrong here, where "no encoding" is a
  // legitimate, and the DEFAULT, state. An unknown stored key resolves to
  // undefined = no encoding, which is also the dropped-ref behaviour.
  // I19c (C2) β€” the chart list lives in `config.display.charts`, so it rides the
  // existing view autosave + viewEcho reconcile and needs no new event type.
  const charts = useMemo<ChartSpec[]>(
    () => cleanCharts(displaySpec?.charts) ?? [],
    [displaySpec?.charts]
  );
  const setCharts = useCallback(
    (next: ChartSpec[]) => {
      const spec = cleanDisplay(config.display);
      if (!spec) return;
      const display = { ...spec, charts: next };
      if (!next.length) delete (display as Record<string, unknown>).charts;
      updateConfig({ ...config, display });
    },
    [config, updateConfig]
  );
  const colorFieldChoices = useMemo(
    () => fields.filter((f) => f.type === "status" || f.type === "select"),
    [fields]
  );
  const sizeFieldChoices = useMemo(
    () => fields.filter((f) => isNumericFieldType(f.type)),
    [fields]
  );
  const mapColorField = displaySpec?.colorField
    ? colorFieldChoices.find((f) => f.key === displaySpec.colorField)
    : undefined;
  const mapSizeField = displaySpec?.sizeField
    ? sizeFieldChoices.find((f) => f.key === displaySpec.sizeField)
    : undefined;
  const calendarField = pickBy(displaySpec?.dateField, dateFieldChoices, "last_order");
  const kanbanField = pickBy(displaySpec?.stackField, stackFieldChoices);
  /* ⭐ WAVE-27 item 8 (C3) β€” the BOUND field, resolved by key and NOT through `pickBy`. `pickBy`

     falls back to the first choice when the stored key is unknown, which is right for a kanban

     (a stack field is a preference) and wrong here: SwipeView SHOWS a rotted binding rather than

     guessing at one, so it must receive the loss instead of a silent substitute β€” the wave-7 trap

     [[wrong-parent-not-broken-control]] and the component's own header note both name. */
  const swipeField = displaySpec?.swipe
    ? fieldByKey.get(displaySpec.swipe.fieldKey)
    : undefined;
  // Calendar/kanban project the FULL pipeline result (a month/stack is its own bound), as
  // DISTINCT data rows β€” grouping can repeat a pid β€” with overlay edits layered so a dragged
  // card restacks and an edited title repaints without waiting on any echo (item 3c).
  const modeDataRows = useMemo(() => {
    if (
      displayMode !== "calendar" &&
      displayMode !== "kanban" &&
      displayMode !== "map" &&
      displayMode !== "chart" &&
      // C-TS close-out stitch: the panel's pids come from these rows; without this line the
      // time-series view asked its question about ZERO customers (caught by the mounted
      // judge β€” the node battery is blind here).
      displayMode !== "timeseries" &&
      /* ═══ W18-C CATALOG ═══ The designer's "add the products this view shows" door reads

         these rows β€” the same rows the toolbar counts, so the two can never disagree about

         which products the filter kept. The catalog's PAINT does not: it joins its stored

         codes against the whole pool, so a filter narrows what you can ADD and never what a

         finished page prints. ═══ end W18-C CATALOG ═══ */
      displayMode !== "catalog" &&
      /* ⭐ WAVE-27 item 8 (C3) β€” the swipe deck is these rows filtered to the undecided ones.

         Without this line the deck is derived from `[]`, so the view paints its "nothing left

         to decide" empty state over a table full of undecided records β€” the C-TS stitch above,

         repeated. */
      displayMode !== "swipe"
    )
      return [];
    const seen = new Set<number>();
    const out: Row[] = [];
    for (const vr of visibleRows) {
      if (vr.kind !== "data" || seen.has(vr.record.pid)) continue;
      seen.add(vr.record.pid);
      const edits = overlayEdits[vr.record.pid];
      out.push(edits ? { ...vr.record, ...edits } : vr.record);
    }
    return out;
  }, [displayMode, visibleRows, overlayEdits]);
  // Owner item 1 β€” the CALL-SITE half of the kanban memo. `KanbanView` is `memo`'d now, but a
  // memo whose props are rebuilt every render never bails, and these two were: `cardKeys` is a
  // fresh array from `.filter().slice()`, `onMove` a fresh closure. With them stable, a
  // `detailPid` change (clicking a card) re-renders the modal and skips the board entirely β€”
  // which is the whole of "laggy record-open". Everything else KanbanView takes was already
  // stable: `modeDataRows`/`fieldByKey` are useMemos, `kanbanField` is a reference INTO the
  // `stackFieldChoices` useMemo, and `onOpen={setDetailPid}` is a setState identity.
  const kanbanCardKeys = useMemo(
    () =>
      kanbanField
        ? visibleKeys.filter((k) => k !== lockedKey && k !== kanbanField.key).slice(0, 3)
        : [],
    [visibleKeys, lockedKey, kanbanField]
  );
  const onKanbanMove = useCallback(
    (pid: number, value: string) => {
      if (!kanbanField) return;
      patchAndRecord(pid, { [kanbanField.key]: value }, "a card move");
    },
    [kanbanField, patchAndRecord]
  );
  /* ⭐ WAVE-27 item 8 (C3) β€” a swipe writes through the NORMAL cell door, the same

     `patchAndRecord` a card move uses. That is the whole reason the deck needs no permission

     logic, no undo entry and no echo handling of its own: it inherits all three. */
  const onSwipeDecide = useCallback(
    (pid: number, value: string) => {
      if (!swipeField) return;
      patchAndRecord(pid, { [swipeField.key]: value }, "a swipe");
    },
    [swipeField, patchAndRecord]
  );
  /**

   * ⭐ WAVE-26 ITEM 12 (owner ruling R8) β€” the kanban's "Add option" door.

   *

   * It opens the ORDINARY ColumnMenu on the stack field, straight into its Edit-field pane. So

   * the option is written into the SHARED field definition by the same `onRetype` upsert the

   * header menu uses β€” never a per-view list β€” and every guarantee that editor already carries

   * (permission wall, rename-by-row-identity, option colours, one upsert for name+choices) comes

   * along without being re-implemented. R8's "do not invent a second options editor", literally.

   *

   * β›” THE PERMISSION QUESTION IS NOT `canEditField`. Adding an option changes the column's

   * DEFINITION; `mayEditField` answers who may type a VALUE into it, and conflating the two is

   * the confusion [[schema-role-is-not-a-value-wall]] exists to prevent. The right predicate is

   * the one that decides whether `onRetype` is supplied at all β€” a created overlay field β€” so it

   * is written ONCE here and read at both doors.

   *

   * `null` (not "absent") when the field cannot take one: a status column is computed by the

   * source system, and an Odoo select's vocabulary lives in Odoo.

   *

   * ⭐ THE PREDICATE ADMITS AN AUTOMATION'S `stage_<id>` COLUMN, and that is INTENDED rather than

   * incidental β€” worth stating because it was arrived at by matching `onRetype`'s condition, and

   * a coincidence and a decision look identical in code. It is exactly what R6 and R8 compose

   * to: R6 deleted the board's built-in terminals, so the lanes a review stage offers are now

   * only the ones a user defined β€” and R8 is the control that lets them define one. Landed

   * without this the pair is worse than either alone (SESSION A's A-7 says the same thing from

   * the engine side: `humanMoves` had to learn to admit user-added options, or the move door

   * would refuse the lane the product just invited you to create).

   * ⚠ CARRIED CONSEQUENCE, pre-existing and not introduced here: the pane this opens is the

   * whole Edit-field window, so it also offers the TYPE picker β€” one wrong click retypes a stage

   * column. The header menu has offered exactly that on the same column since wave 6; this door

   * adds a second way in, not a new hazard. Written down rather than left to be rediscovered.

   */
  /* ⭐ WAVE-29 T27: the same stratum predicate as the Edit-field pane, for the same reason β€” this

     door OPENS that pane, so gating the two differently means offering an add-option control that

     leads to a pane with no editor in it. On a `ut_*` kanban (every automation board) the old

     `custom` test was false for every column, so the lane header offered nothing. */
  const kanbanCanAddOption =
    !!kanbanField && kanbanField.type === "select" &&
    isUserSchemaField(kanbanField, isUserTable);
  const onKanbanAddOption = useCallback(
    (anchor: AnchorRect) => {
      if (!kanbanField) return;
      setColumnMenu({ fieldKey: kanbanField.key, anchor, pane: "edit" });
    },
    [kanbanField]
  );
  const onListToggleGroup = useCallback((groupKey: string) => {
    setCollapsed((current) => {
      const next = new Set(current);
      if (next.has(groupKey)) next.delete(groupKey);
      else next.add(groupKey);
      return next;
    });
  }, []);
  /**

   * Item 7 (C-TS) β€” the pid set the time series asks about: exactly the rows the current

   * filter kept, so the panel and the toolbar count can never disagree about "who".

   *

   * `modeDataRows` is already the de-duplicated data rows for a non-grid mode, so this is a

   * projection of it and NOT a second pipeline. The server intersects with the caller's book

   * anyway β€” this narrows the question, it can never widen the answer.

   */
  const timeseriesPids = useMemo(
    () => (displayMode === "timeseries" ? modeDataRows.map((r) => r.pid) : []),
    [displayMode, modeDataRows]
  );
  /* ═══ W18-C CATALOG ═══ (owner item 4, contract C6)

     The catalogs this view holds, and the door that persists an edit to them.



     `displaySpec.catalogs` is ALREADY validated β€” `cleanDisplay` ran `cleanCatalogs` over it on

     read β€” so there is no second normalisation here and no chance of the two disagreeing.



     ⚠ The write goes through `updateConfig` exactly like `onTimeseriesDisplay` below, which

     means a catalog edit is a VIEW-CONFIG save. That is the point: a catalogue is authored

     content and has to survive a reload, and the display spec is the only per-view store the

     grid has. It also means the 500-code / 40-page / 12-catalog caps are enforced twice on the

     round trip (here on read, and by the host's `_clean_catalogs` on write) β€” the designer

     states its budget in the toolbar so the cap is never the user's first news of it. */
  const catalogs = useMemo<CatalogSpec[]>(
    () => (displayMode === "catalog" ? (displaySpec?.catalogs ?? []) : []),
    [displayMode, displaySpec]
  );
  /** The codes the current filter kept β€” the designer's "add what the view shows" shortcut.

   *  Derived from `modeDataRows`, so it counts what the toolbar counts. */
  const catalogFilteredCodes = useMemo(
    () =>
      displayMode === "catalog"
        ? modeDataRows
            .map((r) => r[CATALOG_CODE_FIELD])
            .filter((c): c is string => typeof c === "string" && !!c)
        : [],
    [displayMode, modeDataRows]
  );
  const onCatalogs = useCallback(
    (next: CatalogSpec[]) => {
      const spec = cleanDisplay(config.display) ?? { mode: "catalog" as const };
      updateConfig({ ...config, display: { ...spec, catalogs: next } });
    },
    [config, updateConfig]
  );
  /* ═══ end W18-C CATALOG ═══ */
  /** Persist a bucket/span/metric pick onto the view, the way every other display key rides. */
  const onTimeseriesDisplay = useCallback(
    (next: Partial<DisplaySpec>) => {
      const spec = cleanDisplay(config.display) ?? { mode: "timeseries" as const };
      updateConfig({ ...config, display: { ...spec, ...next } });
    },
    [config, updateConfig]
  );
  const kanbanCanMove =
    !!kanbanField && kanbanField.type === "select" && canEditField(kanbanField);
  const kanbanReason = !kanbanField
    ? null
    : kanbanField.type === "status"
      ? `Stacked by ${kanbanField.label} β€” read-only, computed from the source system.`
      : !canEditField(kanbanField)
        ? "You do not have permission to edit this field, so cards cannot be moved."
        : null;
  /* ⭐ WAVE-27 item 8 (C3) β€” the kanban pair, said again for the deck. Same wall, same words

     shaped for the gesture: a swipe writes a VALUE, so `canEditField` is the right predicate. */
  const swipeCanWrite = !!swipeField && swipeField.type === "select" && canEditField(swipeField);
  const swipeReason = !swipeField
    ? null
    : swipeField.type === "status"
      ? `Bound to ${swipeField.label} β€” read-only, computed from the source system.`
      : !canEditField(swipeField)
        ? "You do not have permission to edit this field, so records cannot be decided."
        : null;

  if (loading || !workspaceReady) {
    /* wave17 GRID β€” item 3 / owner R6: one small bare rotating icon, NO WORDS. `aria-label`

       is not a word on screen and stays: `.lp-spin` is an empty span, so without it the wait

       is announced to a screen reader as nothing at all. (C-SPIN, SHELL defines the class.)

       `--lg` because this is the case C-SPIN sizes it for β€” the whole surface is this mark and

       nothing else, where the 14px version "reads as dust". */
    return (
      <div className="cg-loading">

        <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" />

      </div>
    );
  }

  const activeView = views.find((view) => view.id === activeViewId);
  // Cohort mode's toolbar control (rendered by Toolbar via the `cohortAction` slot; the popover
  // it opens is with the other overlays at the bottom). Disabled without an active cohort β€”
  // zero cohorts is the host page's near-empty state, not this button's error to explain.
  const cohortAction = cohortMode ? (
    <button

      type="button"

      className="cg-tb-btn cg-tb-addcust"

      ref={addCustRef}

      disabled={!activeCohortId}

      onClick={() => setAddCustOpen((o) => !o)}

      aria-expanded={addCustOpen}

      aria-haspopup="dialog"

    >

      + Add customers

    </button>
  ) : undefined;
  // Wave-7 item W9 β€” the Fields panel's permanent delete rides the SAME wall as the
  // column menu's Delete: created strata only (`custom`), never the locked identity
  // column. One predicate, two doors.
  //
  // ⚠ WAVE-29 T22 NARROWED WHAT THIS SET CONTAINS, and the narrowing is CORRECT rather than an
  // oversight β€” said out loud because it looks like a regression. A grid-created column on a
  // `ut_*` database now lives in the shared DEFINITION and carries no `custom` flag, so it drops
  // out of this set. It has to: this door emits `field_delete`, which scrubs the per-user
  // workspace overlay β€” a bucket the definition never reads β€” so the column would vanish for one
  // paint and be back on the next fetch (`deleteDefinitionField`'s note says the same thing from
  // the other side). β›” The consequence is real and is NOT silently widened here: a definition
  // column can only be deleted through the column menu, which offers it for `link`/`rollup`/
  // `formula` alone (D-114's deliberate narrowness β€” every other kind holds real values). Booked
  // as pending work rather than fixed by handing a type-blind delete to a panel.
  const deletableKeys = new Set(
    fields.filter((f) => f.custom && f.key !== lockedKey).map((f) => f.key)
  );
  const menuField = columnMenu ? fieldByKey.get(columnMenu.fieldKey) : undefined;
  // Wave-5 item 3 β€” what the CURRENT VIEW does with the menu's field, so the conditional
  // "Don't sort/filter/group" entries render exactly when they apply.
  const menuSortedDir = menuField
    ? config.sorts.find((s) => s.colId === menuField.key)?.dir ?? null
    : null;
  const menuIsFiltered = menuField
    ? treeNamesField(config.filters, menuField.key, measureCols)
    : false;
  // Item 11c β€” is the menu's field the current frozen boundary (its Pin would be a no-op)?
  const menuVisIndex = menuField ? visibleKeys.indexOf(menuField.key) : -1;
  const menuPinnedTo = menuVisIndex >= 0 && frozenN > 1 && menuVisIndex + 1 === frozenN;
  // Item 10 β€” the toolbar's mode switcher (grid-only on windowed tables, see displayMode).
  const modeControl = serverWindowed || embedded ? undefined : (
    <ModeSwitch

      mode={displayMode}

      onMode={setDisplayMode}

      // I12 (C3) β€” a locked view's mode is frozen, so the switcher stops being a switcher.

      // The field pickers beside it stay: C3 freezes the MODE, and a kanban's stack field is

      // config, not mode ("filters/sorts/columns stay editable").

      locked={!!activeView && isModeFrozen(activeView)}

      dateField={calendarField}

      dateChoices={dateFieldChoices}

      stackField={kanbanField}

      stackChoices={stackFieldChoices}

      colorField={mapColorField}

      colorChoices={colorFieldChoices}

      sizeField={mapSizeField}

      sizeChoices={sizeFieldChoices}

      onPickField={setDisplayField}

      // Items 3 + 4 (C-DISP). `kanbanClamp` is absent-means-clamped, so the boolean handed

      // down is `!== false` rather than a truthiness test β€” the one place that distinction

      // decides whether the user's opt-out survives a reload.

      clamped={displaySpec?.kanbanClamp !== false}

      onClamp={setKanbanClamp}

      calendarMode={displaySpec?.calendarMode ?? "records"}

      onCalendarMode={setCalendarMode}

      calendarMetrics={displaySpec?.calendarMetrics}

      // The numeric family, exactly what C-DISP makes eligible β€” and the same memo the map's

      // bubble-size picker feeds from, so "what can be totalled" has one definition.

      metricChoices={sizeFieldChoices}

      onCalendarMetrics={setCalendarMetrics}

    />
  );
  // ⭐ Wave-23 C7 β€” the open document, resolved exactly like the picker's value below it:
  // the OPTIMISTIC edit wins over the raw record, so a save the server has not echoed yet is
  // what re-opening the cell shows (the echo-suppression law β€” reading the raw row here would
  // make a just-saved document appear to revert).
  const jsonField = jsonAt ? fieldByKey.get(jsonAt.fieldKey) : undefined;
  const jsonRow = jsonAt ? rawRows.find((r) => r.pid === jsonAt.pid) : undefined;
  const jsonValue = String(
    (jsonAt && overlayEdits[jsonAt.pid]?.[jsonAt.fieldKey])
    ?? (jsonField && jsonRow ? jsonRow[jsonField.key] : "")
    ?? ""
  );
  const linkField = linkAt ? fieldByKey.get(linkAt.fieldKey) : undefined;
  const linkRow = linkAt ? rawRows.find((row) => row.pid === linkAt.pid) : undefined;
  const linkValue = String(
    (linkAt && overlayEdits[linkAt.pid]?.[linkAt.fieldKey])
    ?? (linkField && linkRow ? linkRow[linkField.key] : "")
    ?? ""
  );
  const linkedRecordIds = [...new Set(
    linkValue.split(",").map((part) => Number(part.trim())).filter(
      (pid) => Number.isInteger(pid) && pid > 0
    )
  )];
  const pickerField = picker ? fieldByKey.get(picker.fieldKey) : undefined;
  // A `user` field's choices come from the HOST's real user list, a `select`'s from its own
  // definition β€” so an assignee is always someone who can log in, and a status is always one of
  // the choices the column was created with.
  const pickerChoices = !pickerField
    ? []
    : pickerField.type === "user"
      ? payload?.userOptions ?? []
      : choiceOptions(pickerField);
  const pickerRow = picker ? rawRows.find((r) => r.pid === picker.pid) : undefined;
  const pickerValue = String(
    (picker && overlayEdits[picker.pid]?.[picker.fieldKey])
    ?? (pickerField && pickerRow ? pickerRow[pickerField.key] : "")
    ?? ""
  );
  // A multiselect cell is a SET: choices TOGGLE and the picker stays open for the next pick
  // (item 5). Single select/user keep pick-and-close.
  const pickerMulti = pickerField?.type === "multiselect";
  const pickerParts = pickerMulti ? splitMulti(pickerValue) : [];
  /** Item 6 β€” which choice receives focus when the picker opens: the current value where it

   *  still exists in the list, else the first choice. Keyboard-only editing starts HERE. */
  const pickerFocusChoice = !pickerChoices.length
    ? null
    : pickerMulti
      ? pickerParts.find((p) => pickerChoices.includes(p)) ?? pickerChoices[0]
      : pickerChoices.includes(pickerValue)
        ? pickerValue
        : pickerChoices[0];

  return (
    // `data-today` is the TENANT'S day, exactly as the payload delivered it. It is here so the
    // date every relative condition resolves against is OBSERVABLE rather than inferred: a live
    // QA that reads its own clock instead compares two engines on "now" and fails whenever a run
    // straddles midnight β€” which is the flake harness/windows.py takes `today` as a parameter to
    // avoid, reintroduced one layer up. It cost a false failure (57 vs 55, both correct, one
    // computed either side of a date change) to notice.
    // `data-measure-rules` / `data-measure-sets` are BUG-1's handshake, published the same way
    // and for the same reason as `data-today`: a measure condition stuck on "Calculating…"
    // renders identically whether the rule carries no id, the host resolved nothing, or the two
    // sides name the rule differently β€” and only the first of those is ours. A console.log
    // cannot serve this: the grid runs in an iframe that is CROSS-ORIGIN on the Space, and every
    // Streamlit rerun replaces it. An attribute survives the remount and is one `get_attribute`
    // away from any harness, local or deployed.
    <div
      className="cg-shell"
      data-today={today ?? ""}
      data-measure-rules={measureRuleKeys}
      data-measure-sets={measureSetKeys}
    >
      {/* ⭐ wave17 R1 / C-LOCKV β€” the COHORT SIDEBAR is gone, and with it the last surface that
          treated a cohort as its own kind of object. `CohortSidebar` was the retired `#/cohort`
          page's left panel: a second rail, with its own rename, delete, export and folder
          machinery, over `workspace.lists`. Under R1 a cohort IS a saved view, so the Views rail
          below renders every one of them and the second rail has nothing to switch between.
          ⚠ `lists` is NOT gone with it β€” it stays the membership channel that feeds `cohortSets`
          (C-LOCKV point 2), which is what the lock resolves against. */}
      {!hideViews && (
        <ViewSidebar
            // Item 12 (C-LOCK) β€” the rail's menu is the only emitter of a SAVED `cohortLock`.
            onCohortLock={onViewCohortLock}
            /**
             * ⭐ ITEM 5 (C7) β€” the rail's order, corrected by the drag this browser just made.
             *
             * ⚠ APPLIED AT THE RAIL, NOT TO `views` ITSELF, and the distinction is load-bearing.
             * `views` is the workspace's list and half this component keys off it (selection,
             * autosave, the echo reconcile, `uniqueDisplayName`). A view ORDER is a rendering
             * fact about ONE surface; folding it into the state would make every consumer's
             * behaviour depend on a drag, and the drag's whole scope is which row sits where.
             */
            views={applyViewOrder(views, folderStamps, Date.now())}
            alertCounts={alertCounts}
            activeViewId={activeViewId}
            saveState={saveState}
            onSelect={selectView}
            onCreate={createView}
            onRename={renameView}
            onNote={setViewNote}
            onDuplicate={duplicateView}
            onDelete={deleteView}
            lists={lists}
            // ⭐ WAVE 21 item 11 (R10) β€” offered on a CLIENT-MODE table only, the same
            // condition "Add to locked view" and Export already carry. A windowed table
            // holds ONE PAGE of the matched set (CG-3), so "not found" would mean "not on
            // this page" for most of a list β€” precisely the silent cap R10 rules out.
            onSelectFromFile={serverWindowed ? undefined : () => setSelectFromFile(true)}
            /* ⭐ WAVE-29 T25 (owner item 6) β€” the Import door, offered ONLY where records can be
               added. `canMutateRecords` is `isUserTable && recordsMutable`: the same predicate the
               "+" row and the delete path read, so a locked database (an Odoo mirror, an
               automation-owned child table) has no Import row at all rather than an Import that
               fails at the server. */
            onImport={canMutateRecords ? () => setImportOpen(true) : undefined}
            onAddToList={serverWindowed ? undefined : addToList}
            today={today}
            onExport={serverWindowed ? undefined : exportViewData}
            folders={folders}
            folderIdOf={folderIdOf}
            onFolderCreate={(name, icon) => {
              const id = newFolderId();
              // Bounded: reconcileFolders drops a local entry once the echo
              // carries it or its create stamp ages out, so this only has to not
              // grow without limit.
              // C5 (I15): the icon rides the LOCAL entry too, or the folder the user just
              // styled renders grey for one round trip and then changes colour under them.
              setLocalFolders((prev) => [...prev.slice(-31), { id, name, order: 9_999, icon }]);
              stampFolder((p) => ({ ...p, created: { ...p.created, [id]: Date.now() } }));
              emitHostEvent({
                id: eventId("foldnew"),
                type: "folder_create",
                surface: "views",
                folderId: id,
                name,
                icon,
              });
            }}
            onFolderRename={(folderId, name) => {
              stampFolder((p) => ({
                ...p,
                renamed: { ...p.renamed, [folderId]: { at: Date.now(), name } },
              }));
              emitHostEvent({
                id: eventId("foldren"),
                type: "folder_rename",
                surface: "views",
                folderId,
                name,
              });
            }}
            onFolderDelete={(folderId) => {
              // The tombstone is stamped BEFORE the emit: between the click and the
              // echo the payload still lists the folder, and rendering it again for
              // one round trip is the delete blip (folders.ts).
              stampFolder((p) => ({ ...p, deleted: { ...p.deleted, [folderId]: Date.now() } }));
              emitHostEvent({
                id: eventId("folddel"),
                type: "folder_delete",
                surface: "views",
                folderId,
              });
            }}
            onFolderDuplicate={(folderId) => {
              const newId = newFolderId();
              const src = folders.find((f) => f.id === folderId);
              setLocalFolders((prev) => [
                ...prev.slice(-31),
                { id: newId, name: `${src?.name ?? "Folder"} copy`, order: 9_999 },
              ]);
              stampFolder((p) => ({ ...p, created: { ...p.created, [newId]: Date.now() } }));
              emitHostEvent({
                id: eventId("folddup"),
                type: "folder_duplicate",
                surface: "views",
                folderId,
                newId,
              });
            }}
            onFolderReorder={(order) => {
              // A-S4-1 (item 19). S4 built the drag and the reconcile behind an OPTIONAL prop, so
              // its absence silently disabled the whole feature rather than breaking anything β€”
              // which is why every gate stayed green while folders would not drag at all. The
              // stamp is what stops the rail snapping back for one round trip (the echo window).
              stampFolder((p) => ({ ...p, ordered: { at: Date.now(), order } }));
              emitHostEvent({
                id: eventId("foldord"),
                type: "folder_reorder",
                surface: "views",
                order,
              });
            }}
            /**
             * ⭐ WAVE 27 Β· OWNER ITEM 5 (contract C7) β€” the rail's new VIEW order.
             *
             * Three things happen and each one is needed:
             *   Β· the LOCAL list is reordered, so the row lands where it was dropped and stays
             *     there for this render;
             *   Β· a STAMP is written, so the next workspace echo β€” which is one round trip
             *     behind and still carries the server's order β€” does not snap it back
             *     (`applyViewOrder` in folders.ts holds it for the echo window and no longer);
             *   Β· ONE event carries the WHOLE order, never a delta. A partial list cannot say
             *     where an UNNAMED view went, so "moved B after C" leaves every other position
             *     to be re-derived by two sides that can disagree. The server's own
             *     `folder_reorder` note states this rule; the same rule, same door.
             *
             * ⚠ AMENDMENT C7-A1 (2026-08-08, SESSION C): the event is
             * `{type: "view_reorder", surface: "views", order}` β€” `surface`, not `workspace`.
             * The contract said `{workspace, order}`; the door `grid_events.py:1299` actually
             * opens on `surface ∈ FOLDER_SURFACES`, and the TABLE is resolved from the request
             * context rather than the payload (`_store_of(ctx)`). Emitting a key the handler
             * does not read would have shipped a drag that persists nothing, behind a green
             * gate on each side.
             */
            onViewReorder={(order) => {
              setViews((cur) => {
                const byId = new Map(cur.map((v) => [v.id, v]));
                const out: SavedView[] = [];
                const placed = new Set<string>();
                for (const id of order) {
                  const v = byId.get(id);
                  if (!v || placed.has(id)) continue;
                  placed.add(id);
                  out.push(v);
                }
                // Anything the order does not name keeps its current place, after the named
                // ones β€” never dropped. A view created in another tab is not evidence the
                // drop was wrong.
                for (const v of cur) if (!placed.has(v.id)) out.push(v);
                return out;
              });
              stampFolder((p) => ({ ...p, orderedViews: { at: Date.now(), order } }));
              // β›” ONE CAST, AT ONE SITE, WITH A RATCHET BEHIND IT (ASK ->D, wave-27 mailbox
              // C-6). `HostEvent`'s union lives in `types.ts`, which is SESSION D's file, and
              // D owns C7's persistence half β€” so the member `{ id; type: "view_reorder";
              // surface: FolderSurface; order: string[] }` is theirs to add. Until it lands
              // this emit cannot be typed from here.
              // ⚠ The gap is DECLARED, not hidden: `verify_wiring.py`'s
              // `PENDING_UNION_MEMBERS` carries `view_reorder`, prints the ask, and goes RED
              // the moment `types.ts` gains the member β€” which forces this cast to be deleted
              // in the same change. That is the D-70 ratchet's shape, and it fired on its own
              // this wave, which is the argument for reusing it rather than a comment.
              emitHostEvent({
                id: eventId("vieword"),
                type: "view_reorder",
                surface: "views",
                order,
              } as unknown as HostEvent);
            }}
            onItemMove={(viewId, folderId) => {
              stampFolder((p) => ({
                ...p,
                moved: { ...p.moved, [viewId]: { at: Date.now(), folderId } },
              }));
              emitHostEvent({
                id: eventId("itemmove"),
                type: "item_move",
                surface: "views",
                itemId: viewId,
                folderId,
              });
            }}
            folderAddPreview={serverWindowed ? undefined : folderAddPreview}
            onFolderAddToList={serverWindowed ? undefined : folderAddToList}
            viewer={viewer}
            onToggleLock={toggleViewLock}
            onToggleImportant={toggleViewImportant}
            userOptions={payload?.userOptions}
        />
      )}
      <main className="cg-main">
        <Toolbar
          nouns={topic.nouns}
          // Item 12 (C-LOCK) β€” the banner's copy. ⚠ BOTH fields are omitted when this reader
          // cannot see the locked set, and that omission is the SIGNAL, not an oversight: it
          // is what selects RECORD's second sentence ("locked to a set you cannot see").
          // Inventing a name or a count for a set we were given no membership for would be
          // disclosing the very thing the permission gate withheld.
          cohortLock={cohortLockChip}
          // Wave-14 close-out stitch (HOST): PANEL's item-13 door β€” absent, the
          // copy-configuration modal renders nowhere (absent beats present-and-inert).
          // `updateConfig` takes a FULL config, so the partial patch spreads over the
          // live one; `copyConfig.ts` computed it against this same view's config.
          copyViews={views.filter((v) => v.id !== activeViewId)}
          onCopyConfig={(patch) => updateConfig({ ...config, ...patch })}
          fields={fields}
          visible={visible}
          lockedKey={lockedKey}
          onColumnVisible={setColumnVisible}
          onColumnsVisible={(keys) =>
            updateConfig({
              ...config,
              visible: [...new Set([lockedKey, ...keys])],
            })
          }
          // Owner item 23 β€” the Hide-fields panel lists and reorders COLUMN order, so it is
          // handed the ordered projection, not the definition-ordered `fields` above.
          // `order` is `useGridColumns`' reconciled copy (locked key first, unknown keys
          // dropped, new keys appended), so the list can never show a field the grid does not
          // have or omit one it does.
          orderedFields={orderedFields}
          onFieldOrder={(keys) => updateConfig({ ...config, order: keys })}
          deletableKeys={deletableKeys}
          onDeleteField={deleteField}
          colorOn={config.colorBy !== null}
          onToggleColor={(on) =>
            updateConfig({
              ...config,
              colorBy: on
                ? fields.find((field) => field.type === "status")?.key ?? null
                : null,
            })
          }
          rowHeightMode={config.rowHeightMode}
          onRowHeightMode={(rowHeightMode) => updateConfig({ ...config, rowHeightMode })}
          filters={config.filters}
          onFilters={(filters) => updateConfig({ ...config, filters })}
          filterConj={config.filterConj ?? "and"}
          onFilterConj={(filterConj) => updateConfig({ ...config, filterConj })}
          sorts={config.sorts}
          onSorts={(sorts) => updateConfig({ ...config, sorts })}
          // the toolbar must not advertise a grouping the pipeline is not applying
          groupBy={serverWindowed ? null : config.groupBy}
          onGroupBy={(groupBy) => updateConfig({ ...config, groupBy })}
          statusValues={statusValues}
          measures={measures}
          unresolvedCount={unresolvedCount}
          lists={lists}
          pendingMeasureCount={pendingMeasureCount}
          search={search}
          onSearch={setSearch}
          recordCount={recordCount}
          scopeCounts={payload?.counts}
          pool={payload?.workspace?.pool}
          serverWindowed={serverWindowed}
          cohortAction={cohortAction}
          filterSeed={filterSeed}
          modeControl={modeControl}
        />
        {/* Wave-10 item 9: the view's description used to render HERE, as a full-width band
            between the toolbar and the grid β€” it cost every row a strip of vertical space and
            read as an alert rather than as a label. It now sits under the view's name in the
            rail (ViewSidebar), where it annotates the thing it describes. */}
        <div
          className="cg-grid-box"
          ref={gridBoxRef}
          // Item 19 β€” THE dismissal. Not glide's out-of-bounds hover: the button sits over the
          // canvas, so reaching for it IS an out-of-bounds event and dismissing there would
          // unmount the control under the arriving pointer. Leaving the whole grid box is the
          // honest "you are done with this row".
          onMouseLeave={() => setExpandAt((prev) => (prev === null ? prev : null))}
        >
          {displayMode === "grid" && (
            <>
            <DataEditor
              ref={gridRef}
              columns={visibleCols}
              getCellContent={getCellContent}
              rows={displayRows.length}
              theme={lightTheme}
              // ⭐ Wave-14 item 15 (R8) β€” was `config.groupBy ? 0 : frozenN`: a grouping UNPINNED
              // EVERY column, which is the "the first field does not stay pinned" the owner
              // reported. The clamp existed on the assumption that glide cannot draw a group
              // bar's `span` across the freeze boundary. **It can, and it is built for it.**
              // `getSpanBounds` (`data-grid-render.walk.js`) returns `[frozenRect, contentRect]`
              // β€” it SPLITS a straddling span in two β€” and the cell renderer keys its
              // already-drawn set on `${row},${startCol},${endCol},${c.sticky}` so the same span
              // is drawn once per pass, taking `areas[0]` when sticky and `areas[1]` when not.
              // The scrollable half then sets `skipContents = true`, so the bar's TEXT is painted
              // by the frozen half and its background continues across the scroll region.
              // Net effect, which is exactly what was wanted: with a grouping active the group
              // label rides the pinned first column and stays readable while you scroll right.
              freezeColumns={frozenN}
              /**
               * ⭐⭐ WAVE-29 T33 (owner item 17) β€” the totals row is glide's OWN frozen trailing
               * row, which is why it is aligned to every column width for free.
               *
               * β›” `showTotals ? 1 : 0`, never a bare `1`: with no totals row appended, freezing
               * one trailing row would pin the LAST DATA RECORD to the bottom of the viewport β€”
               * a record that then appears twice while scrolling, which reads as duplicated data
               * rather than as a layout bug.
               */
              freezeTrailingRows={showTotals ? 1 : 0}
              rowHeight={rowHeight}
              headerHeight={36}
              rowMarkers="both"
              // ═══ W18-B VOID ═══ PINNED, not left to default. The marker column is part of
              // the content width the void's right-hand edge is measured from, and a width we
              // merely predicted could disagree with the one glide drew β€” four pixels of white
              // against the tint, visible on screen and invisible to every gate. `rowMarkerPx`
              // reproduces glide's own ladder verbatim (data-editor.js:103), so this changes no
              // pixel of the marker column; it only makes its width a number we own.
              // ═══ end W18-B VOID ═══
              rowMarkerWidth={rowMarkerPx(displayRows.length)}
              /**
               * ⭐⭐ W30-T42 (contract C2) β€” THE SCROLL THAT ASKS FOR THE NEXT WINDOW.
               *
               * ⚠ The W18-B VOID note above says there is deliberately no such handler "anywhere
               * near it", and that stays true of the void, which is arithmetic over the box and
               * must not become scroll-tracking. This one is a different subject: how far down
               * the LOADED rows the viewport has reached, which is the only question a windowed
               * grid can answer paging with. It is a no-op on every whole-book table (the
               * callback returns on `!serverWindowed` before reading anything).
               */
              onVisibleRegionChanged={onVisibleRegionChanged}
              gridSelection={gridSelection}
              onGridSelectionChange={onGridSelectionChange}
              getRowThemeOverride={getRowThemeOverride}
              onItemHovered={onItemHovered}
              onCellClicked={onCellClicked}
              onCellActivated={onCellActivated}
              onCellEdited={onCellEdited}
              onPaste={onGridPaste}
              // R4 β€” Backspace/Delete over a selection is ONE undoable action. Returning
              // `false` from here takes the write over from glide's per-cell path.
              onDelete={onGridDelete}
              validateCell={validateCell}
              onColumnResize={onColumnResize}
              onColumnMoved={onColumnMoved}
              onColumnProposeMove={onColumnProposeMove}
              drawHeader={drawGridHeader}
              onHeaderMenuClick={(column, bounds) => openHeaderMenu(column, bounds)}
              onHeaderClicked={onHeaderClicked}
              onHeaderContextMenu={onHeaderClicked}
              onKeyDown={onGridKeyDown}
              maxColumnWidth={600}
              getCellsForSelection={true}
              rowSelectionMode="multi"
              smoothScrollX
              smoothScrollY
              width={gridSize.width}
              height={gridSize.height}
              customRenderers={[ratingCellRenderer, userCellRenderer, imageCellRenderer]}
              headerIcons={HEADER_ICONS}
              rightElement={embedded ? undefined : (
                // Wave-6 item 4 β€” the "+" of the header row: the create-field form,
                // insert-at-end.
                //
                // ⚠ Wave-20 owner item 5 UNPINNED it. It used to be `sticky: true` ("so it
                // stays visible however far the columns scroll"), which parked it against the
                // right edge of the WINDOW β€” on a four-column table that is half a screen of
                // white between the last field and the control that adds the next one, and it
                // reads as page chrome rather than as part of the table. It now sits
                // immediately after the last column, where Airtable puts it.
                //
                // TWO changes are needed and neither works alone: `sticky:false` stops glide
                // pinning the wrapper (`infinite-scroller.js:204` sets `right` only when
                // sticky), and the CSS region kills `.dvn-spacer`'s `flex-grow: 1`, which
                // would otherwise expand to fill the scroller and push the button right back
                // to the edge. Consequence, accepted: on a table wider than the viewport the
                // "+" is off-screen until you scroll to the end of the columns β€” which is
                // where the new column is going to land anyway.
                <button
                  type="button"
                  className="cg-add-field-btn"
                  aria-label="Add field"
                  title="Add a field"
                  onClick={(event) => {
                    const r = event.currentTarget.getBoundingClientRect();
                    setPlusMenu({
                      left: r.left,
                      top: r.top,
                      right: r.right,
                      bottom: r.bottom,
                      width: r.width,
                      height: r.height,
                    });
                  }}
                >
                  +
                </button>
              )}
              rightElementProps={{ sticky: false, fill: false }}
              // Owner item 4 (R8) β€” the trailing "+" row, USER DATABASES ONLY. Passing
              // `onRowAppended` is what makes glide paint the ghost row at all, so the
              // affordance exists exactly where a POST can succeed. See `appendRow`.
              onRowAppended={canMutateRecords ? appendRow : undefined}
              trailingRowOptions={
                canMutateRecords
                  ? {
                      // The hint sits in the identity column (targetColumn 0), which is the
                      // one a new record is named in β€” the same cell the cursor lands on.
                      hint: "New record",
                      sticky: false,
                      targetColumn: 0,
                    }
                  : undefined
              }
            />
            {/* ═══ W18-B VOID ═══ (wave 18, owner item 1b / ruling R12) β€” the two rectangles.

                They are SIBLINGS of the canvas, immediately after it and before everything else
                `.cg-grid-box` holds, which is the whole of their stacking story: `z-index: auto`
                plus tree order puts them over the canvas, and `.cg-selbar` / the popovers carry
                explicit `--cg-z-*` and stay over them. `pointer-events: none` keeps glide's
                scroller β€” which is UNDER this and owns every mouse event the grid reacts to β€”
                hit-testable straight through them.

                The right-hand one starts BELOW the header rather than at 0: in `Airtable 7.png`
                the header band continues past the last column in its own near-white (#FBFCFE at
                (1250,141)), and it is where the add-field "+" lives. The two rectangles overlap
                in the bottom-right corner; they are the same flat colour, so the overlap is not
                visible and neither one needs to know about the other. */}
            {gridVoid.below !== null && (
              <div
                className="cg-grid-void"
                aria-hidden
                style={{
                  top: gridVoid.below,
                  left: 0,
                  width: gridVoid.clientW,
                  height: gridVoid.clientH - gridVoid.below,
                }}
              />
            )}
            {gridVoid.right !== null && (
              <div
                className="cg-grid-void"
                aria-hidden
                style={{
                  top: HEADER_PX,
                  left: gridVoid.right,
                  width: gridVoid.clientW - gridVoid.right,
                  height: gridVoid.clientH - HEADER_PX,
                }}
              />
            )}
            {/* ═══ end W18-B VOID ═══ */}
            </>
          )}
          {displayMode === "list" && (
            <ListView
              rows={displayRows}
              fieldByKey={fieldByKey}
              visibleKeys={visibleKeys}
              titleKey={lockedKey}
              onOpen={setDetailPid}
              onToggleGroup={onListToggleGroup}
            />
          )}
          {displayMode === "calendar" &&
            (calendarField ? (
              <CalendarView
                rows={modeDataRows}
                field={calendarField}
                today={today}
                titleKey={lockedKey}
                // Item 4 (C-DISP) β€” records vs summaries, and the metrics a summary day shows.
                mode={displaySpec?.calendarMode ?? "records"}
                metrics={displaySpec?.calendarMetrics}
                fieldByKey={fieldByKey}
                /* wave17 item 9 / R4 β€” the surface the day-grain measure channel is asked
                   about (C-CAL). The server refuses `product` in words. */
                scope={scope}
                onOpen={setDetailPid}
                /* owner item 3 β€” the summary month, so the view menu's Export can carry it. */
                onSheet={onCalSheet}
              />
            ) : (
              <div className="cg-mode-empty">
                This table has no date field to place records by.
              </div>
            ))}
          {displayMode === "kanban" &&
            (kanbanField ? (
              <KanbanView
                rows={modeDataRows}
                field={kanbanField}
                fieldByKey={fieldByKey}
                cardKeys={kanbanCardKeys}
                titleKey={lockedKey}
                canMove={kanbanCanMove}
                readOnlyReason={kanbanReason}
                clamped={displaySpec?.kanbanClamp !== false}
                onMove={onKanbanMove}
                onOpen={setDetailPid}
                /* Item 12 (R8). ⚠ A `useCallback` or the literal `null` β€” NEVER an inline arrow.
                   KanbanView is memo'd and every prop here is referentially stable on purpose
                   (see the note above `kanbanCardKeys`); a fresh closure each render undoes that
                   fix and nothing goes red. */
                onAddOption={kanbanCanAddOption ? onKanbanAddOption : null}
              />
            ) : (
              <div className="cg-mode-empty">
                This table has no status or single-select field to stack by.
              </div>
            ))}
          {/* ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) β€” the SWIPE deck.
              ⚠ No `field ? ... : empty-state` fork, and the asymmetry with kanban above is
              deliberate. A kanban with no select field cannot exist, so the host answers for it.
              A swipe deck with no binding is the ORDINARY state of a view somebody just created,
              and SwipeView owns that state along with the three ways a stored binding rots β€”
              each one re-opening the picker rather than being repaired by a guess. Forking here
              would put a second, dumber explanation in front of the good one. */}
          {displayMode === "swipe" && (
            <SwipeView
              rows={modeDataRows}
              fields={fields}
              fieldByKey={fieldByKey}
              spec={displaySpec?.swipe}
              cardKeys={kanbanCardKeys}
              titleKey={lockedKey}
              canWrite={swipeCanWrite}
              readOnlyReason={swipeReason}
              /* β›” NOT `swipeCanWrite`. Binding the deck changes the VIEW's config; writing a
                 cell changes a VALUE. Conflating them is [[schema-role-is-not-a-value-wall]],
                 and the two genuinely differ here β€” a viewer with a read-only grant on a shared
                 view may still decide records through it. */
              canBind={!!activeView && mayEditView(activeView, viewer)}
              onSpec={setSwipeSpec}
              onSwipe={onSwipeDecide}
              onOpen={setDetailPid}
              /* ⭐⭐ WAVE-29 T26 (owner R9) β€” the card renders the RECORD, so the deck now gets
                 what the modal gets: the view's visible fields (not the three-key kanban
                 summary), this surface's scope so comments can key on it, and the document
                 plumbing.
                 ⚠ `scope` is OPTIONAL on this grid and stays that way β€” the standalone embed
                 supplies none, and a card must render WITHOUT comments rather than throw. That
                 precondition is pre-existing (`RecordDetail` carries the same one); T26 keeps it
                 honest instead of forcing it.
                 ⚠ The doc handlers take a PID here, unlike the modal's, which close over the one
                 open record β€” a deck paints many at once. */
              detailKeys={[...visible].filter((k) => k !== lockedKey)}
              scope={scope}
              viewer={viewer}
              docs={payload?.docs}
              docPayload={payload?.docPayload}
              onDocAdd={
                payload?.docs
                  ? (pid, file) =>
                      emitHostEvent({
                        id: eventId("docadd"),
                        type: "doc_add",
                        pid,
                        docId: `doc_${eventId("d").slice(2, 14).replace(/[^a-z0-9]/gi, "")}`,
                        ...file,
                      })
                  : undefined
              }
              onDocFetch={
                payload?.docs
                  ? (pid, docId) =>
                      emitHostEvent({ id: eventId("docget"), type: "doc_fetch", pid, docId })
                  : undefined
              }
              onDocDelete={
                payload?.docs
                  ? (pid, docId) =>
                      emitHostEvent({ id: eventId("docdel"), type: "doc_delete", pid, docId })
                  : undefined
              }
            />
          )}
          {/**
            * ⭐⭐ WAVE-29 T29 / CONTRACT C4 (owner R7) β€” THE FORM INTERFACE, mounted.
            *
            * β›” THE WAVE'S ONLY CROSS-FENCE WIRING, and the single most reliably-dropped artifact
            * in this protocol: four consecutive waves lost one, and one wave shipped four dead
            * features behind 43 green gates. C declared it, A carries the `verify_wiring` row,
            * and this is the mount β€” three parties, so the session that REQUESTS a wiring cannot
            * be the one that certifies it.
            *
            * β›” EIGHT PROPS, ALL REQUIRED, and none of them guessed β€” C published the exact names
            * and the exact expressions in its mailbox before this ticket started. `spec` is
            * required-but-NULLABLE and the `?? null` is the contract: `displaySpec?.form` is
            * `undefined`, and widening the prop to accept it would be the optional-prop
            * degradation wearing another hat.
            * ⚠ `readOnlyReason` carries the `canEdit` reason ONLY. A locked database is a
            * different sentence and `FormInterface` owns it, because it is a property of the
            * database rather than of this viewer's grant.
            */}
          {displayMode === "form" && (
            <FormInterface
              /* ⚠ THE TABLE KEY, not the `TopicConfig` object. C's hand-off wrote
                 `topicForScope(scope)` and gave `ut_leads` as the example; that helper returns a
                 CONFIG (`{key, scope, rowsPath, …}`), and `routes_forms._may_administer_view`
                 takes a `table_key`. The example is the contract β€” a config object would have
                 stringified into a query parameter nothing can resolve. Caught by `tsc`, and
                 posted back to C rather than fixed silently. */
              topic={scope ?? ""}
              viewId={activeView?.id ?? null}
              fields={fields}
              spec={displaySpec?.form ?? null}
              onSpec={setFormSpec}
              canEdit={!!activeView && mayEditView(activeView, viewer)}
              readOnlyReason={
                !activeView
                  ? "A form lives on a saved view β€” save this one first."
                  : mayEditView(activeView, viewer)
                    ? null
                    : "You have view-only access to this view, so its form cannot be changed."
              }
              canCollect={canMutateRecords}
            />
          )}
          {/* Wave-8 I19c β†’ wave-9 I10 (C2) β€” CHART is a VIEW like the rest: the charts
              are computed from `modeDataRows`, the very rows the grid counts, so a filter
              change moves the charts and the toolbar count together.
              ⚠ Only 'chart' is tested, never 'dashboard': `cleanDisplay` normalises the
              legacy value on READ, so a stored 'dashboard' has already become 'chart' by
              the time it reaches here. Testing both would hide a broken normalisation. */}
          {displayMode === "chart" && (
            <DashboardView
              rows={modeDataRows}
              fields={fields}
              fieldByKey={fieldByKey}
              charts={charts}
              onCharts={setCharts}
            />
          )}
          {/* Owner item 7 (C-TS) β€” Time series is a VIEW: metric rows x bucket columns over
              the pids the current filter kept, so the table and the series answer the same
              question. The panel is HOST-AGNOSTIC by contract (RECORD re-mounts it inside the
              record modal for item 13), which is why it takes pids and fields rather than
              reaching into anything here. */}
          {displayMode === "timeseries" && (
            <TimeSeriesPanel
              scope={scope}
              pids={timeseriesPids}
              fields={fields}
              /* wave17 item 5 / R9 β€” the SAME rows `timeseriesPids` is derived from (see its
                 memo), so a snapshot metric and a server metric on one sheet cannot be
                 answering about different populations. */
              rows={modeDataRows}
              display={displaySpec}
              onDisplay={onTimeseriesDisplay}
              /* owner item 3 β€” the built sheet, so the view menu's Export can carry it. */
              onSheet={onTsSheet}
            />
          )}
          {/* ═══ W18-C CATALOG ═══ Owner item 4 (C6) β€” Catalog is a VIEW, and the only one
              whose payload is authored CONTENT rather than an arrangement of the rows. It
              joins its stored product codes against the WHOLE pool (`rawRows`), not the
              filtered rows: a finished page must keep printing the products it names after
              somebody narrows the view. The filter still has a job β€” `catalogFilteredCodes`
              is the "add what this view shows" door β€” but it narrows what you can ADD, never
              what a page prints.

              ⚠ Gated on the product surface. A catalog joins products to their images by
              `code`, which is `product_data`'s business key AND the C2-ASSET key; on the
              customer table the primary field is a customer NAME, and joining on it would ask
              the asset route for a picture of a person. The refusal says so in words rather
              than rendering an empty designer. */}
          {displayMode === "catalog" &&
            (scope === "product" ? (
              <CatalogView
                catalogs={catalogs}
                onCatalogs={onCatalogs}
                fields={fields}
                fieldByKey={fieldByKey}
                poolRows={rawRows}
                filteredCodes={catalogFilteredCodes}
              />
            ) : (
              <div className="cg-mode-empty">
                A catalog prints products. Open the Products table to build one.
              </div>
            ))}
          {/* ═══ end W18-C CATALOG ═══ */}
          {/* Wave-7 item W11c (C3) β€” Map is a VIEW: same pipeline rows, pins for rows
              with host-supplied coords, click-through to the same record detail, and
              an honest no-location chip. */}
          {displayMode === "map" && fieldByKey.get(lockedKey) && (
            <MapView
              rows={modeDataRows}
              field={fieldByKey.get(lockedKey)!}
              colorField={mapColorField}
              sizeField={mapSizeField}
              selectedPids={selectedPids}
              onSelectPids={selectPids}
              onOpen={setDetailPid}
            />
          )}
          {/* Owner item 19 β€” the hover-only Expand. The COUNTERPART to item 17: the single
              click that used to open a record now highlights it, and this is where opening
              moved to. `position: fixed` because glide reports viewport coordinates (the same
              space `.cg-header-tip` is placed in).

              ⚠ `onMouseDown` preventDefault, not just onClick: mousedown would otherwise reach
              the canvas underneath, move the selection to the primary cell, and repaint the
              row a frame before the panel opens β€” a visible flicker on every expand.

              Rendered only in `grid` mode: list / calendar / kanban / map have their own
              open affordances and glide is not mounted to report bounds for them. */}
          {!embedded && displayMode === "grid" && expandAt && (
            <button
              type="button"
              className="cg-row-expand"
              style={{
                left: expandAt.x,
                top: expandAt.y,
                width: expandAt.size,
                height: expandAt.size,
              }}
              title="Expand record"
              aria-label="Expand record"
              onMouseDown={(event) => event.preventDefault()}
              onClick={() => setDetailPid(expandAt.pid)}
            >
              {/* Airtable's expand mark: two corner brackets pushing apart. SVG, never a
                  glyph β€” no emojis in this UI, and a unicode arrow renders differently on
                  every platform. Sized in the parent's em so it tracks the button. */}
              <svg viewBox="0 0 16 16" width="13" height="13" aria-hidden focusable="false">
                <path
                  d="M9.5 2.5H13.5V6.5M6.5 13.5H2.5V9.5M13.5 2.5L9 7M2.5 13.5L7 9"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            </button>
          )}
          {/* Wave-5 item 6 β€” the header description tip. pointer-events:none + aria-hidden:
              it can never become a click target, so the control under it stays clickable
              (the tooltip-swallows-the-next-click trap, paid for once already). */}
          {headerTip && (
            <div
              className="cg-header-tip"
              style={{ left: headerTip.x, top: headerTip.y }}
              aria-hidden
            >
              {headerTip.text}
            </div>
          )}
          {/* I2 β€” the cell tip. `pointer-events: none` + `aria-hidden` are not styling here,
              they are the contract: the control under the tip must stay clickable, and a
              screen reader already has the cell's own value. */}
          {cellTip && (
            <div
              className="cg-header-tip cg-cell-tip"
              style={{ left: cellTip.x, top: cellTip.y }}
              aria-hidden
            >
              {cellTip.text}
            </div>
          )}
          {/* Owner item 2's point: checked customers accumulate, and the selection DOES
              something. FLOATED over the grid, never in the flow: a bar that reflows the grid
              on first selection shifts every row under the user's cursor mid-click-run (and
              broke this gate's own coordinate math before it broke a user). It states the
              count and offers "Add to cohort" over exactly the checked pids β€” the same guarded
              add_to_list event the view menu uses, so the host treats both alike. */}
          {!embedded && selectedPids.size > 0 && !serverWindowed &&
            (displayMode === "grid" || displayMode === "map") && (
            <div className="cg-selbar">
              <span className="cg-selbar-count">
                {selectedPids.size.toLocaleString()} selected
              </span>
              {/* ⭐ 2026-08-06 (owner) β€” *"right now it only shows 'Add to cohort'"*. On a user
                  database the checked rows are RECORDS the reader owns, and there was no door to
                  remove one; the whole delete path existed server-side with nothing calling it.
                  ⚠ ONLY on a `ut_` database: the customer and product grids are projections of
                  Odoo, where a "delete" would be a write to somebody else's system of record β€”
                  the server refuses it, and a button that must be refused is worse than none. */}
              {canMutateRecords && (
                <button
                  type="button"
                  /* ARMED is a VISIBLE state, not just a changed handler: the button that is
                     about to do something irreversible-feeling has to look different from the
                     one that merely offered. Same `is-armed` idiom the column menu, the docs
                     list and the views rail already use for their deletes. */
                  className={
                    "cg-btn cg-btn--danger cg-selbar-del" +
                    (delArmed && delArmed === [...selectedPids].join(",") ? " is-armed" : "")
                  }
                  style={ONE_LINE}
                  onClick={() => void deleteRecords([...selectedPids])}
                >
                  {delArmed && delArmed === [...selectedPids].join(",")
                    ? "Delete anyway?"
                    : `Delete ${selectedPids.size === 1 ? "record" : "records"}`}
                </button>
              )}
              {cohortMode ? (
                // Item 2c: on the Cohort page the selection EDITS MEMBERSHIP of the fixed set β€”
                // "Remove from cohort" replaces "Add to cohort". Direct (no popover): the
                // checked set is explicit, the button says what it does, and re-adding is one
                // picker away.
                <button
                  type="button"
                  className="cg-btn cg-btn--danger cg-selbar-remove"
                  style={ONE_LINE}
                  onClick={removeSelectionFromCohort}
                >
                  Remove from cohort
                </button>
              ) : (
                <button
                  type="button"
                  className="cg-btn cg-btn--primary cg-selbar-add"
                  style={ONE_LINE}
                  ref={selAddRef}
                  onClick={() => {
                    // Item 4: seed the new-cohort name as `<view name> Β· <today>` β€” today from
                    // the PAYLOAD verbatim, never the browser clock; no date when absent.
                    if (!selAddOpen) {
                      const vn = activeView?.name ?? "Customers";
                      setSelListName(today ? `${vn} Β· ${today}` : vn);
                    }
                    setSelAddOpen(!selAddOpen);
                  }}
                  aria-expanded={selAddOpen}
                  aria-haspopup="dialog"
                >
                  Add to cohort
                </button>
              )}
              {/* ⭐ Owner item 9 β€” the counterpart, and it renders ONLY when it can do
                  something: the checked rows have to be in a cohort this viewer may edit for
                  "Remove from cohort…" to mean anything. Same bar, same selection, opposite
                  direction β€” the ellipsis says a picker follows, because unlike cohort mode
                  the target is not implied by where you are standing. */}
              {!cohortMode && removableLists.length > 0 && (
                <button
                  type="button"
                  className="cg-btn cg-selbar-remove-pick"
                  style={ONE_LINE}
                  ref={selRemoveRef}
                  onClick={() => setSelRemoveOpen((open) => !open)}
                  aria-expanded={selRemoveOpen}
                  aria-haspopup="dialog"
                >
                  Remove from cohort…
                </button>
              )}
              <button type="button" className="cg-btn" style={ONE_LINE}
                      onClick={clearSelection}>
                Clear
              </button>
            </div>
          )}
        </div>
        {/* Owner item 8 β€” the cap is VISIBLE, beside the control that lifts it. The toolbar
            count above still states the full matched count; this bar says what is painted.
            Grid + list only: calendar/kanban project the FULL set with their own stated
            bounds (a month, a stack's Show-all). */}
        {/* ⭐ W30-T42 β€” the WINDOWED grid's honest footnotes, in the strip that already exists
            for exactly this job. Reuses `.cg-more` / `.cg-more-note` rather than adding a
            class: `index.css` is another lane's fence this wave, and this needs no new pixel.
            `foldNote` is null unless a totals row is folded over a partial window; `limitNote`
            is null unless the SERVER declared a limit on this response (R6's second sentence β€”
            short on screen, the full cause and recommendation one hover away, the same
            short-form/`title` split `countLabelCompact` uses for the same strip). */}
        {/* ⭐⭐ WAVE 31 Β· T22 (D-173) β€” THE LIMIT SENTENCE IS NO LONGER GATED ON `!capped`.
            β›” THE DEFECT IN ONE LINE: `capped` means "this grid has more rows than the display
            cap", i.e. it becomes TRUE at exactly the size that makes a server-declared limit
            worth reading β€” and the note was hidden precisely then. A limit reported only on small
            tables is a limit not reported at all, which is the violation R6's second sentence
            names ("if it can't be done, tell me why and recommend a fix"), not the limit itself.
            ⚠ The display cap and the server's limits are INDEPENDENT FACTS about one grid: one is
            how much we are painting, the other is what the server could not do. They belong in
            the same strip and neither may suppress the other. */}
        {(foldNote || limitNote || capabilityNote) && (
          <div className="cg-more">
            {foldNote && <span className="cg-more-note">{foldNote}</span>}
            {limitNote && (
              <span className="cg-more-note" title={limitNote.full}>{limitNote.short}</span>
            )}
            {capabilityNote && (
              <span className="cg-more-note" title={capabilityNote.full}>
                {capabilityNote.short}
              </span>
            )}
          </div>
        )}
        {capped && (displayMode === "grid" || displayMode === "list") && (
          <div className="cg-more">
            <span className="cg-more-note">
              Showing first {shownRecords.toLocaleString()} of{" "}
              {recordCount.toLocaleString()}
            </span>
            <button
              type="button"
              className="cg-link-btn"
              onClick={() => setDisplayCap((c) => c + DISPLAY_STEP)}
            >
              See more
            </button>
            <button
              type="button"
              className="cg-link-btn"
              onClick={() => setDisplayCap(visibleRows.length)}
            >
              Show all
            </button>
          </div>
        )}
      </main>

      {menuField && columnMenu && (
        <ColumnMenu
          key={menuField.key}
          state={columnMenu}
          field={menuField}
          fields={fields}
          /**
           * ⭐ 2026-08-10 β€” SELF-LINKING, and somebody asked for it (owner, D-113).
           *
           * The note this replaces excluded the current database with `linkTargets.filter(t =>
           * t.key !== scope)` and said so honestly: "a legal relation in Airtable and a confusing
           * one to explain in a one-line picker … left out until somebody asks". It was a taste
           * call, not a constraint, and nothing below the picker ever needed it β€” `_clean_link`
           * only requires a `ut_*` key, and `sync_reciprocal_link` puts the backlink on the target
           * whichever table that is. "This lead is a duplicate of that lead" and "this record's
           * parent" are the ordinary cases, and both were unbuildable.
           *
           * ⚠ THE UNFILTERED LIST ALSO REPAIRS THE ROLLUP EDITOR, which is the half a one-line
           * change hides: it resolves the fold's source columns with
           * `linkTargets.find(t => t.key === chosenLink.link.table)`, so a rollup over a self-link
           * would have offered an EMPTY column picker and looked like the rollup was broken.
           * ⚠ Both `<ColumnMenu>` renders take the same list β€” the full menu and the "+" create
           * menu. One of the two is the half-landing this repo keeps paying for.
           */
          linkTargets={linkTargets}
          rollupSourceOffer={rollupSourceOffer}
          locked={menuField.key === lockedKey}
          schemaLocked={isSchemaLocked(menuField)}
          viewer={viewer}
          sortedDir={menuSortedDir}
          isFiltered={menuIsFiltered}
          isGrouped={config.groupBy === menuField.key}
          groupable={isGroupableField(menuField, lockedKey)}
          // Item 12 (R8) β€” the kanban's "Add option" opens THIS menu straight into its Edit-field
          // pane. Absent for every other opening, which is the action list as before.
          initialPane={columnMenu.pane}
          onClose={() => setColumnMenu(null)}
          onNote={(note) => saveField({ ...menuField, note })}
          onHide={() => {
            setColumnVisible(menuField.key, false);
            setColumnMenu(null);
          }}
          onCreate={createField}
          onChangeField={(newKey) => changeField(menuField.key, newKey)}
          onCreateAndSwap={(label, type, options, extra) =>
            createAndSwapField(menuField.key, label, type, options, extra)
          }
          onProfileFlag={isUserTable ? setProfileFlag : undefined}
          onFieldConfig={isUserTable ? (patch) => setFieldConfig(menuField.key, patch) : undefined}
          onRetype={
            // Item 2 β€” a CREATED field retypes IN PLACE from the pane.
            //
            // ⭐⭐ WAVE-29 T27 (owner item 14): the predicate is `isUserSchemaField`, not the raw
            // `custom` flag. `user_tables._clean_field` never stamps `custom`, so EVERY column on
            // a `ut_*` database failed the old test β€” the Field-type picker vanished, the pane was
            // left showing only the "Change field" swap picker (a different feature entirely,
            // holding the autofocus), and the owner reported the innocent control as broken.
            isUserSchemaField(menuField, isUserTable)
              ? (type, options, extra) =>
                  retypeField(menuField.key, type, options, extra)
              : undefined
          }
          onRename={
            // Item 5 β€” rename is a def edit on created strata.
            //
            // β›” T27: withheld by the SAME flag, which is why the Name box went disabled saying
            // *"A source field keeps its name and type from the data source"* about a column the
            // user created themselves. A `ut_*` definition field renames through the DEFINITION
            // door; `saveField` would fork it into a private overlay copy of itself (the reason
            // `onFormula` below already branches this way).
            !isUserSchemaField(menuField, isUserTable)
              ? undefined
              : menuField.custom
              ? (label) => saveField({ ...menuField, label })
              : (label) => setFieldConfig(menuField.key, { label })
          }
          onFormula={
            // Owner item 8 β€” edit a created FORMULA field's source in place; the optional
            // label rides the SAME upsert (see ColumnMenu's one-upsert rule).
            //
            // ⭐⭐ 2026-08-10 β€” TWO STRATA, TWO DOORS, and the gate is `custom` rather than the
            // type. A formula column on a `ut_*` database now lives in the SHARED definition, and
            // definition fields carry no `custom` flag (`_clean_field` never stamps one) β€” so the
            // old single condition made the expression editor DISAPPEAR for exactly the columns
            // this change creates: creatable and then permanently frozen, which is a worse state
            // than the one it replaces. `setFieldConfig` PATCHes the definition; `saveField`
            // writes this user's overlay, and sending a definition field down that path would
            // fork the column into a private second copy of itself.
            menuField.type !== "formula"
              ? undefined
              : isUserTable && !menuField.custom
              ? (formula, label) =>
                  setFieldConfig(menuField.key, {
                    formula,
                    ...(label ? { label } : {}),
                  })
              : menuField.custom
              ? (formula, label) =>
                  saveField({
                    ...menuField,
                    formula,
                    ...(label ? { label } : {}),
                  })
              : undefined
          }
          onPeriod={
            menuField.measure
              ? (w) => changeMeasurePeriod(menuField.key, w)
              : undefined
          }
          onDelete={
            menuField.custom && menuField.key !== lockedKey
              ? () => {
                  deleteField(menuField.key);
                  setColumnMenu(null);
                }
              : /**
                 * ⭐⭐ 2026-08-10 β€” the DEFINITION stratum's own delete.
                 *
                 * β›” NARROWED TO THE THREE KINDS THAT HOLD NO DATA OF THEIR OWN, which is
                 * `preset_editable`'s argument reused rather than a new one: a link, a rollup and
                 * a formula are all QUESTIONS asked of other cells, so removing one destroys no
                 * measurement and can be undone by asking it again. Every other definition column
                 * on a `ut_*` database holds real values, and offering a type-blind Delete over
                 * those is a destructive widening this change has no mandate for (booked as
                 * D-114). It is also exactly the three kinds `createField` now routes to the
                 * definition β€” so what a user can make here, a user can unmake.
                 * ⚠ `schemaLocked` still gates the button inside ColumnMenu, so a pre-set link
                 * never shows it; a pre-set ROLLUP does, by the same owner ruling that made it
                 * editable, and the confirm says it will come back.
                 */
                isUserTable &&
                !menuField.custom &&
                menuField.key !== lockedKey &&
                (menuField.type === "link" || menuField.type === "rollup" ||
                 menuField.type === "formula")
              ? () => {
                  deleteDefinitionField(menuField.key);
                  setColumnMenu(null);
                }
              : undefined
          }
          onDuplicate={
            // Creatable strata only β€” a base Odoo field offers no Duplicate (contract).
            menuField.custom ? () => duplicateField(menuField) : undefined
          }
          onPermissions={
            // Creatable strata only; ColumnMenu further gates on the viewer (creator/admin).
            menuField.custom
              ? (edit) => saveField({ ...menuField, permissions: { edit } })
              : undefined
          }
          onFormat={(format) => saveField({ ...menuField, format })}
          /**
           * ⭐ WAVE-29 T33 (owner item 17) β€” the column summary, through whichever door owns this
           * column's definition. Same two-strata split as `onRename` above: a `ut_*` definition
           * field PATCHes the definition (`_clean_field` stores `agg`), everything else rides the
           * ordinary overlay upsert. ⚠ `undefined` CLEARS it, and the clear has to travel β€” a
           * PATCH that merely omits `agg` keeps the stored one, which is the stickiness the money
           * columns depend on.
           */
          onAggregate={(agg) =>
            isUserTable && !menuField.custom
              ? setFieldConfig(menuField.key, { agg: agg ?? "" })
              : saveField({ ...menuField, agg })
          }
          onSort={(dir) =>
            updateConfig({ ...config, sorts: [{ colId: menuField.key, dir }] })
          }
          onClearSort={() =>
            updateConfig({
              ...config,
              sorts: config.sorts.filter((s) => s.colId !== menuField.key),
            })
          }
          onFilterBy={() =>
            // Item 6c β€” a MEASURE-carrying column seeds the equivalent MEASURE condition
            // (same measure key + window, value empty); every other filterable column seeds
            // an ordinary column condition. Same signal, one consumer (the Toolbar).
            setFilterSeed((prev) => ({
              n: (prev?.n ?? 0) + 1,
              ...(menuField.measure
                ? { measure: { key: menuField.measure.key, window: menuField.measure.window } }
                : { key: menuField.key }),
            }))
          }
          pinnedTo={menuPinnedTo}
          onPinTo={
            // Item 11c β€” pinning the identity column is the same as unpinning; skip it.
            menuVisIndex > 0 && !menuPinnedTo
              ? () => pinFieldTo(menuField.key)
              : undefined
          }
          onUnpin={frozenN > 1 ? unpinFields : undefined}
          scopeChoice={scopeChoice}
          onClearFilter={() =>
            updateConfig({
              ...config,
              filters: dropFieldFromTree(config.filters, menuField.key, measureCols),
            })
          }
          onGroupByField={() => updateConfig({ ...config, groupBy: menuField.key })}
          onClearGroup={() => updateConfig({ ...config, groupBy: null })}
          userOptions={payload?.userOptions ?? []}
          measures={measures}
        />
      )}

      {/* Wave-6 item 4 β€” the header "+": the SAME ColumnMenu, opened straight into its
          create form in insert-at-end mode. Anchored on the button; the nominal field is the
          locked identity column (only its position matters β€” the create form never shows it).
          The action/pane handlers below are unreachable in this mode (create-only; Cancel
          closes), supplied inert to satisfy the surface. */}
      {plusMenu && fieldByKey.get(lockedKey) && (
        <ColumnMenu
          key="__add-at-end__"
          state={{ fieldKey: lockedKey, anchor: plusMenu }}
          field={fieldByKey.get(lockedKey)!}
          fields={fields}
          locked
          viewer={viewer}
          sortedDir={null}
          isFiltered={false}
          isGrouped={false}
          groupable={false}
          initialPosition="end"
          onClose={() => setPlusMenu(null)}
          onNote={() => undefined}
          onHide={() => undefined}
          onCreate={createField}
          onChangeField={() => undefined}
          onCreateAndSwap={() => undefined}
          onSort={() => undefined}
          onClearSort={() => undefined}
          onFilterBy={() => undefined}
          onClearFilter={() => undefined}
          onGroupByField={() => undefined}
          onClearGroup={() => undefined}
          scopeChoice={scopeChoice}
          userOptions={payload?.userOptions ?? []}
          measures={measures}
          // β›”β›” 2026-08-09 β€” THE SECOND HALF OF THE SAME DEFECT. The sibling instance above has
          // passed these since the relational types shipped; this one never did, so a rollup
          // created through "+" had no databases to resolve its link against and no source offer
          // to switch modes with β€” the Column picker held its placeholder and nothing else.
          // ⚠ TWO THINGS WERE BOTH WRONG (the fetch was gated on `columnMenu` and these props
          // were absent), so fixing either alone would still have shipped an empty picker and
          // read as "the fix did not work" β€” [[defects-that-mask-each-other]].
          // ⚠ 2026-08-10 β€” THE SELF-EXCLUSION IS GONE FROM BOTH SITES (D-113). The line this
          // replaces said the two call sites "must not disagree about that", and it was right for
          // a reason it did not anticipate: the exclusion was removed from the sibling first and
          // this copy kept it, so for one edit the "+" menu and the column menu offered DIFFERENT
          // databases β€” caught by grepping the prop rather than by the build, which is happy
          // either way. See the sibling's note for why self-links are offered now.
          linkTargets={linkTargets}
          rollupSourceOffer={rollupSourceOffer}
        />
      )}

      {/* ⭐ WAVE 21 item 11 (R10 / contract C5) β€” "Select records from a list".
          ⚠ `inView` is `visibleRows`, NOT `displayRows`. `displayRows` is a capped slice
          (`DISPLAY_PAGE`) of what the view matched; matching over it would report every
          record past the cap as "not found" β€” a lie that grows with the table. The whole
          pool goes in beside it so a value the FILTER hides is reported as filtered, not
          as missing. */}
      {/* ⭐ WAVE-29 T25 β€” the import dialog, mounted as a conditional sibling exactly like
          `SelectFromFile` above it. `scope` is the `ut_*` table key the import door is per. */}
      {importOpen && (
        <ImportDialog
          fields={fields}
          scope={scope ?? ""}
          tableName={activeView?.name ?? "this database"}
          onImported={(count) => {
            signal(TOAST_EVENT,
              `${count.toLocaleString()} record${count === 1 ? "" : "s"} imported.`);
            signal(ROWS_STALE_EVENT);
          }}
          onClose={() => setImportOpen(false)}
        />
      )}

      {selectFromFile && (
        <SelectFromFile
          fields={fields}
          primaryKey={lockedKey}
          inView={visibleRows.flatMap((vr) => (vr.kind === "data" ? [vr.record] : []))}
          wholeTable={computedRows}
          viewName={activeView?.name ?? "this view"}
          onSelect={(pids) => selectPids(pids, "replace")}
          onClose={() => setSelectFromFile(false)}
        />
      )}

      {/* The selection bar's cohort picker: existing cohorts, or a new one by name. Mirrors the
          view menu's Add-to-list surface so the two ways of building a cohort read identically. */}
      {selAddOpen && selAddRef.current && selectedPids.size > 0 && (
        <AnchoredOverlay
          anchor={selAddRef.current}
          className="cg-pop cg-add-list-pop"
          placement="bottom-start"
          role="dialog"
          ariaLabel="Add selected customers to a locked view"
          onDismiss={() => setSelAddOpen(false)}
          dataKind="selection-add-to-list"
        >
          <div className="cg-pop-title">Add to locked view</div>
          <div className="cg-pop-note">
            Adds the {selectedPids.size.toLocaleString()} checked customer
            {selectedPids.size === 1 ? "" : "s"}. The cohort stays fixed as the data changes.
          </div>
          {lists.map((l) => (
            <button
              type="button"
              key={l.id}
              className="cg-pick-row"
              onClick={() => addSelectionToList(l.id, l.name)}
            >
              {l.name}
            </button>
          ))}
          <div className="cg-view-create">
            <label htmlFor="cg-sel-new-list">Lock records into a new view</label>
            <input
              id="cg-sel-new-list"
              className="cg-input"
              data-overlay-autofocus
              value={selListName}
              placeholder="e.g. Q3 call plan"
              onChange={(event) => setSelListName(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === "Enter" && selListName.trim())
                  addSelectionToList("", selListName.trim());
              }}
            />
            <div className="cg-form-actions">
              <button
                type="button"
                className="cg-btn cg-btn--primary"
                style={ONE_LINE}
                disabled={!selListName.trim()}
                onClick={() => addSelectionToList("", selListName.trim())}
              >
                Create and add
              </button>
            </div>
          </div>
        </AnchoredOverlay>
      )}

      {/* ⭐ Owner item 9 β€” the remove picker. Every row states how many of the CHECKED rows it
          would take out ("3 of 4"), because the selection and the cohort are two different sets
          and the difference is the whole reason this needs a picker rather than a button. */}
      {selRemoveOpen && selRemoveRef.current && removableLists.length > 0 && (
        <AnchoredOverlay
          anchor={selRemoveRef.current}
          className="cg-pop cg-add-list-pop"
          placement="bottom-start"
          role="dialog"
          ariaLabel="Remove selected customers from a locked view"
          onDismiss={() => setSelRemoveOpen(false)}
          dataKind="selection-remove-from-list"
        >
          <div className="cg-pop-title">Remove from locked view</div>
          <div className="cg-pop-note">
            Only the locked views holding one of the {selectedPids.size.toLocaleString()} checked
            customer{selectedPids.size === 1 ? "" : "s"} are listed. The records themselves are
            not touched.
          </div>
          {removableLists.map((l) => (
            <button
              type="button"
              key={l.id}
              className="cg-pick-row"
              onClick={() => removeSelectionFromList(l.id)}
            >
              {l.name}
              <span className="cg-pick-hint">
                {l.hits.toLocaleString()} of {selectedPids.size.toLocaleString()}
              </span>
            </button>
          ))}
        </AnchoredOverlay>
      )}

      {/* Cohort mode's "+ Add customers" picker (item 2c): search the POOL, tick many, confirm
          once. Candidates exclude current members; picks ACCUMULATE across searches, so the
          confirm button carries the running total. The 50-row render cap is stated beside the
          list β€” nothing silently truncated. */}
      {cohortMode && addCustOpen && addCustRef.current && activeCohortId && (
        <AnchoredOverlay
          anchor={addCustRef.current}
          className="cg-pop cg-addcust-pop"
          placement="bottom-start"
          role="dialog"
          ariaLabel="Add customers to this locked view"
          onDismiss={() => setAddCustOpen(false)}
          dataKind="cohort-add-customers"
        >
          <div className="cg-pop-title">Add customers</div>
          <div className="cg-pop-note">
            Search your customer pool and tick who to add to{" "}
            <strong>{activeCohort?.name ?? "this locked view"}</strong>.
          </div>
          <input
            type="text"
            className="cg-input cg-addcust-search"
            data-overlay-autofocus
            placeholder="Search customers…"
            aria-label="Search customers"
            value={addCustQuery}
            onChange={(e) => setAddCustQuery(e.target.value)}
          />
          <div className="cg-pick-list cg-addcust-list">
            {addCandidates.slice(0, 50).map((c) => (
              <label key={c.pid} className="cg-check-row">
                <input
                  type="checkbox"
                  checked={addCustPicked.has(c.pid)}
                  onChange={() =>
                    setAddCustPicked((prev) => {
                      const next = new Set(prev);
                      if (next.has(c.pid)) next.delete(c.pid);
                      else next.add(c.pid);
                      return next;
                    })
                  }
                />
                <span className="cg-check-label">{c.name}</span>
              </label>
            ))}
            {addCandidates.length === 0 && (
              <div className="cg-pop-note">
                {addCustQuery.trim()
                  ? "No customer outside this locked view matches your search."
                  : "Every customer in your pool is already in this locked view."}
              </div>
            )}
          </div>
          {addCandidates.length > 50 && (
            <div className="cg-field-hint">
              Showing the first 50 of {addCandidates.length.toLocaleString()} matches β€” keep
              typing to narrow.
            </div>
          )}
          <div className="cg-form-actions">
            <button
              type="button"
              className="cg-btn cg-btn--primary"
              style={ONE_LINE}
              disabled={addCustPicked.size === 0}
              onClick={addCustomersToCohort}
            >
              {addCustPicked.size === 0
                ? "Add customers"
                : `Add ${addCustPicked.size.toLocaleString()} customer${
                    addCustPicked.size === 1 ? "" : "s"
                  }`}
            </button>
            <button
              type="button"
              className="cg-btn"
              style={ONE_LINE}
              onClick={() => setAddCustOpen(false)}
            >
              Cancel
            </button>
          </div>
        </AnchoredOverlay>
      )}

      {/* ⭐ Wave-23 C7 β€” the document viewer. `onSave` is OMITTED, not disabled, when the reader
          may not edit: an absent handler is what makes the raw tab a `<pre>` instead of a
          textarea, so there is no editor to be refused by. */}
      {jsonField && jsonAt && (
        <JsonViewer
          label={jsonField.label}
          value={jsonValue}
          onSave={
            canEditField(jsonField)
              ? (next) => patchAndRecord(jsonAt.pid, { [jsonField.key]: next }, "a document")
              : undefined
          }
          onClose={closeJson}
        />
      )}
      {linkField?.type === "link" && linkField.link?.table.startsWith("ut_") && linkAt && (
        <LinkGridModal
          label={linkField.label}
          table={linkField.link.table as SurfaceScope}
          recordIds={linkedRecordIds}
          editable={canEditField(linkField) && !isDerivedLink(linkField)}
          single={linkField.link.single === true}
          onSave={(ids) => patchAndRecord(
            linkAt.pid,
            { [linkField.key]: ids.join(",") },
            "linked records"
          )}
          onClose={closeLink}
        />
      )}
      {pickerField && picker && (
        <AnchoredOverlay
          anchor={picker.anchor}
          className="cg-pop cg-pick-pop"
          placement="bottom-start"
          role="listbox"
          ariaLabel={`Choose ${pickerField.label}`}
          onDismiss={closePicker}
          dataKind="cell-picker"
          // Owner item 6 (2026-07-31) β€” the picker is a KEYBOARD surface: it opens focused on
          // the current choice (fallback: the first), arrows move between choices, Enter picks
          // (native button activation), Escape closes, and closePicker hands focus back to the
          // grid so the next Enter keeps walking the column.
          initialFocus="[data-overlay-autofocus]"
          onKeyDown={(e) => {
            const fwd = e.key === "ArrowDown" || e.key === "ArrowRight";
            const back = e.key === "ArrowUp" || e.key === "ArrowLeft";
            if (!fwd && !back) return;
            const items = Array.from(
              e.currentTarget.querySelectorAll<HTMLButtonElement>(
                ".cg-pick-row, .cg-star-btn"
              )
            );
            if (!items.length) return;
            e.preventDefault();
            const at = items.indexOf(document.activeElement as HTMLButtonElement);
            const next = fwd
              ? (at + 1) % items.length
              : (at - 1 + items.length) % items.length;
            items[next]?.focus();
          }}
        >
          {/* Wave-5 item 11 β€” a RATING cell's picker is the star row itself. */}
          {pickerField.type === "rating" && (
            <div
              className="cg-stars"
              role="radiogroup"
              aria-label={`Set ${pickerField.label}`}
            >
              {Array.from({ length: ratingMax(pickerField) }, (_, i) => i + 1).map(
                (n) => (
                  <button
                    key={n}
                    type="button"
                    className="cg-star-btn"
                    role="radio"
                    aria-checked={Number(pickerValue) === n}
                    data-overlay-autofocus={
                      Number(pickerValue) === n || (!pickerValue && n === 1)
                        ? true
                        : undefined
                    }
                    aria-label={`${n} star${n === 1 ? "" : "s"}`}
                    onClick={() => {
                      patchAndRecord(picker.pid, { [pickerField.key]: String(n) }, "a rating");
                      closePicker();
                    }}
                  >
                    <StarIcon on={Number(pickerValue) >= n} />
                  </button>
                )
              )}
            </div>
          )}
          {pickerField.type !== "rating" && pickerChoices.length === 0 && (
            <div className="cg-pop-note">
              {pickerField.type === "user"
                ? "No assignable people were supplied for this workspace."
                : "This field has no choices yet. Add them from the column menu."}
            </div>
          )}
          <div className="cg-pick-list" aria-multiselectable={pickerMulti || undefined}>
            {pickerChoices.map((choice) => {
              const tint = optionTint(pickerField, choice);
              const on = pickerMulti
                ? pickerParts.includes(choice)
                : pickerValue === choice;
              return (
                <button
                  type="button"
                  role="option"
                  aria-selected={on}
                  key={choice}
                  data-overlay-autofocus={choice === pickerFocusChoice ? true : undefined}
                  className={"cg-pick-row" + (on ? " is-on" : "")}
                  onClick={() => {
                    if (pickerMulti) {
                      // Toggle membership; each toggle persists (the event log absorbs the
                      // burst), and the picker STAYS OPEN so a set is built in one visit.
                      const next = on
                        ? pickerParts.filter((p) => p !== choice)
                        : [...pickerParts, choice];
                      patchAndRecord(picker.pid, {
                        [pickerField.key]: next.join(","),
                      }, "a choice");
                      return;
                    }
                    patchAndRecord(picker.pid, { [pickerField.key]: choice }, "a choice");
                    closePicker();
                  }}
                >
                  {/* Wave-14 item 11 / R6 β€” a PICKER shows the avatar AND the name. The grid
                      cell shows the face alone (you already know who your people are); this is
                      where you find out which face is whose, so dropping the name here would
                      make the feature unusable the first time two colleagues share initials.
                      ⚠ Inline styles, no new class rules: `index.css` is PANEL's fence this
                      wave. The class name is a QA hook only and styles nothing. */}
                  {pickerField.type === "user" && (
                    <span
                      className="cg-pick-avatar"
                      aria-hidden="true"
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        justifyContent: "center",
                        flex: "0 0 auto",
                        width: 20,
                        height: 20,
                        borderRadius: "50%",
                        overflow: "hidden",
                        marginRight: 8,
                        fontSize: 9,
                        fontWeight: 600,
                        lineHeight: 1,
                        position: "relative",
                        background: pickTint(choice).bg,
                        color: pickTint(choice).fg,
                      }}
                    >
                      {/* ⚠ The initials are ALWAYS rendered and the photo is laid OVER them, so
                          a corrupt data URL hides itself and the fallback is already underneath.
                          C-AVATAR's rule is "never a broken-image glyph, anywhere" β€” the canvas
                          path honours it via `img.onerror`, and this is the DOM path's version
                          of the same promise. It cannot fire until HOST serves a photo, which is
                          exactly why it is easy to ship without. */}
                      {avatarInitials(choice)}
                      {userAvatars?.[choice] && (
                        <img
                          src={userAvatars[choice]}
                          alt=""
                          onError={(e) => {
                            e.currentTarget.style.visibility = "hidden";
                          }}
                          style={{
                            position: "absolute",
                            inset: 0,
                            width: "100%",
                            height: "100%",
                            objectFit: "cover",
                          }}
                        />
                      )}
                    </span>
                  )}
                  <span
                    className="cg-pick-pill"
                    style={tint ? { background: tint.bg, color: tint.fg } : undefined}
                  >
                    {choice}
                  </span>
                </button>
              );
            })}
          </div>
          {pickerMulti && (
            <div className="cg-form-actions">
              <button
                type="button"
                className="cg-btn"
                style={ONE_LINE}
                onClick={closePicker}
              >
                Done
              </button>
            </div>
          )}
          {/* Clearing must be possible, and it must write "" rather than delete the key β€”
              the overlay patch contract is a value per field, and a missing key would leave
              the previous value standing on the next render. */}
          {pickerValue !== "" && (
            <button
              type="button"
              className="cg-pick-row cg-pick-clear"
              // Fallback focus target for a picker with a value but no choices left
              // (the querySelector takes the FIRST match, so a real choice row wins).
              data-overlay-autofocus={pickerChoices.length === 0 ? true : undefined}
              onClick={() => {
                patchAndRecord(picker.pid, { [pickerField.key]: "" }, "a choice");
                closePicker();
              }}
            >
              Clear
            </button>
          )}
        </AnchoredOverlay>
      )}

      {!embedded && detailRecord && detailPid !== null && (
        <RecordDetail
          fields={fields}
          record={detailRecord}
          titleKey={lockedKey}
          positionLabel={`Record ${dataPosition.toLocaleString()} of ${recordCount.toLocaleString()}`}
          canPrev={neighborExists(-1)}
          canNext={neighborExists(1)}
          onPrev={() => go(-1)}
          onNext={() => go(1)}
          onClose={() => setDetailPid(null)}
          // Item 5 / C-LAYOUT β€” see `recordLayout` above. Both optional on RECORD's side, so
          // this compiles whether or not their reorder UI has landed yet.
          recordLayout={recordLayout}
          onRecordLayout={onRecordLayout}
          // Item 13 / C-EMBED β€” the host names WHICH question Insights asks. Without this the
          // tab deliberately does not render (RECORD's no-safe-default rule: a wrong scope
          // succeeds with plausible wrong numbers, so absence must mean absent, not guessed).
          scope={scope}
          docs={payload?.docs?.[String(detailPid)] ?? []}
          docPayload={payload?.docPayload}
          // C5 β€” documents ride the ordinary event log. The host answers a fetch
          // on the NEXT render via `payload.docPayload`; Documents.tsx matches it
          // to its own pending request before touching it.
          onDocAdd={
            payload?.docs
              ? (file) =>
                  emitHostEvent({
                    id: eventId("docadd"),
                    type: "doc_add",
                    pid: detailPid,
                    docId: `doc_${eventId("d").slice(2, 14).replace(/[^a-z0-9]/gi, "")}`,
                    ...file,
                  })
              : undefined
          }
          onDocFetch={
            payload?.docs
              ? (docId) =>
                  emitHostEvent({
                    id: eventId("docget"),
                    type: "doc_fetch",
                    pid: detailPid,
                    docId,
                  })
              : undefined
          }
          onDocDelete={
            payload?.docs
              ? (docId) =>
                  emitHostEvent({
                    id: eventId("docdel"),
                    type: "doc_delete",
                    pid: detailPid,
                    docId,
                  })
              : undefined
          }
          onNotesChange={(key, value) =>
            setOverlayEdits((current) => ({
              ...current,
              [detailPid]: { ...current[detailPid], [key]: value },
            }))
          }
          onNotesCommit={(key, value) => patchAndRecord(detailPid, { [key]: value })}
          viewer={viewer}
          // Wave-14 close-out stitch (HOST): TSREC's two light-switch props, unwired when
          // the GRID session ended β€” item 9's picker vocabulary + item 11's photos. Same
          // values the grid's own surfaces already read (the wave-13 sixth-prop precedent).
          userOptions={payload?.userOptions ?? []}
          userAvatars={userAvatars}
        />
      )}
    </div>
  );
}

export default memo(CustomerGrid);