File size: 164,795 Bytes
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
 
4cfab62
 
8873406
 
8729c1d
c1fc133
 
dec006b
efda0e6
 
8873406
1d4419b
c1fc133
4cfab62
89af3b2
 
639b859
 
4cfab62
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
f462120
 
 
 
 
 
 
 
 
dec006b
aadfd74
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
3fac176
 
 
 
971c29d
ce9586e
 
 
 
8729c1d
 
 
 
 
 
 
 
 
4cfab62
 
 
ce9586e
8729c1d
ce9586e
4cfab62
 
 
8873406
aadfd74
 
 
 
 
 
 
4cfab62
f462120
dec006b
 
4cfab62
 
 
 
 
 
 
 
 
 
dec006b
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
f462120
4cfab62
 
 
 
 
f462120
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
4cfab62
 
dec006b
 
 
4cfab62
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338556b
 
c1fc133
 
338556b
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338556b
c1fc133
338556b
c1fc133
 
 
 
 
 
 
 
 
338556b
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338556b
c1fc133
 
 
 
 
 
 
 
2eae9f0
 
 
 
 
 
3fac176
 
 
 
 
 
 
 
 
 
 
 
 
2eae9f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
dec006b
 
c1fc133
 
 
 
338556b
 
 
 
 
c1fc133
 
 
3fac176
 
c1fc133
 
 
 
2eae9f0
c1fc133
 
dec006b
 
8729c1d
c1fc133
 
 
4cfab62
338556b
 
 
4cfab62
338556b
4cfab62
338556b
4cfab62
338556b
 
4cfab62
 
 
 
 
 
 
 
2eae9f0
3fac176
4cfab62
 
 
 
2eae9f0
4cfab62
 
dec006b
 
8729c1d
4cfab62
 
 
 
 
 
 
 
 
 
e174d2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
f462120
 
2eae9f0
 
4cfab62
 
 
 
 
1d4419b
 
 
 
 
 
 
 
 
 
 
2e7e617
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
4cfab62
c1fc133
4cfab62
f462120
 
4cfab62
 
 
 
 
 
 
 
1d4419b
 
 
 
 
 
 
2e7e617
 
 
 
2eae9f0
 
 
 
4cfab62
 
 
2eae9f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
4cfab62
 
f462120
4cfab62
 
 
 
 
 
 
 
f462120
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
f462120
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8ef3da
 
338556b
 
 
 
 
 
4cfab62
 
 
338556b
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
8873406
dec006b
 
 
8873406
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
8729c1d
 
4cfab62
 
82cdb59
3fac176
f462120
8729c1d
 
f462120
c1fc133
82cdb59
3fac176
 
 
4cfab62
f462120
 
dec006b
 
f462120
 
 
 
 
 
 
8729c1d
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
338556b
f462120
 
 
 
 
 
 
 
 
 
 
 
89af3b2
338556b
 
 
f462120
 
 
338556b
 
f462120
338556b
89af3b2
 
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
89af3b2
 
 
3fac176
f462120
89af3b2
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
f462120
 
8729c1d
4cfab62
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
 
82cdb59
 
f462120
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eae9f0
f530297
 
 
 
 
1d4419b
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92127d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
2eae9f0
92127d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
1d4419b
 
 
 
 
 
82cdb59
1d4419b
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
 
 
 
 
82cdb59
 
 
 
 
 
1d4419b
82cdb59
1d4419b
 
82cdb59
1d4419b
 
82cdb59
 
 
1d4419b
82cdb59
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
1d4419b
 
 
 
82cdb59
1d4419b
 
 
 
 
82cdb59
 
 
 
 
 
 
1d4419b
 
 
82cdb59
 
 
 
 
 
 
 
 
 
1d4419b
 
4cfab62
 
 
 
 
 
 
 
 
 
971c29d
 
4cfab62
971c29d
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
971c29d
 
4cfab62
 
 
 
971c29d
 
4cfab62
2eae9f0
 
 
 
 
971c29d
 
 
2eae9f0
 
 
4cfab62
 
971c29d
 
4cfab62
 
971c29d
 
 
 
4cfab62
 
 
 
971c29d
ce9586e
971c29d
 
ce9586e
971c29d
4cfab62
971c29d
ce9586e
971c29d
 
 
 
 
 
 
 
8729c1d
971c29d
8729c1d
 
971c29d
 
ce9586e
971c29d
ce9586e
 
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
3fac176
 
971c29d
8729c1d
 
 
 
 
 
971c29d
 
 
 
3fac176
971c29d
 
 
ce9586e
 
 
 
338556b
 
 
8729c1d
971c29d
8729c1d
 
 
 
 
 
 
4cfab62
338556b
 
4cfab62
338556b
 
 
 
 
639b859
 
338556b
971c29d
338556b
8729c1d
4cfab62
338556b
4cfab62
8729c1d
971c29d
 
 
 
 
 
4cfab62
 
 
ce9586e
 
 
338556b
ce9586e
3fac176
ce9586e
4cfab62
338556b
ce9586e
971c29d
 
 
 
 
 
 
 
 
 
 
8729c1d
971c29d
 
 
 
4cfab62
 
 
 
 
971c29d
 
 
8729c1d
971c29d
 
 
 
 
c1fc133
 
971c29d
c1fc133
f462120
c1fc133
 
 
ce9586e
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
c1fc133
8729c1d
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efda0e6
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
efda0e6
 
 
 
 
 
 
 
8729c1d
 
efda0e6
8729c1d
 
4cfab62
 
 
 
 
 
efda0e6
 
 
 
 
 
 
4cfab62
8729c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
efda0e6
 
 
 
 
 
4cfab62
 
2e7e617
 
4cfab62
 
 
efda0e6
8729c1d
 
 
efda0e6
8729c1d
 
efda0e6
8729c1d
 
 
 
 
 
 
efda0e6
 
 
 
 
8729c1d
 
 
efda0e6
 
4cfab62
 
 
efda0e6
 
 
2e7e617
 
 
 
4cfab62
efda0e6
 
 
 
 
4cfab62
 
 
efda0e6
4cfab62
efda0e6
 
4cfab62
 
 
 
2e7e617
 
 
 
 
 
dec006b
 
 
8729c1d
 
 
 
 
 
 
dec006b
 
8729c1d
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
4cfab62
 
 
 
 
dec006b
4cfab62
aadfd74
dec006b
8873406
 
 
 
 
 
 
 
 
 
 
dec006b
 
8873406
4cfab62
dec006b
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
 
 
4cfab62
 
 
8cbc29f
 
 
4cfab62
 
 
 
 
8cbc29f
4cfab62
 
8cbc29f
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f648119
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04567e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
918e158
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
4cfab62
dec006b
4cfab62
 
 
dec006b
4cfab62
 
 
dec006b
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
4cfab62
 
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
8873406
 
 
 
 
 
 
 
 
8729c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
8873406
8729c1d
8873406
 
 
 
 
 
f462120
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
 
8873406
 
 
 
 
 
 
 
f709e48
 
 
 
 
 
 
 
 
 
 
 
8873406
f709e48
8873406
 
 
 
 
 
4cfab62
 
c1fc133
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
4cfab62
 
 
 
 
 
 
8873406
8729c1d
 
 
4cfab62
 
 
8873406
4cfab62
 
8873406
4cfab62
8873406
4cfab62
 
8873406
8729c1d
4cfab62
 
 
8873406
 
 
 
 
 
4cfab62
8729c1d
4cfab62
 
 
 
 
c1fc133
 
 
 
f462120
c1fc133
 
4cfab62
 
 
 
 
 
 
 
 
 
8729c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
c1fc133
8729c1d
 
 
 
8873406
8729c1d
8873406
 
4cfab62
 
 
 
 
 
 
8873406
 
 
 
8729c1d
8873406
 
4cfab62
64268da
8873406
 
64268da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ---------------------------------------------------------------------------
// customer-grid / apiBridge.ts β€” the STANDALONE half of the data path (X2).
//
// The branch beside hostBridge.ts. Where `hostBridge` speaks the Streamlit
// Components v1 protocol to a surrounding Python app, this speaks HTTP to the
// API β€” the SAME event objects, the same ids, the same optimism semantics on
// the client. Which one is live is decided once, by mode, and never mixed:
// `installStandaloneBridge()` is called from main.tsx ONLY in standalone, so
// the embed bundle never registers a sink and its behaviour is byte-unchanged
// (pinned by verify_bridge.py, which was written BEFORE this file existed).
//
// ⚠ WHAT THIS WAVE'S WRITE PATH CAN AND CANNOT DO β€” read before extending.
// The client's whole write model is "emit β†’ the host reruns β†’ a fresh payload
// arrives β†’ the UI reflects it" (CustomerGrid's own words: *"the emit itself
// triggers the host rerun, so the fresh name/list arrives with the next payload
// β€” no local mutation to drift from the store"*). Standalone has no rerun and
// X2 fixes `GET /api/v1/customers` at the EXACT current shape β€” `{fields, rows,
// today, pulled_at}`, with no `workspace`, no `cohorts`, no `docs`. So:
//
//   VISIBLE + DURABLE   view_upsert Β· view_delete Β· field_* Β· overlay_patch
//                       (the client already holds these in state + localStorage;
//                        the POST is what makes them durable server-side)
//   DURABLE, INVISIBLE  cohort_* Β· add_to_list Β· folder_* Β· item_move
//                       (they reach the store, but nothing re-reads them until
//                        the payload carries that state β€” EXIT-5). The server's
//                        `toast` is the only feedback the user gets, which is
//                        why it is wired through and not dropped.
//   NOT REACHABLE       doc_add / doc_fetch / doc_delete β€” the Documents panel
//                       is driven by `payload.docs`, which standalone never
//                       receives, so no doc event can be emitted at all. X2's
//                       `doc` field is therefore deliberately NOT handled here:
//                       wiring a response nobody can trigger is untestable dead
//                       code. When `/customers` grows `docs`, feed `doc` into
//                       the same `payload.docPayload` slot the embed uses.
//
// NOTHING HERE FALLS BACK TO `sample_customers.json`. That affordance ("the
// grid still renders with no backend") is unreachable now β€” the frame requires
// a session before CustomerGrid mounts at all β€” and behind a login, sample
// revenue rendered after a server hiccup is fabricated data on a screen the
// user has every reason to trust. An honest failure, always.
// ---------------------------------------------------------------------------

import {
  API_V1,
  CREDENTIALS,
  DATA_ERROR_EVENT,
  ROWS_STALE_EVENT,
  TOAST_EVENT,
  WORKSPACE_STALE_EVENT,
  UNAUTHORIZED_EVENT,
  checkTenant,
  currentTenant,
  PRINCIPAL_HEADER,
  TENANT_HEADER,
  signal,
} from "../apiContract";
import { createEditOutbox, OUTBOX_CHANGED_EVENT } from "./editOutbox";
import type { OutboxEdit, OutboxFailure, OutboxIdentity, OutboxReceipt, StoredEdit } from "./editOutbox";
import { applyPendingOps } from "./viewOps";
import { ROWS_CHUNK } from "./pipelineWorker";
import type { RowsReply, RowsRequest } from "./pipelineWorker";
import { eventId, setStandaloneSink } from "./hostBridge";
import { changedBuckets } from "./liveWorkspace";
import type { ChangeTokens } from "./liveWorkspace";
import { CUSTOMER_TOPIC, relatedEntries, relatedRefusals, topicForScope } from "./types";
import type { CustomersPayload, Field, FilterNode, GridLimit, GridWorkspace, HostEvent,
  RelatedEntry, RelatedPin, RelatedRefusal, Row, SortSpec, TopicConfig, ViewConfig } from "./types";
import type { TsPayload, TsRequest } from "./timeSeriesData";
import { AMAZON_STILL_LOADING_MESSAGE, MIRROR_RETRY_DELAYS, isMirrorNotLoaded,
  waitForMirror } from "./mirrorLoading";
import { FIRST_ANSWER_DEADLINE_MS, READ_DEADLINE_MS, WORKSPACE_DEADLINE_MS, armDeadline, fetchWithDeadline,
  isReadTimeout } from "../net/deadline";

const JSON_HEADERS = { "Content-Type": "application/json" };

/** R8 layout vocabulary. Membership, row values and schema never ride this door. */
export type PersonalGridLayout = Pick<ViewConfig,
  "order" | "visible" | "widths" | "sorts" | "filters" | "filterConj" | "groupBy">;

export function personalGridLayout(config: ViewConfig): PersonalGridLayout {
  return {
    order: config.order, visible: config.visible, widths: config.widths,
    sorts: config.sorts, filters: config.filters, filterConj: config.filterConj ?? "and",
    groupBy: config.groupBy,
  };
}

// Only outstanding writes live here, never a user's cached prefs. Remounts await the write
// before GET; a tab switch cannot cancel it or hydrate from the server's pre-save snapshot.
const personalLayoutWrites = new Map<string, {
  next: PersonalGridLayout | null;
  task: Promise<boolean>;
}>();

export function savePersonalGridLayout(key: string, layout: PersonalGridLayout): Promise<boolean> {
  const pending = personalLayoutWrites.get(key);
  if (pending) {
    pending.next = layout;
    return pending.task;
  }
  const entry = { next: layout as PersonalGridLayout | null, task: Promise.resolve(false) };
  personalLayoutWrites.set(key, entry);
  entry.task = Promise.resolve().then(async () => {
    let saved = true;
    try {
      while (entry.next) {
        const next = entry.next;
        entry.next = null;
        try {
          const res = await fetch(`${API_V1}/nav/prefs`, {
            method: "POST", credentials: CREDENTIALS, headers: JSON_HEADERS,
            body: JSON.stringify({ linkedLayouts: { [key]: next } }),
            keepalive: true,
          });
          if (handledSession(res)) { entry.next = null; return false; }
          if (!res.ok) {
            const body = await readJson(res);
            if ((body as { error?: { code?: string } } | null)?.error?.code === "data_input_frozen") {
              entry.next = null;
              signal(TOAST_EVENT, refusalMessage(body, res.status));
              return false;
            }
            throw new Error("layout write refused");
          }
        } catch {
          saved = false;
          signal(TOAST_EVENT, "Your grid layout could not be saved. Change a view control to retry.");
        }
      }
      return saved;
    } finally {
      personalLayoutWrites.delete(key);
    }
  });
  return entry.task;
}

export async function fetchPersonalGridLayout(key: string): Promise<{
  ok: boolean; layout: Partial<PersonalGridLayout> | null;
}> {
  await personalLayoutWrites.get(key)?.task;
  try {
    const res = await fetch(`${API_V1}/nav/prefs`, { credentials: CREDENTIALS, cache: "no-store" });
    if (handledSession(res)) return { ok: false, layout: null };
    if (!res.ok) throw new Error("layout read refused");
    const json = await readJson(res) as { prefs?: { linkedLayouts?: Record<string, PersonalGridLayout> } } | null;
    if (!json?.prefs) throw new Error("invalid preferences");
    const layout = json.prefs.linkedLayouts?.[key];
    return { ok: true, layout: layout && typeof layout === "object" ? layout : null };
  } catch {
    signal(TOAST_EVENT, "Your saved grid layout could not be loaded. Reopen this tab to retry.");
    return { ok: false, layout: null };
  }
}

async function readJson(res: Response): Promise<unknown> {
  try {
    return await res.json();
  } catch {
    return null;
  }
}

/** 401 is the one status that is never a data problem. Raised once, centrally,
 *  so every call site cannot forget to. Returns true when it handled it.
 *  The rows caches die with the session β€” the next signed-in user may not
 *  be the same person, and a cached book must never cross that boundary. */
function handledUnauthorized(status: number): boolean {
  if (status !== 401) return false;
  clearCustomersCache();
  signal(UNAUTHORIZED_EVENT);
  return true;
}

/**
 * The session check every authenticated call makes: the 401 above, PLUS the TENANT swap the
 * 401 path structurally cannot see.
 *
 * β›” WHY `handledUnauthorized` WAS NEVER ENOUGH. Its own note says the rows cache "dies with the
 * session β€” the next signed-in user may not be the same person". That is the USER boundary, and
 * it is enforced on 401. A TENANT swap produces no 401 at all: `aios_session` is one cookie per
 * ORIGIN, so signing into another tenant in a second tab repoints this one, and every request
 * here keeps returning a cheerful 200 full of somebody else's data. `checkTenant` reads the
 * server's own stamp and reloads the frame; see `apiContract.ts::TENANT_HEADER`.
 */
/**
 * ⭐ W62-T18 β€” WIDENED FROM `Response` TO WHAT IT ACTUALLY READS, and no further. A `Response`
 * still satisfies it, so every existing call site is unchanged; what it now also accepts is the
 * `{status, headers}` shim `rowsThroughWorker` builds from the worker's reply, because a worker
 * that did the fetch holds no `Response` for the main thread to hand over. `checkTenant` was
 * already written to this structural type (`apiContract.ts:99`) β€” this brings its caller into
 * line rather than inventing a second session check for the worker path, which is the one way
 * a tenant swap could have been missed on the read that matters most.
 */
interface SessionFacts {
  status: number;
  headers: { get(name: string): string | null };
}

function handledSession(res: SessionFacts): boolean {
  if (checkTenant(res)) { clearCustomersCache(); return true; }
  return handledUnauthorized(res.status);
}

// --- the READ (CP-B) -------------------------------------------------------

/**
 * The last good `/customers` payload, reused across surface switches. The rows
 * are a 15-minute-cached Odoo pull SERVER-side, but every Customer⇄Cohort
 * route change remounts the grid and re-downloaded the whole ~1 MB payload β€”
 * three full transfers in one short session, measured live. Within this window
 * a remount reuses the copy; the workspace (the cheap per-scope call) is always
 * re-fetched, so views/cohorts stay live.
 *
 * β›” THE CACHE IS SESSION-SCOPED OR IT IS A LEAK. It is cleared on ANY 401 and
 * on sign-out/sign-in (Shell calls `clearCustomersCache`) β€” one browser, two
 * accounts, and a cached book served across the boundary would be the exact
 * cross-user leak EXIT-3b exists to prevent, client-side this time.
 *
 * Own edits stay visible ([[the NO-BLIP law]]): `patchCustomer` writes accepted
 * values through into the cached rows, so a scope switch after an edit shows
 * the edit, not the pre-edit pull.
 */
const CUSTOMERS_FRESH_MS = 5 * 60_000;
// Wave 16 C-TOPIC: ONE cache map keyed by the topic's rows path, so the product pull and the
// customer pull each get the same 5-minute remount window without ever serving each other.
const rowsCache = new Map<string, { at: number; payload: CustomersPayload }>();
const rowWrites = new Map<string, Promise<boolean>>();
const rowVersions = new Map<string, number>();
type WindowCursor = string | number;
type WindowPayload = CustomersPayload & { next_cursor?: WindowCursor | null };
type WindowPaging = {
  table: string; version: number | undefined; at: number;
  next?: { offset: number; rowOffset: number; cursor: WindowCursor; seen: Set<WindowCursor>; stalled?: boolean };
};
type WindowReadBudget = { remaining: number; until: number; recoveries: number; mirrorRetries: number };
const windowPaging = new Map<string, WindowPaging>();
const WINDOW_REQUEST_BUDGET = 32;
let rowsSession = 0;
// Bumped only at an account boundary: a cache refresh must never cancel a cell write in flight.
let writeSession = 0;

/**
 * ⭐⭐ WAVE 31 · T21 (owner item 7: *"It still takes a very long time to load from one Database
 * into another"*) β€” THE WORKSPACE ENVELOPE, MEMOISED PER SCOPE.
 *
 * β›” WHAT WAS MISSING, stated exactly: `rowsCache` above has memoised ROWS since EXIT wave 1, and
 * `fetchWorkspace` had NO cache of any kind. So switching back to a database whose rows were
 * still warm STILL paid a full `/workspace` round trip β€” and that call is not cheap: it is
 * `ut_assembly`, which on tenant #0 reads a **28.6 MB** document (703 ms of deep copy, warm) plus
 * the whole `grid_events` workspace build. Measured live on `283b815`: **2,430 ms** for
 * `?scope=customer`. Every database→database hop paid it, both directions, for an envelope that
 * had not changed.
 *
 * ⚠ THE FRESHNESS WINDOW IS THE ROWS CACHE'S, ON PURPOSE. Two windows over one surface would
 * drift into a grid whose columns are newer than its rows, or the reverse β€” a shape this repo has
 * already paid for. One constant, both memos.
 *
 * β›” AND IT IS EVICTED BY THE WRITE PATH, NOT ONLY BY TIME. Every accepted grid event fires
 * `WORKSPACE_STALE_EVENT` β†’ `useCustomerData.reread()`, which calls this with no `allowCached`,
 * so it re-fetches AND overwrites this entry. Without that overwrite a person could hide a
 * field, switch away, switch back, and be served the pre-write envelope β€” the write silently
 * undone on screen, which is worse than the wait it replaced.
 */
const wsCache = new Map<string, { at: number; ws: GridWorkspace; current: boolean }>();
type WorkspaceRead = { ws: GridWorkspace | null; failure?: string; forbidden?: boolean; superseded?: boolean };
/** `forbidden`: the server refused this person the table, so a retry cannot help. */
export type WorkspaceStatus = { scope: SurfaceScope; state: "ready" | "absent" | "error"; message?: string;
  forbidden?: boolean };
export const WORKSPACE_ERROR_EVENT = "aios:workspace-error";
// Pending reads belong to the same memo, not a second result cache. Uncached post-write
// reads replace the joinable flight; an older completion must not remove that newer one.
const wsFlights = new Map<string, Promise<WorkspaceRead>>();
let wsCacheEpoch = 0;
let workspaceOrder = 0;
// Reads stamp request start. ACKs patch the memo before suppressing older flights.
const workspaceWrites = new Map<string, number>();
const workspaceReads = new WeakMap<GridWorkspace, number>();

/** Local read/ACK order survives workspace projections without changing the wire shape. */
export function workspaceReadOrder(workspace: GridWorkspace | undefined): number {
  return workspace ? workspaceReads.get(workspace) ?? 0 : 0;
}

export function clearWorkspaceCache(): void {
  wsCache.clear();
  wsFlights.clear();
  workspaceWrites.clear();
  wsCacheEpoch += 1;
}

export function clearCustomersCache(): void {
  editOutbox.sessionBoundary();
  rowWrites.clear();
  writeSession += 1;
  refreshCustomersCache();
}

/** Drop every cached read and keep the cell writes in flight: a stale workspace is not a sign-out. */
export function refreshCustomersCache(): void {
  rowsCache.clear();
  windowPaging.clear();
  rowVersions.clear();
  rowsSession += 1;
  // β›” THE ENVELOPE IS SESSION-SCOPED FOR THE SAME REASON THE ROWS ARE, and it carries MORE that
  // is per-account than they do: `viewer`, `userOptions`, the user's own views and folders. One
  // browser, two accounts, and a cached workspace served across the boundary would show the
  // previous person's saved views under the new person's name.
  clearWorkspaceCache();
  // β›” AND THE READ-THROUGH ROSTER, which is a per-SESSION fact, not a per-topic one. It names
  // which tables this tenant serves through the mirror; a second account signing into the same
  // browser is a different tenant's answer. Same boundary the rows cache is cleared on, and for
  // the same reason.
  readThroughMemo = null;
  connectedTablesMemo = null;
}

/**
 * Drop ONE topic's rows memo. The change poller's companion (wave 29, item 20).
 *
 * β›” NOT `clearCustomersCache()`, and the difference is a megabyte. That clears every topic's
 * window, so a poll that noticed a change on the Product grid would also force the Customer pool
 * to be re-downloaded on the next surface switch. One bucket changed; one memo is dropped.
 *
 * ⚠ WAVE 30 β€” it now sweeps a PREFIX, because one table can have many cache entries. A windowed
 * grid's key carries its offset and its predicate (see `windowRowsPath`), so `ut_odoo_orders`
 * may hold a dozen. Deleting the bare path would leave every one of them live.
 */
export function clearTopicRowsCache(rowsPath: string): void {
  const table = rowsPath === "customers" ? "customer_data" : rowsPath === "products" ? "product_data"
    : /^(?:odoo-tables|tables)\/([^/]+)\/rows$/.exec(rowsPath)?.[1];
  if (table) invalidateWindowPaging(decodeURIComponent(table));
  rowsCache.delete(rowsPath);
  for (const key of [...rowsCache.keys()])
    if (key.startsWith(`${rowsPath}?`)) rowsCache.delete(key);
}

/**
 * ⭐⭐ WAVE 30 Β· W30-T42 β€” DROP EVERY CACHED ROWS RESPONSE FOR ONE TABLE, WHICHEVER DOOR SERVED IT.
 *
 * β›” THE DEFECT THIS PREVENTS, AND IT IS THIS REPO'S NAMED CLASS. Before C2 a table had exactly
 * one rows key (`tables/<key>/rows`) and eight call sites deleted that literal. A read-through
 * grid is served by a DIFFERENT route (`odoo-tables/<key>/rows`) under MANY keys (one per
 * offset Γ— predicate), so every one of those literals silently stopped invalidating anything β€”
 * a write that returned 200 and a grid that kept painting the pre-write page, with no error
 * anywhere. Two invalidation laws for one question is [[one-question-two-normalizers]]; there
 * is one law and it lives here.
 *
 * ⚠ IT MATTERS DESPITE `recordsMutable: false`. A read-through Odoo grid refuses record edits,
 * but W30-T28 shipped tenant-wide SHARED COLUMNS on exactly these grids β€” `PATCH
 * /tables/{key}/shared/{pid}` writes a cell that rides the window payload's own `fields`/rows.
 */
export function dropTableRowsCache(tableKey: string): void {
  tableKey = tableKey === "customer" ? "customer_data" : tableKey === "product" ? "product_data" : tableKey;
  invalidateWindowPaging(tableKey);
  const prefixes = [`tables/${tableKey}/rows`, `odoo-tables/${tableKey}/rows`];
  for (const key of [...rowsCache.keys()])
    if (prefixes.some((p) => key === p || key.startsWith(`${p}?`))) rowsCache.delete(key);
}

function invalidateWindowPaging(tableKey: string): void {
  for (const [query, paging] of windowPaging)
    if (paging.table === tableKey) windowPaging.delete(query);
  rowVersions.set(tableKey, (rowVersions.get(tableKey) ?? 0) + 1);
}

/**
 * X2 `GET /api/v1/<topic.rowsPath>` β†’ `{fields, rows, today, pulled_at}`, rows already
 * scoped to the session's BU pool (EXIT-3b). The cookie replaces HTTP Basic.
 *
 * Returns null on ANY failure, having raised the matching signal. A null is not
 * an empty table: the frame renders a failure, not "this tenant has no
 * records", because those two look identical and only one of them is true.
 */
/**
 * ⭐ WAVE 30 (D-79's second half) β€” THE ONE READER OF A SERVER REFUSAL, and the reason it exists.
 *
 * β›” MEASURED: five call sites in this file read `body.detail.message`, and **the server has never
 * sent that shape.** `main.py`'s `_error_shape` handler unwraps `deps.err`'s `detail` before the
 * response leaves, so every non-2xx body on the wire is `{"error": {"code", "message"}}` β€” the
 * X2 contract, stated in that handler's own docstring. `body.detail` is `undefined` at all five,
 * so every carefully-worded refusal in the API ("this database already has a profile column β€”
 * 'Handle'. A database has at most one…") was replaced by "The server answered 400."
 *
 * That is worse than a missing feature: the product LOOKED like it was explaining itself. Sixteen
 * other call sites across the client already read `error.message` correctly, which is why nobody
 * noticed β€” the wrong shape survived only where nobody had recently read a refusal out loud.
 *
 * ⚠ THE `detail` LEG STAYS, AS A STRING. FastAPI's own `RequestValidationError` does NOT pass
 * through `_error_shape`, so a 422 from a malformed body still arrives shaped `{"detail": …}`.
 * Reading it as a string is honest; reading `.message` off it never was.
 */
export function refusalMessage(body: unknown, status: number, fallback?: string): string {
  const shaped = body as { error?: { message?: unknown }; message?: unknown;
    refused?: { message?: unknown }; detail?: unknown } | null | undefined;
  const named = shaped?.error?.message;
  if (typeof named === "string" && named.trim()) return named;
  const detail = shaped?.detail as { message?: unknown; error?: { message?: unknown } } | null;
  const supplied = shaped?.refused?.message ?? detail?.message ?? detail?.error?.message ?? shaped?.message;
  if (typeof supplied === "string" && supplied.trim()) return supplied;
  if (typeof shaped?.detail === "string" && shaped.detail.trim()) return shaped.detail;
  return fallback ?? `The server answered ${status}.`;
}

/**
 * ⭐⭐ W62-T18 / R51 β€” THE ROWS READ, OFF THE MAIN THREAD, IN BOUNDED PIECES.
 *
 * β›” THE MEASUREMENT IS THE WHOLE ARGUMENT, and it is committed beside this code in
 * `AutoWiki/waves/wave62/proto/T18-measure.md`. On staging's `sale.order.line.agent` database
 * (137,327 rows, 13 columns) the rows body is **69,944,226 bytes** (5.69 MB gzipped on the wire).
 * `await res.json()` over it cost **731 ms** unthrottled and **2,916 ms** at 4x CPU throttling,
 * and produced the only main-thread tasks over 200 ms in the whole open: 355 ms unthrottled,
 * **1,523 ms and 1,384 ms** throttled. A CPU profile of the same open attributes 870.6 ms of self
 * time to V8's `(program)` (the native parse) and 168.6 ms to the collector, against **22.6 ms
 * for the largest application frame in the profile**. The freeze is this one line, not the grid.
 *
 * β›” AND IT IS NOT THE PIPELINE, WHICH IS WHERE THE TICKET POINTED FIRST. `runPipeline` over the
 * same 137,327 rows costs 20-39 ms on open and 67-101 ms on a filter change; typing five
 * characters into the search box produced five tasks, none over 102 ms. Moving THAT to a worker
 * would have bought nothing and cost every feature R28 protects its synchronous access to the
 * rows. R51 asked for the cost to be measured before it was fixed; this is what the measurement
 * changed.
 *
 * β›” CHUNKED, BECAUSE ONE MESSAGE IS ONE TASK. The worker could hand the whole payload back in a
 * single `postMessage` (measured: 472 ms of main-thread wall unthrottled, 1,314 ms at 4x), or
 * columnar with a rebuild on this side (measured: a 256 ms rebuild at 4x β€” over budget on its
 * own). Ten-thousand-row slices measured 208 ms total unthrottled with NO long task recorded at
 * all, and a worst task of **70 ms** at 4x. The bound is the point: each slice is deserialised in
 * its own task, so the main thread stays interruptible however far the table grows.
 * ⚠ 2,000-row slices measured WORSE at both speeds (293 ms / 1,131 ms, the only long tasks the
 * experiment recorded on any chunked leg) β€” per-message overhead and the garbage it makes. Do not
 * "tune" this down without re-running the experiment in that file.
 *
 * ⭐ NO CAP, ANYWHERE (standing rule 1). Every row the server sends is accumulated and handed to
 * the caller; the chunking is a delivery schedule, not a window. There is no paging, no "See
 * more" and no second virtualiser β€” the grid is still glide's canvas.
 *
 * ⚠ ONE WORKER, REUSED, AND IT MAY REFUSE TO EXIST. Any environment without `Worker` (the gates
 * execute parts of this client under node) or any construction failure falls back to the old
 * main-thread read, which is exactly today's behaviour. `workerDead` latches so a browser that
 * cannot build workers pays the attempt once rather than once per read.
 */
let rowsWorker: Worker | null = null;
let rowsWorkerDead = false;
let rowsRequestId = 0;

function theRowsWorker(): Worker | null {
  if (rowsWorkerDead) return null;
  if (rowsWorker) return rowsWorker;
  try {
    if (typeof Worker === "undefined") { rowsWorkerDead = true; return null; }
    rowsWorker = new Worker(new URL("./pipelineWorker.ts", import.meta.url), { type: "module" });
    // An error that reaches here killed the worker, not one read: drop it and let the next
    // caller take the main-thread path rather than wait on a worker that cannot answer.
    rowsWorker.addEventListener("error", () => {
      rowsWorkerDead = true;
      try { rowsWorker?.terminate(); } catch { /* already gone */ }
      rowsWorker = null;
    });
    return rowsWorker;
  } catch {
    rowsWorkerDead = true;
    rowsWorker = null;
    return null;
  }
}

/** The worker's header map as something `checkTenant`/`handledSession` can read. Case-insensitive,
 *  like the `Headers.get` it stands in for. */
function headerReader(map: Record<string, string>): SessionFacts["headers"] {
  return { get: (name: string) => map[name.toLowerCase()] ?? null };
}

/** What `rowsThroughWorker` hands back: the same three outcomes the main-thread read has, kept
 *  apart so the caller raises exactly what it raises today. */
type WorkerRead =
  | { ok: true; payload: unknown; facts: SessionFacts }
  | { ok: false; kind: "refused"; body: unknown; facts: SessionFacts }
  | { ok: false; kind: "unavailable" }
  | { ok: false; kind: "stalled" };

/**
 * ⚠ The only bound is FIRST_ANSWER_DEADLINE_MS before the head arrives ("stalled"): a server that
 * never answers ends in an error, while a body that is arriving is never cut off.
 * ⚠ NO BODY TIMEOUT HERE, AND THAT IS A DECISION RATHER THAN AN OVERSIGHT. A worker that dies loudly
 * raises `error` (the listener above retires it) and a fetch that fails posts `failed`, so both
 * realistic failures already fall back. What is left uncovered is a worker that hangs silently -
 * and the main-thread read this replaces has no timeout either, so a timer here would not close a
 * gap, it would only add a way to fire DURING a healthy read: this table's own rows request
 * measured 10-48 s, so any bound short enough to be useful is short enough to re-request 66.7 MB
 * that was already on its way.
 */
function rowsThroughWorker(url: string): Promise<WorkerRead> {
  const worker = theRowsWorker();
  if (!worker) return Promise.resolve({ ok: false, kind: "unavailable" });
  const id = ++rowsRequestId;
  return new Promise<WorkerRead>((resolve) => {
    let head: Record<string, unknown> | null = null;
    let facts: SessionFacts | null = null;
    /* ⭐ PRE-ALLOCATED FROM THE HEAD'S OWN `total`, and it is worth the extra field. Measured at 4x
       CPU throttling on the 137,327-row table: growing this array with `push` cost 1,038 ms of
       main-thread self time - the single largest application frame in the whole profiled open,
       ahead of the pipeline (133 ms) and React's own commit - because a 137k-element array grows
       by reallocating and copying about twenty times on the way up. Writing into a right-sized
       array at a running offset pays none of that. The bound per slice is unchanged; what goes
       away is the copying between slices. */
    let rows: unknown[] = [];
    let filled = 0;
    let firstAnswer: ReturnType<typeof setTimeout> | undefined;
    const finish = (result: WorkerRead): void => {
      clearTimeout(firstAnswer);
      worker.removeEventListener("message", onMessage);
      resolve(result);
    };
    const onMessage = (event: MessageEvent<RowsReply>): void => {
      const reply = event.data;
      // ⚠ ONE WORKER SERVES EVERY READER, so a reply that is not this request's is another
      // caller's rows. Ignoring it here is what makes the shared worker safe.
      if (!reply || reply.id !== id) return;
      if (reply.op === "head") {
        clearTimeout(firstAnswer);
        head = reply.head;
        facts = { status: reply.status, headers: headerReader(reply.headers) };
        rows = new Array(reply.total);
        filled = 0;
      } else if (reply.op === "slice") {
        // A loop, not `push(...slice)`: spreading 10,000 arguments is a stack overflow on some
        // engines, and this path exists to be dependable on a big table.
        // ⚠ `filled` rather than the array's length, because the array is already at its final
        // length. A server that sent more rows than its own `total` still lands them all - the
        // assignment grows the array the ordinary way - so this cannot drop a row.
        for (let i = 0; i < reply.slice.length; i += 1) rows[filled + i] = reply.slice[i];
        filled += reply.slice.length;
      } else if (reply.op === "refused") {
        finish({ ok: false, kind: "refused", body: reply.body,
                 facts: { status: reply.status, headers: headerReader(reply.headers) } });
      } else if (reply.op === "failed") {
        // The fetch never happened, or the body was unreadable. Fall back rather than raise: the
        // main-thread read owns those two messages and must keep owning them.
        finish({ ok: false, kind: "unavailable" });
      } else if (reply.op === "done") {
        if (!head || !facts) finish({ ok: false, kind: "unavailable" });
        // A short count means a slice was lost between the two threads. Trimming keeps the array
        // honest rather than handing the grid trailing holes that read as blank records.
        else finish({ ok: true, payload: { ...head, rows: filled === rows.length ? rows : rows.slice(0, filled) }, facts });
      }
    };
    worker.addEventListener("message", onMessage);
    firstAnswer = setTimeout(() => finish({ ok: false, kind: "stalled" }), FIRST_ANSWER_DEADLINE_MS);
    try {
      worker.postMessage({ id, url, chunk: ROWS_CHUNK } satisfies RowsRequest);
    } catch {
      finish({ ok: false, kind: "unavailable" });
    }
  });
}

/** The machine code of an X2 refusal (`{error: {code, message}}`), or "" when it names none. */
function refusalCode(body: unknown): string {
  const code = (body as { error?: { code?: unknown } } | null | undefined)?.error?.code;
  return typeof code === "string" ? code : "";
}

/** The code a rows failure carries when the server refused this person the table. */
export const FORBIDDEN_CODE = "forbidden";
/** The one line a table shows when the server refuses this person access to it. */
export const ACCESS_REFUSED_MESSAGE = "You do not have access to this table. Ask an Administrator.";
/** A 403, or a refusal coded `forbidden`. Decided by status and code, never by the message text. */
export function isForbiddenRefusal(status: number, body: unknown): boolean {
  return status === 403 || refusalCode(body) === FORBIDDEN_CODE;
}
/** A rows refusal's code, with every 403 normalised to `FORBIDDEN_CODE`. */
function rowsRefusalCode(status: number, body: unknown): string {
  return isForbiddenRefusal(status, body) ? FORBIDDEN_CODE : refusalCode(body);
}

/**
 * β›” D-3495 (staging, 2026-09-29) β€” A `window_required` REFUSAL FROM THIS DOOR MEANS THE ROSTER
 * WAS WRONG, so the memo is dropped right here, for every caller. The roster is memoised per
 * session, and a tab that asked it before the Amazon mirror restore (about 19 minutes after
 * every boot) held an answer with no `ut_amzn_*` key for as long as the tab stayed open. Every
 * Amazon read-through grid then opened on THIS whole-book door and got 409 until a manual
 * reload, however correct the server's registry had become. The next `readThroughTables()` asks
 * the server again. `onFailure`, like `fetchTableWindow`'s, lets a caller that can recover (the
 * grid reroutes to the window door) take the refusal instead of the global error signal.
 */
export async function fetchTopicRows(
  topic: TopicConfig,
  onFailure?: (reason: string, code: string) => void
): Promise<CustomersPayload | null> {
  const fail = (reason: string, code = "") => {
    if (code === "window_required") readThroughMemo = null;
    if (onFailure) onFailure(reason, code);
    else signal(DATA_ERROR_EVENT, reason);
  };
  const cached = rowsCache.get(topic.rowsPath);
  if (cached && Date.now() - cached.at < CUSTOMERS_FRESH_MS) {
    return cached.payload;
  }
  const version = rowVersions.get(topic.key);
  const session = rowsSession;
  // ⭐ W62-T18 β€” the worker leg FIRST, the main-thread read below as the fallback. Both end in
  // the same three outcomes and the same cache write; what differs is only which thread pays for
  // `JSON.parse`. See `rowsThroughWorker` for the measurement that put it here.
  const offThread = await rowsThroughWorker(`${API_V1}/${topic.rowsPath}`);
  if (!offThread.ok && offThread.kind === "stalled") {
    // A server that never answered is not retried on the main thread: that would double the wait.
    fail(DATABASE_TIMEOUT_MESSAGE);
    return null;
  }
  if (offThread.ok || offThread.kind === "refused") {
    if (handledSession(offThread.facts)) return null;
    if (!offThread.ok) {
      fail(refusalMessage(offThread.body, offThread.facts.status),
        rowsRefusalCode(offThread.facts.status, offThread.body));
      return null;
    }
    const carried = offThread.payload as CustomersPayload | null;
    if (!carried || !Array.isArray(carried.rows) || !Array.isArray(carried.fields)) {
      fail("The server sent an unreadable payload.");
      return null;
    }
    if (session !== rowsSession) return null;
    if (version !== rowVersions.get(topic.key)) return fetchTopicRows(topic, onFailure);
    observeCanonicalRows(topic, carried);
    rowsCache.set(topic.rowsPath, { at: Date.now(), payload: carried });
    return carried;
  }
  let res: Response;
  // Bounds the wait for the server's first answer only; the body below is never timed.
  const controller = new AbortController();
  const firstAnswer = armDeadline(controller, FIRST_ANSWER_DEADLINE_MS);
  try {
    res = await fetch(`${API_V1}/${topic.rowsPath}`, { credentials: CREDENTIALS, signal: controller.signal });
  } catch {
    fail(firstAnswer.expired() ? DATABASE_TIMEOUT_MESSAGE : "Cannot reach the server.");
    return null;
  } finally {
    firstAnswer.disarm();
  }
  if (handledSession(res)) return null;
  if (!res.ok) {
    // ⭐ WAVE 30 β€” R's ask, and it is the SIXTH site of the shape T44 closed five of. This path
    // answered every non-2xx with a bare status while `refusalMessage` sat 50 lines above it,
    // and TWO cause-carrying refusals now arrive here: `store_not_ready` (503, live on a
    // connected grid before the mirror's first sync) and the window route's own 409. Both name
    // their cause and their fix; both used to render as "The server answered 503."
    const refused = await readJson(res);
    fail(refusalMessage(refused, res.status), rowsRefusalCode(res.status, refused));
    return null;
  }
  const body = (await readJson(res)) as CustomersPayload | null;
  if (!body || !Array.isArray(body.rows) || !Array.isArray(body.fields)) {
    fail("The server sent an unreadable payload.");
    return null;
  }
  if (session !== rowsSession) return null;
  if (version !== rowVersions.get(topic.key)) return fetchTopicRows(topic, onFailure);
  observeCanonicalRows(topic, body);
  rowsCache.set(topic.rowsPath, { at: Date.now(), payload: body });
  return body;
}

/** The customer topic's fetch β€” kept under its own name because half the write-path notes in
 *  this repo cite it; it IS `fetchTopicRows(CUSTOMER_TOPIC)`. */
export function fetchCustomers(): Promise<CustomersPayload | null> {
  return fetchTopicRows(CUSTOMER_TOPIC);
}

/** C4/R9: assigned rows are selected by the server, never re-filtered from a wider client cache. */
export async function fetchAssignedCustomerRows(viewId: string): Promise<CustomersPayload | null> {
  try {
    const res = await fetch(`${API_V1}/customers/assigned/${encodeURIComponent(viewId)}/rows`,
      { credentials: CREDENTIALS });
    if (!res.ok) {
      signal(DATA_ERROR_EVENT, refusalMessage(await readJson(res), res.status));
      return null;
    }
    const body = await readJson(res) as CustomersPayload | null;
    return body && Array.isArray(body.rows) && Array.isArray(body.fields) ? body : null;
  } catch {
    signal(DATA_ERROR_EVENT, "Cannot reach the assigned view.");
    return null;
  }
}

// ═══════════════════════════════════════════════════════════════════════════════════════════
// ⭐⭐ WAVE 30 Β· W30-T42 β€” THE READ-THROUGH WINDOW (owner ruling R6 via R7, contract C2).
// ═══════════════════════════════════════════════════════════════════════════════════════════
//
// THE SHAPE OF THE PROBLEM, in the owner's numbers. `tables/<key>/rows` serves a table by
// copying it out of the tenant's `user_tables` document, which is why `MAX_ROWS = 60_000`
// exists and why order lines (255,286) and GL lines (963,783) could never be grids at all.
// W30-T26 built the other door: `odoo-tables/<key>/rows` reads the DuckDB mirror and answers
// `{rows, total, totalUnfiltered, offset, limit, limits}` β€” the requested slice plus a
// `SELECT count(*)` that tells the truth about the whole.
//
// β›” THE CLIENT MACHINERY FOR THIS ALREADY EXISTED AND WAS DORMANT β€” `TableMode`,
// `ScopeCounts`, `countLabel`'s "showing 200 of 201,558", `useVisibleRows`' pass-through and
// every `serverWindowed` guard in `CustomerGrid`. What did not exist was anything that ever
// SET `counts.windowed`: a mode reachable only by a payload no fetch path had ever built. So
// what is added below is a fetch and a mapping, not an engine.
//
// β›” `counts.matched` IS THE SERVER'S `total`, NEVER `rows.length`. That is the fabricated
// aggregate this repo has paid for twice ([[no-unverifiable-aggregates]]) and it is the ONE
// number the whole contract exists to protect: a 200-row response describing 32,826 orders.

/** One window's worth of rows. 200 is what D measured the route at (79 ms warm on 32,700
 *  orders, against 474 ms for the whole read); the server clamps anything over
 *  `datastore.WINDOW_MAX` (5,000) and REPORTS the clamp rather than trimming quietly. */
// HOTFIX 2026-09-23 (owner): "pagination or next page and only load 50 at a time". The grid
// pages a read-through table 50 rows at a time with Prev / Next; `total` stays the server's.
export const WINDOW_ROWS = 100;

/** HOTFIX 2026-09-24 (owner): "a pagination option, 50/100/200 at a time, while 100 record at a
 *  time is the default." One vocabulary for every database, remembered per browser. */
export const PAGE_SIZES = [50, 100, 200] as const;
const PAGE_SIZE_KEY = "cg.pageSize";

export function readPageSize(): number {
  try {
    const n = Number(localStorage.getItem(PAGE_SIZE_KEY));
    return (PAGE_SIZES as readonly number[]).includes(n) ? n : WINDOW_ROWS;
  } catch {
    return WINDOW_ROWS;
  }
}

export function writePageSize(n: number): void {
  try {
    localStorage.setItem(PAGE_SIZE_KEY, String(n));
  } catch {
    /* a blocked store only loses the preference, never the page */
  }
}

export interface RowWindowRequest {
  offset: number;
  limit: number;
  /** A server continuation takes precedence over a jump offset. */
  cursor?: WindowCursor | null;
  /** Cell/link record IDs, intersected on the server before counting and paging. */
  ids?: readonly number[];
  /** The saved view's OWN objects. β›” Not translated β€” see `windowRowsPath`. */
  filters?: FilterNode[] | null;
  filterConj?: string;
  sorts?: SortSpec | null;
  search?: string;
  /**
   * ⭐⭐ W51-T06 / C6 β€” THE PINNED READ. `{table, record, via}`: narrow this window to the rows
   * related to ONE record of another database, ahead of `filters`.
   *
   * β›” IT IS PART OF THE PATH, therefore part of the CACHE KEY, and that is not a nicety.
   * `rowsCache` is keyed by path (see `windowRowsPath`), so a pin that stayed out of the string
   * would make a pinned read a cache HIT on the unpinned one this browser already holds β€” the
   * whole table painted under a tab that names one record, served from memory, with no request
   * to see in the network panel.
   */
  related?: RelatedPin | null;
  /** HOTFIX 2026-09-23 β€” page ONE group of `/aggregates`' grouping. `key` is the group key
   *  exactly as `/aggregates` put it on the wire (`null` = the blank bucket). Part of the path,
   *  therefore part of the cache key. */
  group?: { by: string; key: string | number | null } | null;
}

/**
 * The request path for one window β€” AND, deliberately, its cache key.
 *
 * β›” THE TICKET'S NAMED TRAP, SOLVED BY CONSTRUCTION. `rowsCache` is keyed by path. A windowed
 * path that omitted its offset would make page 2 a cache HIT on page 1 β€” a scroll that fetches,
 * succeeds, and paints the same rows forever. Rather than remember to key the cache on
 * "path + offset + predicate" at each call site, ONE function builds the string and the caller
 * uses it for both. They cannot disagree because they are the same value.
 *
 * β›” THE PREDICATE RIDES AS THE CLIENT'S OWN VOCABULARY. `filters` is `ViewConfig.filters`
 * (a `FilterNode[]`), `filterConj` is `ViewConfig.filterConj`, `sorts` is `ViewConfig.sorts` β€”
 * JSON, verbatim, no translation layer. D built `compile_filter_tree` to take exactly these
 * objects, and an unparseable `filters` is answered with a 400 rather than "no filter",
 * because a condition that is quietly dropped WIDENS and a wider answer looks plausible.
 *
 * ⚠ Empty parts are OMITTED, not sent blank: a view with no filter must produce the identical
 * path the first (predicate-free) window used, or the very first scroll misses the cache.
 */
export function usesPinnedRows(tableKey: string, related: RelatedPin | null | undefined): boolean {
  return Boolean(tableKey && related);
}

export function windowRowsPath(tableKey: string, req: RowWindowRequest): string {
  tableKey = tableKey === "customer" ? "customer_data" : tableKey === "product" ? "product_data" : tableKey;
  const q = new URLSearchParams();
  if (req.cursor != null) q.set("cursor", String(req.cursor));
  else q.set("offset", String(Math.max(0, Math.floor(req.offset || 0))));
  q.set("limit", String(Math.max(1, Math.floor(req.limit || WINDOW_ROWS))));
  if (req.filters && req.filters.length) {
    q.set("filters", JSON.stringify(req.filters));
    if (req.filterConj === "or") q.set("filterConj", "or");
  }
  if (req.sorts && req.sorts.length) q.set("sorts", JSON.stringify(req.sorts));
  const search = (req.search ?? "").trim();
  if (search) q.set("search", search);
  /* ⭐⭐ W51-T06 / C6 β€” THE PIN RIDES AS A JSON QUERY STRING, copying the `filters` precedent one
     argument over, because `GET /odoo-tables/{key}/rows` is a GET and its `related` argument is
     `Query(default=None)` (`routes_odoo_tables.py::odoo_table_rows`). β›” THE AGGREGATES DOOR IS
     A POST AND TAKES THE SAME OBJECT AS A BODY KEY β€” see `fetchAggregates`. Two transports, one
     payload; assuming both were bodies is the half-wired contract that paints the right rows
     under a summary computed over the whole table. */
  if (req.related) q.set("related", JSON.stringify(req.related));
  if (req.group && req.group.by) {
    q.set("groupBy", req.group.by);
    q.set("groupKey", JSON.stringify(req.group.key ?? null));
  }
  /* S66-T48: a cell's record set rides in the POST BODY (`windowRowsInit`), because a drill of
     thousands of ids overflows a URL. The path carries only its count and digest, so the path is
     still the one cache key: two sets never share an entry, one set in any order shares one. */
  if (req.ids !== undefined) q.set("ids", `${new Set(req.ids).size}.${idSetDigest(req.ids)}`);
  return `odoo-tables/${encodeURIComponent(tableKey)}/rows?${q.toString()}`;
}

/** Stable set identity for component dependencies and the path's id digest. */
export function recordIdsKey(ids: readonly number[] | undefined): string {
  return ids === undefined ? "" : JSON.stringify([...new Set(ids)].sort((a, b) => a - b));
}

/** A 53-bit digest of the sorted id set: the path names WHICH records without carrying them.
 *  Synchronous on purpose, so `windowRowsPath` stays one pure string builder. */
function idSetDigest(ids: readonly number[]): string {
  const key = recordIdsKey(ids);
  let h1 = 0xdeadbeef, h2 = 0x41c6ce57;
  for (let i = 0; i < key.length; i++) {
    const ch = key.charCodeAt(i);
    h1 = Math.imul(h1 ^ ch, 2654435761);
    h2 = Math.imul(h2 ^ ch, 1597334677);
  }
  h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
  h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
}

/** How the window at `windowRowsPath` is fetched: a GET, or with a record set a POST whose body
 *  is that set and nothing else (every other part of the question stays in the path). */
export function windowRowsInit(req: RowWindowRequest): RequestInit {
  if (req.ids === undefined) return { credentials: CREDENTIALS };
  return {
    method: "POST", credentials: CREDENTIALS, headers: JSON_HEADERS,
    body: JSON.stringify({ ids: JSON.parse(recordIdsKey(req.ids)) as number[] }),
  };
}

/**
 * D's window envelope β†’ the payload this client already knows how to render.
 *
 * β›” `windowed` IS TRUE FOR EVERY READ-THROUGH RESPONSE, INCLUDING ONE THAT HAPPENS TO HOLD THE
 * WHOLE TABLE, and that is not sloppiness. The mode is about WHO EVALUATES THE PREDICATE, not
 * about whether this particular response was truncated. A 192-row table answered in full still
 * had its filter compiled to SQL β€” flipping to `whole-book` because nothing was cut would
 * switch the TypeScript engine back on and filter the server's already-filtered rows a second
 * time. `countLabel` handles the no-truncation case honestly on its own (`shown >= matched`
 * renders a plain count with no "showing … of"), so nothing is lost by keeping the mode stable.
 *
 * Returns null on a shape it cannot read β€” the caller raises the signal, because a payload the
 * client cannot parse is a failure, never an empty table.
 */
export function windowPayload(body: unknown): WindowPayload | null {
  const b = body as {
    fields?: unknown; rows?: unknown; total?: unknown; totalUnfiltered?: unknown;
    limits?: unknown; today?: unknown; recordsMutable?: unknown; next_cursor?: unknown;
  } | null;
  if (!b || !Array.isArray(b.rows) || !Array.isArray(b.fields)) return null;
  if (typeof b.total !== "number" || !Number.isFinite(b.total)) return null;
  const rows = b.rows as Row[];
  const unfiltered =
    typeof b.totalUnfiltered === "number" && Number.isFinite(b.totalUnfiltered)
      ? b.totalUnfiltered
      : b.total;
  if (b.next_cursor != null && !((typeof b.next_cursor === "string" && b.next_cursor.length > 0)
      || (typeof b.next_cursor === "number" && Number.isSafeInteger(b.next_cursor) && b.next_cursor >= 0))) return null;
  const out: WindowPayload = {
    fields: b.fields as Field[],
    rows,
    counts: {
      shown: rows.length,
      // β›” FROM THE SERVER'S COUNT STATEMENT. Never `rows.length`.
      matched: b.total,
      total: unfiltered,
      windowed: true,
    },
  };
  if (Array.isArray(b.limits)) out.limits = b.limits as GridLimit[];
  if (typeof b.today === "string") out.today = b.today;
  if (typeof b.recordsMutable === "boolean") out.recordsMutable = b.recordsMutable;
  if (b.next_cursor !== undefined) out.next_cursor = b.next_cursor as WindowCursor | null;
  return out;
}

/**
 * Fold a freshly-fetched window into what this browser already holds.
 *
 * β›” `offset === 0` REPLACES BUT MUST NOT BLANK THE WORKSPACE. A predicate change re-requests
 * from the top, and the window route serves rows β€” it knows nothing about saved views, folders,
 * cohorts, measures, documents or the viewer, all of which `withWorkspace` merged into the live
 * payload from a different call. Returning the bare response would empty the Views sidebar on
 * every keystroke in the search box. So the window's keys land OVER the existing payload.
 *
 * β›” AN APPEND WHOSE OFFSET DOES NOT MEET THE LOADED COUNT IS DROPPED, NOT GUESSED. Windows are
 * contiguous under a total order; a page that starts anywhere else is a response to a question
 * this browser no longer holds the answer to (a predicate changed mid-flight, two scrolls
 * raced). Appending it anyway would duplicate or skip rows β€” data the user sees, with nothing
 * erroring. Dropping it costs one scroll's latency and the next event re-asks.
 */
export function mergeWindow(
  prev: CustomersPayload | null,
  next: CustomersPayload,
  offset: number
): CustomersPayload | null {
  if (offset <= 0) return { ...(prev ?? {}), ...next };
  if (!prev || !prev.counts?.windowed) return prev;
  if (offset !== prev.rows.length) return prev;
  const rows = [...prev.rows, ...next.rows];
  return {
    ...prev,
    rows,
    limits: next.limits,
    // The NEWEST scope-wide numbers win (the table can move under a long scroll); only `shown`
    // is ours, because only this browser knows how much of it is actually here.
    counts: { ...(next.counts ?? prev.counts), shown: rows.length },
  };
}

/**
 * Which of this tenant's tables are served THROUGH the mirror β€” asked once per session.
 *
 * β›” READ FROM THE SERVER, NEVER A KEY LIST HERE. The bindings convert one bucket at a time
 * (`GRID_SOURCES`), and `odoo-tables/status` reports `readThrough` per table for exactly this
 * reason. A hard-coded list in the client would go stale on D's next spec row and fail in the
 * dangerous direction β€” asking the window route for a table it cannot serve, which answers 409.
 *
 * ⚠ `bound_not_declared` keys are DELIBERATELY not here: they ride a separate map on that
 * response because a binding whose field declaration has not landed answers 404 on the rows
 * route. Reading only `tables` is what keeps a half-shipped grid out of windowed mode.
 *
 * β›” FAIL-SOFT, AND IN THE SAFE DIRECTION. Any failure yields the empty set, i.e. today's
 * whole-book behaviour, and the memo is NOT poisoned β€” a transient 500 must not pin a session
 * into the slow path for as long as the tab is open.
 */
let readThroughMemo: Promise<Set<string>> | null = null;

export function readThroughTables(): Promise<Set<string>> {
  if (!readThroughMemo) {
    readThroughMemo = (async () => {
      try {
        // The grid needs only the read-through flag, never the operator status's counts/stamps.
        // `brief=1` is server-derived from the connected-grid registry and reads no table rows.
        // A stalled server rejects at the deadline, so only a resolved success stays memoised.
        // The session check runs before the body is parsed: a tenant swap reloads unread.
        let handled = false;
        const { res, body: read } = await fetchWithDeadline(`${API_V1}/odoo-tables/status?brief=1`,
          { credentials: CREDENTIALS }, (r) => (handled = handledSession(r)) ? Promise.resolve(null) : readJson(r));
        if (handled || !res.ok) {
          readThroughMemo = null;
          return new Set<string>();
        }
        const body = read as
          { tables?: Record<string, { readThrough?: boolean }> } | null;
        const out = new Set<string>();
        for (const [key, t] of Object.entries(body?.tables ?? {}))
          if (t?.readThrough === true) out.add(key);
        return out;
      } catch {
        readThroughMemo = null;
        return new Set<string>();
      }
    })();
  }
  return readThroughMemo;
}

let connectedTablesMemo: Promise<Set<string> | null> | null = null;

/** Connected tables use overlay events whether their source rows are materialized or read through. */
function connectedTables(abort: AbortSignal): Promise<Set<string> | null> {
  if (!connectedTablesMemo) {
    connectedTablesMemo = (async () => {
      try {
        const res = await fetch(`${API_V1}/tables?brief=1`, { credentials: CREDENTIALS, signal: abort });
        if (handledSession(res) || !res.ok) {
          connectedTablesMemo = null;
          return null;
        }
        const body = await readJson(res) as { tables?: { key: string; connected?: boolean }[] } | null;
        if (!Array.isArray(body?.tables) || body.tables.some((table) =>
          table.key.startsWith("ut_") && typeof table.connected !== "boolean")) {
          connectedTablesMemo = null;
          return null;
        }
        return new Set(body.tables.filter((table) => table.connected === true).map((table) => table.key));
      } catch {
        connectedTablesMemo = null;
        return null;
      }
    })();
  }
  return connectedTablesMemo;
}

/**
 * S85-T27: the window this session already fetched for exactly this question, or null.
 *
 * The key is `windowRowsPath`, so scope, filter, sort, search, group page, pin and offset all
 * select it, never a view id. No age limit: a cell write patches or drops it (`adoptCachedRow`),
 * an outside change and a session boundary drop it, and the caller refreshes it after painting.
 * `fresh` is true inside the read window `fetchTableWindow` itself would serve without a request.
 */
export function peekTableWindow(tableKey: string, req: RowWindowRequest):
    { payload: WindowPayload; fresh: boolean } | null {
  const held = rowsCache.get(windowRowsPath(tableKey, req));
  return held ? { payload: held.payload as WindowPayload, fresh: Date.now() - held.at < CUSTOMERS_FRESH_MS } : null;
}

/** One window, mapped. A failure returns null and reports through the caller's handler or
 * the default data-error signal; null is never an empty table. `fresh` skips the memo read
 * and still stores the answer: the refresh of a window painted from `peekTableWindow`. */
export async function fetchTableWindow(
  tableKey: string,
  req: RowWindowRequest,
  onFailure?: (reason: string, code?: string) => void,
  budget: WindowReadBudget = { remaining: WINDOW_REQUEST_BUDGET,
    until: Date.now() + READ_DEADLINE_MS, recoveries: 0, mirrorRetries: 0 },
  fresh = false
): Promise<WindowPayload | null> {
  tableKey = tableKey === "customer" ? "customer_data" : tableKey === "product" ? "product_data" : tableKey;
  // Optional record enrichment reports its failure inline without replacing the open drawer.
  // A 403 carries `FORBIDDEN_CODE`, so the grid can paint its access line in place of an error card.
  const fail: (reason: string, code?: string) => void = onFailure
    ?? ((reason) => signal(DATA_ERROR_EVENT, reason));
  const path = windowRowsPath(tableKey, req);
  const query = windowRowsPath(tableKey, { ...req, offset: 0, cursor: undefined });
  const pagingKey = query;
  const version = rowVersions.get(tableKey);
  const session = rowsSession;
  let paging = windowPaging.get(pagingKey);
  if (!paging || paging.version !== version
      || Date.now() - paging.at >= CUSTOMERS_FRESH_MS) {
    paging = { table: tableKey, version, at: Date.now() };
    windowPaging.set(pagingKey, paging);
  }
  const cached = rowsCache.get(path);
  if (cached && !fresh && Date.now() - cached.at < CUSTOMERS_FRESH_MS) return cached.payload as WindowPayload;
  // Page numbers and record drains address the same server continuation differently.
  const checkpoint = paging.next && (paging.next.offset === req.offset
    || paging.next.rowOffset === req.offset) ? paging.next : undefined;
  if ((checkpoint?.stalled && req.cursor == null)
      || (paging.next?.stalled && req.cursor === paging.next.cursor)) {
    fail("Cannot load the next page. Reload this database to continue.");
    return null;
  }
  let cursor = req.cursor ?? checkpoint?.cursor;
  const seen = new Set(checkpoint?.seen ?? (cursor != null ? [cursor] : []));
  const isCurrent = () => session === rowsSession && version === rowVersions.get(tableKey)
    && windowPaging.get(pagingKey) === paging;
  const recover = (): Promise<WindowPayload | null> => {
    if (session !== rowsSession) return Promise.resolve(null);
    if (budget.recoveries++ >= 1) {
      fail("Database paging changed again. Reload this database to continue.");
      return Promise.resolve(null);
    }
    if (windowPaging.get(pagingKey) === paging) windowPaging.delete(pagingKey);
    rowsCache.delete(path);
    return fetchTableWindow(tableKey, { ...req, cursor: undefined }, onFailure, budget);
  };
  let res: Response;
  let body: unknown;
  let payload: WindowPayload;
  for (;;) {
    if (session !== rowsSession) return null;
    if (version !== rowVersions.get(tableKey)) return recover();
    if (windowPaging.get(pagingKey) !== paging) return null;
    const remainingMs = budget.until - Date.now();
    if (remainingMs <= 0 || budget.remaining-- <= 0) {
      fail(remainingMs <= 0 ? "Database paging timed out. Try this page again."
        : "Cannot load this page yet. Try again.");
      return null;
    }
    const wire = cursor != null ? windowRowsPath(tableKey, { ...req, cursor }) : path;
    try {
      // One page is bounded by the deadline, body included, so a stalled server cannot spin the grid.
      // The session check runs before the body is parsed: a tenant swap reloads unread.
      let handled = false;
      ({ res, body } = await fetchWithDeadline(`${API_V1}/${wire}`, windowRowsInit(req),
        (r) => (handled = handledSession(r)) ? Promise.resolve(null) : readJson(r),
        Math.min(READ_DEADLINE_MS, remainingMs)));
      if (handled) return null;
    } catch (error) {
      if (!isCurrent()) return null;
      fail(isReadTimeout(error) ? DATABASE_TIMEOUT_MESSAGE : "Cannot reach the server.");
      return null;
    }
    if (session !== rowsSession) return null;
    if (rowVersions.get(tableKey) !== version) return recover();
    if (windowPaging.get(pagingKey) !== paging) return null;
    if (!res.ok) {
      const code = (body as { error?: { code?: string } } | null)?.error?.code;
      if (cursor != null && res.status === 400 && code === "window_cursor_invalid") return recover();
      if (res.status === 503 && isMirrorNotLoaded(body)) {
        const delay = MIRROR_RETRY_DELAYS[budget.mirrorRetries++];
        if (delay === undefined) {
          fail(AMAZON_STILL_LOADING_MESSAGE);
          return null;
        }
        // The existing cold-mirror retries add their fixed wait once, never per empty page.
        budget.until += delay + READ_DEADLINE_MS;
        await waitForMirror(delay);
        continue;
      }
      fail(refusalMessage(body, res.status), isForbiddenRefusal(res.status, body) ? FORBIDDEN_CODE : undefined);
      return null;
    }
    const page = windowPayload(body);
    if (!page) {
      fail("The server sent an unreadable payload.");
      return null;
    }
    const next = page.next_cursor;
    if (next != null) {
      const stalled = seen.has(next) || (typeof cursor === "number" && typeof next === "number" && next <= cursor);
      // Keep valid rows, but refuse an unusable continuation before the next read.
      if (stalled && !page.rows.length) {
        paging.next = undefined;
        fail("Cannot load the next page. Reload this database to continue.");
        return null;
      }
      seen.add(next);
      paging.next = { offset: page.rows.length ? req.offset + req.limit : req.offset,
        rowOffset: req.offset + page.rows.length,
        cursor: next, seen: new Set(seen), stalled };
    } else paging.next = undefined;
    if (!page.rows.length && next != null) {
      cursor = next;
      continue;
    }
    payload = page;
    paging.at = Date.now();
    break;
  }
  if (req.related && payload.fields.some((field) => field.measure)) {
    const scoped = await fetchRelatedMeasureValues(tableKey, payload.rows.map((row) => Number(row.pid)),
      req.related, () => true);
    if (!scoped.values) {
      fail(scoped.reason);
      return null;
    }
    const allowed = new Set(scoped.fields);
    const hidden = new Set(payload.fields.filter((field) => field.measure && !allowed.has(field.key))
      .map((field) => field.key));
    payload.fields = payload.fields.filter((field) => !hidden.has(field.key));
    payload.rows = payload.rows.map((row) => ({ ...Object.fromEntries(Object.entries(row)
      .filter(([key]) => !hidden.has(key))), ...scoped.values?.[row.pid] } as Row));
    if (scoped.reason) payload.limits = [...(payload.limits ?? []).filter((limit) => limit.subject !== "Linked metrics"), {
      subject: "Linked metrics", cause: scoped.reason,
      recommendation: "Check the metric source binding and period, then reopen this tab.",
    }];
  }
  if (session !== rowsSession) return null;
  if (rowVersions.get(tableKey) !== version) return recover();
  if (!isCurrent()) return null;
  observeCanonicalRows(topicForScope(tableKey === "customer_data" ? "customer" : tableKey === "product_data" ? "product" : tableKey), payload);
  rowsCache.set(path, { at: Date.now(), payload });
  return payload;
}

/** C10: find this exact record within the named pin, then return only its Metric values.
 * No pid filter: undeclared filter keys can be dropped by the rows door. Each page uses the
 * existing window path/cache, including `related`, and stops when the drawer leaves this frame.
 */
export function isRelatedProductMetricScope(tableKey: string, related: RelatedPin | null): boolean {
  if (tableKey !== "product_data" || related?.table !== "customer_data") return false;
  const via = related.via;
  return Array.isArray(via)
    ? via.length === 1 && via[0] === "products_ordered"
    : via.direction === "forward" && (via.field === "products_ordered" || via.key === "products_ordered");
}

/** Linked-grid metrics follow pin presence, including manual and two-hop paths. */
export function isRelatedMetricScope(tableKey: string, related: RelatedPin | null): boolean {
  return usesPinnedRows(tableKey, related);
}

/** The server owns fields, catalogue admission, membership and refusals. */
export async function fetchRelatedMeasureValues(
  tableKey: string, pids: number[], related: RelatedPin, isCurrent: () => boolean
): Promise<{ values: Record<number, Partial<Row>> | null; fields: string[]; reason: string }> {
  const unavailable = { values: null, fields: [], reason: "Metrics for these linked records are unavailable. Try again." };
  if (!isCurrent()) return unavailable;
  try {
    const res = await fetch(`${API_V1}/tables/${encodeURIComponent(tableKey)}/related-metrics`, {
      method: "POST", credentials: CREDENTIALS, headers: JSON_HEADERS,
      body: JSON.stringify({ related, pids }),
    });
    if (handledSession(res) || !isCurrent()) return unavailable;
    const body = await readJson(res) as {
      ok?: boolean; values?: Record<number, Partial<Row>>; fields?: string[];
      refusals?: { field?: string; message?: string }[];
      scope?: { table?: string; related?: RelatedPin; pids?: number[] };
    } | null;
    if (!res.ok) return { ...unavailable, reason: refusalMessage(body, res.status) };
    if (!body?.ok || body.scope?.table !== tableKey
        || JSON.stringify(body.scope.related) !== JSON.stringify(related)
        || !Array.isArray(body.fields) || !Array.isArray(body.refusals)) return unavailable;
    const values: Record<number, Partial<Row>> = {};
    for (const pid of pids) {
      const cell = body.values?.[pid];
      if (!cell || !body.scope.pids?.includes(pid)
          || body.fields.some((key) => !Object.prototype.hasOwnProperty.call(cell, key))) return unavailable;
      values[pid] = Object.fromEntries(body.fields.map((key) => [key,
        body.refusals?.some((refusal) => !refusal.field || refusal.field === key) ? null : cell[key]]));
    }
    return { values, fields: body.fields,
      reason: [...new Set(body.refusals.map((refusal) => refusal.message).filter(Boolean))].join(" ") };
  } catch {
    return unavailable;
  }
}

/** Customer-scoped Metric overlays; no client amounts, field specs or Odoo ids are authority. */
export async function fetchRelatedProductMeasureValues(
  pids: number[], fields: Field[], related: RelatedPin, isCurrent: () => boolean
): Promise<{ values: Record<number, Partial<Row>> | null; reason: string }> {
  const unavailable = { values: null, reason: "Metrics for these related products are unavailable." };
  if (!isCurrent()) return unavailable;
  try {
    const res = await fetch(`${API_V1}/tables/product_data/related-metrics`, {
      method: "POST", credentials: CREDENTIALS, headers: JSON_HEADERS,
      body: JSON.stringify({ related, pids }),
    });
    if (handledSession(res) || !isCurrent()) return unavailable;
    const body = await readJson(res) as {
      ok?: boolean; values?: Record<string, Partial<Row>>; fields?: string[];
      scope?: { customer?: number; products?: Record<string, number> }; reason?: string;
    } | null;
    if (!res.ok) return { values: null, reason: refusalMessage(body, res.status) };
    if (!isCurrent() || !body?.ok || body.scope?.customer !== related.record) return unavailable;
    const keys = fields.filter((field) => field.measure).map((field) => field.key);
    const values: Record<number, Partial<Row>> = {};
    for (const pid of pids) {
      const cell = body.values?.[pid];
      if (!cell || !Number.isSafeInteger(body.scope.products?.[pid])
          || keys.some((key) => !body.fields?.includes(key)
            || !Object.prototype.hasOwnProperty.call(cell, key))) return unavailable;
      values[pid] = Object.fromEntries(keys.map((key) => [key, cell[key]]));
    }
    return { values, reason: body.reason ?? "" };
  } catch {
    return unavailable;
  }
}

export async function fetchRecordMeasureValues(
  tableKey: string,
  pid: number,
  fields: Field[],
  related: RelatedPin,
  isCurrent: () => boolean
): Promise<{ values: Partial<Row> | null; reason: string }> {
  if (isRelatedProductMetricScope(tableKey, related)) {
    const result = await fetchRelatedProductMeasureValues([pid], fields, related, isCurrent);
    return { values: result.values?.[pid] ?? null, reason: result.reason };
  }
  const measureKeys = fields.filter((field) => field.measure).map((field) => field.key);
  let offset = 0;
  let cursor: WindowCursor | undefined;
  const seen = new Set<WindowCursor>();
  while (isCurrent()) {
    let reason = "Metric values are unscoped because the related record read failed.";
    const payload = await fetchTableWindow(tableKey, { offset, limit: WINDOW_ROWS, related, cursor },
      (failure) => { reason = `Metric values are unscoped because the related record read failed: ${failure}`; });
    if (!payload || !isCurrent()) return { values: null, reason };
    // A successful HTTP response can still report a refused or incomplete calculation.
    const limit = payload.limits?.find((item) => item.effect !== "none");
    if (limit) return {
      values: null,
      reason: `Metric values are unscoped because the related read is limited: ${limit.cause}`,
    };
    const row = payload.rows.find((candidate) => Number(candidate.pid) === pid);
    if (row) {
      if (measureKeys.some((key) => !Object.prototype.hasOwnProperty.call(row, key))) {
        return { values: null,
          reason: "Metric values are unscoped because the related read did not return every metric field." };
      }
      const values: Partial<Row> = {};
      for (const key of measureKeys) values[key] = row[key];
      return { values, reason: "" };
    }
    if (payload.next_cursor != null) {
      if (seen.has(payload.next_cursor)) return { values: null,
        reason: "Cannot load related metric values. Reopen this record to try again." };
      seen.add(payload.next_cursor);
      cursor = payload.next_cursor;
      offset += WINDOW_ROWS;
    } else {
      cursor = undefined;
      offset += payload.rows.length;
      if (!payload.rows.length || offset >= (payload.counts?.matched ?? offset)) break;
    }
  }
  return { values: null,
    reason: "Metric values are unscoped because this record was not found within the related records." };
}

// ═══════════════════════════════════════════════════════════════════════════════════════════
// ⭐⭐ WAVE 50 Β· W50-T03 β€” CONTRACT C1: THE WINDOWED AGGREGATE (owner ruling R1, second half).
// ═══════════════════════════════════════════════════════════════════════════════════════════
//
// R1, verbatim: *"on a server-windowed table the summary bar and group aggregates are computed
// SERVER-SIDE over the whole predicate (fixes D-159)."*
//
// β›” THE ROUTE IS LANE F'S (W50-T31) AND IT DOES NOT EXIST IN THIS TREE. That is stated rather
// than worked around: this half of the contract is the CONSUMER, written to C1's shape, and its
// only correct behaviour while the producer is absent is to say so honestly and let the caller
// fall back to the loaded window with a sentence that names the window. Hand-faking the numbers
// would put a fabricated aggregate on screen β€” the exact thing R1 exists to end
// ([[no-unverifiable-aggregates]]) β€” and stalling would ship nothing at all.
//
// β›” A REFUSAL IS NOT AN ERROR TOAST HERE. `fetchTableWindow` above raises `DATA_ERROR_EVENT`
// because a window it cannot fetch means an empty grid. A summary it cannot fetch means a
// summary over the loaded window, which is a WORSE answer and not a broken screen β€” so this
// returns `null` quietly and the bar discloses its own scope. A toast on every paint of every
// Odoo grid until lane F lands would train the owner to dismiss the one that matters.

/** C1's request. `groupBy` is a colId; omit it for the table-wide answer. */
export interface AggregateRequest {
  ids?: readonly number[];
  filters?: FilterNode[] | null;
  filterConj?: string;
  search?: string;
  groupBy?: string;
  aggs: { colId: string; agg: string; p?: number }[];
  /**
   * ⭐⭐ W51-T06 / C6 β€” THE SAME PIN THE WINDOW CARRIES, or the summaries describe a different
   * population than the rows under them.
   *
   * β›”β›” THIS IS THE HALF-WIRING TRAP, NAMED. Wire only `/rows` and the grid shows one record's
   * related rows under a count and a summary bar folded over the WHOLE table: a plausible
   * number, which is exactly the fabricated aggregate `no-unverifiable-aggregates` exists to
   * forbid. `_compiled_read` is shared between the two doors server-side, so the ONLY way they
   * can pin differently is this argument being dropped on one of them.
   */
  related?: RelatedPin | null;
}

/** C1's response, as this client reads it. `null` for a column means the server ANSWERED and
 *  the value is blank β€” never a silent 0, which is what the contract's `limits` is for. */
export interface AggregateResult {
  totalRows: number;
  aggregates: Record<string, number | null>;
  groups?: { key: string; label: string; count: number;
             aggregates: Record<string, number | null> }[];
  limits: GridLimit[];
}

/** Read C1's envelope, or null if it is not C1's envelope. Kept separate from the fetch so the
 *  gate and the node harness can drive the parse without a server. */
export function aggregatePayload(body: unknown): AggregateResult | null {
  const b = body as {
    ok?: unknown; total_rows?: unknown; aggregates?: unknown; groups?: unknown; limits?: unknown;
  } | null;
  if (!b || b.ok === false) return null;
  if (!b.aggregates || typeof b.aggregates !== "object") return null;
  const values: Record<string, number | null> = {};
  for (const [colId, v] of Object.entries(b.aggregates as Record<string, unknown>))
    values[colId] = typeof v === "number" && Number.isFinite(v) ? v : null;
  const out: AggregateResult = {
    totalRows: typeof b.total_rows === "number" ? b.total_rows : 0,
    aggregates: values,
    limits: Array.isArray(b.limits) ? (b.limits as GridLimit[]) : [],
  };
  if (Array.isArray(b.groups)) {
    out.groups = (b.groups as Record<string, unknown>[]).map((g) => ({
      key: String(g.key ?? ""),
      label: String(g.label ?? ""),
      count: typeof g.count === "number" ? g.count : 0,
      aggregates: (g.aggregates ?? {}) as Record<string, number | null>,
    }));
  }
  return out;
}

/** Refuse broken pagination metadata before another aggregate page is requested. */
export function aggregatePageProgress(body: unknown, offset: number, size: number | undefined,
  expected?: number): { total?: number; done: boolean } | null {
  if (!body || typeof body !== "object" || size === undefined) return null;
  const meta = body as { total_groups?: number; group_offset?: number; group_limit?: number;
    has_more?: boolean };
  if (meta.total_groups === undefined) {
    return offset === 0 && expected === undefined
      && (meta.has_more === undefined || meta.has_more === false)
      && (meta.group_offset === undefined || meta.group_offset === 0)
      ? { done: true } : null;
  }
  const total = meta.total_groups;
  if (!Number.isSafeInteger(total) || total < 0 || meta.group_offset !== offset
      || !Number.isSafeInteger(meta.group_limit) || (meta.group_limit ?? 0) <= 0
      || size > meta.group_limit!
      || (expected !== undefined && expected !== total)) return null;
  const next = offset + size;
  if (next > total || (size === 0 && next < total)
      || (meta.has_more !== undefined && meta.has_more !== (next < total))) return null;
  return { total, done: next === total };
}

/**
 * `POST /api/v1/odoo-tables/<key>/aggregates` β€” C1, over the WHOLE predicate.
 *
 * β›” DEGRADES TO `null`, NEVER TO A NUMBER. A 404 (lane F's route not merged), a 405, a 500 or
 * an unreachable server all land in the same place: the caller has no server answer and must
 * say what it is showing instead.
 */
export async function fetchAggregates(
  tableKey: string,
  req: AggregateRequest
): Promise<AggregateResult | null> {
  if (!req.aggs.length && !req.groupBy) return null;
  let offset = 0;
  let answer: AggregateResult | null = null;
  let expectedGroups: number | undefined;
  do {
    let res: Response;
    try {
      res = await fetch(
        `${API_V1}/odoo-tables/${encodeURIComponent(tableKey)}/aggregates`,
        {
          method: "POST",
          credentials: CREDENTIALS,
          headers: JSON_HEADERS,
          body: JSON.stringify({
            ...(req.ids !== undefined ? { ids: req.ids } : {}),
            filters: req.filters ?? [],
            filterConj: req.filterConj === "or" ? "or" : "and",
            search: (req.search ?? "").trim(),
            ...(req.groupBy ? { groupBy: req.groupBy } : {}),
            ...(req.groupBy ? { groupOffset: offset, groupLimit: 1000 } : {}),
            /* β›” A BODY KEY HERE, A QUERY STRING ON `/rows` (`windowRowsPath`). Same object, two
               transports, because this door is a POST and that one is a GET. */
            ...(req.related ? { related: req.related } : {}),
            aggs: req.aggs,
          }),
        }
      );
    } catch {
      return null;
    }
    if (handledSession(res) || !res.ok) return null;
    const body = await readJson(res);
    const page = aggregatePayload(body);
    if (!page) return null;
    if (!req.groupBy) return page;
    const progress = aggregatePageProgress(body, offset, page.groups?.length, expectedGroups);
    if (!progress) return null;
    expectedGroups = progress.total;
    if (!answer) answer = page;
    else {
      if (answer.totalRows !== page.totalRows
          || JSON.stringify(answer.aggregates) !== JSON.stringify(page.aggregates)) return null;
      answer.groups = [...(answer.groups ?? []), ...(page.groups ?? [])];
    }
    offset += page.groups?.length ?? 0;
    if (progress.done) return answer;
  } while (true);
}

// ═══════════════════════════════════════════════════════════════════════════════════════════
// ⭐⭐ W51-T06 Β· RULING R2 Β· CONTRACT C6 β€” WHAT THIS DATABASE IS RELATED TO, AND WHETHER THE
// RELATION CAN BE PINNED TODAY.
// ═══════════════════════════════════════════════════════════════════════════════════════════

/**
 * ⭐⭐ W53-T24 Β· R13 Β· C3 β€” THE LISTING IS TWO LISTS NOW, AND THAT IS THE WHOLE POINT.
 *
 * `related` is what a reader may follow; `refusals` is what was walled off on the way. R13 says
 * "no related rows", "you may not see this table" and "this hop was filtered" are three
 * different answers, and an answer that arrived only as a SHORTER `related` array would be
 * indistinguishable from the database simply having fewer edges. So both travel, together, and
 * the caller renders the second rather than dropping it.
 * β›” THE REFUSALS NEVER WIDEN THE ENTRIES. They are parsed by a different function off a
 * different key, so there is no path by which one becomes the other.
 */
export interface RelatedListing {
  entries: RelatedEntry[];
  refusals: RelatedRefusal[];
}

/** A stable identity, so a failed listing is not a fresh object on every render. */
const EMPTY_LISTING: RelatedListing = { entries: [], refusals: [] };

/**
 * ⭐ W53-T24 Β· R13 β€” WHAT A REFUSED PIN ANSWERS WITH: the server's CODE and the server's
 * SENTENCE. `null` still means the pin is served, unchanged.
 */
export interface RelatedRead {
  code: string;
  reason: string;
  /**
   * ⚠ THE X2 ENVELOPE'S OWN `table` AND `hop`, CARRIED BECAUSE R13 ASKS THE REFUSAL TO NAME ITS
   * SUBJECT and the client must not mine the sentence for it. `table` rides on `forbidden_table`
   * and MAY name the INTERMEDIATE table of a two-hop path, which is the exact case R13 exists
   * for: read on both ends, walled out of the middle. `hop` rides on `hop_filtered` and names
   * the edge key the wall took.
   */
  table?: string;
  hop?: string;
}

/**
 * `GET /api/v1/grid/{table}/related?depth=2` β€” every edge THIS ACCOUNT may follow, forward then
 * reverse then bridge, and (at depth 2) the SECOND JUMPS beyond them.
 *
 * β›” AN EMPTY LISTING ON ANY FAILURE, NEVER A THROW. A record whose relations cannot be listed
 * still opens on its Fields tab; a rejected promise here would take the whole drawer down for a
 * list that is chrome.
 * ⚠ The permission narrowing happens SERVER-SIDE (`routes_grid.related_entries` filters on
 * `_may_open`), so an edge that is not in this answer is also an edge that cannot be pinned.
 * There is deliberately no second, laxer resolution on this side.
 *
 * ⭐ R12 CAPS THE TRAVERSAL AT TWO, so `depth` is typed `1 | 2` rather than `number`: depth 3 is
 * a refusal the server has to author (it names the missing hop), and this client cannot even
 * spell the request that would earn it. MEASURED 2026-09-05 on this branch: `?depth=2` is
 * ACCEPTED AND IGNORED β€” 200, the same six entries, no `hops` and no `path` on any of them β€”
 * so sending it today changes nothing and is what makes the consumer ready the day D lands.
 */
export async function fetchRelated(table: string, depth: 1 | 2 = 2): Promise<RelatedListing> {
  try {
    const res = await fetch(
      `${API_V1}/grid/${encodeURIComponent(table)}/related?depth=${depth}`,
      { credentials: CREDENTIALS }
    );
    if (handledSession(res) || !res.ok) return EMPTY_LISTING;
    const body = await readJson(res);
    return { entries: relatedEntries(body), refusals: relatedRefusals(body) };
  } catch {
    return EMPTY_LISTING;
  }
}

/**
 * ⭐⭐ CAN THIS EDGE BE SERVED AS A PINNED READ, AND IF NOT, IN WHOSE WORDS?
 *
 * β›”β›” THE SENTENCE HAS EXACTLY ONE AUTHOR, AND IT IS THE SERVER. `relations.py` already writes
 * three of them (`unknown_via_refusal`, `unresolvable_source_refusal`,
 * `unserved_target_refusal`), each naming a cause and a recommendation. Spelling a fourth here
 * would be a second opinion about one wire contract, which is how a feature ships with both
 * halves correct and disagreeing [[two-lanes-one-contract-dead-feature]]. So this asks for ONE
 * row and reports what came back: `null` when the pin is served, the server's own sentence when
 * it is not.
 *
 * β›” AND IT IS WHY THE TAB DOES NOT SIMPLY MOUNT AND HOPE. `useCustomerData`'s failure channel
 * is `DATA_ERROR_EVENT`, which REPLACES the surface with an error card; a declared-but-unserved
 * relation is a reported limit, not a broken screen. `bridge_customer_open_invoices` is the one
 * such edge today (`ut_odoo_invoices` is materialised and absent from `GRID_SOURCES`), and a
 * link whose target is an ordinary user table is the same shape for a different reason: that
 * door (`routes_tables.table_rows`) takes no predicate at all.
 *
 * ⭐⭐ W53-T24 Β· R13 β€” IT NOW RETURNS THE **CODE** BESIDE THE SENTENCE, AND THAT IS NOT A SECOND
 * OPINION ABOUT THE WORDS. R13 asks for three refusals to be TOLD APART; a bare string can be
 * printed but it cannot be branched on without the client re-reading the server's prose, which
 * is the same "second author of one contract" mistake wearing a regular expression. The code
 * picks the TREATMENT (which voice, which `role`, which emphasis); the sentence stays the
 * server's, verbatim, in every one of the three.
 * ⚠ Read from `body.error.code` β€” the X2 envelope, the same one `refusalMessage` documents 400
 * lines above. `""` when the body carries no code, which is honest rather than a guess.
 */
export async function probeRelatedRead(
  tableKey: string,
  related: RelatedPin
): Promise<RelatedRead | null> {
  const path = windowRowsPath(tableKey, { offset: 0, limit: 1, related });
  let res: Response;
  try {
    res = await fetch(`${API_V1}/${path}`, { credentials: CREDENTIALS });
  } catch {
    return {
      // ⚠ NO CODE. The server never answered, so there is no code to report and no state to
      // treat specially; the caller falls through to printing this sentence plainly.
      code: "",
      reason: "The server could not be reached, so these related records cannot be shown yet. "
        + "Check the connection and open this tab again.",
    };
  }
  if (handledSession(res)) return null;
  if (res.ok) return null;
  const body = await readJson(res);
  const err = (body as { error?: { code?: unknown; table?: unknown; hop?: unknown } } | null)
    ?.error;
  const out: RelatedRead = {
    code: typeof err?.code === "string" ? err.code : "",
    reason: refusalMessage(body, res.status),
  };
  if (typeof err?.table === "string" && err.table) out.table = err.table;
  if (typeof err?.hop === "string" && err.hop) out.hop = err.hop;
  return out;
}

/**
 * `GET /api/v1/workspace` β€” the saved views, custom fields, folders and cohorts
 * for the session user (S1's amendment, 2026-07-30). It exists because X2 pins
 * `/customers` at the EXACT current shape, which carries no `workspace`, and
 * without one the standalone write path is WRITE-ONLY: a saved view reaches the
 * store and is gone from the screen on reload.
 *
 * The body is `{workspace: GridWorkspace}` β€” the client's own built type
 * (types.ts `GridWorkspace`), which is what the embed's host already projects.
 *
 * ⚠ A 404 retains compatibility with a host that does not ship this route:
 * views in memory, no `storageKey`, nothing durable. It degrades to the
 * honest gap rather than failing the whole read, because the workspace is an
 * enhancement of the table, not a precondition for it. A malformed 200 needs
 * a scoped error and Retry. A 401 still ends the session.
 *
 * β›” WAVE 21 item 3 (3c) β€” BUT A REFUSAL IS NOT AN ABSENCE, and conflating the
 * two is half of the "RI fields on a new database" report.
 *
 * This used to answer `null` to every unhappy path alike: route-not-shipped,
 * 403, 500, connection refused, garbage body. The caller cannot tell those
 * apart, so it did the only thing it could β€” carried on without a workspace β€”
 * and `CustomerGrid` then had no `storageKey` and fell back to a bucket shared
 * with every other surface (see the note at its `storageKey`). A tenant whose
 * `/workspace` 403s for `ut_*` therefore got ANOTHER TABLE'S views and fields,
 * silently, with the grid looking entirely healthy.
 *
 * Workspace failures use a scoped status and a nonfatal notification. The rows
 * reader owns DATA_ERROR_EVENT; metadata cannot replace independently ready rows.
 *
 * ⚠ IT IS OFF BY DEFAULT, and that is load-bearing rather than cautious.
 * `reread()` calls this on every workspace-stale signal, and its own rule is
 * "absent stays absent β€” never blank a live panel"; a signal from there would
 * let one dropped packet replace a working table with an error card. Callers
 * can consume onStatus to offer an inline metadata retry instead.
 */
/**
 * HOTFIX 2026-09-29 (owner: "clicking edit for cell database ... is still very slow"). The memo's
 * answer for `scope` when it is inside its freshness window, WITHOUT a request, else null. A
 * panel paints from it at once and still asks the server; the server's answer replaces it.
 */
export function peekWorkspace(scope: SurfaceScope, opts: { fieldsOnly?: boolean } = {}): GridWorkspace | null {
  const key = opts.fieldsOnly ? `${scope}:fields` : scope;
  const hit = wsCache.get(key);
  return hit && Date.now() - hit.at < CUSTOMERS_FRESH_MS ? workspaceWithoutMetricCells(hit.ws) : null;
}

export async function fetchWorkspace(
  scope: SurfaceScope = "customer",
  opts: { announceFailure?: boolean; allowCached?: boolean; refresh?: boolean; fieldsOnly?: boolean;
    onStatus?: (status: WorkspaceStatus) => void } = {},
): Promise<GridWorkspace | null> {
  const loud = opts.announceFailure === true;
  const fieldsOnly = opts.fieldsOnly === true;
  const key = fieldsOnly ? `${scope}:fields` : scope;
  const requestEpoch = wsCacheEpoch;
  const fullAtStart = wsCache.get(scope);
  // ⭐ W31-T21 β€” OPT IN, NEVER BY DEFAULT. Only the first-paint read of a surface may be served
  // from the memo; the post-write `reread()` calls this with no options and therefore always goes
  // to the server, which is what keeps the memo from becoming a second source of truth.
  if (opts.allowCached === true) {
    const hit = wsCache.get(key);
    // A warm-open refresh bypasses only the completed memo, and still joins pending work.
    if (!opts.refresh && hit && Date.now() - hit.at < CUSTOMERS_FRESH_MS) {
      opts.onStatus?.({ scope, state: "ready" });
      return workspaceWithoutMetricCells(hit.ws);
    }
  }
  let pending = opts.allowCached === true ? wsFlights.get(key) : undefined;
  if (!pending) {
    // A fresh full question invalidates older schema offers through this same memo.
    if (!fieldsOnly) {
      wsCache.delete(`${scope}:fields`);
      wsFlights.delete(`${scope}:fields`);
      const previousFull = wsCache.get(scope);
      if (previousFull) previousFull.current = false;
    }
    const epoch = wsCacheEpoch;
    const readOrder = ++workspaceOrder;
    let flight: Promise<WorkspaceRead>;
    flight = readWorkspace(scope, epoch, fieldsOnly, readOrder,
      () => wsFlights.get(key) === flight && readOrder > (workspaceWrites.get(scope) ?? 0));
    pending = flight;
    wsFlights.set(key, pending);
    void flight.then(() => {
      if (wsFlights.get(key) === flight) wsFlights.delete(key);
    });
  }
  let result = await pending;
  if (fieldsOnly && result.superseded && requestEpoch === wsCacheEpoch) {
    // A Sheet full read may supersede the editor's schema read. Follow the current
    // existing flight, then use only an authoritative full memo published since this
    // question began. A failed full read cannot turn an older offer into a fresh one.
    let full = wsFlights.get(scope);
    while (full) {
      result = await full;
      if (requestEpoch !== wsCacheEpoch) return null;
      const next = wsFlights.get(scope);
      full = next !== full ? next : undefined;
    }
    const current = wsCache.get(scope);
    result = current && current.current && current !== fullAtStart && Date.now() - current.at < CUSTOMERS_FRESH_MS
      ? { ws: workspaceWithoutMetricCells(current.ws) }
      : { ws: null, failure: result.failure, ...(result.forbidden ? { forbidden: true } : {}) };
  }
  const latestWrite = workspaceWrites.get(scope) ?? 0;
  if (result.ws && workspaceReadOrder(result.ws) < latestWrite) {
    const current = wsCache.get(key)?.ws;
    result = current && workspaceReadOrder(current) >= latestWrite
      ? { ws: current } : { ws: null, superseded: true };
  }
  // A departed session or superseded request cannot publish even a failure into the new scope.
  if (requestEpoch !== wsCacheEpoch || result.superseded) return null;
  // Each joiner receives its own scoped status; response parsing/session handling happen once.
  const status: WorkspaceStatus = result.failure
    ? { scope, state: "error", message: result.failure, ...(result.forbidden ? { forbidden: true } : {}) }
    : { scope, state: result.ws ? "ready" : "absent" };
  opts.onStatus?.(status);
  if (loud && result.failure) signal(WORKSPACE_ERROR_EVENT, status);
  const good = result.ws;
  return good ? workspaceWithoutMetricCells(good) : null;
}

/** The one sentence a database shows when its saved views and columns stall past the deadline. */
export const DATABASE_TIMEOUT_MESSAGE = "This database did not load in time.";

async function readWorkspace(scope: SurfaceScope, epoch: number, fieldsOnly: boolean, readOrder: number,
  isCurrent: () => boolean): Promise<WorkspaceRead> {
  const superseded = (): WorkspaceRead => {
    const latestWrite = workspaceWrites.get(scope) ?? 0;
    const current = wsCache.get(fieldsOnly ? `${scope}:fields` : scope)?.ws;
    // A read started before the ACK can return only the patched memo, never its old body.
    return epoch === wsCacheEpoch && readOrder < latestWrite && current && workspaceReadOrder(current) >= latestWrite
      ? { ws: current } : { ws: null, superseded: true };
  };
  let res: Response;
  let body: unknown;
  let handled = false;
  try {
    // The body read shares the deadline: a stalled server ends in the error state, never a spinner.
    // The session and epoch checks run before the body is parsed: a tenant swap reloads unread.
    ({ res, body } = await fetchWithDeadline(
      `${API_V1}/workspace?scope=${encodeURIComponent(scope)}${fieldsOnly ? "&fields_only=1" : ""}`,
      { credentials: CREDENTIALS },
      (r) => (handled = handledSession(r)) || epoch !== wsCacheEpoch ? Promise.resolve(null) : readJson(r),
      fieldsOnly ? READ_DEADLINE_MS : WORKSPACE_DEADLINE_MS));
  } catch (error) {
    return epoch === wsCacheEpoch && isCurrent()
      ? { ws: null, failure: isReadTimeout(error) ? DATABASE_TIMEOUT_MESSAGE : "Cannot reach the server." }
      : superseded();
  }
  if (handled || epoch !== wsCacheEpoch) return { ws: null };
  if (!res.ok) {
    if (!isCurrent()) return superseded();
    if (isCurrent() && (res.status === 403 || res.status === 404)) {
      wsCache.delete(scope);
      wsCache.delete(`${scope}:fields`);
      wsFlights.delete(scope);
      wsFlights.delete(`${scope}:fields`);
    }
    // 404 is the ONE status that means "this host does not serve a workspace",
    // which is the enhancement posture above and stays quiet. Everything else
    // is a server that had an answer and would not give it.
    return res.status === 404 ? { ws: null } : {
      ws: null,
      failure: refusalMessage(
        body, res.status,
        `The server answered ${res.status} for this table's saved views and columns.`),
      ...(isForbiddenRefusal(res.status, body) ? { forbidden: true } : {}),
    };
  }
  const ws = body as { workspace?: GridWorkspace } | null;
  if (epoch !== wsCacheEpoch) return { ws: null };
  const w = ws?.workspace as (GridWorkspace & { fieldsOnly?: boolean }) | undefined;
  // Only 404 means compatibility absence. An unreadable 200 needs an actionable retry.
  const good = w && typeof w.storageKey === "string" && w.storageKey.length > 0 && Array.isArray(w.views)
    && w.views.every((view) => view && typeof view.id === "string")
    && (w.fields === undefined || (Array.isArray(w.fields)
      && w.fields.every((field) => field && typeof field.key === "string")))
    && (w.measures === undefined || (Array.isArray(w.measures)
      && w.measures.every((measure) => measure && typeof measure.key === "string")))
    && (w.derived === undefined || (w.derived && typeof w.derived === "object" && !Array.isArray(w.derived)
      && Object.values(w.derived).every((cells) => cells && typeof cells === "object" && !Array.isArray(cells))))
    && (fieldsOnly ? w.fieldsOnly === true : w.fieldsOnly !== true) ? w : null;
  if (!isCurrent()) return superseded();
  if (!good) {
    wsCache.delete(fieldsOnly ? `${scope}:fields` : scope);
    return { ws: null, failure: "Saved views could not be loaded." };
  }
  // ⭐ W31-T21 β€” EVERY SUCCESSFUL READ REFRESHES THE MEMO, including the post-write `reread()`
  // that is not allowed to CONSUME it. That asymmetry is the whole safety argument: the write
  // path can never leave a stale envelope behind for the next switch to serve.
  // ⚠ A FAILURE LEAVES THE PREVIOUS ENTRY ALONE rather than poisoning it with `null` β€” the same
  // "absent stays absent, never blank a live panel" posture `reread()` already takes.
  if (good && isCurrent()) {
    const key = fieldsOnly ? `${scope}:fields` : scope;
    const previous = wsCache.get(key)?.ws;
    workspaceReads.set(good, readOrder);
    wsCache.set(key, { at: Date.now(), ws: good, current: true });
    if (!fieldsOnly) {
      wsCache.delete(`${scope}:fields`);
      wsFlights.delete(`${scope}:fields`);
    }
    // A refreshed metric definition or answer is read again through each grid's own pin.
    // The same rows door still supplies the ordinary record's global Details values.
    if (!fieldsOnly && previous && JSON.stringify(metricWorkspaceCells(previous)) !== JSON.stringify(metricWorkspaceCells(good))) {
      rowsCache.clear();
      windowPaging.clear();
      signal(ROWS_STALE_EVENT);
    }
  }
  return { ws: good };
}

function metricWorkspaceCells(workspace: GridWorkspace): unknown {
  const fields = (workspace.fields ?? []).filter((field) => field.measure);
  if (fields.length === 0) return null;
  const keys = new Set(fields.map((field) => field.key));
  return { fields, cells: Object.fromEntries(Object.entries(workspace.derived ?? {}).map(([pid, cells]) =>
    [pid, Object.fromEntries(Object.entries(cells).filter(([key]) => keys.has(key)))])) };
}

/** Workspace metadata is shared by pinned and ordinary grids; metric amounts are row data. */
export function workspaceWithoutMetricCells(workspace: GridWorkspace): GridWorkspace {
  const metrics = new Set((workspace.fields ?? []).filter((field) => field.measure).map((field) => field.key));
  const admitted = Array.isArray(workspace.measures) ? new Set(workspace.measures.map((measure) => measure.key)) : null;
  const fields = workspace.fields?.filter((field) => !field.measure || admitted === null || admitted.has(field.measure.key));
  const projected = { ...workspace, fields, derived: Object.fromEntries(Object.entries(workspace.derived ?? {}).map(([pid, cells]) =>
    [pid, Object.fromEntries(Object.entries(cells).filter(([key]) => !metrics.has(key)))])) };
  workspaceReads.set(projected, workspaceReadOrder(workspace));
  return projected;
}

// --- the CHANGE POLLER (wave 29, item 20 / R11 / contract C6) ---------------

/**
 * `GET /api/v1/changes?scope=…` β†’ `{bucket: opaque token}`, or null.
 *
 * ⚠ A FAILED POLL IS SILENT. It raises no `DATA_ERROR_EVENT`, because the frame REPLACES the whole
 * surface with an error card on that signal β€” so one dropped packet, six times a minute, would turn
 * a working grid into a failure screen. `changedBuckets` reads a null as "no baseline, no change"
 * and the tab simply carries on with what it has. 401 still ends the session: that is the one
 * status which is never about this route.
 */
export async function fetchChangeTokens(scope: string): Promise<ChangeTokens | null> {
  let res: Response;
  try {
    res = await fetch(`${API_V1}/changes?scope=${encodeURIComponent(scope)}`,
                      // This header marks a current, user-return check. Legacy bundles lack it,
                      // so their former 10-second requests remain database-free on Pg.
                      { credentials: CREDENTIALS, headers: { "X-AIOS-Change-Check": "focus-v1" } });
  } catch {
    return null;
  }
  if (handledSession(res)) return null;
  if (!res.ok) return null;
  const body = (await readJson(res)) as { tokens?: unknown } | null;
  const tokens = body?.tokens;
  if (!tokens || typeof tokens !== "object" || Array.isArray(tokens)) return null;
  const out: ChangeTokens = {};
  for (const [bucket, token] of Object.entries(tokens as Record<string, unknown>))
    out[bucket] = typeof token === "string" ? token : null;
  return out;
}

/**
 * A grid reloads only when the person returns to the tab or window. There is no timer and no
 * background token request.
 */

interface ChangeWatch {
  listeners: Set<(changed: string[]) => void>;
  tokens: ChangeTokens | null;
  /** The last own write `tokens` is known to include. */
  ownSeq: number;
  inFlight: boolean;
  /** `rebaseline`: a read after this tab's own write. It runs in a hidden tab too. */
  refresh: (rebaseline?: boolean) => Promise<void>;
  /** ⭐ ONE poll implementation per watch, held here so the interval and the visibility handler
   *  call the SAME function. The visibility handler used to re-inline the body, which quietly
   *  skipped `inFlight` β€” so returning to a tab whose poll was still outstanding stacked a second
   *  request on top of it, exactly what that guard exists to prevent. */
}

const changeWatches = new Map<string, ChangeWatch>();
let visibilityBound = false;
function refreshVisibleChanges(): void {
  if (document.visibilityState !== "visible") return;
  for (const watched of changeWatches.values())
    void watched.refresh();
}

// S85-T26: a token read that can contain this tab's own write moves the baseline and reports
// nothing. Only a read taken after every own write settled can report an outside change.
let ownWritesOpen = 0;
let ownWriteSeq = 0;
let rebaselineTimer: ReturnType<typeof setTimeout> | undefined;
/** A burst of own writes costs one token read, taken this long after the last one settles. */
export const CHANGE_REBASELINE_MS = 300;

/** Run one write from this tab so the change baseline moves past it. An abort also ends it, so
 *  a transport that ignores its signal cannot hold every later check open. */
async function ownWrite<T>(work: () => Promise<T>, abort?: AbortSignal): Promise<T> {
  let open = true;
  const close = () => {
    if (!open) return;
    open = false;
    ownWritesOpen -= 1;
    ownWriteSeq += 1;
    if (rebaselineTimer !== undefined) clearTimeout(rebaselineTimer);
    rebaselineTimer = undefined;
    if (changeWatches.size) rebaselineTimer = setTimeout(() => {
      rebaselineTimer = undefined;
      for (const watched of changeWatches.values()) void watched.refresh(true);
    }, CHANGE_REBASELINE_MS);
  };
  ownWritesOpen += 1;
  abort?.addEventListener("abort", close, { once: true });
  try {
    return await work();
  } finally {
    abort?.removeEventListener("abort", close);
    close();
  }
}

/**
 * Watch one scope for server-side changes. Returns its unsubscribe.
 *
 * ⭐ ONE WATCH PER SCOPE, REFCOUNTED. A linked-record grid can mount a second `useCustomerData` on
 * the same surface, and both listeners share one mount baseline and one return-to-tab refresh.
 *
 * β›” IT NEVER POLLS. Own writes update the current tab from their response; a change made elsewhere
 * is checked when the person returns to this tab or focuses its window. A forgotten tab left open
 * overnight creates no database traffic.
 */
export function subscribeChanges(scope: string,
                                 onChange: (changed: string[]) => void,
                                 { baseline = true }: { baseline?: boolean } = {}): () => void {
  if (typeof window === "undefined") return () => {};
  let watch = changeWatches.get(scope);
  if (!watch) {
    const w0: ChangeWatch = {
      listeners: new Set(), tokens: null, ownSeq: ownWriteSeq, inFlight: false,
      refresh: async (rebaseline = false) => {
        if (w0.inFlight || (!rebaseline && document.visibilityState !== "visible")) return;
        w0.inFlight = true;
        const seq = ownWriteSeq, quiet = ownWritesOpen === 0;
        let next: ChangeTokens | null = null;
        try {
          next = await fetchChangeTokens(scope);
          const settled = quiet && ownWritesOpen === 0 && ownWriteSeq === seq;
          const changed = settled && w0.ownSeq === seq ? changedBuckets(w0.tokens, next) : [];
          if (next) {
            w0.tokens = next;
            if (settled) w0.ownSeq = seq;
          }
          if (changed.length)
            for (const listener of [...w0.listeners]) listener(changed);
        } finally {
          w0.inFlight = false;
        }
        // An own write that overlapped this read may have landed after it. Read once more.
        if (next && w0.ownSeq !== ownWriteSeq && ownWritesOpen === 0 && rebaselineTimer === undefined
            && changeWatches.get(scope) === w0) void w0.refresh(true);
      },
    };
    watch = w0;
    changeWatches.set(scope, w0);
  }
  const w = watch;
  w.listeners.add(onChange);

  // S65-T12: baseline on subscribe by default; grids defer this read until their first payload
  // lands. Racing the rows fetch cost 4,857 ms; the same read alone took 5 ms. Later user returns
  // can still preserve the browser cache when nothing changed. It is never an interval.
  if (baseline) primeChangeBaseline(scope);

  if (!visibilityBound) {
    visibilityBound = true;
    window.addEventListener("visibilitychange", refreshVisibleChanges);
    window.addEventListener("focus", refreshVisibleChanges);
  }

  return () => {
    w.listeners.delete(onChange);
    if (w.listeners.size === 0) {
      // ⚠ The tokens are DROPPED with the last listener. A remount must re-baseline rather than
      // compare against a token from before it was unmounted.
      changeWatches.delete(scope);
    }
  };
}

/** Take a subscribed scope's first baseline through its ONE guarded refresh path. */
export function primeChangeBaseline(scope: string): void {
  const w = changeWatches.get(scope);
  if (w && w.tokens === null && !w.inFlight) void w.refresh();
}

/** A refusal keeps its machine code separate from the sentence shown by the existing toast. */
export interface CellWriteFailure { code: string; message: string }

/** Only admitted canonical row reads can invalidate a successful cell duplicate. */
function observeCanonicalRows(topic: TopicConfig, payload: CustomersPayload): void {
  const fields = payload.fields.map((field) => field.key);
  for (const row of payload.rows) editOutbox.observeCells(topic.scope, row.pid,
    Object.fromEntries(fields.map((key) => [key, row[key]])));
}

/** Update each cached page without extending its source freshness or widening its field wall. */
function adoptCachedRow(topic: TopicConfig, pid: number, accepted: Partial<Row>): boolean {
  editOutbox.observeCells(topic.scope, pid, accepted);
  const keys = new Set(Object.keys(accepted));
  const prefixes = [topic.rowsPath, `tables/${topic.key}/rows`, `odoo-tables/${topic.key}/rows`];
  const fields = new Map<string, Field>();
  const relationFields = [...wsCache.values()].map(({ ws }) => ws.fields ?? [])
    .concat([...rowsCache.values()].map(({ payload }) => payload.fields));
  const mentions = (raw: string | null): boolean => {
    if (!raw) return false;
    try {
      const visit = (value: unknown): boolean => Array.isArray(value) ? value.some(visit)
        : !!value && typeof value === "object" && Object.entries(value).some(([key, item]) =>
          (key === "colId" && typeof item === "string" && keys.has(item)) || visit(item));
      return visit(JSON.parse(raw));
    } catch { return true; }
  };
  for (const [path, cached] of rowsCache) {
    if (!prefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}?`))) continue;
    const allowed = new Set(cached.payload.fields.map((field) => field.key));
    for (const field of cached.payload.fields) fields.set(field.key, field);
    const row = cached.payload.rows.find((record) => record.pid === pid);
    if (row) for (const [key, value] of Object.entries(accepted))
      if (allowed.has(key)) row[key] = value;
    const query = new URLSearchParams(path.split("?")[1] ?? "");
    const changesLinks = cached.payload.fields.some((field) => keys.has(field.key) && field.type === "link");
    // Membership and order can change even when this page did not contain the edited row.
    if (query.get("search") || mentions(query.get("filters")) || mentions(query.get("sorts"))
        || keys.has(query.get("groupBy") ?? "") || (query.has("related") && changesLinks)) rowsCache.delete(path);
  }
  const workspaceFields = wsCache.get(topic.scope)?.ws.fields ?? [];
  for (const field of workspaceFields) fields.set(field.key, field);
  rowVersions.set(topic.key, (rowVersions.get(topic.key) ?? 0) + 1);
  return [...keys].some((key) => fields.get(key)?.type === "link")
    || relationFields.some((book) => book.some((field) => {
      const rollup = field.rollup;
      const link = book.find((candidate) => candidate.key === rollup?.link)?.link;
      return link?.table === topic.key && !!rollup &&
        [rollup.field, rollup.sortBy, rollup.distinctBy,
          ...(rollup.where ?? []).map((rule) => rule.field), ...(rollup.conditions ?? []).map((rule) => rule.field)]
          .some((key) => !!key && keys.has(key));
    }));
}

/** Queue synchronously so page exit also covers the IndexedDB persistence gap. */
export async function patchTopicRow(
  topic: TopicConfig,
  pid: number,
  updates: Partial<Row>,
  onAccepted?: (accepted: Partial<Row>, cleared: string[]) => void,
  onFailure?: (failure: CellWriteFailure) => void,
): Promise<boolean> {
  const session = writeSession;
  const rowKey = `${topic.rowsPath}/${pid}`;
  const id = eventId("cell");
  const task = editOutbox.enqueue({ id, kind: "row", scope: topic.scope,
    payload: { pid, updates } }, (receipt) => {
    if (session !== writeSession) return;
    const result = receipt.result as { accepted: Partial<Row>; cleared: string[] } | undefined;
    if (result) onAccepted?.(result.accepted, result.cleared);
    if (receipt.ok) {
      return;
    } else {
      const failure = { code: receipt.code ?? "write_refused",
        message: receipt.message ?? "This edit could not be saved." };
      if (onFailure) onFailure(failure);
      else signal(TOAST_EVENT, failure.message);
      refreshFrozenOutboxRefusal(receipt);
    }
  });
  rowWrites.set(rowKey, task);
  try { return await task; }
  finally { if (rowWrites.get(rowKey) === task) rowWrites.delete(rowKey); }
}

/** The customer topic's patch, by its historical name. */
export function patchCustomer(pid: number, updates: Partial<Row>): Promise<boolean> {
  return patchTopicRow(CUSTOMER_TOPIC, pid, updates);
}

/**
 * ⭐ Wave-20 owner item 4 / contract C-ADDROW β€” **APPEND A ROW TO A USER DATABASE**, and
 * (C-UNDO) restore a deleted one under its old id.
 *
 * USER TABLES ONLY, and the refusal is structural rather than checked here: no other scope has
 * a `/tables/{key}/rows` endpoint at all. A connector's rows are read-synced from its source β€”
 * R8 is explicit that a "+" which must refuse is a fake affordance, so the caller never renders
 * one there.
 *
 * ⚠ THE ANSWER IS THE ID THAT WAS STORED, never the one that was asked for. An undo that
 * requests `rid` may find that id re-used, and the server's own note says it answers with what
 * it actually wrote; the caller re-anchors on the returned value rather than assuming.
 *
 * ⚠ The rows cache is CLEARED on success. `fetchTopicRows` holds a 5-minute window per topic,
 * so a re-read straight after an append would serve the payload from before it β€” the new row
 * would appear minutes later, which reads as "the button did nothing". Same reason the shell's
 * retired Add-record bar cleared it (wave 20 item 4 moved that door here).
 */
export interface TableRowAcknowledgement {
  rid: string | number;
  pid: number;
  values?: Record<string, string | number | null>;
}

export async function addTableRow(
  tableKey: string,
  values: Record<string, unknown> = {},
  rid?: string | number,
  restore = false
): Promise<TableRowAcknowledgement | null> {
  try {
    const res = await fetch(`${API_V1}/tables/${encodeURIComponent(tableKey)}/rows`, {
      method: "POST",
      credentials: CREDENTIALS,
      headers: JSON_HEADERS,
      body: JSON.stringify(rid === undefined ? { values, restore } : { rid, values, restore }),
    });
    if (handledSession(res)) return null;
    const body = (await readJson(res)) as { rid?: string | number; pid?: number; values?: unknown;
                                            error?: { message?: string } } | null;
    if (!res.ok) {
      // The server states WHY (a row cap, a store refusal). Surfacing its sentence beats a
      // generic failure toast, and staying silent would be the worst of the three.
      const why = refusalMessage(body, res.status);
      signal(TOAST_EVENT, why);
      return null;
    }
    if (body?.rid === undefined || typeof body?.pid !== "number") {
      signal(DATA_ERROR_EVENT, "The server did not say which row it created.");
      return null;
    }
    dropTableRowsCache(tableKey);
    const accepted: TableRowAcknowledgement["values"] = body.values &&
      typeof body.values === "object" && !Array.isArray(body.values) ? {} : undefined;
    if (accepted) for (const [key, value] of Object.entries(body.values as Record<string, unknown>)) {
      if (key === "pid") continue;
      if (value === null || typeof value === "string" ||
          (typeof value === "number" && Number.isFinite(value))) accepted[key] = value;
      else if (typeof value === "boolean") accepted[key] = value ? "True" : "False";
    }
    return { rid: body.rid, pid: body.pid, ...(accepted ? { values: accepted } : {}) };
  } catch {
    signal(DATA_ERROR_EVENT, "Cannot reach the server.");
    return null;
  }
}

/**
 * ⭐ WAVE 21 item 7 (contract C2) β€” ADD A COLUMN TO A USER DATABASE'S **DEFINITION**,
 * not to this user's overlay.
 *
 * β›” THE BUG THIS EXISTS FOR. Every column the grid creates has always gone out as a
 * `field_upsert` EVENT, which lands in the per-user workspace stratum
 * (`<key>_table_workspace`). That is right for the connector surfaces, where a custom
 * column IS one person's annotation of somebody else's data. It is wrong for a user
 * database, where the columns ARE the table β€” and it is why the automation editor's
 * "Automation column" picker was empty by construction: that picker reads the DEFINITION
 * (`user_tables`), which the grid had never written to. Two stores, one word, and the two
 * surfaces disagreed with no error anywhere. The route has existed since wave 18 with no
 * client caller; this is that caller, and `routes_tables.py`'s own comment above it names
 * this exact defect.
 *
 * ⚠ SCOPED TO THE AUTOMATION KIND THIS WAVE (C2, deliberately narrow). Moving EVERY kind
 * onto the definition is the right end state and is booked as debt: it changes who can see
 * a column (everyone with the table, not just its author), which is a visible change to
 * shipped behaviour on three surfaces and does not belong in a wave that is fixing this
 * one's blindness.
 *
 * ⚠ THE SERVER'S FIELD IS THE ANSWER, never the request. `add_field` re-slugs and
 * re-types on the way in, so the caller inserts what came BACK β€” a column ordered under a
 * key the store does not hold is a column that renders nowhere.
 */
/**
 * ⭐⭐ 2026-08-07 (D-79's last half) β€” PATCH one column's DEFINITION on a user table.
 *
 * β›” WHY IT EXISTS: wave 25 shipped the profile flag's READER everywhere β€” the column-menu line,
 * the cell validator, R6's clear-on-write, the one-per-table refusal β€” and never its WRITER. The
 * route (`PATCH /tables/{key}/fields/{fkey}`) has accepted `profile` since that wave with no
 * client caller, so the enrich action could not be bound to any database a person made
 * themselves. This is that caller.
 *
 * ⚠ THE SERVER'S FIELD IS THE ANSWER, never the request β€” the same rule `addTableField` carries.
 * `_clean_field` enforces `type: 'text'` for a profile flag and refuses a SECOND one with a
 * sentence naming the column that already has it, so the refusal is worth surfacing verbatim.
 */
/**
 * ⭐ 2026-08-07 β€” the sibling databases a `link` column may point at, WITH their fields.
 *
 * `GET /tables` already returns exactly this (key, label, fields) filtered by `may_open`, so
 * there is no new route and no new wall: a database you cannot open is a database you cannot
 * link to, decided by the same predicate that decides whether you can see it at all.
 *
 * ⚠ Returns `[]` on any failure rather than throwing. The link editor renders "no other
 * databases yet" for an empty list, which is the truthful reading of both an empty workspace
 * and an unreachable server β€” and a create pane that explodes because a picker could not fetch
 * is worse than one that says it has nothing to offer.
 */
export async function fetchLinkTargets(): Promise<LinkTarget[]> {
  try {
    // A link picker uses only key/label/schema. `brief=1` keeps the server's table wall but does
    // not transfer row counts or the row-bearing `user_tables` document for this one field menu.
    const res = await fetch(`${API_V1}/tables?brief=1`, { credentials: CREDENTIALS });
    if (handledSession(res) || !res.ok) return [];
    const body = (await readJson(res)) as { tables?: LinkTarget[] } | null;
    return Array.isArray(body?.tables) ? body.tables : [];
  } catch {
    return [];
  }
}

export interface LinkTarget {
  key: string;
  label: string;
  fields: Field[];
}

/**
 * ⭐⭐ 2026-08-09 β€” the READ-THROUGH rollup's offer: which governed Odoo topic, which metric of
 * it, grouped by which dimension, over which date window.
 *
 * β›” WHY THIS IS A DIFFERENT LIST FROM `fetchLinkTargets`. A LINK rollup folds rows that live in
 * the workspace, so its offer is "the other databases". A SOURCE rollup folds rows that were
 * never copied here at all β€” 256,810 order lines answered by one grouped SQL query β€” so its
 * offer is the semantic model, and the server derives it from `model/topics/*.yml` +
 * `model/metrics/*.yml` rather than from anything the client knows.
 *
 * ⚠ Returns an EMPTY offer on any failure rather than throwing, for the same reason the link
 * picker does: the editor then renders "no live sources are available", which is the truthful
 * reading of both a tenant with no Odoo mirror and an unreachable server.
 */
export async function fetchRollupSources(): Promise<RollupSourceOffer> {
  try {
    const res = await fetch(`${API_V1}/tables/rollup-sources`, { credentials: CREDENTIALS });
    if (handledSession(res) || !res.ok) return { topics: [], windows: [] };
    const body = (await readJson(res)) as Partial<RollupSourceOffer> | null;
    return {
      topics: Array.isArray(body?.topics) ? body!.topics! : [],
      windows: Array.isArray(body?.windows) ? body!.windows! : [],
    };
  } catch {
    return { topics: [], windows: [] };
  }
}

export interface RollupSourceOffer {
  topics: RollupSourceTopic[];
  windows: { key: string; label: string }[];
}

export interface RollupSourceTopic {
  key: string;
  label: string;
  grain: string;
  /** `keyedBy` says whether the group key is an Odoo ID or the dimension's own value β€” which is
   *  what decides which column on THIS database it should be matched against. */
  dims: { key: string; label: string; keyedBy: "id" | "value" }[];
  measures: { key: string; label: string; format: string; description: string }[];
}

/**
 * W42-T08/T37: the semantic one-hop authoring offer is deliberately fetched from its own
 * endpoint.  It is not a projection of RollupSourceOffer: hop dimensions carry their real
 * date/number/text types, which choose the filter operators rendered by FilterBuilderPanel.
 */
export interface HopTopic {
  key: string;
  label: string;
  dims: Field[];
  measures: { key: string; label: string }[];
}

export interface HopTopicOffer {
  topics: HopTopic[];
  windows: { key: string; label: string }[];
  omissions: { topic: string; label: string; reasons: string[] }[];
}

/** Preserve the server's typed dimensions; malformed envelopes fail closed to an empty offer. */
export function hopTopicOfferFromBody(body: unknown): HopTopicOffer {
  const raw = body && typeof body === "object" && !Array.isArray(body)
    ? body as Partial<HopTopicOffer>
    : null;
  return {
    topics: Array.isArray(raw?.topics) ? raw.topics : [],
    windows: Array.isArray(raw?.windows) ? raw.windows : [],
    omissions: Array.isArray(raw?.omissions) ? raw.omissions : [],
  };
}

export async function fetchHopTopics(): Promise<HopTopicOffer> {
  const empty: HopTopicOffer = { topics: [], windows: [], omissions: [] };
  try {
    const res = await fetch(`${API_V1}/grid/hop-topics`, { credentials: CREDENTIALS });
    if (handledSession(res) || !res.ok) return empty;
    return hopTopicOfferFromBody(await readJson(res));
  } catch {
    return empty;
  }
}

export async function patchTableField(
  tableKey: string,
  fieldKey: string,
  patch: Record<string, unknown>
): Promise<Field | null> {
  try {
    const res = await fetch(
      `${API_V1}/tables/${encodeURIComponent(tableKey)}/fields/${encodeURIComponent(fieldKey)}`,
      { method: "PATCH", credentials: CREDENTIALS, headers: JSON_HEADERS,
        body: JSON.stringify(patch) }
    );
    if (handledSession(res)) return null;
    const body = (await readJson(res)) as
      | { field?: Field; error?: { message?: string } }
      | null;
    if (!res.ok) {
      signal(TOAST_EVENT, refusalMessage(body, res.status));
      return null;
    }
    // ⭐ 2026-08-09 β€” the rows cache is a SCHEMA behind after this too, and for a rollup it is a
    // VALUES behind: `PATCH /fields` refreshes the relations host-side, so the aggregate in every
    // row changed the moment this returned. `addTableField` has dropped it since the day it was
    // written; this door needed the same line and did not have it.
    dropTableRowsCache(tableKey);
    return body?.field ?? null;
  } catch {
    signal(TOAST_EVENT, "That change did not reach the server.");
    return null;
  }
}

/**
 * Owner, 2026-09-02 - REMOVE a select / multiselect OPTION together with the cells that hold it.
 * TWO PHASES through one door: `confirm: false` COUNTS server-side (the browser holds one page of
 * rows and the field's universe is uncapped, so a count taken here would be wrong exactly when it
 * matters); `confirm: true` retires the option and clears its values in this user's stratum, the
 * tenant-wide stratum and a user database's rows alike. The server owns the wall.
 */
export interface ChoiceRemoval {
  key: string;
  options: string[];
  cells: number;
  applied: boolean;
  usage?: Record<string, number>;
}

export async function removeChoice(
  scope: SurfaceScope,
  key: string,
  options: string[],
  confirm: boolean
): Promise<ChoiceRemoval | null> {
  try {
    const res = await fetch(`${API_V1}/grid/choice-remove?scope=${encodeURIComponent(scope)}`, {
      method: "POST", credentials: CREDENTIALS, headers: JSON_HEADERS,
      body: JSON.stringify({ key, options, confirm }),
    });
    if (handledSession(res)) return null;
    const body = await readJson(res);
    if (!res.ok) {
      signal(TOAST_EVENT, refusalMessage(body, res.status, "That option could not be removed."));
      return null;
    }
    const got = body as Partial<ChoiceRemoval> | null;
    if (!got || typeof got.cells !== "number") return null;
    return {
      key: String(got.key ?? key),
      options: Array.isArray(got.options) ? got.options.map(String) : options,
      cells: got.cells,
      applied: got.applied === true,
      ...(got.usage && typeof got.usage === "object"
        ? { usage: got.usage as Record<string, number> }
        : {}),
    };
  } catch {
    signal(TOAST_EVENT, "That change did not reach the server.");
    return null;
  }
}

/**
 * ⭐⭐ 2026-08-10 β€” REMOVE a column from a user database's SHARED definition.
 *
 * β›” THE ROUTE HAS EXISTED SINCE THE DEFINITION DOORS WERE BUILT AND NOTHING EVER CALLED IT β€”
 * `DELETE /api/v1/tables/{key}/fields/{fkey}`, mounted, guarded by `_field_or_refuse`, and
 * unreachable from the product ([[artifact-with-no-importer]] from the consumer end). The
 * consequence was invisible while only `link`/`rollup` used that stratum, because both arrive as
 * pre-set columns on the databases people actually have. It stops being invisible the moment a
 * FORMULA column lands there: `field_delete` (the overlay event) scrubs a per-user bucket the
 * definition does not read, so the column would come back on the next render and the Delete
 * control would be a button that lies.
 *
 * ⚠ NOT optimistic, unlike the overlay delete. The server refuses the last remaining column and
 * refuses a pre-set one (`may_edit_field`), and removing a column from the screen that the store
 * still holds is the same lie in the other direction.
 */

export async function deleteTableField(
  tableKey: string,
  fieldKey: string
): Promise<boolean> {
  try {
    const res = await fetch(
      `${API_V1}/tables/${encodeURIComponent(tableKey)}/fields/${encodeURIComponent(fieldKey)}`,
      { method: "DELETE", credentials: CREDENTIALS }
    );
    if (handledSession(res)) return false;
    if (!res.ok) {
      const body = (await readJson(res)) as { error?: { message?: string } } | null;
      signal(TOAST_EVENT, refusalMessage(body, res.status));
      return false;
    }
    // The schema moved, and a deleted LINK takes its reciprocal and every rollup that folded it
    // with it (`_refresh_relations` runs on this route) β€” so the cached rows are values behind,
    // not just a column behind. Same line `patchTableField` needed.
    dropTableRowsCache(tableKey);
    return true;
  } catch {
    signal(TOAST_EVENT, "That delete did not reach the server.");
    return false;
  }
}

/** Per-column verdict returned by the plural schema delete door. */
export interface FieldDeleteResult {
  key: string;
  status: "deleted" | "refused";
  code?: string;
  reason?: string;
  contract?: unknown;
  removed?: unknown;
}

export interface FieldDeleteOutcome {
  deleted: string[];
  refused: string[];
  results: FieldDeleteResult[];
  /** The server accepted the request but did not name any affected key. */
  unreadable: boolean;
}

const DELETE_ANSWER_NAMED_NO_COLUMN =
  "The server accepted that delete without saying which columns went, so the table is being read " +
  "again rather than guessed at.";

function refusedWholesale(
  fieldKeys: readonly string[],
  reason: string | undefined,
  code: string,
  unreadable = false,
): FieldDeleteOutcome {
  return {
    deleted: [],
    refused: [...fieldKeys],
    results: fieldKeys.map((key) => ({ key, status: "refused" as const, code, reason })),
    unreadable,
  };
}

/**
 * Delete every selected definition through one request, including a one-item selection. The
 * caller reconciles only the keys the server explicitly reports as deleted.
 */
export async function deleteTableFields(
  tableKey: string,
  fieldKeys: readonly string[],
): Promise<FieldDeleteOutcome> {
  if (fieldKeys.length === 0) {
    return { deleted: [], refused: [], results: [], unreadable: false };
  }
  let res: Response;
  try {
    res = await fetch(`${API_V1}/tables/${encodeURIComponent(tableKey)}/fields/delete`, {
      method: "POST",
      credentials: CREDENTIALS,
      headers: JSON_HEADERS,
      body: JSON.stringify({ keys: [...fieldKeys] }),
    });
  } catch {
    return refusedWholesale(fieldKeys, "That delete did not reach the server.", "unreachable");
  }
  if (handledSession(res)) return refusedWholesale(fieldKeys, undefined, "session_ended");
  const body = (await readJson(res)) as {
    results?: unknown;
    deleted?: unknown;
    refused?: unknown;
    error?: { message?: string; code?: string };
  } | null;
  if (!res.ok) {
    const code = typeof body?.error?.code === "string" ? body.error.code : "refused";
    return refusedWholesale(fieldKeys, refusalMessage(body, res.status), code);
  }
  const results: FieldDeleteResult[] = [];
  if (Array.isArray(body?.results)) {
    for (const entry of body.results) {
      const raw = entry as Record<string, unknown> | null;
      if (!raw || typeof raw.key !== "string") continue;
      results.push({
        key: raw.key,
        status: raw.status === "deleted" ? "deleted" : "refused",
        code: typeof raw.code === "string" ? raw.code : undefined,
        reason: typeof raw.reason === "string" ? raw.reason : undefined,
        contract: raw.contract,
        removed: raw.removed,
      });
    }
  } else {
    const named = (value: unknown): string[] =>
      Array.isArray(value) ? value.filter((key): key is string => typeof key === "string") : [];
    for (const key of named(body?.deleted)) results.push({ key, status: "deleted" });
    for (const key of named(body?.refused)) results.push({ key, status: "refused" });
  }
  if (results.length === 0) {
    dropTableRowsCache(tableKey);
    return refusedWholesale(fieldKeys, DELETE_ANSWER_NAMED_NO_COLUMN, "unreadable_answer", true);
  }
  const deleted = results.filter((item) => item.status === "deleted").map((item) => item.key);
  const refused = results.filter((item) => item.status === "refused").map((item) => item.key);
  if (deleted.length > 0) dropTableRowsCache(tableKey);
  return { deleted, refused, results, unreadable: false };
}

/**
 * ⭐⭐ 2026-08-09 β€” THE DEFINITION SHAPE, NOT A THREE-KEY SUMMARY.
 *
 * This used to be typed `{key, label, type}`, which was not merely narrow β€” it was the second
 * half of the defect that made a user-built Rollup permanently blank. `ColumnMenu` builds a
 * complete `rollup` bag and hands it over; a parameter type naming three keys meant the only
 * caller sent three keys, so the bag never left the browser. `_clean_field` REFUSES a rollup
 * with no bag, so the shape below is what makes the create legal at all.
 */
export interface TableFieldDefinition {
  key: string;
  label: string;
  type: string;
  link?: Record<string, unknown>;
  rollup?: Record<string, unknown>;
  options?: string[];
  [extra: string]: unknown;
}

export async function addTableField(
  tableKey: string,
  field: TableFieldDefinition
): Promise<Field | null> {
  try {
    const res = await fetch(`${API_V1}/tables/${encodeURIComponent(tableKey)}/fields`, {
      method: "POST",
      credentials: CREDENTIALS,
      headers: JSON_HEADERS,
      body: JSON.stringify(field),
    });
    if (handledSession(res)) return null;
    const body = (await readJson(res)) as
      | { ok?: boolean; value?: Field | null; refused?: boolean; reason?: string;
          field?: Field; error?: { message?: string } }
      | null;
    if (!res.ok || body?.ok === false || body?.refused === true) {
      // The server states WHY β€” the column cap, an unknown type (this is the 400 to expect
      // until `UT_FIELD_TYPES` learns `automation`, C2's other half), a wall refusal. Its
      // sentence beats anything invented here.
      const why = refusalMessage(body, res.status, body?.reason?.trim() || undefined);
      signal(TOAST_EVENT, why);
      return null;
    }
    const made = body && "value" in body ? body.value : body?.field;
    if (!made || typeof made.key !== "string") {
      signal(DATA_ERROR_EVENT, "The server did not say which column it created.");
      return null;
    }
    // The definition feeds BOTH payloads for a user table (`ut_assembly` builds the rows
    // envelope and `/workspace` from the same `fields_base`), so the cached rows are now a
    // schema behind. Cheap to drop, and a stale schema is not a stale number β€” it is a
    // column that exists on the server and nowhere on screen.
    dropTableRowsCache(tableKey);
    return made;
  } catch {
    signal(DATA_ERROR_EVENT, "Cannot reach the server.");
    return null;
  }
}

/**
 * ⭐ WAVE 21 item 11 (ruling R10, contract C5) β€” parse an uploaded `.xlsx`/`.csv` and
 * hand back its COLUMNS AND VALUES as strings.
 *
 * β›” THE FILE NEVER BECOMES DATA. This reads a spreadsheet to find out which records the
 * user means; nothing here writes a row, creates a field, or keeps the file. The server
 * parses (openpyxl is not a thing a browser has) and answers with strings β€” the matching
 * itself is client-side, over rows this browser already holds (`fileSelect.ts`).
 *
 * ⚠ `truncated` IS THE CONTRACT'S POINT. C5 caps a column at 20k values, and a cap the
 * caller cannot see is a silent wrong answer: a 30k-row file would report ten thousand
 * records "not found" that are simply past the cap. The dialog surfaces this flag as its
 * own sentence, never folded into the miss count ([[no-unverifiable-aggregates]]).
 */
export interface TabularUpload {
  columns: string[];
  rows: number;
  values: Record<string, string[]>;
  truncated: boolean;
}

export async function uploadTabular(file: File): Promise<TabularUpload | null> {
  const form = new FormData();
  form.append("file", file);
  try {
    // ⚠ NO Content-Type HEADER. The browser must set it, because only the browser knows
    // the multipart boundary it generated β€” writing `multipart/form-data` by hand omits
    // the boundary and the server cannot parse the body at all.
    const res = await fetch(`${API_V1}/uploads/tabular`, {
      method: "POST",
      credentials: CREDENTIALS,
      body: form,
    });
    if (handledSession(res)) return null;
    const body = (await readJson(res)) as
      | { columns?: unknown; rows?: unknown; values?: unknown; truncated?: unknown;
          error?: { message?: string } }
      | null;
    if (!res.ok) {
      const why = refusalMessage(
        body,
        res.status,
        `The file could not be read (the server answered ${res.status}).`
      );
      signal(TOAST_EVENT, why);
      return null;
    }
    const columns = Array.isArray(body?.columns)
      ? body.columns.filter((c): c is string => typeof c === "string")
      : [];
    const rawValues = (body?.values && typeof body.values === "object" ? body.values : {}) as
      Record<string, unknown>;
    const values: Record<string, string[]> = {};
    for (const col of columns)
      values[col] = Array.isArray(rawValues[col])
        ? (rawValues[col] as unknown[]).map((v) => (v === null || v === undefined ? "" : String(v)))
        : [];
    if (!columns.length) {
      signal(TOAST_EVENT, "That file has no readable columns.");
      return null;
    }
    return {
      columns,
      rows: typeof body?.rows === "number" ? body.rows : 0,
      values,
      truncated: body?.truncated === true,
    };
  } catch {
    signal(DATA_ERROR_EVENT, "Cannot reach the server.");
    return null;
  }
}

/** C-UNDO's other half: drop a row this session just added. Same cache rule as the append. */
export async function deleteTableRow(
  tableKey: string,
  rid: string | number
): Promise<boolean> {
  try {
    const res = await fetch(
      `${API_V1}/tables/${encodeURIComponent(tableKey)}/rows/${encodeURIComponent(String(rid))}`,
      { method: "DELETE", credentials: CREDENTIALS }
    );
    if (handledSession(res)) return false;
    if (res.ok) dropTableRowsCache(tableKey);
    return res.ok;
  } catch {
    return false;
  }
}

/**
 * Item 7 (contract C-TS) β€” `POST /api/v1/grid/timeseries`.
 *
 * A READ that is a POST, because the request body carries a pid list that can run to
 * thousands: a URL cannot hold the caller's book, and putting customer ids in a query string
 * would also put them in every access log. The server intersects those pids with the caller's
 * `allowed_pids` regardless, so the body narrows the answer and can never widen it.
 *
 * ⚠ RETURNS `null` ON EVERY FAILURE, AND THE PANEL MUST SAY SO RATHER THAN DRAW ZEROES.
 * That is the difference between this and a payload of empty buckets: "we could not ask" and
 * "the answer is nothing" look identical on a chart and are not the same claim. A 400 is the
 * honest "narrow the span"; a 403 is `out_of_scope` (every requested pid was outside the
 * caller's book); a 401 ends the session like everywhere else.
 */
export async function fetchTimeseries(
  body: TsRequest,
  scope: SurfaceScope = surfaceScope
): Promise<{ payload: TsPayload | null; status: number }> {
  try {
    const res = await fetch(
      `${API_V1}/grid/timeseries?scope=${encodeURIComponent(scope)}`,
      {
        method: "POST",
        credentials: CREDENTIALS,
        headers: JSON_HEADERS,
        body: JSON.stringify(body),
      }
    );
    if (handledSession(res)) return { payload: null, status: res.status };
    if (!res.ok) return { payload: null, status: res.status };
    const json = (await readJson(res)) as TsPayload | null;
    // Shape-check before trusting it: `columns` and `rows` are indexed POSITIONALLY against
    // each other, so a payload missing either would index into undefined all the way down.
    if (!json || !Array.isArray(json.columns) || !Array.isArray(json.rows))
      return { payload: null, status: res.status };
    return { payload: json, status: res.status };
  } catch {
    return { payload: null, status: 0 };
  }
}

/**
 * wave17 owner item 9 / ruling R4 (contract C-CAL) β€” per-DAY measure values.
 *
 * β›” WHY A SECOND CHANNEL rather than a parameter on the time-series one: **every group carries
 * its OWN pid set.** A calendar day holds whatever records the date field placed there, so the
 * subject changes from cell to cell; one `allowed_pids` for the whole request would compute
 * every day over everybody, which is a different question with the same shape.
 *
 * The caps are the SERVER's and it answers a 400 with its reason rather than trimming: 31 days,
 * 6 fields, 186 cells. The client's job is to send no more than that, never to guess what was
 * dropped. `values[field][day] === null` is UNANSWERED β€” a day past the tenant's today, a day
 * whose pids are all outside the reader's book, or a measure that could not resolve β€” and the
 * renderer draws "β€”" for all three. Never 0.
 */
export interface CalMetricsResponse {
  values: Record<string, Record<string, number | null>>;
  today?: string;
  /** C-TSWIN at day grain: which window each metric was resolved under. */
  windows?: Record<string, { kind: string; label: string }>;
  dropped?: { field: string; reason: string }[];
  problems?: string[];
}

export async function fetchCalendarMetrics(
  body: { groups: { key: string; pids: number[] }[]; fields: string[] },
  scope: SurfaceScope = surfaceScope
): Promise<{ payload: CalMetricsResponse | null; status: number }> {
  try {
    const res = await fetch(
      `${API_V1}/grid/calendar_metrics?scope=${encodeURIComponent(scope)}`,
      {
        method: "POST",
        credentials: CREDENTIALS,
        headers: JSON_HEADERS,
        body: JSON.stringify(body),
      }
    );
    if (handledSession(res)) return { payload: null, status: res.status };
    if (!res.ok) return { payload: null, status: res.status };
    const json = (await readJson(res)) as CalMetricsResponse | null;
    // Shape-checked before it is trusted, the `fetchTimeseries` rule: every lookup below is
    // `values[field][day]`, so a payload without `values` would read `undefined` as a value and
    // paint blanks that look like real "β€”" refusals.
    if (!json || !json.values || typeof json.values !== "object")
      return { payload: null, status: res.status };
    return { payload: json, status: res.status };
  } catch {
    return { payload: null, status: 0 };
  }
}

// --- the WRITE (CP-C) ------------------------------------------------------

/** Legacy export for embed consumers. Durable browser edits have no replay cap. */
export const MAX_REPLAY = 24;

/** Use the real session envelope and opaque principal stamp, never a local account label. */
async function outboxIdentity(abort: AbortSignal): Promise<OutboxIdentity | null> {
  const session = writeSession;
  const response = await fetch(`${API_V1}/auth/me`, { credentials: CREDENTIALS, cache: "no-store", signal: abort });
  if (handledSession(response) || session !== writeSession || !response.ok) return null;
  const body = await readJson(response) as { tenant?: unknown; user?: { username?: unknown } } | null;
  const tenant = response.headers.get(TENANT_HEADER);
  const principal = response.headers.get(PRINCIPAL_HEADER);
  if (typeof body?.user?.username !== "string" || !body.user.username || !tenant || !principal
      || body.tenant !== tenant || currentTenant() !== tenant || session !== writeSession) return null;
  return { tenant, principal };
}

function refusedReceipt(id: string, body: unknown, status: number, fallback: string): OutboxReceipt {
  const results = (body as { results?: { id?: string }[] } | null)?.results;
  const matched = Array.isArray(results) ? results.find((result) => result.id === id) : undefined;
  if (matched) return refusedReceipt(id, matched, status, fallback);
  const shaped = body as { reason?: unknown; refused?: { code?: unknown };
    detail?: { reason?: unknown; error?: { code?: unknown }; code?: unknown } } | null;
  const code = refusalCode(body) || shaped?.refused?.code || shaped?.detail?.error?.code
    || shaped?.detail?.code || shaped?.reason || shaped?.detail?.reason;
  return { id, ok: false, code: typeof code === "string" ? code : "write_refused",
    message: refusalMessage(body, status, fallback) };
}

/** Receipts identify outcomes. A transport error never proves a refusal was final. */
function matchingRefusal(id: string, body: unknown, status: number, grid: boolean): boolean {
  if (status >= 500) return false;
  const answer = body as { id?: string; opId?: string; detail?: unknown; results?: unknown[] } | null;
  if (!answer) return false;
  if ((grid ? answer.id : answer.opId) === id) return true;
  if (answer.detail && matchingRefusal(id, answer.detail, status, grid)) return true;
  return Array.isArray(answer.results) && answer.results.some((result) => matchingRefusal(id, result, status, grid));
}

/** Refresh frozen-store reads without crossing the unsent edit's session boundary. */
function refreshFrozenOutboxRefusal(receipt: OutboxReceipt): void {
  if (receipt.code !== "data_input_frozen") return;
  refreshCustomersCache();
  signal(ROWS_STALE_EVENT);
  signal(WORKSPACE_STALE_EVENT);
}

/** Both grid adapters use this transport. No caller also sends its own optimistic cell event. */
async function sendOutboxEdit(edit: StoredEdit, abort: AbortSignal): Promise<OutboxReceipt> {
  if (edit.kind !== "row" && edit.kind !== "event") {
    const transport = outboxTransports.get(edit.kind);
    if (!transport) throw new Error("Open this edit's document to finish saving.");
    return transport(edit, abort);
  }
  const session = writeSession;
  const headers = { ...JSON_HEADERS, [TENANT_HEADER]: edit.owner.tenant,
    [PRINCIPAL_HEADER]: edit.owner.principal };
  const topic = topicForScope(edit.scope);
  const patch = edit.payload as { pid: number; updates: Partial<Row> };
  const tables = edit.kind === "row" && topic.scope.startsWith("ut_")
    ? await connectedTables(abort) : new Set<string>();
  if (session !== writeSession || abort.aborted) throw new Error("The signed-in account changed.");
  if (!tables) return refusedReceipt(edit.id, null, 0, "This database's write capabilities could not be loaded. Try again.");
  const connected = tables.has(topic.key);
  const event: HostEvent = edit.kind === "event" ? { ...edit.payload as HostEvent, id: edit.id }
    : { id: edit.id, type: "overlay_patch", pid: patch.pid, updates: patch.updates };
  const grid = edit.kind === "event" || connected;
  const response = await fetch(grid ? `${API_V1}/grid/events` : `${API_V1}/${topic.rowsPath}/${patch.pid}`, {
    method: grid ? "POST" : "PATCH", credentials: CREDENTIALS, headers, signal: abort,
    body: JSON.stringify(grid ? { events: [event], scopeKey: edit.scope }
      : { ...patch.updates, opId: edit.id }),
  });
  if (handledSession(response) || session !== writeSession) throw new Error("Sign in again to save this edit.");
  const envelope = await readJson(response);
  if (event.type === "view_op") {
    const rows = (envelope as { results?: unknown[] } | null)?.results;
    const body = (Array.isArray(rows) ? rows : []).find((row) =>
      (row as { opId?: unknown } | null)?.opId === event.client_op_id) as {
        opId: string; applied?: boolean; member?: string;
        refused?: { reason?: string; member?: string; message?: string };
      } | undefined;
    if (body?.member !== event.member || edit.id !== event.client_op_id || response.status >= 500)
      return refusedReceipt(edit.id, null, response.status, "The server did not confirm this view edit.");
    if (body.refused && body.refused.member === event.member)
      return { id: edit.id, ok: false, confirmedRefusal: true,
        code: body.refused.reason, message: body.refused.message ?? "This view edit was refused.", result: body };
    if (!response.ok || body.applied !== true)
      return refusedReceipt(edit.id, null, response.status, "The server did not confirm this view edit.");
    const workspaceWriteOrder = ++workspaceOrder;
    workspaceWrites.set(edit.scope, workspaceWriteOrder);
    wsFlights.delete(edit.scope);
    wsFlights.delete(`${edit.scope}:fields`);
    wsCache.delete(`${edit.scope}:fields`);
    const cached = wsCache.get(edit.scope);
    if (cached && (event.op !== "undo" || edit.viewPaint) && cached.ws.views.some((view) => view.id === event.view_id)) {
      const paint = edit.viewPaint ?? event;
      const ws = { ...cached.ws, views: cached.ws.views.map((view) => view.id === event.view_id
        ? { ...view, ...applyPendingOps(view, [paint]) } : view) };
      workspaceReads.set(ws, workspaceWriteOrder);
      wsCache.set(edit.scope, { ...cached, ws, current: true });
    } else wsCache.delete(edit.scope);
    applyEventResult(envelope, edit.id, true);
    signal(WORKSPACE_STALE_EVENT);
    return { id: edit.id, ok: true, result: body, workspaceWriteOrder };
  }
  if (!response.ok) return { ...refusedReceipt(edit.id, envelope, response.status, "This edit could not be saved."),
    confirmedRefusal: matchingRefusal(edit.id, envelope, response.status, grid) };
  type Answer = { id?: string; opId?: string; ok?: boolean; value?: unknown; updates?: unknown;
    refused?: unknown; cleared?: unknown; routeSwaps?: unknown; reason?: string };
  const results = (envelope as { results?: Answer[] } | null)?.results;
  const body = grid ? (Array.isArray(results) ? results.find((result) => result.id === edit.id) : null)
    : envelope as Answer | null;
  const matches = grid ? body?.id === edit.id : body?.opId === edit.id;
  if (!matches) return refusedReceipt(edit.id, null, response.status, "The server did not confirm this edit.");
  const refused = Array.isArray(body?.refused) ? body.refused.length > 0 : !!body?.refused;
  const failure = applyEventResult(envelope, grid ? edit.id : undefined);
  if (edit.kind === "event" && event.type !== "overlay_patch") {
    if (failure || refused || body?.ok === false || body?.reason)
      return { ...(failure ?? refusedReceipt(edit.id, body, response.status, "This edit could not be saved.")),
        confirmedRefusal: true };
    if (event.type === "field_duplicate" && body?.ok === true)
      return { id: edit.id, ok: true, result: body };
    return { id: edit.id, ok: true };
  }
  const draft = edit.kind === "event" ? event as Extract<HostEvent, { type: "overlay_patch" }> : patch;
  const refusalKeys = Array.isArray(body?.refused) ? body.refused.filter((key): key is string => typeof key === "string") : [];
  const raw = body && "value" in body ? body.value : body?.updates;
  const accepted = Object.fromEntries(raw && typeof raw === "object" && !Array.isArray(raw)
    ? Object.entries(raw).filter(([key, value]) => key !== "pid" && !refusalKeys.includes(key) && (value === null
      || typeof value === "string" || typeof value === "number" || typeof value === "boolean")) : []) as Partial<Row>;
  const cleared = Array.isArray(body?.cleared)
    ? body.cleared.filter((key): key is string => typeof key === "string" && key !== "pid" && !refusalKeys.includes(key)) : [];
  for (const key of cleared) accepted[key] = "";
  if (failure || refused || body?.ok === false || body?.reason) {
    const knownKeys = refusalKeys.length > 0;
    const updates = Object.fromEntries(Object.entries(draft.updates).filter(([key]) =>
      !knownKeys || refusalKeys.includes(key) || !Object.prototype.hasOwnProperty.call(accepted, key)));
    const receipt = failure ?? refusedReceipt(edit.id, body, response.status, "One or more cell values could not be saved.");
    if (knownKeys && Object.keys(accepted).length) {
      adoptCachedRow(topic, draft.pid, accepted);
      signal(ROWS_STALE_EVENT);
    }
    return { ...receipt, confirmedRefusal: true, retryPayload: { ...draft, updates },
      cellFailures: Object.fromEntries(Object.keys(updates).map((key) => [key, receipt.message ?? "This cell could not be saved."])),
      result: knownKeys ? { accepted, cleared } : undefined };
  }
  if (edit.kind === "event") {
    if (Object.keys(accepted).length) adoptCachedRow(topic, draft.pid, accepted);
    signal(ROWS_STALE_EVENT);
    return { id: edit.id, ok: true, result: { accepted, cleared } };
  }
  const acknowledged = Object.keys(patch.updates).every((key) => Object.prototype.hasOwnProperty.call(accepted, key));
  const valid = acknowledged && (!connected || (body?.ok === true && body.refused === false));
  if (!valid) return refusedReceipt(edit.id, body, response.status, "The server did not confirm this edit.");
  const relationsChanged = adoptCachedRow(topic, patch.pid, accepted);
  if (relationsChanged) {
    windowPaging.clear();
    for (const key of [...rowsCache.keys()])
      if (key.startsWith("tables/") || key.startsWith("odoo-tables/")) rowsCache.delete(key);
  }
  if (Array.isArray(body?.routeSwaps) && body.routeSwaps.length > 0) clearTopicRowsCache(topic.rowsPath);
  signal(ROWS_STALE_EVENT);
  return { id: edit.id, ok: true, result: { accepted, cleared } };
}

const outboxTransports = new Map<string, (edit: StoredEdit, abort: AbortSignal) => Promise<OutboxReceipt>>();

/** Sheet and notes register their receipt adapters on the same ordered outbox and save state. */
// Adapters inherit the attempt bound and must pass the signal through all I/O, including body reads.
// Adapters match wire ids. Only retryNow replaces the id of a confirmed refusal.
export function registerOutboxTransport(kind: string,
  transport: (edit: StoredEdit, abort: AbortSignal) => Promise<OutboxReceipt>): () => void {
  if (kind === "row" || kind === "event") throw new Error("The grid owns this outbox transport.");
  outboxTransports.set(kind, transport);
  return () => { if (outboxTransports.get(kind) === transport) outboxTransports.delete(kind); };
}

export const editOutbox = createEditOutbox({ identity: outboxIdentity,
  send: (edit, abort) => ownWrite(() => sendOutboxEdit(edit, abort), abort) });
editOutbox.subscribe(() => signal(OUTBOX_CHANGED_EVENT, editOutbox.snapshot()));

export const CELL_NOTES_KEY = "__cell_notes__";
export const CELL_NOTE_RECEIPT_EVENT = "aios:cell-note-receipt";
export interface CellNoteChange { pid: number; field: string; text: string | null }

function objectValue(value: unknown): Record<string, unknown> | undefined {
  return value !== null && typeof value === "object" && !Array.isArray(value)
    ? value as Record<string, unknown> : undefined;
}

/** Reserved row metadata never enters the scalar cell adoption path. */
export function cellNoteText(row: unknown, field: string): string | null {
  const notes = objectValue(objectValue(row)?.[CELL_NOTES_KEY]);
  const text = notes && Object.prototype.hasOwnProperty.call(notes, field) ? notes[field] : undefined;
  return typeof text === "string" && text.trim() ? text : null;
}

export function withCellNote(row: Row, field: string, text: string | null): Row {
  const notes = { ...objectValue(objectValue(row)?.[CELL_NOTES_KEY]) };
  if (text === null) delete notes[field];
  else Object.defineProperty(notes, field, { value: text, enumerable: true, configurable: true, writable: true });
  // Row describes scalar cells. Only this guarded metadata seam carries the reserved map.
  return { ...row, [CELL_NOTES_KEY]: notes } as unknown as Row;
}

export function readCellNoteChange(payload: unknown): CellNoteChange | null {
  const value = objectValue(payload);
  return value && typeof value.pid === "number" && Number.isSafeInteger(value.pid)
    && typeof value.field === "string" && !!value.field && value.field !== CELL_NOTES_KEY
    && (value.text === null || typeof value.text === "string")
    ? { pid: value.pid, field: value.field, text: value.text } : null;
}

export function pendingCellNotes(scope: string) {
  const snapshot = editOutbox.snapshot();
  return snapshot.pending.flatMap((edit) => {
    if (edit.kind !== "cell-note" || !gridEditScope(edit, scope)) return [];
    const change = readCellNoteChange(edit.payload);
    return change ? [{ ...change, id: edit.id, failure: snapshot.failures[edit.id] }] : [];
  });
}

/** C1 merges just one field note. Null explicitly deletes it without replacing sibling notes. */
export function patchCellNote(scope: string, pid: number, field: string, text: string | null): Promise<boolean> {
  return editOutbox.enqueue({ id: eventId("cell-note"), kind: "cell-note", scope,
    payload: { pid, field, text } });
}

async function sendCellNote(edit: StoredEdit, abort: AbortSignal): Promise<OutboxReceipt> {
  const session = writeSession;
  const change = readCellNoteChange(edit.payload);
  if (!change) throw new Error("This cell note has an unreadable draft.");
  const topic = topicForScope(edit.scope);
  const { pid, field, text } = change;
  const response = await fetch(`${API_V1}/${topic.rowsPath}/${pid}`, {
    method: "PATCH", credentials: CREDENTIALS, signal: abort,
    headers: { ...JSON_HEADERS, [TENANT_HEADER]: edit.owner.tenant, [PRINCIPAL_HEADER]: edit.owner.principal },
    body: JSON.stringify({ opId: edit.id, [CELL_NOTES_KEY]: { [field]: text } }),
  });
  if (handledSession(response) || session !== writeSession || abort.aborted)
    throw new Error("Sign in again to save this note.");
  const envelope = await readJson(response);
  if (session !== writeSession || abort.aborted) throw new Error("The note save was cancelled.");
  const body = objectValue(envelope);
  const sameIdentity = response.headers.get(TENANT_HEADER) === edit.owner.tenant
    && response.headers.get(PRINCIPAL_HEADER) === edit.owner.principal;
  const matches = body?.opId === edit.id && sameIdentity;
  const refused = Array.isArray(body?.refused) ? body.refused.length > 0 : !!body?.refused;
  if (!response.ok || (matches && (body?.ok === false || refused || body?.reason))) {
    const receipt = { ...refusedReceipt(edit.id, envelope, response.status, "This cell note could not be saved."),
      confirmedRefusal: sameIdentity && matchingRefusal(edit.id, envelope, response.status, false) };
    signal(TOAST_EVENT, receipt.message);
    refreshFrozenOutboxRefusal(receipt);
    return receipt;
  }
  const value = objectValue(body?.value ?? body?.updates);
  const notes = objectValue(value?.[CELL_NOTES_KEY]);
  const present = !!notes && Object.prototype.hasOwnProperty.call(notes, field);
  if (!matches || !notes || !present || notes[field] !== text)
    return refusedReceipt(edit.id, null, response.status, "The server did not confirm this cell note.");
  // Replayed edits have no original callback. Reconcile caches and mounted rows in the adapter.
  for (const [path, cached] of rowsCache) {
    const prefixes = [topic.rowsPath, `tables/${topic.key}/rows`, `odoo-tables/${topic.key}/rows`];
    if (!prefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}?`))) continue;
    cached.payload = { ...cached.payload, rows: cached.payload.rows.map((row) =>
      row.pid === pid ? withCellNote(row, field, text) : row) };
  }
  rowVersions.set(topic.key, (rowVersions.get(topic.key) ?? 0) + 1);
  signal(CELL_NOTE_RECEIPT_EVENT, { scope: topic.scope, ...change });
  signal(ROWS_STALE_EVENT);
  return { id: edit.id, ok: true, result: change };
}

registerOutboxTransport("cell-note", sendCellNote);

/** Restore only this authenticated owner's unsent cell changes for the mounted grid. */
export function gridEditScope(edit: OutboxEdit, scope: string): boolean {
  return (edit.kind === "row" || edit.kind === "event" || edit.kind === "cell-note")
    && topicForScope(edit.scope).scope === topicForScope(scope).scope;
}

export interface PendingCellEdit {
  id: string;
  kind: string;
  scope: string;
  failure?: OutboxFailure;
  pid: number;
  updates: Partial<Row>;
}

export function pendingCellEdits(scope: string): PendingCellEdit[] {
  const snapshot = editOutbox.snapshot();
  return snapshot.pending.flatMap((edit) => {
    if (!gridEditScope(edit, scope)) return [];
    const evidence = { id: edit.id, kind: edit.kind, scope: edit.scope, failure: snapshot.failures[edit.id] };
    if (edit.kind === "row") return [{ ...edit.payload as { pid: number; updates: Partial<Row> }, ...evidence }];
    const event = edit.payload as HostEvent;
    return edit.kind === "event" && event.type === "overlay_patch"
      ? [{ pid: event.pid, updates: event.updates, ...evidence }] : [];
  });
}

/**
 * Foreground surface identity for legacy shell/read consumers. W60-T27 removes it from
 * event stamping: emitHostEvent takes a scope captured by the emitting grid instance.
 *
 * ⚠ The server refuses an unknown value rather than defaulting it, so this is
 * never a free-text field. Read and write must agree on what a scope is: the
 * grid asks `/workspace?scope=X` and every event it then emits says `X`.
 */
export type SurfaceScope = "customer" | "cohort" | "product" | `ut_${string}`;
let surfaceScope: SurfaceScope = "customer";

export function setSurfaceScope(scope: SurfaceScope): void {
  surfaceScope = scope;
}

/**
 * ⭐ 2026-08-14 (owner item 2) β€” WHAT THE MOUNTED GRID IS ACTUALLY DRAWING.
 *
 * β›” ADDED BECAUSE THE FRAME USED TO DERIVE THIS FROM THE HASH, AND THE HASH STOPPED BEING
 * ABLE TO ANSWER. `Shell.tsx`'s alert-create handler read `window.location.hash` and mapped
 * it (`product_data` β†’ `product`, `ut_*` β†’ itself, else `customer`) β€” correct while every
 * grid lived at a route named after its database. The Query module is a grid at `#/query`,
 * so that derivation would have filed every alert raised there against the CUSTOMER topic:
 * a silently wrong write, on a door that answers 200.
 *
 * This reports the foreground grid only. A nested grid never binds it, and no event writer
 * reads it. Each event carries the scope of the instance that created its callback.
 */
export function currentSurfaceScope(): SurfaceScope {
  return surfaceScope;
}

/** For the gate: the queue is module state and a test needs a known start. */
export function _resetQueue(): void {
  editOutbox.sessionBoundary();
  for (const timer of viewSelectTimers.values()) clearTimeout(timer);
  viewSelectTimers.clear();
  viewSelects.clear();
}

export function _pendingIds(): string[] {
  return editOutbox.snapshot().pending.map((edit) => edit.id);
}

/** Structural events and cell patches share one persisted order, including across reloads. */
async function drain(): Promise<void> {
  await editOutbox.flush();
}

/** Return the matching event refusal before publishing stale notifications. */
function applyEventResult(body: unknown, operationId?: string, quiet = false): OutboxReceipt | undefined {
  const b = body as {
    toast?: unknown; rerender?: unknown; results?: unknown; derived?: unknown;
  } | null;
  const results = Array.isArray(b?.results)
    ? (b.results as { id?: string; rerender?: unknown; refused?: unknown; ok?: boolean; reason?: string }[]) : [];
  const refusal = operationId ? results.find((result) => result.id === operationId
    && ((Array.isArray(result.refused) ? result.refused.length > 0 : !!result.refused)
      || result.ok === false || !!result.reason)) : undefined;
  if (refusal) return refusedReceipt(operationId!, refusal, 200, "One or more cell values could not be saved.");
  const toast = b?.toast;
  if (!quiet && typeof toast === "string" && toast.trim() !== "") signal(TOAST_EVENT, toast.trim());

  // owner item 2 β€” a measure column's values, computed server-side right after the write and
  // returned here rather than waiting for the `/workspace` re-read below. Raised BEFORE the
  // stale signal so the numbers paint on the earlier of the two, whichever the server sent.
  // Shape-checked, because a shortcut that corrupts rows is worse than no shortcut.
  if (b?.derived && typeof b.derived === "object" && !Array.isArray(b.derived)) {
    // A broadcast has no parent pin. Re-read every receiver through its own rows door.
    // Non-metric derived cells still arrive through the workspace refresh below.
    rowsCache.clear();
    windowPaging.clear();
    signal(ROWS_STALE_EVENT);
  }

  // The server already tells us when a write changed durable state β€” `rerender`
  // is exactly the flag the Streamlit adapter uses to trigger its own rerun. We
  // were dropping it, which is why cohort membership, list adds and folder moves
  // never appeared in standalone until a manual reload.
  if (b?.rerender === true || results.some((r) => r?.rerender === true)) {
    signal(WORKSPACE_STALE_EVENT);
  }
}

// S85-T26: `view_select` records the open view. It leaves on its own path, never behind queued
// saves, only the last click of a burst is sent, and it is never stored in the browser.
/** Clicks inside this window collapse into one `view_select`. */
export const VIEW_SELECT_SETTLE_MS = 250;
const viewSelects = new Map<string, { event: HostEvent; session: number }>();
const viewSelectTimers = new Map<string, ReturnType<typeof setTimeout>>();
const viewSelectFlights = new Map<string, Promise<void>>();

function queueViewSelect(event: HostEvent, scope: SurfaceScope): void {
  viewSelects.set(scope, { event, session: writeSession });
  const timer = viewSelectTimers.get(scope);
  if (timer !== undefined) clearTimeout(timer);
  viewSelectTimers.set(scope, setTimeout(() => {
    viewSelectTimers.delete(scope);
    void sendViewSelect(scope);
  }, VIEW_SELECT_SETTLE_MS));
}

async function sendViewSelect(scope: string, keepalive = false): Promise<void> {
  // One request per scope at a time. A click made during it is sent after it.
  const flight = viewSelectFlights.get(scope);
  if (flight && !keepalive) {
    await flight;
    if (viewSelectTimers.has(scope)) return;
  }
  const latest = viewSelects.get(scope);
  if (!latest) return;
  viewSelects.delete(scope);
  if (latest.session !== writeSession) return;
  const tenant = currentTenant();
  const task = ownWrite(async () => {
    try {
      const response = await fetch(`${API_V1}/grid/events`, {
        method: "POST", credentials: CREDENTIALS, keepalive,
        headers: { ...JSON_HEADERS, ...(tenant ? { [TENANT_HEADER]: tenant } : {}) },
        body: JSON.stringify({ events: [latest.event], scopeKey: scope }),
      });
      handledSession(response);
    } catch {
      // The view is already on screen. A lost choice only changes where a new browser opens.
    }
  });
  viewSelectFlights.set(scope, task);
  try {
    await task;
  } finally {
    if (viewSelectFlights.get(scope) === task) viewSelectFlights.delete(scope);
  }
}

/** Send every waiting view choice now, because the page is going away. */
function flushViewSelects(): void {
  for (const [scope, timer] of [...viewSelectTimers]) {
    clearTimeout(timer);
    viewSelectTimers.delete(scope);
    void sendViewSelect(scope, true);
  }
}

/** The sink hostBridge falls through to in standalone. Returns true: the event
 *  is now OURS (queued and owned), which is all the caller ever needed. */
function standaloneSink(event: HostEvent, scope: SurfaceScope): boolean {
  if (event.type === "view_select") {
    queueViewSelect(event, scope);
    return true;
  }
  void editOutbox.enqueue({ id: event.id, kind: "event", scope, payload: event }, (receipt) => {
    if (event.type !== "view_op" && !receipt.ok && receipt.message) signal(TOAST_EVENT, receipt.message);
    if (!receipt.ok) refreshFrozenOutboxRefusal(receipt);
  });
  return true;
}

/** Called from main.tsx in standalone ONLY. Never in the embed β€” that is the
 *  whole of "standalone-only branches", enforced at the one wiring point. */
export function installStandaloneBridge(): void {
  setStandaloneSink(standaloneSink);
  if (!outboxListenersBound && typeof window !== "undefined") {
    outboxListenersBound = true;
    window.addEventListener("beforeunload", editOutbox.beforeUnload);
    window.addEventListener("online", () => { void drain(); });
    window.addEventListener("pagehide", flushViewSelects);
  }
  void editOutbox.start();
}

let outboxListenersBound = false;

/**
 * ⭐⭐ WAVE 34 (owner ruling R13, `W34-T54`) β€” RUN AN `ai_enrich` COLUMN OVER A SCOPE.
 *
 * `POST /api/v1/tables/{key}/fields/{fkey}/enrich`, body `{scope: "blank" | "always"}`.
 * `blank` fills only cells nothing has written; `always` re-runs every row.
 *
 * β›” ADDED BY THE INTEGRATOR AT CLOSE-OUT, and the reason is worth stating rather than burying.
 * Lane F built the server door, the menu row and the field kind, and left the host call site as an
 * OPTIONAL prop with the note *"nothing breaks if you decline"*. That is true of the BUILD and
 * false of the FEATURE: this is the only path that makes the bulk run reachable, and `W34-T54`'s
 * own `done-when` reads *"the bulk menu offers at least all rows and rows never filled"*. Left
 * unwired, that ticket would have been BUILT with its acceptance test unreachable β€” the exact
 * shape this repo has shipped five times ([[mounted-is-not-callable]]).
 *
 * ⚠ IT SPENDS MONEY, so it reports rather than returns a boolean. The server answers a RUN REPORT
 * (`filled`, `failed`, `skipped` by reason, `tokens`, `limit`) and the caller shows the sentence:
 * a bulk enrichment that quietly did 3 of 900 rows because a ceiling bit is precisely the silent
 * cap R6's standing rule forbids, and a `true` would hide it.
 */
export async function enrichField(
  tableKey: string,
  fieldKey: string,
  scope: "blank" | "always"
): Promise<EnrichReport | null> {
  try {
    const res = await fetch(
      `${API_V1}/tables/${encodeURIComponent(tableKey)}/fields/${encodeURIComponent(fieldKey)}/enrich`,
      {
        method: "POST",
        credentials: CREDENTIALS,
        headers: JSON_HEADERS,
        body: JSON.stringify({ scope }),
      }
    );
    if (handledSession(res)) return null;
    const body = (await readJson(res)) as (EnrichReport & { error?: { message?: string } }) | null;
    if (!res.ok) {
      // The server states WHY (no key, a token ceiling, a locked column). Its sentence beats ours.
      signal(TOAST_EVENT, refusalMessage(body, res.status));
      return null;
    }
    return body ?? null;
  } catch {
    signal(DATA_ERROR_EVENT, "The enrichment run could not be reached. Nothing was changed.");
    return null;
  }
}

/** What `POST .../enrich` answers. Shapes the sentence the caller shows. */
export type EnrichReport = {
  filled?: number;
  failed?: number;
  skipped?: Record<string, number>;
  tokens?: number;
  limit?: number;
};