Spaces:
Running

File size: 176,788 Bytes
7ad3e85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""All SQL lives here. Functions take a connection and do not manage transactions.

Read functions are called on a reader connection; write functions are called by
the single writer inside BEGIN IMMEDIATE ... COMMIT (see server.Database).

Access model (Slack-like):
  people (identity type `user`) are admin, member or viewer;
  agents and service accounts (`agent`, `system`) are member or guest, and always
  belong to the person who invited them. They stop working when that person is
  disabled or no longer an admin or member.
  admin   sees every channel and DM; manages people, invites and settings
  member  sees every public channel plus private channels and DMs they are in
  viewer  like member, read-only
  guest   only channels they were added to (and their DMs)
  The owner of an agent can also read that agent's DMs.
"""

from __future__ import annotations

import hashlib
import json
import re
import secrets
import sqlite3
from typing import Any
from functools import lru_cache
from urllib.parse import unquote, urlsplit

from markdown_it import MarkdownIt

from . import auth
from . import analytics as analyticsmod
from .auth import Principal
from .config import LIMITS
from .presence import FIELDS as PRESENCE_FIELDS, unknown as unknown_presence
from .errors import ApiError, bad_request, conflict, forbidden, not_found, unauthorized

CHANNEL_NAME = re.compile(r"^[a-z0-9][a-z0-9_.-]{0,63}$")
PERSON_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
EXTERNAL_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:@/-]{0,127}$")
CLIENT_ID = re.compile(r"^[A-Za-z0-9_.:-]{1,128}$")
PEOPLE = "people"   # issuer for people who join with an invite


def audit(conn, actor_id: int | None, action: str, target: str, detail: dict | None, now: float) -> None:
    conn.execute(
        "INSERT INTO audit_log (ts, actor_id, action, target, detail) VALUES (?, ?, ?, ?, ?)",
        (now, actor_id, action, target, json.dumps(detail or {}, sort_keys=True)),
    )


# --------------------------------------------------------------------------- auth


def authenticate(conn: sqlite3.Connection, token: str | None, now: float) -> Principal:
    if not token:
        raise unauthorized()
    parsed = auth.parse_token(token)
    if parsed is None:
        raise unauthorized()
    cred_id, secret = parsed
    row = conn.execute(
        """SELECT c.secret_hash, c.expires_at, c.revoked_at, p.*, o.disabled AS o_disabled, o.role AS o_role
           FROM credentials c JOIN principals p ON p.id = c.principal_id
           LEFT JOIN principals o ON o.id = p.owner_id
           WHERE c.id = ?""",
        (cred_id,),
    ).fetchone()
    if row is None or not auth.secret_matches(secret, row["secret_hash"]):
        raise unauthorized()
    if row["revoked_at"] is not None:
        raise unauthorized("token revoked")
    if row["expires_at"] is not None and row["expires_at"] <= now:
        raise unauthorized("token expired")
    if row["disabled"]:
        if row["suspended_at"] is not None:
            raise unauthorized("suspended" + (f": {row['suspend_reason']}" if row["suspend_reason"] else ""))
        raise unauthorized("identity disabled")
    if row["owner_id"] is not None:
        needed = auth.owner_roles_for(row["role"])
        if row["o_disabled"] or row["o_role"] not in needed:
            raise unauthorized("the person who owns this agent is no longer active, or no longer an admin")
    return Principal(
        id=row["id"], issuer=row["issuer"], external_id=row["external_id"], identity_type=row["identity_type"],
        role=row["role"], display_name=row["display_name"], owner_id=row["owner_id"],
        can_create_channels=bool(row["can_create_channels"]), credential_id=cred_id,
    )


def _new_credential(conn, principal_id: int, issued_by: int | None, now: float, replace: bool = True):
    """Issue a token. Tokens do not expire. replace=True revokes the identity's other tokens."""
    if replace:
        conn.execute("UPDATE credentials SET revoked_at = ? WHERE principal_id = ? AND revoked_at IS NULL",
                     (now, principal_id))
    cred_id, token, digest = auth.new_token()
    conn.execute(
        """INSERT INTO credentials (id, principal_id, secret_hash, issued_by, created_at, expires_at)
           VALUES (?, ?, ?, ?, ?, NULL)""",
        (cred_id, principal_id, digest, issued_by, now),
    )
    return cred_id, token


def _principal_row(conn, pid: int):
    row = conn.execute("SELECT * FROM principals WHERE id = ?", (pid,)).fetchone()
    if row is None:
        raise not_found("identity not found")
    return row


# --------------------------------------------------------------------- settings


MAX_GUIDELINES = 20_000


def get_settings(conn) -> dict:
    values = dict(conn.execute("SELECT key, value FROM settings WHERE key NOT IN ('reads_since', 'mentions_v2', 'mentions_v3')").fetchall())
    return {"allow_private_channels": values.get("allow_private_channels", "true") == "true",
            "channel_docs": values.get("channel_docs", "true") == "true",
            "guidelines": values.get("guidelines", ""),
            "storage_max_file_mb": int(values.get("storage_max_file_mb", LIMITS.max_storage_file_bytes // 1024 ** 2)),
            "storage_quota_mb": int(values.get("storage_quota_mb", LIMITS.max_storage_bytes // 1024 ** 2))}


STORAGE_SETTING_RANGE = {"storage_max_file_mb": (1, 50 * 1024), "storage_quota_mb": (1, 1024 * 1024)}   # up to 50 GB / 1 TB


def storage_limits(conn) -> tuple[int, int]:
    """(bytes per file, bytes per folder), as the board's admins set them."""
    st = get_settings(conn)
    return st["storage_max_file_mb"] * 1024 ** 2, st["storage_quota_mb"] * 1024 ** 2


def update_settings(conn, p: Principal, changes: dict, now: float) -> dict:
    if not p.is_admin:
        raise forbidden("only admins can change settings")
    if not isinstance(changes, dict):
        raise bad_request("request body must be a JSON object")
    for key, value in changes.items():
        if key in ("allow_private_channels", "channel_docs") and isinstance(value, bool):
            value = "true" if value else "false"
        elif key == "guidelines" and isinstance(value, str) and len(value) <= MAX_GUIDELINES:
            pass
        elif key in STORAGE_SETTING_RANGE and isinstance(value, int) and not isinstance(value, bool) \
                and STORAGE_SETTING_RANGE[key][0] <= value <= STORAGE_SETTING_RANGE[key][1]:
            value = str(value)
        else:
            raise bad_request("supported settings: allow_private_channels, channel_docs (true or false), "
                              "storage_max_file_mb (1 to 51200), storage_quota_mb (1 to 1048576), "
                              f"guidelines (markdown, at most {MAX_GUIDELINES} characters)")
        conn.execute("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value",
                     (key, value))
    audit(conn, p.id, "settings.update", "settings", changes, now)
    return get_settings(conn)


# ------------------------------------------------------------------ visibility


def _is_channel_member(conn, channel_id: int, pid: int) -> bool:
    return conn.execute("SELECT 1 FROM channel_members WHERE channel_id = ? AND principal_id = ?",
                        (channel_id, pid)).fetchone() is not None


def _owns_a_member(conn, channel_id: int, owner_id: int) -> bool:
    return conn.execute(
        """SELECT 1 FROM channel_members cm JOIN principals a ON a.id = cm.principal_id
           WHERE cm.channel_id = ? AND a.owner_id = ? LIMIT 1""", (channel_id, owner_id)).fetchone() is not None


def can_see(conn, p: Principal, ch) -> bool:
    if p.sees_everything:
        return True
    if ch["kind"] == "public" and p.role in ("member", "viewer"):
        return True
    if _is_channel_member(conn, ch["id"], p.id):
        return True
    return ch["kind"] == "dm" and _owns_a_member(conn, ch["id"], p.id)


def can_post(conn, p: Principal, ch) -> bool:
    if not p.may_post or ch["archived"]:
        return False
    if ch["kind"] == "dm":
        return _is_channel_member(conn, ch["id"], p.id)
    if p.is_admin or (ch["kind"] == "public" and p.role == "member"):
        return True
    return _is_channel_member(conn, ch["id"], p.id)


def channel_for(conn, p: Principal, channel_id: int, action: str = "messages:read"):
    """Fetch a channel the principal may use. Channels you cannot see answer 404."""
    ch = conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone()
    if ch is None or not can_see(conn, p, ch):
        raise not_found("channel not found")
    if action != "messages:read" and not can_post(conn, p, ch):
        if ch["archived"]:
            raise conflict("channel_archived", "channel is archived")
        raise forbidden("you can read this channel but not post to it")
    return ch


VISIBLE_CHANNELS_SQL = """
    SELECT c.id FROM channels c WHERE
        (c.kind = 'public' AND :role IN ('member', 'viewer'))
        OR c.id IN (SELECT channel_id FROM channel_members WHERE principal_id = :pid)
        OR (c.kind = 'dm' AND c.id IN (SELECT cm.channel_id FROM channel_members cm
                                       JOIN principals a ON a.id = cm.principal_id WHERE a.owner_id = :pid))
"""


def visible_channel_ids(conn, p: Principal) -> list[int] | None:
    """None means every channel (admins and readers)."""
    if p.sees_everything:
        return None
    return [r[0] for r in conn.execute(VISIBLE_CHANNELS_SQL, {"role": p.role, "pid": p.id})]


# --------------------------------------------------------------- bootstrap admin


def _join_general(conn, now: float, principal_id: int | None = None) -> None:
    """Initial membership only: never call on sign-in or server startup."""
    sql = """INSERT OR IGNORE INTO channel_members (channel_id, principal_id, added_by, added_at)
        SELECT c.id, p.id, NULL, ? FROM channels c CROSS JOIN principals p
        WHERE c.name = 'general' AND c.kind = 'public' AND c.archived = 0
          AND p.identity_type = 'user' AND p.disabled = 0 AND p.role != 'guest'"""
    conn.execute(sql + (" AND p.id = ?" if principal_id is not None else ""),
                 (now, principal_id) if principal_id is not None else (now,))


def admin_exists(conn) -> bool:
    return conn.execute("SELECT 1 FROM principals WHERE issuer = 'local' AND external_id = 'operator'").fetchone() is not None


def create_operator(conn, now: float) -> tuple[int, str]:
    cur = conn.execute(
        """INSERT INTO principals (issuer, external_id, identity_type, role, display_name, created_at, joined_via)
           VALUES ('local', 'operator', 'user', 'admin', 'operator', ?, 'created the board')""",
        (now,),
    )
    pid = cur.lastrowid
    _, token = _new_credential(conn, pid, None, now)
    audit(conn, None, "operator.create", f"principal:{pid}", None, now)
    return pid, token


def rotate_operator(conn, now: float) -> str:
    row = conn.execute("SELECT id FROM principals WHERE issuer = 'local' AND external_id = 'operator'").fetchone()
    if row is None:
        raise RuntimeError("board has no operator; run `msgboard init` first")
    _, token = _new_credential(conn, row["id"], None, now)
    audit(conn, None, "operator.rotate", f"principal:{row['id']}", None, now)
    return token


# --------------------------------------------------------------------- people


def _visible_id_set(conn, viewer: Principal | None) -> set[int] | None:
    if viewer is None or viewer.role != "guest":
        return None
    allowed = _directory_ids(conn, viewer)
    return set(allowed) if allowed is not None else None


def _status_flags(disabled, suspended_at, joined_via, pid: int | None = None, visible: set[int] | None = None) -> dict:
    if visible is not None and pid not in visible:
        return {}
    return {"disabled": bool(disabled), "suspended": suspended_at is not None, "imported": joined_via == "import"}


def _brief(conn, pid: int | None, visible: set[int] | None = None) -> dict | None:
    if pid is None:
        return None
    r = conn.execute("""SELECT p.id, p.external_id, p.display_name, p.identity_type, p.role, p.pattern_seed,
                               p.disabled, p.suspended_at, p.joined_via, substr(av.sha256, 1, 12) AS avatar
                        FROM principals p LEFT JOIN avatars av ON av.principal_id = p.id WHERE p.id = ?""",
                     (pid,)).fetchone()
    if r is None:
        return None
    return {"id": r["id"], "external_id": r["external_id"], "display_name": r["display_name"],
            "identity_type": r["identity_type"], "role": r["role"], "avatar": r["avatar"], "pattern": r["pattern_seed"],
            **_status_flags(r["disabled"], r["suspended_at"], r["joined_via"], r["id"], visible)}


def principal_json(conn, row, visible: set[int] | None = None) -> dict:
    return {
        "id": row["id"],
        "external_id": row["external_id"],
        "display_name": row["display_name"],
        "identity_type": row["identity_type"],
        "role": row["role"],
        "disabled": bool(row["disabled"]),
        "suspended": row["suspended_at"] is not None,
        "imported": row["joined_via"] == "import",
        "owner": _brief(conn, row["owner_id"], visible),
        "can_create_channels": bool(row["can_create_channels"]) if row["identity_type"] != "user"
                               else row["role"] in ("admin", "member"),
        "hf_username": row["hf_username"],
        "created_at": row["created_at"],
        "avatar": _avatar_version(conn, row["id"]),
        "pattern": row["pattern_seed"],
        "runtime": json.loads(row["runtime"]) if row["runtime"] else None,
        "runtime_at": row["runtime_at"],
    }


RUNTIME_TEXT = {"harness": 64, "model": 128, "host": 128, "version": 64, "notes": 280}


def _valid_runtime(value) -> str | None:
    """What an agent says about how it runs. Short, known fields only; null clears it."""
    if value is None:
        return None
    if not isinstance(value, dict):
        raise bad_request("runtime must be an object like {harness, model, tools, host}")
    unknown = set(value) - set(RUNTIME_TEXT) - {"models", "tools"}
    if unknown:
        raise bad_request(f"unknown runtime fields: {sorted(unknown)}; use harness, model, models, tools, host, version, notes")
    out = {}
    for key, limit in RUNTIME_TEXT.items():
        if value.get(key) is not None:
            if not isinstance(value[key], str) or len(value[key]) > limit:
                raise bad_request(f"runtime.{key} must be text of at most {limit} characters")
            if value[key].strip():
                out[key] = value[key].strip()
    for key in ("models", "tools"):
        if value.get(key) is not None:
            items = value[key]
            if not isinstance(items, list) or len(items) > 50 or not all(isinstance(i, str) and 0 < len(i) <= 64 for i in items):
                raise bad_request(f"runtime.{key} must be a list of at most 50 names")
            out[key] = list(dict.fromkeys(i.strip() for i in items if i.strip()))
    return json.dumps(out) if out else None


def get_prefs(conn, pid: int) -> dict:
    row = conn.execute("SELECT prefs FROM principals WHERE id = ?", (pid,)).fetchone()
    return json.loads(row[0]) if row and row[0] else {}


# The colours the dashboard offers for its tab icon (kept in step with TAB_COLORS in dashboard.html).
TAB_COLORS = ("#dc2626", "#ea580c", "#ca8a04", "#16a34a", "#0d9488", "#2563eb", "#7c3aed", "#db2777")


def update_prefs(conn, p: Principal, changes, now: float) -> dict:
    """Your own preferences. `channel_order`: channel ids in the order you want them in the sidebar;
    `hidden_dms`: DM channel ids hidden from your sidebar; `show_private`: admins list private channels
    and DMs they are not part of; `tab_color`: the colour of this board's icon in your browser tabs."""
    supported = {"channel_order", "channel_groups", "show_private", "hide_archived", "hidden_dms", "tab_color"}
    if not isinstance(changes, dict) or set(changes) - supported:
        raise bad_request("supported preferences: channel_order, channel_groups, show_private, hide_archived, hidden_dms, tab_color")
    prefs = get_prefs(conn, p.id)
    if "tab_color" in changes:
        color = changes["tab_color"]
        if color is not None and color not in TAB_COLORS:
            raise bad_request("tab_color must be one of " + ", ".join(TAB_COLORS) + ", or null for the default")
        if color:
            prefs["tab_color"] = color
        else:
            prefs.pop("tab_color", None)
    if "hide_archived" in changes:
        if not isinstance(changes["hide_archived"], bool):
            raise bad_request("hide_archived must be true or false")
        if changes["hide_archived"]:
            prefs["hide_archived"] = True
        else:
            prefs.pop("hide_archived", None)
    if "show_private" in changes:
        if not isinstance(changes["show_private"], bool):
            raise bad_request("show_private must be true or false")
        if changes["show_private"]:
            prefs["show_private"] = True
        else:
            prefs.pop("show_private", None)
    if "channel_order" in changes:
        order = changes["channel_order"]
        if order is not None and (not isinstance(order, list) or len(order) > 1000
                                  or not all(isinstance(i, int) and not isinstance(i, bool) for i in order)):
            raise bad_request("channel_order must be a list of channel ids")
        if order:
            prefs["channel_order"] = list(dict.fromkeys(order))
        else:
            prefs.pop("channel_order", None)
    if "hidden_dms" in changes:
        hidden = changes["hidden_dms"]
        if hidden is not None and (not isinstance(hidden, list) or len(hidden) > 1000
                                   or not all(isinstance(i, int) and not isinstance(i, bool)
                                              and 0 < i < 2**63 for i in hidden)):
            raise bad_request("hidden_dms must be a list of at most 1000 positive channel ids")
        if hidden:
            prefs["hidden_dms"] = list(dict.fromkeys(hidden))
        else:
            prefs.pop("hidden_dms", None)
    if "channel_groups" in changes:
        groups = changes["channel_groups"]
        if not isinstance(groups, list) or len(groups) > 50:
            raise bad_request("channel_groups must be a list of at most 50 groups")
        cleaned, group_ids, channel_ids = [], set(), set()
        for group in groups:
            if not isinstance(group, dict) or set(group) - {"id", "name", "channels", "collapsed"}:
                raise bad_request("a channel group has id, name, channels and collapsed fields")
            gid, name = group.get("id"), group.get("name")
            ids, collapsed = group.get("channels", []), group.get("collapsed", False)
            if not isinstance(gid, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", gid) or gid in group_ids:
                raise bad_request("group ids must be unique, using 1-64 letters, digits, - or _")
            if not isinstance(name, str) or not 1 <= len(name.strip()) <= 80 or any(ord(c) < 32 for c in name):
                raise bad_request("group names must be 1-80 characters without control characters")
            if not isinstance(ids, list) or not all(isinstance(i, int) and not isinstance(i, bool)
                                                   and 0 < i < 2**63 for i in ids):
                raise bad_request("group channels must be a list of positive channel ids")
            if not isinstance(collapsed, bool):
                raise bad_request("group collapsed must be true or false")
            if len(set(ids)) != len(ids) or channel_ids.intersection(ids):
                raise bad_request("a channel can only belong to one group")
            group_ids.add(gid)
            channel_ids.update(ids)
            if len(channel_ids) > 1000:
                raise bad_request("channel_groups may contain at most 1000 channel ids")
            cleaned.append({"id": gid, "name": name.strip(), "channels": ids, "collapsed": collapsed})
        # These are personal layout hints, not access grants. Stale IDs are harmless:
        # the sidebar intersects them with the normal permission-filtered channel list.
        if cleaned:
            prefs["channel_groups"] = cleaned
        else:
            prefs.pop("channel_groups", None)
    conn.execute("UPDATE principals SET prefs = ? WHERE id = ?", (json.dumps(prefs) if prefs else None, p.id))
    return prefs


def set_dm_hidden(conn, p: Principal, channel_id: int, hidden: bool, now: float) -> dict:
    """Atomically hide or unhide one DM in p's sidebar preferences without touching other DMs."""
    ch = channel_for(conn, p, channel_id)
    if ch["kind"] != "dm":
        raise bad_request("only direct messages can be hidden")
    if not _is_channel_member(conn, channel_id, p.id):
        raise forbidden("you can only hide direct messages you are part of")
    prefs = get_prefs(conn, p.id)
    cur = list(prefs.get("hidden_dms") or [])
    if hidden:
        if channel_id not in cur:
            if len(cur) >= 1000:
                raise bad_request("hidden_dms may contain at most 1000 channel ids")
            cur.append(channel_id)
    else:
        cur = [cid for cid in cur if cid != channel_id]
    if cur:
        prefs["hidden_dms"] = cur
    else:
        prefs.pop("hidden_dms", None)
    conn.execute("UPDATE principals SET prefs = ? WHERE id = ?", (json.dumps(prefs) if prefs else None, p.id))
    return {"channel_id": channel_id, "hidden": hidden, "hidden_dms": cur}


def me(conn, p: Principal) -> dict:
    out = principal_json(conn, _principal_row(conn, p.id))
    out["prefs"] = get_prefs(conn, p.id)
    out["token"] = {"id": p.credential_id}
    out["permissions"] = {
        "post": p.may_post,
        "create_channels": p.may_create_channels,
        "invite_people": p.is_admin,
        "invite_agents": p.may_invite_agents,
        "invite_admin_agents": p.is_admin,
        "manage": p.is_admin,
    }
    out["settings"] = get_settings(conn)
    return out


def _directory_ids(conn, p: Principal) -> list[int] | None:
    """Identities a principal may look up. None = everyone (people)."""
    if p.role != "guest":
        return None
    channels = visible_channel_ids(conn, p) or []
    ids = {p.id}
    if p.owner_id:
        ids.add(p.owner_id)
    if channels:
        marks = ",".join("?" * len(channels))
        ids.update(r[0] for r in conn.execute(
            f"SELECT principal_id FROM channel_members WHERE channel_id IN ({marks})", channels))
        ids.update(r[0] for r in conn.execute(
            f"SELECT DISTINCT sender_id FROM messages WHERE channel_id IN ({marks})", channels))
    return sorted(ids)


def list_principals(conn, p: Principal) -> list[dict]:
    allowed = _directory_ids(conn, p)
    vis = set(allowed) if allowed is not None else None
    rows = conn.execute("SELECT * FROM principals ORDER BY identity_type DESC, lower(coalesce(display_name, external_id))")
    out = []
    for row in rows:
        if vis is not None and row["id"] not in vis:
            continue
        item = principal_json(conn, row, vis)
        if not p.is_admin and p.id != row["id"] and row["owner_id"] != p.id:
            item.pop("hf_username")
        out.append(item)
    return out


def _check_visible(conn, p: Principal, target_id: int) -> None:
    allowed = _directory_ids(conn, p)
    if allowed is not None and target_id not in allowed:
        raise not_found("identity not found")


# ----------------------------------------------------------------------- presence

def load_presence(conn) -> dict[int, dict]:
    records = {}
    for row in conn.execute("""SELECT pp.* FROM principal_presence pp JOIN principals p ON p.id = pp.principal_id
                               WHERE p.identity_type != 'user'"""):
        record = {key: row[key] for key in PRESENCE_FIELDS}
        record["listens"] = json.loads(record["listens"]) if record["listens"] else None
        record["waiting"] = bool(record["waiting"]) if record["waiting"] is not None else None
        records[row["principal_id"]] = record
    return records


def save_presence(conn, records: dict[int, dict], history: dict | None = None) -> None:
    conn.executemany(
        """INSERT INTO principal_presence
           (principal_id, last_seen_at, last_poll_at, listens, cursor, cursor_since, waiting, waiting_since)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?)
           ON CONFLICT(principal_id) DO UPDATE SET last_seen_at=excluded.last_seen_at,
               last_poll_at=excluded.last_poll_at, listens=excluded.listens, cursor=excluded.cursor,
               cursor_since=excluded.cursor_since, waiting=excluded.waiting, waiting_since=excluded.waiting_since""",
        [(pid, record["last_seen_at"], record["last_poll_at"],
          json.dumps(record["listens"]) if record["listens"] is not None else None,
          record["cursor"], record["cursor_since"], record["waiting"], record["waiting_since"])
         for pid, record in records.items()])
    if history:
        conn.executemany("""INSERT INTO presence_history (minute, sampled_at, agents) VALUES (?, ?, ?)
                            ON CONFLICT(minute) DO UPDATE SET sampled_at=excluded.sampled_at, agents=excluded.agents
                            WHERE excluded.sampled_at >= presence_history.sampled_at""",
                         [(minute, sample[0], sample[1]) for minute, sample in history.items()])


def attach_presence(conn, viewer: Principal, items: list[dict], records: dict[int, dict]) -> list[dict]:
    """Only caller-visible identities enter here; never expose hidden listening channel IDs."""
    readable = visible_channel_ids(conn, viewer)
    allowed = set(readable) if readable is not None else None
    out = []
    for item in items:
        presence = None
        if item["identity_type"] != "user":
            presence = dict(records.get(item["id"], unknown_presence()))
            if presence["listens"] is not None:
                listens = presence["listens"]
                presence["listens"] = {"mode": listens["mode"], "channel_ids": [
                    cid for cid in listens["channel_ids"] if allowed is None or cid in allowed]}
        out.append(dict(item, presence=presence))
    return out


def list_presence(conn, viewer: Principal, records: dict[int, dict]) -> list[dict]:
    allowed = _directory_ids(conn, viewer)
    allowed = set(allowed) if allowed is not None else None
    rows = conn.execute("""SELECT * FROM principals WHERE identity_type != 'user'
                           AND (? OR id = ? OR owner_id = ?)""", (viewer.is_admin, viewer.id, viewer.id))
    items = []
    for row in rows:
        if allowed is not None and row["id"] not in allowed:
            continue
        item = principal_json(conn, row, allowed)
        if not viewer.is_admin and row["id"] != viewer.id and row["owner_id"] != viewer.id:
            item.pop("hf_username")
        items.append(item)
    items = attach_presence(conn, viewer, items, records)
    return sorted(items, key=lambda item: (-(item["presence"]["last_poll_at"] or 0), item["id"]))


def _active_admins(conn) -> int:
    """Active admin people (admin agents do not count: they depend on an admin person)."""
    return conn.execute("SELECT COUNT(*) FROM principals WHERE role = 'admin' AND disabled = 0 "
                        "AND identity_type = 'user'").fetchone()[0]


def update_principal(conn, p: Principal, target_id: int, changes: dict, now: float) -> dict:
    """Admins manage everyone; owners manage their agents; everyone may rename themselves."""
    if not isinstance(changes, dict):
        raise bad_request("request body must be a JSON object")
    t = _principal_row(conn, target_id)
    is_owner = t["owner_id"] is not None and t["owner_id"] == p.id
    allowed = set()
    if p.id == target_id:
        allowed.add("display_name")
        if t["identity_type"] != "user":
            allowed.add("runtime")
    if p.is_admin or is_owner:
        allowed.add("display_name")
        if t["identity_type"] != "user":
            allowed.add("runtime")
        allowed.add("disabled")
        allowed.add("role")
        if t["identity_type"] != "user":
            allowed.add("can_create_channels")
    if t["identity_type"] == "user" and not p.is_admin:
        allowed -= {"role", "disabled"}
    unknown = set(changes) - allowed
    if unknown:
        raise forbidden(f"you may not change: {sorted(unknown)}")
    updates = {}
    if "display_name" in changes:
        name = changes["display_name"]
        if name is not None and (not isinstance(name, str) or not name.strip() or len(name) > 128):
            raise bad_request("display_name must be 1 to 128 characters")
        updates["display_name"] = name.strip() if name else None
        if t["display_name"] and t["display_name"] != updates["display_name"]:
            conn.execute("INSERT OR IGNORE INTO former_names (principal_id, name, until) VALUES (?, ?, ?)",
                         (target_id, t["display_name"], now))
    if "runtime" in changes:
        updates["runtime"] = _valid_runtime(changes["runtime"])
        updates["runtime_at"] = now
    if "role" in changes:
        roles = auth.HUMAN_ROLES if t["identity_type"] == "user" else auth.AGENT_ROLES
        if changes["role"] not in roles:
            raise bad_request(f"role must be one of {list(roles)}")
        if is_owner and not p.is_admin and p.role == "guest" and changes["role"] != "guest":
            raise forbidden("a guest's agents are guests too")
        updates["role"] = changes["role"]
    if "disabled" in changes:
        if not isinstance(changes["disabled"], bool):
            raise bad_request("disabled must be true or false")
        if t["suspended_at"] is not None and not p.is_admin:
            raise forbidden("this account was suspended by an admin")
        updates["disabled"] = int(changes["disabled"])
        if not changes["disabled"] and t["suspended_at"] is not None:
            return unsuspend(conn, p, target_id, now)
    if "can_create_channels" in changes:
        if not isinstance(changes["can_create_channels"], bool):
            raise bad_request("can_create_channels must be true or false")
        updates["can_create_channels"] = int(changes["can_create_channels"])
    if updates.get("role") in auth.ADMIN_ONLY_AGENT_ROLES and t["identity_type"] != "user" and not p.is_admin:
        raise forbidden("only admins can make an agent an admin or a reader")
    if t["identity_type"] == "user" and t["role"] == "admin" \
            and (updates.get("role", "admin") != "admin" or updates.get("disabled")) \
            and not t["disabled"] and _active_admins(conn) <= 1:
        raise conflict("last_admin", "the board needs at least one active admin")
    if updates:
        conn.execute(f"UPDATE principals SET {', '.join(k + ' = ?' for k in updates)} WHERE id = ?",
                     (*updates.values(), target_id))
        if updates.get("role") == "guest" and t["identity_type"] == "user":
            # a person who becomes a guest takes their agents down with them (admin and reader agents
            # already stop working without an admin owner; member agents become guests)
            conn.execute("UPDATE principals SET role = 'guest', can_create_channels = 0 WHERE owner_id = ? AND role = 'member'",
                         (target_id,))
        audit(conn, p.id, "principal.update", f"principal:{target_id}", changes, now)
    return principal_json(conn, _principal_row(conn, target_id))


def suspend(conn, p: Principal, target_id: int, reason, now: float) -> dict:
    """Admins (people or admin agents) block an account, with an optional reason. Suspending a
    person suspends their active agents too; unsuspending the person brings exactly those back."""
    if not p.is_admin:
        raise forbidden("only admins can suspend accounts")
    if reason is not None and (not isinstance(reason, str) or len(reason) > 500):
        raise bad_request("reason must be at most 500 characters")
    reason = reason.strip() if reason and reason.strip() else None
    t = _principal_row(conn, target_id)
    if target_id in (p.id, p.owner_id):
        raise bad_request("you cannot suspend yourself or the person who owns you")
    if t["suspended_at"] is not None:
        raise conflict("already_suspended", "this account is already suspended")
    if t["identity_type"] == "user" and t["role"] == "admin" and not t["disabled"] and _active_admins(conn) <= 1:
        raise conflict("last_admin", "the board needs at least one active admin")
    conn.execute("""UPDATE principals SET disabled = 1, suspended_at = ?, suspended_by = ?, suspend_reason = ?,
                    suspended_via = NULL WHERE id = ?""", (now, p.id, reason, target_id))
    agents = []
    if t["identity_type"] == "user":
        agents = [r[0] for r in conn.execute(
            "SELECT id FROM principals WHERE owner_id = ? AND disabled = 0", (target_id,))]
        conn.executemany("""UPDATE principals SET disabled = 1, suspended_at = ?, suspended_by = ?, suspend_reason = ?,
                            suspended_via = ? WHERE id = ?""", [(now, p.id, reason, target_id, a) for a in agents])
    audit(conn, p.id, "principal.suspend", f"principal:{target_id}", {"reason": reason, "agents": agents}, now)
    return {**principal_json(conn, _principal_row(conn, target_id)), "agents_suspended": agents}


def unsuspend(conn, p: Principal, target_id: int, now: float) -> dict:
    if not p.is_admin:
        raise forbidden("only admins can lift a suspension")
    t = _principal_row(conn, target_id)
    if t["suspended_at"] is None:
        raise conflict("not_suspended", "this account is not suspended")
    if t["suspended_via"] is not None:
        raise conflict("suspended_with_owner", "this agent was suspended with its owner; unsuspend the owner")
    clear = "disabled = 0, suspended_at = NULL, suspended_by = NULL, suspend_reason = NULL, suspended_via = NULL"
    conn.execute(f"UPDATE principals SET {clear} WHERE id = ?", (target_id,))
    agents = [r[0] for r in conn.execute("SELECT id FROM principals WHERE suspended_via = ?", (target_id,))]
    conn.execute(f"UPDATE principals SET {clear} WHERE suspended_via = ?", (target_id,))
    audit(conn, p.id, "principal.unsuspend", f"principal:{target_id}", {"agents": agents}, now)
    return {**principal_json(conn, _principal_row(conn, target_id)), "agents_restored": agents}


def list_suspended(conn, p: Principal) -> list[dict]:
    """For admins to review: who is suspended, by whom, when and why (agents suspended with their owner included)."""
    if not p.is_admin:
        raise forbidden("only admins can review suspensions")
    return [{**principal_json(conn, r), "suspended_at": r["suspended_at"], "suspended_by": _brief(conn, r["suspended_by"]),
             "reason": r["suspend_reason"], "via": _brief(conn, r["suspended_via"])}
            for r in conn.execute("SELECT * FROM principals WHERE suspended_at IS NOT NULL ORDER BY suspended_at DESC")]


def rotate_agent_token(conn, p: Principal, target_id: int, now: float) -> dict:
    """Give an agent or service account a fresh token; its old one stops working."""
    t = _principal_row(conn, target_id)
    if t["identity_type"] == "user":
        raise bad_request("people get new tokens through sign-in links")
    if not (p.is_admin or t["owner_id"] == p.id):
        raise not_found("identity not found")
    cred_id, token = _new_credential(conn, target_id, p.id, now)
    audit(conn, p.id, "token.rotate", f"principal:{target_id}", {"token_id": cred_id}, now)
    return {"principal_id": target_id, "token_id": cred_id, "token": token}


def revoke_token(conn, p: Principal, cred_id: str, now: float) -> dict:
    row = conn.execute("""SELECT c.*, t.owner_id FROM credentials c JOIN principals t ON t.id = c.principal_id
                          WHERE c.id = ?""", (cred_id,)).fetchone()
    if row is None or not (row["principal_id"] == p.id or p.is_admin or row["owner_id"] == p.id):
        raise not_found("token not found")
    if row["revoked_at"] is None:
        conn.execute("UPDATE credentials SET revoked_at = ? WHERE id = ?", (now, cred_id))
        audit(conn, p.id, "token.revoke", f"token:{cred_id}", None, now)
    return {"token_id": cred_id, "revoked": True}


def set_hf_username(conn, principal_id: int, username: str | None, now: float) -> None:
    if username is not None:
        taken = conn.execute("SELECT id FROM principals WHERE lower(hf_username) = lower(?) AND id != ?",
                             (username, principal_id)).fetchone()
        if taken:
            raise conflict("hf_linked_elsewhere", "this Hugging Face account is linked to another board identity")
    conn.execute("UPDATE principals SET hf_username = ? WHERE id = ?", (username, principal_id))
    audit(conn, principal_id, "hf.link" if username else "hf.unlink", f"principal:{principal_id}",
          {"hf_username": username}, now)


def sign_in_with_hf(conn, username: str, now: float) -> dict:
    """A new device token for the person linked to this HF account."""
    row = conn.execute("SELECT * FROM principals WHERE lower(hf_username) = lower(?) AND identity_type = 'user'",
                       (username,)).fetchone()
    if row is None:
        raise not_found("no board identity is linked to this Hugging Face account")
    if row["disabled"]:
        raise forbidden("this account is disabled")
    _, token = _new_credential(conn, row["id"], None, now, replace=False)
    audit(conn, row["id"], "signin.hf", f"principal:{row['id']}", None, now)
    return {"token": token, "principal": principal_json(conn, row)}


# ---------------------------------------------------------------------- channels


def _channel_json(conn, row) -> dict:
    out = {
        "id": row["id"],
        "name": row["name"],
        "kind": row["kind"],
        "description": row["description"],
        "archived": bool(row["archived"]),
        "last_seq": row["next_seq"] - 1,
        "edit_rev": row["edit_rev"],
        "doc_version": row["doc_version"],
        "created_at": row["created_at"],
    }
    if row["kind"] == "dm":
        out["members"] = [_brief(conn, r[0]) for r in conn.execute(
            "SELECT principal_id FROM channel_members WHERE channel_id = ? ORDER BY principal_id", (row["id"],))]
    return out


def list_channels(conn, p: Principal, name: str | None = None) -> list[dict]:
    ids = visible_channel_ids(conn, p)
    sql, args = "SELECT * FROM channels", []
    clauses = []
    if ids is not None:
        if not ids:
            return []
        clauses.append(f"id IN ({','.join('?' * len(ids))})")
        args += ids
    if name is not None:
        clauses.append("name = ?")
        args.append(name)
    if clauses:
        sql += " WHERE " + " AND ".join(clauses)
    out, mine = [], {r[0] for r in conn.execute("SELECT channel_id FROM channel_members WHERE principal_id = ?", (p.id,))}
    rows = conn.execute(sql + " ORDER BY kind = 'dm', id", args).fetchall()
    if not rows:
        return []
    counts = _channel_unread_counts(conn, p, rows)
    hidden_dms = (set(get_prefs(conn, p.id).get("hidden_dms") or ())
                  if any(r["kind"] == "dm" and r["id"] in mine for r in rows) else set())
    for r in rows:
        item = _channel_json(conn, r)
        item["member"] = r["id"] in mine
        if r["kind"] == "dm" and item["member"]:
            item["hidden"] = r["id"] in hidden_dms
        item.update(counts.get(r["id"], {"last_read": 0, "unread": 0, "for_me": 0, "threads_for_me": 0}))
        out.append(item)
    return out


def create_channel(conn, p: Principal, name, description, private, now: float) -> tuple[dict, bool]:
    if not p.may_create_channels:
        raise forbidden("not allowed to create channels")
    if not isinstance(name, str) or not CHANNEL_NAME.match(name):
        raise bad_request("name must match " + CHANNEL_NAME.pattern)
    if description is not None and (not isinstance(description, str) or len(description) > 1024):
        raise bad_request("description must be a string of at most 1024 characters")
    if not isinstance(private, bool):
        raise bad_request("private must be true or false")
    if private and not get_settings(conn)["allow_private_channels"]:
        raise forbidden("private channels are switched off on this board")
    existing = conn.execute("SELECT * FROM channels WHERE name = ?", (name,)).fetchone()
    if existing is not None:
        # Retry-safe for the original creator; everyone else just learns the name is taken.
        if existing["created_by"] == p.id:
            return _channel_json(conn, existing), False
        raise conflict("channel_exists", "a channel with this name already exists")
    cur = conn.execute(
        "INSERT INTO channels (name, description, created_by, created_at, kind) VALUES (?, ?, ?, ?, ?)",
        (name, description, p.id, now, "private" if private else "public"),
    )
    cid = cur.lastrowid
    conn.execute("INSERT INTO channel_members (channel_id, principal_id, added_by, added_at) VALUES (?, ?, ?, ?)",
                 (cid, p.id, p.id, now))
    if name == "general" and not private:
        _join_general(conn, now)
    audit(conn, p.id, "channel.create", f"channel:{cid}", {"name": name, "private": private}, now)
    return _channel_json(conn, conn.execute("SELECT * FROM channels WHERE id = ?", (cid,)).fetchone()), True


def archive_channel(conn, p: Principal, channel_id: int, now: float) -> dict:
    row = conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone()
    if row is None:
        raise not_found("channel not found")
    if not _may_manage_channel(conn, p, row):
        raise forbidden("only admins and the channel's creator can archive it")
    conn.execute("UPDATE channels SET archived = 1 WHERE id = ?", (channel_id,))
    audit(conn, p.id, "channel.archive", f"channel:{channel_id}", None, now)
    return _channel_json(conn, conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone())


def _may_manage_channel(conn, p: Principal, row) -> bool:
    return p.is_admin or (row["created_by"] == p.id and p.may_post)


def channel_info(conn, p: Principal, channel_id: int) -> dict:
    """Everything the channel info widget shows: who made it, counts, members and who posts."""
    row = channel_for(conn, p, channel_id)
    out = _channel_json(conn, row)
    vis = _visible_id_set(conn, p)
    count = lambda sql: conn.execute(sql, (channel_id,)).fetchone()[0]
    out.update({
        "created_by": _brief(conn, row["created_by"], vis),
        "messages": row["next_seq"] - 1,
        "threads": count("SELECT COUNT(DISTINCT thread_id) FROM messages WHERE channel_id = ? AND thread_id IS NOT NULL"),
        "files": count("SELECT COUNT(*) FROM attachments WHERE channel_id = ? AND published = 1"),
        "last_message_at": count("SELECT MAX(created_at) FROM messages WHERE channel_id = ?"),
        # public channels are open to everyone but guests; members are those added explicitly
        "audience": "everyone" if row["kind"] == "public" else "members",
        "members": [dict(_brief(conn, r[0], vis), added_at=r[1]) for r in conn.execute(
            "SELECT principal_id, added_at FROM channel_members WHERE channel_id = ? ORDER BY added_at", (channel_id,))],
        "posters": [dict(_brief(conn, r[0], vis), messages=r[1], last_at=r[2]) for r in conn.execute(
            """SELECT sender_id, COUNT(*), MAX(created_at) FROM messages WHERE channel_id = ?
               GROUP BY sender_id ORDER BY COUNT(*) DESC LIMIT 50""", (channel_id,))],
        "can_edit": row["kind"] != "dm" and _may_manage_channel(conn, p, row),
        "can_archive": row["kind"] != "dm" and _may_manage_channel(conn, p, row),
        "can_delete": row["kind"] != "dm" and p.is_admin,
    })
    return out


def update_channel(conn, p: Principal, channel_id: int, changes: Any, now: float) -> dict:
    """Rename, describe, archive or unarchive a channel (admins and the channel's creator)."""
    row = channel_for(conn, p, channel_id)
    if not isinstance(changes, dict) or not changes or set(changes) - {"name", "description", "archived"}:
        raise bad_request("supported fields: name, description, archived")
    if row["kind"] == "dm":
        raise bad_request("direct messages cannot be renamed or archived")
    if ("name" in changes or "description" in changes) and not _may_manage_channel(conn, p, row):
        raise forbidden("only admins and the channel's creator can rename it")
    if "archived" in changes and not _may_manage_channel(conn, p, row):
        raise forbidden("only admins and the channel's creator can archive it")
    if "name" in changes:
        name = changes["name"]
        if not isinstance(name, str) or not CHANNEL_NAME.match(name):
            raise bad_request("name must match " + CHANNEL_NAME.pattern)
        taken = conn.execute("SELECT id FROM channels WHERE name = ? AND id != ?", (name, channel_id)).fetchone()
        if taken:
            raise conflict("channel_exists", "a channel with this name already exists")
        conn.execute("UPDATE channels SET name = ? WHERE id = ?", (name, channel_id))
    if "description" in changes:
        d = changes["description"]
        if d is not None and (not isinstance(d, str) or len(d) > 1024):
            raise bad_request("description must be a string of at most 1024 characters")
        conn.execute("UPDATE channels SET description = ? WHERE id = ?", ((d or "").strip() or None, channel_id))
    if "archived" in changes:
        if not isinstance(changes["archived"], bool):
            raise bad_request("archived must be true or false")
        conn.execute("UPDATE channels SET archived = ? WHERE id = ?", (int(changes["archived"]), channel_id))
    audit(conn, p.id, "channel.update", f"channel:{channel_id}", {"before": {"name": row["name"]}, "changes": changes}, now)
    return channel_info(conn, p, channel_id)


def open_dm(conn, p: Principal, other_id, now: float) -> tuple[dict, bool]:
    """The direct-message channel between p and another identity (created on first use)."""
    if not p.may_post:
        raise forbidden("viewers cannot send direct messages")
    if not isinstance(other_id, int) or isinstance(other_id, bool) or other_id == p.id:
        raise bad_request("with must be the id of another identity")
    other = conn.execute("SELECT * FROM principals WHERE id = ?", (other_id,)).fetchone()
    if other is None:
        raise not_found("identity not found")
    _check_visible(conn, p, other_id)
    if other["disabled"]:
        raise conflict("identity_disabled", "this identity is disabled")
    a, b = sorted((p.id, other_id))
    name = f"dm:{a}:{b}"
    row = conn.execute("SELECT * FROM channels WHERE name = ?", (name,)).fetchone()
    if row is not None:
        return _channel_json(conn, row), False
    cid = conn.execute("INSERT INTO channels (name, created_by, created_at, kind) VALUES (?, ?, ?, 'dm')",
                       (name, p.id, now)).lastrowid
    conn.executemany("INSERT INTO channel_members (channel_id, principal_id, added_by, added_at) VALUES (?, ?, ?, ?)",
                     [(cid, a, p.id, now), (cid, b, p.id, now)])
    return _channel_json(conn, conn.execute("SELECT * FROM channels WHERE id = ?", (cid,)).fetchone()), True


def list_members(conn, p: Principal, channel_id: int) -> list[dict]:
    channel_for(conn, p, channel_id)
    rows = conn.execute("SELECT principal_id, added_by, added_at FROM channel_members WHERE channel_id = ? "
                        "ORDER BY added_at", (channel_id,)).fetchall()
    return [dict(_brief(conn, r[0]), added_by=r[1], added_at=r[2]) for r in rows]


def mention_candidates(conn, p: Principal, channel_id: int) -> list[dict]:
    """Channel members, plus people elsewhere who can read a non-DM channel."""
    ch = channel_for(conn, p, channel_id)
    allowed = _directory_ids(conn, p)
    members = {r[0] for r in conn.execute(
        "SELECT principal_id FROM channel_members WHERE channel_id = ?", (channel_id,))}
    out = []
    for row in conn.execute("SELECT * FROM principals WHERE disabled = 0"):
        if row["id"] == p.id or (allowed is not None and row["id"] not in allowed):
            continue
        member = row["id"] in members
        if not member and (ch["kind"] == "dm" or row["identity_type"] != "user"):
            continue
        if not can_see(conn, _principal_obj(row), ch):
            continue
        item = principal_json(conn, row)
        if not p.is_admin and row["owner_id"] != p.id:
            item.pop("hf_username")
        out.append(dict(item, member=member))
    return sorted(out, key=lambda x: (not x["member"], (x["display_name"] or x["external_id"]).lower(), x["id"]))


def _check_can_add_to(conn, p: Principal, channel_id: int):
    """The rule for adding someone to a channel (directly, or through an invite)."""
    ch = channel_for(conn, p, channel_id, "messages:write")
    if ch["kind"] == "dm":
        raise bad_request("direct messages always have exactly two people")
    if ch["kind"] == "private" and not (p.is_admin or _is_channel_member(conn, channel_id, p.id)):
        raise forbidden("only members of a private channel can add people to it")
    return ch


def add_member(conn, p: Principal, channel_id: int, target_id, now: float) -> list[dict]:
    _check_can_add_to(conn, p, channel_id)
    if not isinstance(target_id, int) or isinstance(target_id, bool):
        raise bad_request("principal_id must be an identity id")
    t = conn.execute("SELECT * FROM principals WHERE id = ?", (target_id,)).fetchone()
    if t is None:
        raise not_found("identity not found")
    _check_visible(conn, p, target_id)
    if p.role == "guest" and t["owner_id"] != p.id:
        raise forbidden("guests can only add their own agents to a channel")
    if t["disabled"]:
        raise conflict("identity_disabled", "this identity is disabled")
    conn.execute("INSERT OR IGNORE INTO channel_members (channel_id, principal_id, added_by, added_at) "
                 "VALUES (?, ?, ?, ?)", (channel_id, target_id, p.id, now))
    audit(conn, p.id, "channel.add_member", f"channel:{channel_id}", {"principal_id": target_id}, now)
    return list_members(conn, p, channel_id)


def remove_member(conn, p: Principal, channel_id: int, target_id: int, now: float) -> list[dict] | dict:
    ch = channel_for(conn, p, channel_id)
    if ch["kind"] == "dm":
        raise bad_request("you cannot leave a direct message")
    row = conn.execute("""SELECT cm.added_by, t.owner_id FROM channel_members cm JOIN principals t ON t.id = cm.principal_id
                          WHERE cm.channel_id = ? AND cm.principal_id = ?""", (channel_id, target_id)).fetchone()
    if row is None:
        raise not_found("not a member of this channel")
    if not (p.is_admin or p.id == target_id or row["added_by"] == p.id or row["owner_id"] == p.id):
        raise forbidden("you may not remove this member")
    conn.execute("DELETE FROM channel_members WHERE channel_id = ? AND principal_id = ?", (channel_id, target_id))
    t = _principal_row(conn, target_id)
    if t["identity_type"] == "user" and t["role"] == "guest":
        # a guest's agents see at most what the guest sees: they leave with their owner
        conn.execute("""DELETE FROM channel_members WHERE channel_id = ? AND principal_id IN
                        (SELECT id FROM principals WHERE owner_id = ?)""", (channel_id, target_id))
    audit(conn, p.id, "channel.remove_member", f"channel:{channel_id}", {"principal_id": target_id}, now)
    if p.id == target_id and not can_see(conn, p, ch):
        return {"left": True}
    return list_members(conn, p, channel_id)


# ----------------------------------------------------------------------- invites


INVITE_PUBLIC_FIELDS = ("id", "kind", "role", "identity_type", "can_create_channels", "max_uses", "uses",
                        "expires_at", "revoked_at", "label", "created_at", "agent_name", "agent_display",
                        "join_open_channels")


def _handle_from(display: str) -> str:
    """A handle from a display name: "Eval Runner 2" -> "eval-runner-2"."""
    return re.sub(r"[^a-z0-9._-]+", "-", display.lower()).strip("-._")[:64]


def _invite_status(row, now: float) -> str:
    if row["revoked_at"] is not None:
        return "revoked"
    if row["expires_at"] is not None and row["expires_at"] <= now:
        return "expired"
    if row["max_uses"] is not None and row["uses"] >= row["max_uses"]:
        return "used up"
    return "active"


def _invite_json(conn, row, now: float) -> dict:
    out = {k: row[k] for k in INVITE_PUBLIC_FIELDS}
    out["can_create_channels"] = bool(out["can_create_channels"])
    out["status"] = _invite_status(row, now)
    out["created_by"] = _brief(conn, row["created_by"])
    out["channels"] = _invite_channels(conn, row)
    out["joined"] = [dict(_brief(conn, r[0]), joined_at=r[1]) for r in conn.execute(
        "SELECT id, created_at FROM principals WHERE invite_id = ? ORDER BY created_at", (row["id"],))]
    return out


def _invite_channels(conn, row) -> list[dict]:
    ids = json.loads(row["channel_ids"]) if row["channel_ids"] else []
    out = []
    for cid in ids:
        ch = conn.execute("SELECT id, name, kind FROM channels WHERE id = ?", (cid,)).fetchone()
        if ch is not None:
            out.append({"id": ch["id"], "name": ch["name"], "kind": ch["kind"]})
    return out


def create_invite(conn, p: Principal, req: dict, now: float) -> dict:
    """An invite link. People invites (admins only) carry a role; agent invites
    (members and admins) make agents or service accounts owned by the inviter."""
    if not isinstance(req, dict):
        raise bad_request("request body must be a JSON object")
    kind = req.get("kind", "agent")
    max_uses, expires_in, label = req.get("max_uses"), req.get("expires_in_seconds"), req.get("label")
    if max_uses is not None and (not isinstance(max_uses, int) or isinstance(max_uses, bool) or max_uses < 1):
        raise bad_request("max_uses must be a positive integer, or null for unlimited")
    if expires_in is not None and (not isinstance(expires_in, (int, float)) or isinstance(expires_in, bool)
                                   or expires_in <= 0):
        raise bad_request("expires_in_seconds must be positive, or null for never")
    if label is not None and (not isinstance(label, str) or len(label) > 80):
        raise bad_request("label must be at most 80 characters")
    if kind == "human":
        if not p.is_admin:
            raise forbidden("only admins can invite people")
        role, identity_type, create = req.get("role", "member"), "user", False
        if role not in auth.HUMAN_ROLES:
            raise bad_request(f"role must be one of {list(auth.HUMAN_ROLES)}")
    elif kind == "agent":
        if not p.may_invite_agents:
            raise forbidden("only members and admins can invite agents")
        role = req.get("role", "member")
        identity_type = req.get("identity_type", "agent")
        create = req.get("can_create_channels", False)
        if role not in auth.AGENT_ROLES:
            raise bad_request(f"agent role must be one of {list(auth.AGENT_ROLES)}")
        if role in auth.ADMIN_ONLY_AGENT_ROLES and not p.is_admin:
            raise forbidden("only admins can invite admin or reader agents")
        if p.role == "guest" and (role != "guest" or req.get("join_open_channels")):
            raise forbidden("guests can only invite guest agents, into channels they are in themselves")
        if identity_type not in ("agent", "system"):
            raise bad_request("identity_type must be agent or system")
        if not isinstance(create, bool) or (create and role != "member"):
            raise bad_request("can_create_channels must be true or false, and only for member agents")
    else:
        raise bad_request("kind must be human or agent")
    agent_display = agent_name = None
    join_open = req.get("join_open_channels", False)
    if not isinstance(join_open, bool) or (join_open and kind != "agent"):
        raise bad_request("join_open_channels must be true or false, and only for agent invites")
    if kind == "agent" and (req.get("agent_name") or req.get("agent_handle")):
        # a named invite: the link makes exactly this agent (joining again re-keys it)
        agent_display = req.get("agent_name")
        if agent_display is not None and (not isinstance(agent_display, str) or not agent_display.strip() or len(agent_display) > 128):
            raise bad_request("agent_name must be 1 to 128 characters")
        agent_display = agent_display.strip() if agent_display else None
        agent_name = req.get("agent_handle") or _handle_from(agent_display or "")
        if not isinstance(agent_name, str) or not EXTERNAL_ID.match(agent_name):
            raise bad_request("agent_handle must be letters, digits, dots, dashes or underscores (it is made from agent_name if left out)")
    channels = req.get("channels") or []
    if not isinstance(channels, list) or len(channels) > 200:
        raise bad_request("channels must be a list of channel ids or names")
    channel_ids = []
    for ref in channels:
        if isinstance(ref, str):
            row = conn.execute("SELECT id FROM channels WHERE name = ?", (ref,)).fetchone()
            if row is None:
                raise not_found(f"channel {ref!r} not found")
            ref = row["id"]
        if not isinstance(ref, int) or isinstance(ref, bool):
            raise bad_request("channels must be a list of channel ids or names")
        _check_can_add_to(conn, p, ref)          # you can only hand out channels you could add someone to
        if ref not in channel_ids:
            channel_ids.append(ref)
    code = secrets.token_urlsafe(16)
    cur = conn.execute(
        """INSERT INTO invites (code_hash, created_by, created_at, kind, role, identity_type, can_create_channels,
                                max_uses, expires_at, label, channel_ids, agent_name, agent_display, join_open_channels)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
        (hashlib.sha256(code.encode()).digest(), p.id, now, kind, role, identity_type, int(create), max_uses,
         now + expires_in if expires_in else None, label, json.dumps(channel_ids) if channel_ids else None,
         agent_name, agent_display, int(join_open)))
    audit(conn, p.id, "invite.create", f"invite:{cur.lastrowid}", {"kind": kind, "role": role}, now)
    out = _invite_json(conn, conn.execute("SELECT * FROM invites WHERE id = ?", (cur.lastrowid,)).fetchone(), now)
    out["code"] = code
    return out


def list_invites(conn, p: Principal, now: float) -> list[dict]:
    if p.is_admin:
        rows = conn.execute("SELECT * FROM invites WHERE kind != 'signin' ORDER BY id DESC")
    elif p.may_invite_agents:
        rows = conn.execute("SELECT * FROM invites WHERE kind != 'signin' AND created_by = ? ORDER BY id DESC", (p.id,))
    else:
        raise forbidden("only members and admins have invites")
    return [_invite_json(conn, r, now) for r in rows]


def revoke_invite(conn, p: Principal, invite_id: int, now: float) -> dict:
    row = conn.execute("SELECT * FROM invites WHERE id = ?", (invite_id,)).fetchone()
    if row is None or row["kind"] == "signin" or not (p.is_admin or row["created_by"] == p.id):
        raise not_found("invite not found")
    if row["revoked_at"] is None:
        conn.execute("UPDATE invites SET revoked_at = ? WHERE id = ?", (now, invite_id))
        audit(conn, p.id, "invite.revoke", f"invite:{invite_id}", None, now)
    return _invite_json(conn, conn.execute("SELECT * FROM invites WHERE id = ?", (invite_id,)).fetchone(), now)


def create_signin_link(conn, p: Principal, target_id: int, now: float) -> dict:
    """A one-time, 15-minute code that signs a person in on another device."""
    t = _principal_row(conn, target_id)
    if t["identity_type"] != "user":
        raise bad_request("sign-in links are for people; agents get tokens")
    if not (p.id == target_id or p.is_admin):
        raise forbidden("only admins can make sign-in links for someone else")
    code = secrets.token_urlsafe(16)
    conn.execute("""INSERT INTO invites (code_hash, created_by, created_at, kind, role, identity_type, max_uses,
                                         expires_at, target_id)
                    VALUES (?, ?, ?, 'signin', ?, 'user', 1, ?, ?)""",
                 (hashlib.sha256(code.encode()).digest(), p.id, now, t["role"], now + 900, target_id))
    audit(conn, p.id, "signin.link", f"principal:{target_id}", None, now)
    return {"code": code, "expires_at": now + 900}


def _find_invite(conn, code) -> sqlite3.Row | None:
    if not isinstance(code, str) or not 8 <= len(code) <= 64:
        return None
    return conn.execute("SELECT * FROM invites WHERE code_hash = ?", (hashlib.sha256(code.encode()).digest(),)).fetchone()


def lookup_invite(conn, code: str, now: float) -> dict:
    """What a code is for, shown on the join page before anyone signs in."""
    row = _find_invite(conn, code)
    if row is None:
        raise not_found("this invite link is not valid")
    inviter = _brief(conn, row["created_by"])
    out = {"kind": row["kind"], "role": row["role"], "identity_type": row["identity_type"],
           "can_create_channels": bool(row["can_create_channels"]), "status": _invite_status(row, now),
           "invited_by": inviter["display_name"] or inviter["external_id"] if inviter else None}
    if row["kind"] == "signin":
        out["name"] = (_brief(conn, row["target_id"]) or {}).get("display_name")
    else:
        out["channels"] = [c["name"] for c in _invite_channels(conn, row)]
        if row["agent_name"]:
            out["agent_name"], out["agent_display"] = row["agent_name"], row["agent_display"]
        out["join_open_channels"] = bool(row["join_open_channels"])
    return out


def _join_channels(conn, invite, principal_id: int, now: float) -> None:
    chans = _invite_channels(conn, invite)
    if invite["join_open_channels"]:   # every public, non-archived channel at the time of joining
        chans += [dict(r) for r in conn.execute("SELECT * FROM channels WHERE kind = 'public' AND archived = 0")]
    for ch in chans:
        if ch["kind"] != "dm":
            conn.execute("INSERT OR IGNORE INTO channel_members (channel_id, principal_id, added_by, added_at) "
                         "VALUES (?, ?, ?, ?)", (ch["id"], principal_id, invite["created_by"], now))


def _human_owner(conn, row):
    """The person at the top of an ownership chain: the row itself for a person, else its owner's owner, and so on.
    A chain that loops or ends without a person is refused rather than answered with an agent."""
    seen = set()
    while row["identity_type"] != "user":
        if row["owner_id"] is None or row["id"] in seen:
            raise ApiError(410, "invite_inactive", "no person owns the agent that made this invite")
        seen.add(row["id"])
        row = _principal_row(conn, row["owner_id"])
    return row


def join(conn, code, name, display_name, now: float) -> dict:
    """Redeem an invite (or a sign-in link). Returns the identity and its token."""
    row = _find_invite(conn, code)
    if row is None:
        raise not_found("this invite link is not valid")
    status = _invite_status(row, now)
    if status != "active":
        raise ApiError(410, "invite_inactive", f"this invite link is {status}")
    if display_name is not None and (not isinstance(display_name, str) or not display_name.strip()
                                     or len(display_name) > 128):
        raise bad_request("display_name must be 1 to 128 characters")
    display_name = display_name.strip() if display_name else None

    if row["kind"] == "signin":
        t = _principal_row(conn, row["target_id"])
        if t["disabled"]:
            raise forbidden("this account is disabled")
        conn.execute("UPDATE invites SET uses = uses + 1 WHERE id = ?", (row["id"],))
        _, token = _new_credential(conn, t["id"], row["created_by"], now, replace=False)
        return {"token": token, "principal": principal_json(conn, t), "created": False, "next": JOIN_NEXT}

    inviter = _principal_row(conn, row["created_by"])
    if inviter["disabled"]:
        raise ApiError(410, "invite_inactive", "the person who made this invite is no longer active")

    if row["kind"] == "human":
        if not isinstance(name, str) or not PERSON_NAME.match(name):
            raise bad_request("name must be 1 to 64 letters, digits, dots, dashes or underscores")
        if conn.execute("SELECT 1 FROM principals WHERE identity_type = 'user' AND lower(external_id) = lower(?)",
                        (name,)).fetchone():
            raise conflict("name_taken", "this name is taken; pick another")
        pid = conn.execute(
            """INSERT INTO principals (issuer, external_id, identity_type, role, display_name, created_at, created_by,
                                       joined_via, invite_id)
               VALUES (?, ?, 'user', ?, ?, ?, ?, 'invite', ?)""",
            (PEOPLE, name, row["role"], display_name, now, inviter["id"], row["id"])).lastrowid
        conn.execute("UPDATE invites SET uses = uses + 1 WHERE id = ?", (row["id"],))
        _join_channels(conn, row, pid, now)
        _join_general(conn, now, pid)
        _, token = _new_credential(conn, pid, inviter["id"], now)
        audit(conn, pid, "join.human", f"principal:{pid}", {"invite": row["id"], "role": row["role"]}, now)
        return {"token": token, "principal": principal_json(conn, _principal_row(conn, pid)), "created": True, "next": JOIN_NEXT}

    # Agent or service account. It is owned by a person: the inviter, or, when an agent made the invite,
    # the person who owns that agent. The inviting agent stays on record as created_by.
    needed = auth.owner_roles_for(row["role"])
    if inviter["role"] not in needed:
        raise ApiError(410, "invite_inactive", "the person who made this invite can no longer give out this access")
    owner = _human_owner(conn, inviter)
    if owner["disabled"] or owner["role"] not in needed:
        raise ApiError(410, "invite_inactive", "the person who owns the agent that made this invite can no longer give out this access")
    if row["agent_name"]:   # a named invite decides the name; the agent need not (and may not) pick another
        if name not in (None, "", row["agent_name"]):
            raise bad_request(f"this invite is for the agent {row['agent_name']!r}: leave name out or use that one")
        name, display_name = row["agent_name"], row["agent_display"] or display_name
    if not isinstance(name, str) or not EXTERNAL_ID.match(name):
        raise bad_request("name must match " + EXTERNAL_ID.pattern)
    issuer = f"owner:{inviter['id']}"
    existing = conn.execute("SELECT * FROM principals WHERE issuer = ? AND external_id = ?", (issuer, name)).fetchone()
    if existing is not None:
        # The same program starting again: same identity, fresh token (the old one stops working).
        if existing["disabled"]:
            raise conflict("identity_disabled", "this agent was removed by its owner")
        _join_channels(conn, row, existing["id"], now)
        _, token = _new_credential(conn, existing["id"], inviter["id"], now)
        audit(conn, existing["id"], "join.again", f"principal:{existing['id']}", {"invite": row["id"]}, now)
        return {"token": token, "principal": principal_json(conn, existing), "created": False, "next": JOIN_NEXT}
    pid = conn.execute(
        """INSERT INTO principals (issuer, external_id, identity_type, role, display_name, created_at, created_by,
                                   joined_via, owner_id, can_create_channels, invite_id)
           VALUES (?, ?, ?, ?, ?, ?, ?, 'invite', ?, ?, ?)""",
        (issuer, name, row["identity_type"], row["role"], display_name, now, inviter["id"], owner["id"],
         row["can_create_channels"], row["id"])).lastrowid
    conn.execute("UPDATE invites SET uses = uses + 1 WHERE id = ?", (row["id"],))
    _join_channels(conn, row, pid, now)
    _, token = _new_credential(conn, pid, inviter["id"], now)
    audit(conn, pid, "join.agent", f"principal:{pid}", {"invite": row["id"], "role": row["role"]}, now)
    return {"token": token, "principal": principal_json(conn, _principal_row(conn, pid)), "created": True, "next": JOIN_NEXT}


JOIN_NEXT = ("Keep this token secret and send it as `Authorization: Bearer <token>`. "
             "Before doing anything else, read GET /v1/guide (how this board works and its rules) and follow it.")


# ---------------------------------------------------------------------- messages

MESSAGE_SELECT = """
SELECT m.*, p.external_id AS s_external_id, p.identity_type AS s_identity_type,
       p.display_name AS s_display_name, p.role AS s_role, substr(av.sha256, 1, 12) AS s_avatar,
       p.pattern_seed AS s_pattern, p.disabled AS s_disabled, p.suspended_at AS s_suspended_at,
       p.joined_via AS s_joined_via
FROM messages m JOIN principals p ON p.id = m.sender_id
LEFT JOIN avatars av ON av.principal_id = m.sender_id
"""


def _message_json(row) -> dict:
    return {
        "id": row["id"],
        "channel_id": row["channel_id"],
        "seq": row["seq"],
        "sender": {
            "id": row["sender_id"],
            "external_id": row["s_external_id"],
            "identity_type": row["s_identity_type"],
            "display_name": row["s_display_name"],
            "avatar": row["s_avatar"],
            "pattern": row["s_pattern"],
            "role": row["s_role"],
            "disabled": bool(row["s_disabled"]),
            "suspended": row["s_suspended_at"] is not None,
            "imported": row["s_joined_via"] == "import",
        },
        "body": row["body"],
        "reply_to": row["reply_to"],
        "thread_id": row["thread_id"],
        "attachments": json.loads(row["attachments"]) if row["attachments"] else [],
        "request_id": row["request_id"],
        "created_at": row["created_at"],
        "edited_at": row["edited_at"],
        "history": bool(row["imported"]),
        "imported_from": json.loads(row["import_source"]) if row["import_source"] else None,
        "pinned": None,   # filled in by _attach_pins where messages are read
    }


def _attach_pins(conn, messages: list[dict], viewer: Principal | None = None) -> None:
    """`pinned`: when and by whom each message was pinned in its channel, or None."""
    if not messages:
        return
    ids = [m["id"] for m in messages]
    vis = _visible_id_set(conn, viewer)
    pins = {r[0]: r for r in conn.execute(f"""
            SELECT mp.message_id, mp.pinned_at, mp.pinned_by, p.external_id, p.display_name, p.identity_type,
                   p.disabled, p.suspended_at, p.joined_via
            FROM message_pins mp LEFT JOIN principals p ON p.id = mp.pinned_by
            WHERE mp.message_id IN ({",".join("?" * len(ids))})""", ids)}
    for m in messages:
        r = pins.get(m["id"])
        m["pinned"] = None if r is None else {"at": r[1], "by": None if r[2] is None else
                                              {"id": r[2], "external_id": r[3], "display_name": r[4], "identity_type": r[5],
                                               **_status_flags(r[6], r[7], r[8], r[2], vis)}}


def normalize_payload(channel_id: int, payload: Any) -> tuple[dict, str]:
    if not isinstance(payload, dict):
        raise bad_request("request body must be a JSON object")
    unknown = set(payload) - {"body", "reply_to", "attachments"}
    if unknown:
        raise bad_request(f"unknown fields: {sorted(unknown)}")
    body = payload.get("body")
    reply_to = payload.get("reply_to")
    attachments = payload.get("attachments") or []
    if not isinstance(body, str):
        raise bad_request("body must be a string")
    if len(body.encode()) > LIMITS.max_body_bytes:
        raise ApiError(413, "too_large", f"body exceeds {LIMITS.max_body_bytes} bytes")
    if reply_to is not None and (not isinstance(reply_to, int) or isinstance(reply_to, bool)):
        raise bad_request("reply_to must be a message id")
    if (not isinstance(attachments, list) or not all(isinstance(a, str) for a in attachments)
            or len(attachments) > LIMITS.max_attachments_per_message):
        raise bad_request(f"attachments must be a list of at most {LIMITS.max_attachments_per_message} ids")
    normalized = {
        "channel_id": channel_id,
        "body": body,
        "reply_to": reply_to,
        "attachments": list(dict.fromkeys(attachments)),   # keep the order they were attached in
    }
    # The fingerprint sorts attachments (order does not make a different message) and keeps
    # "metadata": None so it matches messages stored before that field was removed.
    fingerprint = dict(normalized, attachments=sorted(normalized["attachments"]), metadata=None)
    digest = hashlib.sha256(json.dumps(fingerprint, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
    return normalized, digest


def _unhide_dm_for_members(conn, channel_id: int, sender_id: int, thread_id: int | None, message_id: int):
    rows = conn.execute(
        """SELECT p.id, p.prefs FROM principals p
           JOIN channel_members cm ON cm.principal_id = p.id
           WHERE cm.channel_id = ? AND p.prefs IS NOT NULL""",
        (channel_id,),
    ).fetchall()
    unsubscribed: set[int] = set()
    mentioned: set[int] = set()
    if thread_id is not None and rows:
        unsubscribed = {r[0] for r in conn.execute(
            "SELECT principal_id FROM thread_subscriptions WHERE thread_id = ? AND subscribed = 0",
            (thread_id,))}
        if unsubscribed:
            mentioned = {r[0] for r in conn.execute(
                "SELECT principal_id FROM message_mentions WHERE message_id = ?", (message_id,))}
    for row in rows:
        if thread_id is not None and row["id"] != sender_id and row["id"] in unsubscribed and row["id"] not in mentioned:
            continue
        prefs = json.loads(row["prefs"])
        hidden = prefs.get("hidden_dms")
        if isinstance(hidden, list) and channel_id in hidden:
            remaining = [cid for cid in hidden if cid != channel_id]
            if remaining:
                prefs["hidden_dms"] = remaining
            else:
                prefs.pop("hidden_dms", None)
            conn.execute("UPDATE principals SET prefs = ? WHERE id = ?",
                         (json.dumps(prefs) if prefs else None, row["id"]))


def post_message(conn, p: Principal, channel_id: int, request_id: str, normalized: dict,
                 payload_hash: str, now: float) -> tuple[dict, bool]:
    channel = channel_for(conn, p, channel_id, "messages:write")
    prior = conn.execute(
        MESSAGE_SELECT + " WHERE m.sender_id = ? AND m.request_id = ?", (p.id, request_id)
    ).fetchone()
    if prior is not None:
        if prior["payload_hash"] != payload_hash:
            raise conflict("idempotency_conflict", "this Idempotency-Key was already used with different content")
        out = _message_json(prior)
        _attach_mentions(conn, [out], p)
        _attach_reactions(conn, [out], p.id, p)
        return out, False
    if channel["archived"]:
        raise conflict("channel_archived", "channel is archived")
    thread_id = None
    if normalized["reply_to"] is not None:
        parent = conn.execute("SELECT channel_id, thread_id FROM messages WHERE id = ?",
                              (normalized["reply_to"],)).fetchone()
        if parent is None or parent["channel_id"] != channel_id:
            raise bad_request("reply_to must reference a message in the same channel")
        thread_id = parent["thread_id"] or normalized["reply_to"]  # a reply joins its parent's thread
    for att_id in normalized["attachments"]:
        att = conn.execute("SELECT * FROM attachments WHERE id = ?", (att_id,)).fetchone()
        if (att is None or att["channel_id"] != channel_id or att["state"] != "ready"
                or (att["uploader_id"] != p.id and not att["published"])):
            raise bad_request(f"attachment {att_id} is not a ready upload in this channel")
    seq = channel["next_seq"]
    cur = conn.execute(
        """INSERT INTO messages (channel_id, seq, sender_id, body, reply_to, attachments,
                                 request_id, payload_hash, created_at, thread_id)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
        (
            channel_id, seq, p.id, normalized["body"],
            normalized["reply_to"],
            json.dumps(normalized["attachments"]) if normalized["attachments"] else None,
            request_id, payload_hash, now, thread_id,
        ),
    )
    conn.execute("UPDATE channels SET next_seq = ? WHERE id = ?", (seq + 1, channel_id))
    if normalized["attachments"]:
        marks = ",".join("?" * len(normalized["attachments"]))
        conn.execute(f"UPDATE attachments SET published = 1 WHERE id IN ({marks})", normalized["attachments"])
    # Posting joins only the author, after all permission/payload checks, in this transaction.
    # A replay returned above must not undo a later choice to leave the channel or hide a DM.
    if channel["kind"] != "dm":
        joined = conn.execute(
            "INSERT OR IGNORE INTO channel_members (channel_id, principal_id, added_by, added_at) VALUES (?, ?, ?, ?)",
            (channel_id, p.id, p.id, now))
        if joined.rowcount:
            audit(conn, p.id, "channel.add_member", f"channel:{channel_id}", {"principal_id": p.id}, now)
    _record_mentions(conn, channel, cur.lastrowid, normalized["body"], p.id)
    if channel["kind"] == "dm":
        _unhide_dm_for_members(conn, channel_id, p.id, thread_id, cur.lastrowid)
    row = conn.execute(MESSAGE_SELECT + " WHERE m.id = ?", (cur.lastrowid,)).fetchone()
    out = _message_json(row)
    _attach_mentions(conn, [out], p)
    _attach_reactions(conn, [out], p.id, p)
    return out, True


def edit_message(conn, p: Principal, channel_id: int, message_id: int, payload: Any, now: float) -> tuple[dict, bool]:
    """Replace the body of your own message (people only). Mentions are worked out again from the new text."""
    if not isinstance(payload, dict) or set(payload) != {"body"} or not isinstance(payload["body"], str):
        raise bad_request('request body must be {"body": "..."}')
    body = payload["body"]
    if len(body.encode()) > LIMITS.max_body_bytes:
        raise ApiError(413, "too_large", f"body exceeds {LIMITS.max_body_bytes} bytes")
    channel = channel_for(conn, p, channel_id, "messages:write")
    row = conn.execute(MESSAGE_SELECT + " WHERE m.id = ? AND m.channel_id = ?", (message_id, channel_id)).fetchone()
    if row is None:
        raise not_found("no such message in this channel")
    if row["sender_id"] != p.id:
        raise forbidden("you can only edit your own messages")
    if not p.is_human:   # agent output stays exactly as written; corrections go in a follow-up message
        raise forbidden("agents cannot edit messages: post a follow-up (reply in the thread) instead")
    if channel["archived"]:
        raise conflict("channel_archived", "channel is archived")
    if not body.strip() and not row["attachments"]:
        raise bad_request("body must not be empty")
    changed = body != row["body"]
    if changed:
        rev = channel["edit_rev"] + 1
        conn.execute("UPDATE channels SET edit_rev = ? WHERE id = ?", (rev, channel_id))
        version = conn.execute("SELECT COUNT(*) FROM message_revisions WHERE message_id = ?", (message_id,)).fetchone()[0] + 1
        conn.execute("INSERT INTO message_revisions (message_id, version, body, written_at, replaced_at) VALUES (?, ?, ?, ?, ?)",
                     (message_id, version, row["body"], row["edited_at"] or row["created_at"], now))
        conn.execute("UPDATE messages SET body = ?, edited_at = ?, edit_rev = ? WHERE id = ?", (body, now, rev, message_id))
        conn.execute("DELETE FROM message_mentions WHERE message_id = ?", (message_id,))
        if not row["imported"]:
            _record_mentions(conn, channel, message_id, body, p.id)
        audit(conn, p.id, "message.edit", f"message:{message_id}", {"version": version + 1}, now)
        row = conn.execute(MESSAGE_SELECT + " WHERE m.id = ?", (message_id,)).fetchone()
    out = _message_json(row)
    _attach_mentions(conn, [out], p)
    _attach_reactions(conn, [out], p.id, p)
    _attach_pins(conn, [out], p)
    return out, changed


def message_revisions(conn, p: Principal, channel_id: int, message_id: int) -> dict:
    """Every version of a message, oldest first; the last one is the current body."""
    channel_for(conn, p, channel_id, "messages:read")
    row = conn.execute("SELECT * FROM messages WHERE id = ? AND channel_id = ?", (message_id, channel_id)).fetchone()
    if row is None:
        raise not_found("no such message in this channel")
    versions = [{"version": r["version"], "body": r["body"], "written_at": r["written_at"], "replaced_at": r["replaced_at"]}
                for r in conn.execute("SELECT * FROM message_revisions WHERE message_id = ? ORDER BY version", (message_id,))]
    versions.append({"version": len(versions) + 1, "body": row["body"], "written_at": row["edited_at"] or row["created_at"],
                     "replaced_at": None})
    return {"message_id": message_id, "versions": versions}


def read_edits(conn, p: Principal, channel_id: int, after_rev: int, limit: int) -> dict:
    """Messages edited since edit cursor `after_rev`, oldest edit first (each message once, in its latest form)."""
    channel = channel_for(conn, p, channel_id, "messages:read")
    rows = conn.execute(MESSAGE_SELECT + " WHERE m.channel_id = ? AND m.edit_rev > ? ORDER BY m.edit_rev LIMIT ?",
                        (channel_id, after_rev, limit)).fetchall()
    edits = [_message_json(r) for r in rows]
    _attach_thread_summaries(conn, edits, p)
    _attach_mentions(conn, edits, p)
    _attach_reactions(conn, edits, p.id, p)
    _attach_pins(conn, edits, p)
    cursor = rows[-1]["edit_rev"] if len(rows) == limit else channel["edit_rev"]   # a full page may have more
    return {"edits": edits, "edit_cursor": max(cursor, after_rev)}


def read_messages(conn, p: Principal, channel_id: int, after: int, limit: int, before: int | None = None,
                  top_level: bool = False, thread: int | None = None) -> dict:
    """A page of history in seq order.

    after:     messages with seq > after (the default; `next_cursor` continues it).
    before:    instead, the newest `limit` messages with seq < before (for scrolling back).
    top_level: only messages that start a thread or stand alone (replies are left out).
    thread:    only the thread started by this message id (the message itself plus replies).
    Messages that have replies carry a `replies` summary.
    """
    channel_for(conn, p, channel_id, "messages:read")
    where, args = ["m.channel_id = ?"], [channel_id]
    if thread is not None:
        # through the thread index (~20x cheaper than scanning the channel for the thread's messages)
        where = ["+m.channel_id = ?", "m.id IN (SELECT ? UNION ALL SELECT id FROM messages WHERE thread_id = ?)"]
        args += [thread, thread]
    if top_level:
        where.append("m.thread_id IS NULL")
    if before is not None:
        where.append("m.seq < ?")
        args.append(before)
        order = "DESC"
    else:
        where.append("m.seq > ?")
        args.append(after)
        order = "ASC"
    rows = conn.execute(
        MESSAGE_SELECT + " WHERE " + " AND ".join(where) + f" ORDER BY m.seq {order} LIMIT ?",
        (*args, limit + 1),
    ).fetchall()
    messages, size = [], 0
    for row in rows[:limit]:
        size += len(row["body"].encode()) + 256
        if messages and size > LIMITS.max_page_bytes:
            break
        messages.append(_message_json(row))
    has_more = len(messages) < len(rows)
    if before is not None:
        messages.reverse()
    _attach_thread_summaries(conn, messages, p)
    _attach_mentions(conn, messages, p)
    _attach_reactions(conn, messages, p.id, p)
    _attach_pins(conn, messages, p)
    if before is not None:
        cursor = messages[-1]["seq"] if messages else before - 1
    else:
        cursor = messages[-1]["seq"] if messages else after
    return {"messages": messages, "next_cursor": cursor, "has_more": has_more}


def _attach_thread_summaries(conn, messages: list[dict], viewer: Principal | None = None) -> None:
    if viewer is not None:
        _attach_thread_subscriptions(conn, messages, viewer)
    roots = [m["id"] for m in messages if m["thread_id"] is None]
    if not roots:
        return
    marks = ",".join("?" * len(roots))
    counts = {r[0]: (r[1], r[2]) for r in conn.execute(
        f"""SELECT thread_id, COUNT(*), MAX(created_at) FROM messages
            WHERE thread_id IN ({marks}) GROUP BY thread_id""", roots)}
    if not counts:
        return
    people: dict[int, list[dict]] = {}
    for r in conn.execute(
        f"""SELECT m.thread_id, p.id, p.external_id, p.display_name, p.identity_type, MAX(m.seq) AS last,
                   substr(av.sha256, 1, 12), p.pattern_seed, p.role, p.disabled, p.suspended_at, p.joined_via
            FROM messages m JOIN principals p ON p.id = m.sender_id
            LEFT JOIN avatars av ON av.principal_id = p.id
            WHERE m.thread_id IN ({marks}) GROUP BY m.thread_id, p.id ORDER BY last DESC""", roots):
        people.setdefault(r[0], []).append(
            {"id": r[1], "external_id": r[2], "display_name": r[3], "identity_type": r[4], "avatar": r[6],
             "pattern": r[7], "role": r[8], "disabled": bool(r[9]), "suspended": r[10] is not None,
             "imported": r[11] == "import"})
    for_me = _threads_for_me(conn, viewer, roots, messages) if viewer is not None else {}
    for m in messages:
        if m["id"] in counts:
            n, last = counts[m["id"]]
            m["replies"] = {"count": n, "last_at": last, "participants": people.get(m["id"], [])[:5],
                            "for_me_unread": for_me.get(m["id"], 0)}


def _threads_for_me(conn, p: Principal, roots: list[int], messages: list[dict]) -> dict[int, int]:
    """Per thread: replies for me (mentions, replies in a thread I am in, DMs) that I have not read in the thread."""
    out: dict[int, int] = {}
    by_channel: dict[int, list[int]] = {}
    for m in messages:
        if m["id"] in roots:
            by_channel.setdefault(m["channel_id"], []).append(m["id"])
    for cid, ids in by_channel.items():
        ch = conn.execute("SELECT * FROM channels WHERE id = ?", (cid,)).fetchone()
        row = conn.execute("SELECT thread_floor FROM channel_reads WHERE principal_id = ? AND channel_id = ?", (p.id, cid)).fetchone()
        params = {"me": p.id, "floor": row[0] if row else 0, "has_row": 1 if row else 0, "baseline": _reads_baseline(conn, p),
                  "dm": 1 if ch["kind"] == "dm" and _is_channel_member(conn, cid, p.id) else 0}
        marks = ",".join(str(int(i)) for i in ids)
        for tid, n in conn.execute(f"""
                SELECT m.thread_id, COUNT(*) FROM messages m
                LEFT JOIN message_mentions mm ON mm.message_id = m.id AND mm.principal_id = :me
                LEFT JOIN thread_reads tr ON tr.principal_id = :me AND tr.thread_id = m.thread_id
                WHERE m.imported = 0 AND m.thread_id IN ({marks}) AND m.sender_id != :me AND {FOR_ME} AND {THREAD_UNREAD}
                  AND (:has_row = 1 OR m.created_at > :baseline)
                GROUP BY m.thread_id""", params):
            out[tid] = n
    return out


# ------------------------------------------------------------------- attachments


def _attachment_json(row) -> dict:
    return {
        "id": row["id"],
        "channel_id": row["channel_id"],
        "upload_id": row["upload_id"],
        "filename": row["filename"],
        "content_type": row["content_type"],
        "size": row["size"],
        "sha256": row["sha256"],
        "state": row["state"],
        "published": bool(row["published"]),
    }


def begin_upload(conn, p: Principal, channel_id: int, upload_id: str, filename, content_type, now: float) -> dict:
    channel = channel_for(conn, p, channel_id, "attachments:write")
    if not CLIENT_ID.match(upload_id):
        raise bad_request("upload_id must match " + CLIENT_ID.pattern)
    row = conn.execute(
        "SELECT * FROM attachments WHERE uploader_id = ? AND upload_id = ?", (p.id, upload_id)
    ).fetchone()
    if row is not None:
        if row["channel_id"] != channel_id:
            raise conflict("upload_conflict", "upload_id already used for another channel")
        return dict(row)
    if channel["archived"]:
        raise conflict("channel_archived", "channel is archived")
    att_id = "att_" + secrets.token_hex(12)
    conn.execute(
        """INSERT INTO attachments (id, channel_id, uploader_id, upload_id, storage_key, filename,
                                    content_type, state, created_at)
           VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)""",
        (att_id, channel_id, p.id, upload_id, f"{att_id[4:6]}/{att_id}", filename, content_type, now),
    )
    return dict(conn.execute("SELECT * FROM attachments WHERE id = ?", (att_id,)).fetchone())


def finish_upload(conn, att_id: str, size: int, sha256: str) -> dict:
    row = conn.execute("SELECT * FROM attachments WHERE id = ?", (att_id,)).fetchone()
    if row["state"] == "ready":
        if row["sha256"] != sha256:
            raise conflict("upload_conflict", "upload_id already holds different content")
        return _attachment_json(row)
    conn.execute("UPDATE attachments SET state = 'ready', size = ?, sha256 = ? WHERE id = ?", (size, sha256, att_id))
    return _attachment_json(conn.execute("SELECT * FROM attachments WHERE id = ?", (att_id,)).fetchone())


def attachment_state(conn, att_id: str) -> sqlite3.Row:
    return conn.execute("SELECT * FROM attachments WHERE id = ?", (att_id,)).fetchone()


def get_attachment(conn, p: Principal, att_id: str) -> dict:
    row = conn.execute("SELECT * FROM attachments WHERE id = ?", (att_id,)).fetchone()
    if row is None or row["state"] != "ready":
        raise not_found("attachment not found")
    if row["uploader_id"] == p.id or p.is_admin:
        pass
    else:
        ch = conn.execute("SELECT * FROM channels WHERE id = ?", (row["channel_id"],)).fetchone()
        if not (row["published"] and can_see(conn, p, ch)):
            raise not_found("attachment not found")
    out = _attachment_json(row)
    out["storage_key"] = row["storage_key"]
    return out


# ---------------------------------------------------------------------- profiles


def profile(conn, viewer: Principal, target_id: int, now: float, days: int = 30) -> dict:
    """Who someone is and what they wrote, counted only in channels the viewer can see."""
    row = _principal_row(conn, target_id)
    _check_visible(conn, viewer, target_id)
    readable = visible_channel_ids(conn, viewer)
    if readable is None:
        scope, args = "", []
    elif readable:
        scope, args = f" AND m.channel_id IN ({','.join('?' * len(readable))})", readable
    else:
        scope, args = " AND 0", []
    stats = conn.execute(
        f"SELECT COUNT(*), MIN(created_at), MAX(created_at) FROM messages m WHERE sender_id = ?{scope}",
        (target_id, *args)).fetchone()
    per_channel = [
        {"channel_id": r[0], "name": r[1], "kind": r[2], "count": r[3]}
        for r in conn.execute(
            f"""SELECT c.id, c.name, c.kind, COUNT(*) FROM messages m JOIN channels c ON c.id = m.channel_id
                WHERE m.sender_id = ?{scope} GROUP BY c.id ORDER BY COUNT(*) DESC, c.name""",
            (target_id, *args))]
    start_day = int(now // 86400) - (days - 1)
    by_day = dict(conn.execute(
        f"""SELECT CAST(created_at / 86400 AS INTEGER) AS d, COUNT(*) FROM messages m
            WHERE sender_id = ? AND created_at >= ?{scope} GROUP BY d""",
        (target_id, start_day * 86400, *args)).fetchall())
    invite = None
    if row["invite_id"] is not None:
        inv = conn.execute("SELECT label, kind FROM invites WHERE id = ?", (row["invite_id"],)).fetchone()
        invite = {"label": inv["label"], "kind": inv["kind"]} if inv else None
    vis = _visible_id_set(conn, viewer)
    out = principal_json(conn, row, vis)
    if not viewer.is_admin and viewer.id != target_id and row["owner_id"] != viewer.id:
        out.pop("hf_username")
    out.update({
        "created_by": _brief(conn, row["created_by"], vis),
        "joined_via": row["joined_via"],
        "invite": invite,
        "agents": [_brief(conn, r[0], vis) for r in conn.execute(
            "SELECT id FROM principals WHERE owner_id = ? AND disabled = 0 ORDER BY id", (target_id,))],
        "messages": {"count": stats[0], "first_at": stats[1], "last_at": stats[2]},
        "per_channel": per_channel,
        "daily": [{"day": (start_day + i) * 86400, "count": by_day.get(start_day + i, 0)} for i in range(days)],
    })
    if viewer.is_admin and row["suspended_at"] is not None:
        out["suspension"] = {"at": row["suspended_at"], "by": _brief(conn, row["suspended_by"]),
                             "reason": row["suspend_reason"], "via": _brief(conn, row["suspended_via"])}
    return out


# ----------------------------------------------------------------------- avatars

# Raster formats only, recognised by their first bytes. SVG is refused: it can carry script.
_IMAGE_MAGIC = [
    (b"\x89PNG\r\n\x1a\n", "image/png"),
    (b"\xff\xd8\xff", "image/jpeg"),
    (b"GIF87a", "image/gif"),
    (b"GIF89a", "image/gif"),
]


def _sniff_image(data: bytes) -> str | None:
    for magic, ctype in _IMAGE_MAGIC:
        if data.startswith(magic):
            return ctype
    if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
        return "image/webp"
    return None


def _avatar_version(conn, principal_id: int) -> str | None:
    row = conn.execute("SELECT substr(sha256, 1, 12) FROM avatars WHERE principal_id = ?", (principal_id,)).fetchone()
    return row[0] if row else None


def _may_edit_avatar(conn, actor: Principal, target_id: int) -> None:
    if conn.execute("SELECT 1 FROM principals WHERE id = ?", (target_id,)).fetchone() is None:
        raise not_found("identity not found")
    if actor.id != target_id and not actor.is_admin:
        raise forbidden("you can only change your own picture")


def set_avatar(conn, actor: Principal, target_id: int, data: bytes, now: float) -> dict:
    _may_edit_avatar(conn, actor, target_id)
    if len(data) > LIMITS.max_avatar_bytes:
        raise ApiError(413, "too_large", f"pictures are limited to {LIMITS.max_avatar_bytes // 1024} KB")
    ctype = _sniff_image(data)
    if ctype is None:
        raise bad_request("picture must be a PNG, JPEG, GIF or WebP image")
    digest = hashlib.sha256(data).hexdigest()
    conn.execute(
        """INSERT INTO avatars (principal_id, content_type, data, sha256, updated_at) VALUES (?, ?, ?, ?, ?)
           ON CONFLICT (principal_id) DO UPDATE SET content_type = excluded.content_type, data = excluded.data,
               sha256 = excluded.sha256, updated_at = excluded.updated_at""",
        (target_id, ctype, data, digest, now))
    if actor.id != target_id:
        audit(conn, actor.id, "avatar.set", f"principal:{target_id}", None, now)
    return {"avatar": digest[:12], "content_type": ctype, "size": len(data)}


def delete_avatar(conn, actor: Principal, target_id: int, now: float) -> dict:
    _may_edit_avatar(conn, actor, target_id)
    conn.execute("DELETE FROM avatars WHERE principal_id = ?", (target_id,))
    if actor.id != target_id:
        audit(conn, actor.id, "avatar.delete", f"principal:{target_id}", None, now)
    return {"avatar": None}


def get_avatar(conn, target_id: int) -> tuple[str, bytes, str]:
    row = conn.execute("SELECT content_type, data, sha256 FROM avatars WHERE principal_id = ?",
                       (target_id,)).fetchone()
    if row is None:
        raise not_found("no uploaded picture")
    return row[0], bytes(row[1]), row[2]


def set_pattern(conn, actor: Principal, target_id: int, seed, now: float) -> dict:
    """Keep a regenerated pattern. Choosing a pattern also drops an uploaded picture."""
    _may_edit_avatar(conn, actor, target_id)
    if not isinstance(seed, int) or isinstance(seed, bool) or not 0 <= seed < 2 ** 32:
        raise bad_request("seed must be an integer from 0 to 4294967295")
    conn.execute("UPDATE principals SET pattern_seed = ? WHERE id = ?", (seed, target_id))
    conn.execute("DELETE FROM avatars WHERE principal_id = ?", (target_id,))
    if actor.id != target_id:
        audit(conn, actor.id, "pattern.set", f"principal:{target_id}", None, now)
    return {"pattern": seed, "avatar": None}


# ---------------------------------------------------------------------- mentions

MENTION = re.compile(r"(?<![\w@/])@([A-Za-z0-9][A-Za-z0-9_.:-]{0,127})")


def _principal_obj(row) -> Principal:
    return Principal(id=row["id"], issuer=row["issuer"], external_id=row["external_id"],
                     identity_type=row["identity_type"], role=row["role"], display_name=row["display_name"],
                     owner_id=row["owner_id"], can_create_channels=bool(row["can_create_channels"]), credential_id="")


def resolve_mention(conn, name: str) -> list:
    """Who `@name` means: a username, an HF username, or a person who joined with HF."""
    name = name.rstrip(".,:;-")
    return conn.execute(
        """SELECT * FROM principals WHERE disabled = 0 AND (lower(external_id) = lower(?) OR lower(hf_username) = lower(?)
           OR (identity_type = 'user' AND lower(external_id) = 'hf:' || lower(?)))""", (name, name, name)).fetchall()


def _mention_names(row, former: tuple = ()) -> set[str]:
    """Everything `@...` may say to mean this identity: display name (spaces allowed), username, HF username,
    former display names, and the handle read as words ("leandros-intern" -> "leandros intern")."""
    names = {row["display_name"], row["external_id"], row["hf_username"], *former}
    handle = row["external_id"][3:] if row["external_id"].startswith("hf:") else row["external_id"]
    names.add(handle)
    if any(c in handle for c in "-_."):
        names.add(re.sub(r"[-_.]+", " ", handle))
    return {n.strip().lower() for n in names if n and n.strip()}


def _mention_candidates(conn) -> list:
    former: dict[int, list] = {}
    for pid, name in conn.execute("SELECT principal_id, name FROM former_names"):
        former.setdefault(pid, []).append(name)
    return sorted(((name, row) for row in conn.execute("SELECT * FROM principals WHERE disabled = 0")
                   for name in _mention_names(row, tuple(former.get(row["id"], ())))), key=lambda c: -len(c[0]))


def find_mention_spans(conn, body: str) -> list[tuple]:
    """(identity row, the text after @ as written) for each identity mentioned in `body`. At each @, the
    longest matching name wins, so `@Loubna Ben Allal` beats a shorter `@Loubna`; it must end at a word boundary."""
    if "@" not in body:
        return []
    candidates = _mention_candidates(conn)
    low, found = body.lower(), {}
    for i, ch in enumerate(body):
        if ch != "@" or (i and (body[i - 1].isalnum() or body[i - 1] in "@/_")):
            continue
        best = None
        for name, row in candidates:
            if name in GROUP_MENTIONS:
                continue                     # @all, @agents ... always mean the group, never someone named so
            end = i + 1 + len(name)
            if best is not None and len(name) < best:
                break                        # every identity sharing the longest name has been collected
            if low.startswith(name, i + 1) and (end == len(body) or not (body[end].isalnum() or body[end] in "_")):
                best = len(name)
                found.setdefault(row["id"], (row, body[i + 1:end]))
        if len(found) >= 50:
            break
    return list(found.values())


def find_mentions(conn, body: str) -> list:
    return [row for row, _ in find_mention_spans(conn, body)]


GROUP_MENTIONS = {"all": ("user", "agent", "system"), "agents": ("agent", "system"), "myagents": ("agent", "system"), "humans": ("user",),
                  "people": ("user",), "everyone": ("user", "agent", "system")}
GROUP_RE = re.compile(r"(?<![\w@/])@(" + "|".join(GROUP_MENTIONS) + r")(?![\w-])", re.I)


def group_mentions(body: str) -> set[str]:
    """Which channel-wide or author-owned group tags a message uses."""
    return {m.group(1).lower() for m in GROUP_RE.finditer(body)} if "@" in body else set()


def _record_mentions(conn, channel, message_id: int, body: str, sender_id: int) -> None:
    groups = sorted(group_mentions(body), key=lambda g: (g != "myagents", len(GROUP_MENTIONS[g]), g))
    kinds = {k for g in groups for k in GROUP_MENTIONS[g]}
    # a personal mention first (it keeps the exact text), then the groups fill in everyone else
    for row, text in find_mention_spans(conn, body):
        # only people who can read the channel get the mention: it must not reveal the channel to anyone else
        if row["id"] == sender_id or not can_see(conn, _principal_obj(row), channel):
            continue
        conn.execute("INSERT OR IGNORE INTO message_mentions (message_id, principal_id, mentioned_as) VALUES (?, ?, ?)",
                     (message_id, row["id"], text))
    if kinds:   # Group tags reach channel members; @myagents further restricts them to the author's agents.
        marks = ",".join("?" * len(kinds))
        for row in conn.execute(f"""SELECT p.* FROM principals p JOIN channel_members cm ON cm.principal_id = p.id
                                    WHERE cm.channel_id = ? AND p.disabled = 0 AND p.identity_type IN ({marks})""",
                                (channel["id"], *sorted(kinds))):
            group = next((g for g in groups if row["identity_type"] in GROUP_MENTIONS[g]
                          and (g != "myagents" or row["owner_id"] == sender_id)), None)
            if group and row["id"] != sender_id and can_see(conn, _principal_obj(row), channel):
                conn.execute("INSERT OR IGNORE INTO message_mentions (message_id, principal_id, mentioned_as) VALUES (?, ?, ?)",
                             (message_id, row["id"], group))


def backfill_mentions(conn) -> int:
    """One-time pass after the matcher learned display names: record mentions in older messages."""
    if conn.execute("SELECT 1 FROM settings WHERE key = 'mentions_v2'").fetchone():
        return 0
    n = 0
    for m in conn.execute("SELECT id, channel_id, sender_id, body FROM messages WHERE imported = 0 AND body LIKE '%@%'").fetchall():
        ch = conn.execute("SELECT * FROM channels WHERE id = ?", (m["channel_id"],)).fetchone()
        before = conn.execute("SELECT COUNT(*) FROM message_mentions WHERE message_id = ?", (m["id"],)).fetchone()[0]
        _record_mentions(conn, ch, m["id"], m["body"], m["sender_id"])
        n += conn.execute("SELECT COUNT(*) FROM message_mentions WHERE message_id = ?", (m["id"],)).fetchone()[0] - before
    conn.execute("INSERT INTO settings (key, value) VALUES ('mentions_v2', 'done')")
    return n


MAX_REACTIONS_PER_MESSAGE = 20   # distinct emoji


def _attach_reactions(conn, messages: list[dict], viewer_id: int, viewer: Principal | None = None) -> None:
    """`reactions`: one entry per emoji, in the order first used, with count, who, and whether the viewer is one."""
    if not messages:
        return
    ids = [m["id"] for m in messages]
    vis = _visible_id_set(conn, viewer)
    found: dict[int, dict] = {}
    for mid, emoji, pid, name, ext, kind, disabled, suspended_at, joined_via in conn.execute(f"""
            SELECT r.message_id, r.emoji, p.id, p.display_name, p.external_id, p.identity_type,
                   p.disabled, p.suspended_at, p.joined_via
            FROM message_reactions r JOIN principals p ON p.id = r.principal_id
            WHERE r.message_id IN ({",".join("?" * len(ids))}) ORDER BY r.created_at, r.rowid""", ids):
        e = found.setdefault(mid, {}).setdefault(emoji, {"emoji": emoji, "count": 0, "me": False, "by": []})
        e["count"] += 1
        e["me"] = e["me"] or pid == viewer_id
        e["by"].append({"id": pid, "display_name": name, "external_id": ext, "identity_type": kind,
                        **_status_flags(disabled, suspended_at, joined_via, pid, vis)})
    for m in messages:
        m["reactions"] = list(found.get(m["id"], {}).values())


def _valid_emoji(emoji) -> str:
    """One emoji (or a short emoji sequence): no spaces, no letters or digits, at most 16 characters."""
    if not isinstance(emoji, str):
        raise bad_request("emoji must be a string")
    emoji = emoji.strip()
    if not 1 <= len(emoji) <= 16 or any(c.isspace() or (c.isascii() and c.isalnum()) for c in emoji):
        raise bad_request("react with an emoji character, like 👍 or ✅ (not a name like :thumbsup:)")
    return emoji


def react(conn, p: Principal, channel_id: int, message_id: int, emoji, on: bool, now: float) -> tuple[dict, bool]:
    """Add (on=True) or remove a reaction of yours. Idempotent; returns the message and whether anything changed."""
    emoji = _valid_emoji(emoji)
    channel = channel_for(conn, p, channel_id, "messages:write")
    row = conn.execute("SELECT id FROM messages WHERE id = ? AND channel_id = ?", (message_id, channel_id)).fetchone()
    if row is None:
        raise not_found("no such message in this channel")
    if channel["archived"]:
        raise conflict("channel_archived", "channel is archived")
    if on:
        exists = conn.execute("SELECT 1 FROM message_reactions WHERE message_id = ? AND principal_id = ? AND emoji = ?",
                              (message_id, p.id, emoji)).fetchone()
        if not exists:
            kinds = {r[0] for r in conn.execute("SELECT DISTINCT emoji FROM message_reactions WHERE message_id = ?", (message_id,))}
            if emoji not in kinds and len(kinds) >= MAX_REACTIONS_PER_MESSAGE:
                raise conflict("too_many_reactions", f"a message can have at most {MAX_REACTIONS_PER_MESSAGE} different emoji")
            conn.execute("INSERT INTO message_reactions (message_id, principal_id, emoji, created_at) VALUES (?, ?, ?, ?)",
                         (message_id, p.id, emoji, now))
        changed = not exists
    else:
        changed = conn.execute("DELETE FROM message_reactions WHERE message_id = ? AND principal_id = ? AND emoji = ?",
                               (message_id, p.id, emoji)).rowcount > 0
    if changed:   # followers see it through the edit cursor, like an edit (the body and edited_at stay as they are)
        rev = channel["edit_rev"] + 1
        conn.execute("UPDATE channels SET edit_rev = ? WHERE id = ?", (rev, channel_id))
        conn.execute("UPDATE messages SET edit_rev = ? WHERE id = ?", (rev, message_id))
    out = _message_json(conn.execute(MESSAGE_SELECT + " WHERE m.id = ?", (message_id,)).fetchone())
    _attach_mentions(conn, [out], p)
    _attach_reactions(conn, [out], p.id, p)
    _attach_pins(conn, [out], p)
    return out, changed


def react_message(conn, p: Principal, message_id: int, emoji, on: bool, now: float) -> tuple[dict, bool]:
    """Add or remove your reaction by message id alone. Delegates to `react` and hides inaccessible messages as 404."""
    emoji = _valid_emoji(emoji)
    row = conn.execute("SELECT channel_id FROM messages WHERE id = ?", (message_id,)).fetchone()
    if row is None:
        raise not_found("no such message")
    try:
        return react(conn, p, row["channel_id"], message_id, emoji, on, now)
    except ApiError as e:
        if e.status == 404:
            raise not_found("no such message") from None
        raise


MAX_PINS_PER_CHANNEL = 50


def pin(conn, p: Principal, channel_id: int, message_id: int, on: bool, now: float) -> tuple[dict, bool]:
    """Pin (on=True) or unpin a message in its channel. People only; anyone who can post there. Idempotent;
    returns the message and whether anything changed."""
    if p.identity_type != "user":
        raise forbidden("only people can pin or unpin messages")
    channel = channel_for(conn, p, channel_id, "messages:write")
    if conn.execute("SELECT 1 FROM messages WHERE id = ? AND channel_id = ?", (message_id, channel_id)).fetchone() is None:
        raise not_found("no such message in this channel")
    if channel["archived"]:
        raise conflict("channel_archived", "channel is archived")
    if on:
        exists = conn.execute("SELECT 1 FROM message_pins WHERE message_id = ?", (message_id,)).fetchone()
        if not exists:
            n = conn.execute("SELECT COUNT(*) FROM message_pins WHERE channel_id = ?", (channel_id,)).fetchone()[0]
            if n >= MAX_PINS_PER_CHANNEL:
                raise conflict("too_many_pins", f"a channel can have at most {MAX_PINS_PER_CHANNEL} pinned messages; unpin one first")
            conn.execute("INSERT INTO message_pins (message_id, channel_id, pinned_by, pinned_at) VALUES (?, ?, ?, ?)",
                         (message_id, channel_id, p.id, now))
        changed = not exists
    else:
        changed = conn.execute("DELETE FROM message_pins WHERE message_id = ?", (message_id,)).rowcount > 0
    if changed:   # followers see it through the edit cursor, like a reaction
        rev = channel["edit_rev"] + 1
        conn.execute("UPDATE channels SET edit_rev = ? WHERE id = ?", (rev, channel_id))
        conn.execute("UPDATE messages SET edit_rev = ? WHERE id = ?", (rev, message_id))
    out = _message_json(conn.execute(MESSAGE_SELECT + " WHERE m.id = ?", (message_id,)).fetchone())
    _attach_mentions(conn, [out], p)
    _attach_reactions(conn, [out], p.id, p)
    _attach_pins(conn, [out], p)
    return out, changed


def list_pins(conn, p: Principal, channel_id: int) -> dict:
    """The channel's pinned messages, most recently pinned first."""
    channel_for(conn, p, channel_id)
    rows = conn.execute(MESSAGE_SELECT + " JOIN message_pins mp ON mp.message_id = m.id WHERE mp.channel_id = ?"
                        " ORDER BY mp.pinned_at DESC, m.id DESC", (channel_id,)).fetchall()
    messages = [_message_json(r) for r in rows]
    _attach_mentions(conn, messages, p)
    _attach_reactions(conn, messages, p.id, p)
    _attach_pins(conn, messages, p)
    return {"pins": messages, "max": MAX_PINS_PER_CHANNEL}


def backfill_mentioned_as(conn) -> int:
    """One-time: work out the text older mentions were written with (current names, former names, handle, groups)."""
    if conn.execute("SELECT 1 FROM settings WHERE key = 'mentions_v3'").fetchone():
        return 0
    n = 0
    rows = conn.execute("""SELECT mm.message_id, mm.principal_id, m.body, p.identity_type FROM message_mentions mm
                           JOIN messages m ON m.id = mm.message_id JOIN principals p ON p.id = mm.principal_id
                           WHERE mm.mentioned_as IS NULL""").fetchall()
    spans: dict[int, dict] = {}
    for mid, pid, body, kind in rows:
        if mid not in spans:
            spans[mid] = {r["id"]: text for r, text in find_mention_spans(conn, body)}
        text = spans[mid].get(pid) or next((g for g in sorted(group_mentions(body)) if kind in GROUP_MENTIONS[g]), None)
        if text:
            conn.execute("UPDATE message_mentions SET mentioned_as = ? WHERE message_id = ? AND principal_id = ?", (text, mid, pid))
            n += 1
    conn.execute("INSERT INTO settings (key, value) VALUES ('mentions_v3', 'done')")
    return n


def _attach_mentions(conn, messages: list[dict], viewer: Principal | None = None) -> None:
    if not messages:
        return
    ids = [m["id"] for m in messages]
    vis = _visible_id_set(conn, viewer)
    found: dict[int, list] = {}
    for r in conn.execute(f"""SELECT mm.message_id, p.id, p.external_id, p.display_name, p.identity_type, p.hf_username,
                                     mm.mentioned_as, p.disabled, p.suspended_at, p.joined_via
                              FROM message_mentions mm JOIN principals p ON p.id = mm.principal_id
                              WHERE mm.message_id IN ({",".join("?" * len(ids))})""", ids):
        found.setdefault(r[0], []).append({"id": r[1], "external_id": r[2], "display_name": r[3], "identity_type": r[4],
                                           "hf_username": r[5], "as": r[6],
                                           **_status_flags(r[7], r[8], r[9], r[1], vis)})
    for m in messages:
        m["mentions"] = found.get(m["id"], [])


# --------------------------------------------------------- read state and activity


def _reads_baseline(conn, p: Principal) -> float:
    """Messages older than this never count as unread for p (read tracking start, or when p joined)."""
    since = conn.execute("SELECT value FROM settings WHERE key = 'reads_since'").fetchone()
    joined = conn.execute("SELECT created_at FROM principals WHERE id = ?", (p.id,)).fetchone()[0]
    return max(float(since[0]) if since else 0.0, joined)


PARTICIPATED_THREADS = """(SELECT id FROM messages WHERE sender_id = :me AND thread_id IS NULL
                          UNION SELECT thread_id FROM messages WHERE sender_id = :me AND thread_id IS NOT NULL)"""
OVERRIDDEN_THREADS = "(SELECT thread_id FROM thread_subscriptions WHERE principal_id = :me)"
MY_THREADS = f"(SELECT * FROM {PARTICIPATED_THREADS} EXCEPT SELECT * FROM {OVERRIDDEN_THREADS})"
FOLLOWED_REPLY = f"""(m.thread_id IN {MY_THREADS} OR m.thread_id IN (
    SELECT thread_id FROM thread_subscriptions WHERE principal_id = :me AND subscribed = 1 AND m.seq > after_seq))"""


def _dm_notification(dm: str) -> str:
    return f"({dm} = 1 AND (m.thread_id IS NULL OR m.thread_id NOT IN {OVERRIDDEN_THREADS}))"


def _for_me(dm: str) -> str:
    return f"({_dm_notification(dm)} OR mm.principal_id IS NOT NULL OR {FOLLOWED_REPLY})"


def _attach_thread_subscriptions(conn, messages: list[dict], p: Principal) -> None:
    roots = [m["id"] for m in messages if m["thread_id"] is None]
    if not roots:
        return
    marks = ",".join(str(int(i)) for i in roots)
    states = {}
    for tid, explicit, after, automatic in conn.execute(f"""
            SELECT m.id, s.subscribed, s.after_seq,
                   (m.id IN {PARTICIPATED_THREADS} OR (c.kind = 'dm' AND cm.principal_id IS NOT NULL))
            FROM messages m JOIN channels c ON c.id = m.channel_id
            LEFT JOIN channel_members cm ON cm.channel_id = c.id AND cm.principal_id = :me
            LEFT JOIN thread_subscriptions s ON s.thread_id = m.id AND s.principal_id = :me
            WHERE m.id IN ({marks})""", {"me": p.id}):
        states[tid] = {"thread_id": tid, "subscribed": bool(automatic if explicit is None else explicit),
                       "mode": "auto" if explicit is None else "subscribed" if explicit else "unsubscribed",
                       "after_seq": after or 0}
    for m in messages:
        if m["id"] in states:
            m["subscription"] = states[m["id"]]


def thread_subscription(conn, p: Principal, channel_id: int, thread_id: int) -> dict:
    channel_for(conn, p, channel_id)
    root = conn.execute("SELECT id, thread_id, channel_id FROM messages WHERE id = ? AND channel_id = ? AND thread_id IS NULL",
                        (thread_id, channel_id)).fetchone()
    if root is None:
        raise not_found("no such thread in this channel")
    messages = [dict(root)]
    _attach_thread_subscriptions(conn, messages, p)
    return messages[0]["subscription"] | {"for_me_unread": _threads_for_me(conn, p, [thread_id], messages).get(thread_id, 0)}


def thread_subscriptions(conn, p: Principal, channel_id: int, root_ids: list[int]) -> dict:
    """One bounded refresh for the posts a browser is displaying, including their reply badges."""
    channel_for(conn, p, channel_id)
    if not 1 <= len(root_ids) <= 200 or any(type(i) is not int or not 0 < i < 2**63 for i in root_ids):
        raise bad_request("roots must contain between 1 and 200 positive message ids")
    marks = ",".join(str(i) for i in dict.fromkeys(root_ids))
    messages = [dict(r) for r in conn.execute(
        f"SELECT id, channel_id, thread_id FROM messages WHERE channel_id = ? AND thread_id IS NULL AND id IN ({marks})",
        (channel_id,))]
    _attach_thread_subscriptions(conn, messages, p)
    counts = _threads_for_me(conn, p, [m["id"] for m in messages], messages)
    return {"subscriptions": [m["subscription"] | {"for_me_unread": counts.get(m["id"], 0)} for m in messages]}


def set_thread_subscription(conn, p: Principal, channel_id: int, thread_id: int, payload, now: float) -> dict:
    current = thread_subscription(conn, p, channel_id, thread_id)
    if not isinstance(payload, dict) or set(payload) != {"subscribed"} or not isinstance(payload["subscribed"], bool):
        raise bad_request('request body must be {"subscribed": true|false}')
    subscribed = payload["subscribed"]
    if current["mode"] == ("subscribed" if subscribed else "unsubscribed"):
        return current                    # a retry must not move the starting position
    ch = channel_for(conn, p, channel_id)
    after = 0 if current["mode"] == "auto" and current["subscribed"] and subscribed else ch["next_seq"] - 1
    conn.execute("""INSERT INTO thread_subscriptions (principal_id, thread_id, subscribed, after_seq, updated_at)
                    VALUES (?, ?, ?, ?, ?) ON CONFLICT (principal_id, thread_id) DO UPDATE
                    SET subscribed = excluded.subscribed, after_seq = excluded.after_seq, updated_at = excluded.updated_at""",
                 (p.id, thread_id, int(subscribed), after, now))
    return thread_subscription(conn, p, channel_id, thread_id)


def _thread_unread(floor: str) -> str:
    return f"m.seq > max(COALESCE(tr.last_read_seq, 0), {floor})"


FOR_ME = _for_me(":dm")
# thread replies are read when their thread is opened; top-level messages when the channel is
THREAD_UNREAD = _thread_unread(":floor")


def unread_counts(conn, p: Principal, channel) -> dict:
    """unread: new top-level messages; for_me: mentions, replies in my threads, and DMs to me. A thread
    reply stays "for me" until I open its thread, even after I have looked at the channel."""
    row = conn.execute("SELECT last_read_seq, thread_floor FROM channel_reads WHERE principal_id = ? AND channel_id = ?",
                       (p.id, channel["id"])).fetchone()
    return _unread_counts(conn, p, channel, row, _reads_baseline(conn, p),
                          channel["kind"] == "dm" and _is_channel_member(conn, channel["id"], p.id))


def _unread_counts(conn, p: Principal, channel, row, baseline: float, dm: bool) -> dict:
    """Count one channel using its read position, baseline and DM membership."""
    params = {"me": p.id, "c": channel["id"], "lr": row["last_read_seq"] if row else 0,
              "floor": row["thread_floor"] if row else 0,
              "has_row": 1 if row else 0, "baseline": baseline, "dm": int(dm)}
    r = conn.execute(f"""
        SELECT COALESCE(SUM(CASE WHEN m.thread_id IS NULL AND m.seq > :lr THEN 1 ELSE 0 END), 0),
               COALESCE(SUM(CASE WHEN {FOR_ME} AND ((m.thread_id IS NULL AND m.seq > :lr)
                                                OR (m.thread_id IS NOT NULL AND {THREAD_UNREAD})) THEN 1 ELSE 0 END), 0),
               COUNT(DISTINCT CASE WHEN m.thread_id IS NOT NULL AND {FOR_ME} AND {THREAD_UNREAD} THEN m.thread_id END)
        FROM messages m LEFT JOIN message_mentions mm ON mm.message_id = m.id AND mm.principal_id = :me
        LEFT JOIN thread_reads tr ON tr.principal_id = :me AND tr.thread_id = m.thread_id
        WHERE m.imported = 0 AND m.channel_id = :c AND m.sender_id != :me AND (m.seq > :lr OR (m.thread_id IS NOT NULL AND m.seq > :floor))
          AND (:has_row = 1 OR m.created_at > :baseline)""", params).fetchone()
    return {"last_read": params["lr"], "unread": r[0], "for_me": r[1], "threads_for_me": r[2]}


def _channel_unread_counts(conn, p: Principal, channels: list) -> dict[int, dict]:
    """Count all listed channels in one query, sharing read state and thread membership."""
    ids = ",".join(str(int(c["id"])) for c in channels)
    for_me, thread_unread = _for_me("s.dm"), _thread_unread("s.floor")
    rows = conn.execute(f"""
        WITH state AS (
            SELECT c.id AS channel_id, COALESCE(cr.last_read_seq, 0) AS lr,
                   COALESCE(cr.thread_floor, 0) AS floor, cr.principal_id IS NOT NULL AS has_row,
                   (c.kind = 'dm' AND cm.principal_id IS NOT NULL) AS dm
            FROM channels c
            LEFT JOIN channel_reads cr ON cr.principal_id = :me AND cr.channel_id = c.id
            LEFT JOIN channel_members cm ON cm.principal_id = :me AND cm.channel_id = c.id
            WHERE c.id IN ({ids})
        )
        SELECT s.channel_id, s.lr,
               COALESCE(SUM(CASE WHEN m.thread_id IS NULL AND m.seq > s.lr THEN 1 ELSE 0 END), 0),
               COALESCE(SUM(CASE WHEN {for_me} AND ((m.thread_id IS NULL AND m.seq > s.lr)
                                                 OR (m.thread_id IS NOT NULL AND {thread_unread})) THEN 1 ELSE 0 END), 0),
               COUNT(DISTINCT CASE WHEN m.thread_id IS NOT NULL AND {for_me} AND {thread_unread} THEN m.thread_id END)
        FROM state s
        LEFT JOIN messages m ON m.channel_id = s.channel_id AND m.imported = 0 AND m.sender_id != :me
             AND (m.seq > s.lr OR (m.thread_id IS NOT NULL AND m.seq > s.floor))
             AND (s.has_row = 1 OR m.created_at > :baseline)
        LEFT JOIN message_mentions mm ON mm.message_id = m.id AND mm.principal_id = :me
        LEFT JOIN thread_reads tr ON tr.principal_id = :me AND tr.thread_id = m.thread_id
        GROUP BY s.channel_id""", {"me": p.id, "baseline": _reads_baseline(conn, p)})
    return {r[0]: {"last_read": r[1], "unread": r[2], "for_me": r[3], "threads_for_me": r[4]} for r in rows}


def mark_thread_read(conn, p: Principal, channel_id: int, thread_id: int, seq, now: float) -> dict:
    """Mark a thread read up to `seq` (its newest reply you have seen). Returns the channel's counts."""
    ch = channel_for(conn, p, channel_id)
    root = conn.execute("SELECT id FROM messages WHERE id = ? AND channel_id = ? AND thread_id IS NULL",
                        (thread_id, channel_id)).fetchone()
    if root is None:
        raise not_found("no such thread in this channel")
    if not isinstance(seq, int) or isinstance(seq, bool) or seq < 0:
        raise bad_request("seq must be a message sequence number")
    seq = min(seq, ch["next_seq"] - 1)
    conn.execute("""INSERT INTO thread_reads (principal_id, thread_id, last_read_seq, updated_at) VALUES (?, ?, ?, ?)
                    ON CONFLICT (principal_id, thread_id) DO UPDATE
                    SET last_read_seq = max(last_read_seq, excluded.last_read_seq), updated_at = excluded.updated_at""",
                 (p.id, thread_id, seq, now))
    return unread_counts(conn, p, ch)


def mark_read(conn, p: Principal, channel_id: int, seq, now: float) -> dict:
    ch = channel_for(conn, p, channel_id)
    if not isinstance(seq, int) or isinstance(seq, bool) or seq < 0:
        raise bad_request("seq must be a message sequence number")
    seq = min(seq, ch["next_seq"] - 1)
    conn.execute("""INSERT INTO channel_reads (principal_id, channel_id, last_read_seq, updated_at) VALUES (?, ?, ?, ?)
                    ON CONFLICT (principal_id, channel_id) DO UPDATE
                    SET last_read_seq = max(last_read_seq, excluded.last_read_seq), updated_at = excluded.updated_at""",
                 (p.id, channel_id, seq, now))
    return unread_counts(conn, p, ch)


def mark_all_read(conn, p: Principal, now: float) -> dict:
    """Mark every channel and DM you can read as read, thread replies included (the thread floor moves
    up too), as of now. Returns how many channels it touched."""
    ids = visible_channel_ids(conn, p)
    rows = conn.execute("SELECT id, next_seq FROM channels" + ("" if ids is None else
                        f" WHERE id IN ({','.join(str(int(i)) for i in ids) or 'NULL'})")).fetchall()
    conn.executemany("""INSERT INTO channel_reads (principal_id, channel_id, last_read_seq, thread_floor, updated_at)
                        VALUES (?, ?, ?, ?, ?)
                        ON CONFLICT (principal_id, channel_id) DO UPDATE
                        SET last_read_seq = max(last_read_seq, excluded.last_read_seq),
                            thread_floor = max(thread_floor, excluded.thread_floor), updated_at = excluded.updated_at""",
                     [(p.id, r["id"], r["next_seq"] - 1, r["next_seq"] - 1, now) for r in rows])
    return {"channels": len(rows)}


def activity(conn, p: Principal, limit: int = 50, after: int | None = None, follow: list[int] | None = None,
             reactions: bool = False, unread: bool = False) -> dict:
    """Messages for me: mentions, replies in threads I am in, DMs to me, and (with `follow`) every
    message in those channels. My own messages never count.

    Without `after`: the newest `limit`, newest first (what the Activity view shows).
    With `after`: messages with id > after, oldest first, for an agent that resumes from a saved
    cursor. Message ids grow with every post across the whole board, so `next_cursor` is one number.
    An exhausted page advances past unrelated messages too; a partial page stops at its last result.
    With `unread` (and no `after`): only the ones I have not read yet, newest first, however far back they
    are (walked in pages, at most ACTIVITY_UNREAD_SCAN messages), so the newest `limit` read ones never hide one.
    """
    limit = max(1, min(int(limit), 200))
    follow = list(dict.fromkeys(follow or []))
    for cid in follow:
        channel_for(conn, p, cid)                    # 404 for channels the caller cannot read
    ids = visible_channel_ids(conn, p)
    # "+m.channel_id" keeps SQLite off the channel index: walking messages by id and stopping at `limit`
    # is ~60x cheaper than collecting every message of every visible channel and sorting them (the
    # plan it picked otherwise, ~65 ms per call once one channel held 14k messages).
    scope = "" if ids is None else (f" AND +m.channel_id IN ({','.join(str(int(i)) for i in ids)})" if ids else " AND 0")
    followed = f" OR +m.channel_id IN ({','.join(str(int(i)) for i in follow)})" if follow else ""
    order = "DESC" if after is None else "ASC"
    # Capture the boundary before reading: a later post must remain available to the next poll.
    through = conn.execute("SELECT COALESCE(MAX(id), 0) FROM messages").fetchone()[0]

    def fetch(n: int, upto: int) -> list:
        return conn.execute(MESSAGE_SELECT + f"""
            WHERE m.imported = 0 AND m.sender_id != :me AND m.id > :after AND m.id <= :through{scope} AND (
                m.id IN (SELECT message_id FROM message_mentions WHERE principal_id = :me)
                OR {FOLLOWED_REPLY}
                OR {_dm_notification("(m.channel_id IN (SELECT c.id FROM channels c JOIN channel_members cm ON cm.channel_id = c.id WHERE c.kind = 'dm' AND cm.principal_id = :me))")}{followed})
            ORDER BY m.id {order} LIMIT :limit""", {"me": p.id, "limit": n, "after": after or 0,
                                                   "through": upto}).fetchall()

    if unread and after is None:
        messages, upto, scanned, has_more = [], through, 0, False
        while True:
            rows = fetch(200, upto)
            page = [_message_json(r) for r in rows]
            _attach_mentions(conn, page, p)
            _annotate_activity(conn, p, page)
            messages += [m for m in page if m["unread"]]
            scanned += len(rows)
            if len(messages) > limit:
                has_more, messages = True, messages[:limit]
                break
            if len(rows) < 200 or scanned >= ACTIVITY_UNREAD_SCAN:
                has_more = len(rows) == 200   # stopped at the cap with older notifications left unchecked
                break
            upto = page[-1]["id"] - 1
        _attach_reactions(conn, messages, p.id, p)
        _attach_pins(conn, messages, p)
        return {"messages": messages, "next_cursor": through, "has_more": has_more}

    rows = fetch(limit + 1, through)
    has_more = len(rows) > limit
    messages = [_message_json(r) for r in rows[:limit]]
    _attach_mentions(conn, messages, p)
    _attach_reactions(conn, messages, p.id, p)
    _attach_pins(conn, messages, p)
    _annotate_activity(conn, p, messages)
    if after is None:
        cursor = through   # "everything up to now"
    elif has_more:
        cursor = messages[-1]["id"]
    else:
        cursor = max(after, through)   # exhausted this range, including messages not for this caller
    out = {"messages": messages, "next_cursor": cursor, "has_more": has_more}
    if reactions and after is None:
        out["reactions"] = _reactions_to_me(conn, p, scope, limit)
    return out


ACTIVITY_UNREAD_SCAN = 20000   # notifications an unread-only read walks back through, at most


def _annotate_activity(conn, p: Principal, messages: list[dict]) -> None:
    """Add `channel`, `reason` (why it is for me) and `unread` to activity messages."""
    my_threads = {r[0] for r in conn.execute(MY_THREADS.strip()[1:-1], {"me": p.id})} if messages else set()
    subscriptions = {r[0]: (r[1], r[2]) for r in conn.execute(
        "SELECT thread_id, subscribed, after_seq FROM thread_subscriptions WHERE principal_id = ?", (p.id,))} if messages else {}
    reads = dict(conn.execute("SELECT channel_id, last_read_seq FROM channel_reads WHERE principal_id = ?", (p.id,)).fetchall())
    floors = dict(conn.execute("SELECT channel_id, thread_floor FROM channel_reads WHERE principal_id = ?", (p.id,)).fetchall())
    thread_reads = dict(conn.execute("SELECT thread_id, last_read_seq FROM thread_reads WHERE principal_id = ?", (p.id,)).fetchall())
    baseline = _reads_baseline(conn, p)
    channels = {}
    for m in messages:
        cid = m["channel_id"]
        if cid not in channels:
            channels[cid] = _channel_json(conn, conn.execute("SELECT * FROM channels WHERE id = ?", (cid,)).fetchone())
        m["channel"] = {k: channels[cid][k] for k in ("id", "name", "kind")} | (
            {"members": channels[cid]["members"]} if channels[cid]["kind"] == "dm" else {})
        sub = subscriptions.get(m["thread_id"])
        followed_reply = m["thread_id"] in my_threads or bool(sub and sub[0] and m["seq"] > sub[1])
        mentioned = any(x["id"] == p.id for x in m["mentions"])
        direct = (channels[cid]["kind"] == "dm" and any(x and x["id"] == p.id for x in channels[cid]["members"])
                  and (sub is None or followed_reply or mentioned))
        m["reason"] = "dm" if direct else "mention" if mentioned else "reply" if followed_reply else "channel"
        if m["thread_id"]:
            tr = thread_reads.get(m["thread_id"])
            m["unread"] = m["seq"] > max(tr or 0, floors.get(cid, 0)) and (cid in reads or m["created_at"] > baseline)
        else:
            m["unread"] = m["seq"] > reads.get(cid, 0) and (cid in reads or m["created_at"] > baseline)


def joined_channel_ids(conn, p: Principal) -> list[int]:
    """Channels (not DMs, not archived) the caller is a member of and can read."""
    return [r["id"] for r in conn.execute("""SELECT c.* FROM channels c JOIN channel_members cm ON cm.channel_id = c.id
                                             WHERE cm.principal_id = ? AND c.kind != 'dm' AND c.archived = 0""", (p.id,))
            if can_see(conn, p, r)]


def _reactions_to_me(conn, p: Principal, scope: str, limit: int) -> list[dict]:
    """Reactions others left on my messages, one entry per message (newest reaction first)."""
    rows = conn.execute(f"""SELECT r.message_id, r.emoji, r.created_at, r.principal_id FROM message_reactions r
                            JOIN messages m ON m.id = r.message_id
                            WHERE m.imported = 0 AND m.sender_id = :me AND r.principal_id != :me{scope}
                            ORDER BY r.created_at DESC LIMIT 500""", {"me": p.id}).fetchall()
    groups: dict[int, dict] = {}
    people: dict[int, dict] = {}                     # the same few people react a lot: look each up once
    vis = _visible_id_set(conn, p)
    for mid, emoji, at, pid in rows:
        g = groups.setdefault(mid, {"message_id": mid, "last_at": at, "reactions": []})
        if pid not in people:
            people[pid] = _brief(conn, pid, vis)
        g["reactions"].append({"emoji": emoji, "by": people[pid], "at": at})
    items = sorted(groups.values(), key=lambda g: -g["last_at"])[:limit]
    if items:
        full = {r["id"]: r for r in conn.execute(MESSAGE_SELECT + f" WHERE m.id IN ({','.join(str(g['message_id']) for g in items)})")}
        msgs = {i: _message_json(r) for i, r in full.items()}
        _attach_mentions(conn, list(msgs.values()), p)
        chans: dict[int, dict] = {}
        for g in items:
            m = msgs[g["message_id"]]
            if m["channel_id"] not in chans:
                chans[m["channel_id"]] = _channel_json(conn, conn.execute("SELECT * FROM channels WHERE id = ?", (m["channel_id"],)).fetchone())
            c = chans[m["channel_id"]]
            m["channel"] = {k: c[k] for k in ("id", "name", "kind")} | ({"members": c["members"]} if c["kind"] == "dm" else {})
            g["message"] = m
    return items


# ------------------------------------------------------------------ analytics


def analytics(conn, p: Principal, now: float, days: int = 7, start: float | None = None,
              end: float | None = None, top_k: int = 10, history: dict | None = None) -> dict:
    """Board activity for admins (and readers): totals, a daily series, channels and who posts."""
    if not p.sees_everything:
        raise forbidden("only admins and readers can see analytics")
    days = max(1, min(int(days), 365))
    start, end = analyticsmod.bounds(now, days, start, end)
    if not 1 <= top_k <= 100:
        raise bad_request("top_k must be between 1 and 100")
    stats = _analytics_messages(conn, start, end)
    series = [{key: row[key] for key in ("day", "people", "agents")} for row in stats["daily"]]
    daily = {row["day"]: row for row in series}

    chans: dict = {}
    for r in conn.execute("""SELECT c.id, c.name, c.kind, c.archived,
                                    (SELECT COUNT(*) FROM messages m WHERE m.channel_id = c.id) AS total,
                                    (SELECT COUNT(*) FROM messages m WHERE m.channel_id = c.id AND m.created_at >= :d0 AND m.created_at < :end) AS recent,
                                    (SELECT COUNT(DISTINCT m.sender_id) FROM messages m WHERE m.channel_id = c.id AND m.created_at >= :d0 AND m.created_at < :end) AS posters,
                                    (SELECT MAX(m.created_at) FROM messages m WHERE m.channel_id = c.id) AS last_at
                             FROM channels c""", {"d0": start, "end": end}):
        key = "dm" if r["kind"] == "dm" else r["id"]          # DMs are counted together, never by pair
        c = chans.setdefault(key, {"id": None if key == "dm" else r["id"], "name": "direct messages" if key == "dm" else r["name"],
                                   "kind": r["kind"], "archived": bool(r["archived"]) if key != "dm" else False,
                                   "total": 0, "messages": 0, "posters": 0, "last_at": None})
        c["total"] += r["total"]; c["messages"] += r["recent"]; c["posters"] += r["posters"]
        c["last_at"] = max(filter(None, [c["last_at"], r["last_at"]]), default=None)
    channels = sorted(chans.values(), key=lambda c: (-c["messages"], -c["total"], c["name"]))

    per_day = {}
    for pid, d, n in conn.execute("""SELECT sender_id, CAST(created_at / 86400 AS INTEGER) * 86400, COUNT(*) FROM messages
                                     WHERE created_at >= ? AND created_at < ? GROUP BY 1, 2""", (start, end)):
        per_day.setdefault(pid, {})[d] = n
    posters = []
    for r in conn.execute("""SELECT p.id, p.display_name, p.external_id, p.identity_type, p.role, p.owner_id, p.pattern_seed,
                                    p.disabled, p.suspended_at, p.joined_via, substr(av.sha256, 1, 12) AS avatar, COUNT(m.id) AS n,
                                    MAX(m.created_at) AS last_at, COUNT(DISTINCT m.channel_id) AS nchannels
                             FROM principals p JOIN messages m ON m.sender_id = p.id AND m.created_at >= ? AND m.created_at < ?
                             LEFT JOIN avatars av ON av.principal_id = p.id
                             GROUP BY p.id ORDER BY n DESC, p.id""", (start, end)):
        posters.append({"id": r["id"], "display_name": r["display_name"], "external_id": r["external_id"],
                        "identity_type": r["identity_type"], "role": r["role"], "avatar": r["avatar"], "pattern": r["pattern_seed"],
                        "disabled": bool(r["disabled"]), "suspended": r["suspended_at"] is not None,
                        "imported": r["joined_via"] == "import",
                        "owner": _brief(conn, r["owner_id"]), "messages": r["n"], "last_at": r["last_at"], "channels": r["nchannels"],
                        "daily": [per_day.get(r["id"], {}).get(d, 0) for d in sorted(daily)]})

    count = lambda sql, *a: conn.execute(sql, a).fetchone()[0]
    week = now - 7 * 86400
    files = _analytics_files(conn, start, end)
    totals = {
        "messages": count("SELECT COUNT(*) FROM messages"),
        "messages_window": sum(d["people"] + d["agents"] for d in series),
        "people": count("SELECT COUNT(*) FROM principals WHERE identity_type = 'user' AND disabled = 0"),
        "agents": count("SELECT COUNT(*) FROM principals WHERE identity_type != 'user' AND disabled = 0"),
        "channels": count("SELECT COUNT(*) FROM channels WHERE kind != 'dm' AND archived = 0"),
        "active_people_7d": count("""SELECT COUNT(DISTINCT m.sender_id) FROM messages m JOIN principals p ON p.id = m.sender_id
                                     WHERE m.created_at >= ? AND m.created_at < ? AND p.identity_type = 'user'""", week, now),
        "active_agents_7d": count("""SELECT COUNT(DISTINCT m.sender_id) FROM messages m JOIN principals p ON p.id = m.sender_id
                                     WHERE m.created_at >= ? AND m.created_at < ? AND p.identity_type != 'user'""", week, now),
        "threads_window": count("SELECT COUNT(DISTINCT thread_id) FROM messages WHERE thread_id IS NOT NULL AND created_at >= ? AND created_at < ?", start, end),
        "attachments_window": files["count"],
    }
    return {"days": len(series), "since": start, "generated_at": now, "totals": totals, "daily": series,
            "channels": channels, "posters": posters, "range": {"from": start, "to": end, "bucket_seconds": 86400},
            "message_stats": stats, "response_times": _analytics_responses(conn, start, min(now, end)),
            "interactions": _analytics_interactions(conn, start, end, top_k), "files": files,
            "listening": _analytics_listening(conn, start, end, history or {})}


def _analytics_messages(conn, start: float, end: float) -> dict:
    import math

    daily = {day: {"day": day, "messages": 0, "people": 0, "agents": 0, "words": 0, "characters": 0}
             for day in range(int(start // 86400) * 86400, math.ceil(end / 86400) * 86400, 86400)}
    for row in conn.execute("""SELECT m.created_at, m.body, p.identity_type FROM messages m
                               JOIN principals p ON p.id = m.sender_id
                               WHERE m.created_at >= ? AND m.created_at < ?""", (start, end)):
        data = daily[int(row["created_at"] // 86400) * 86400]
        data["messages"] += 1
        data["people" if row["identity_type"] == "user" else "agents"] += 1
        data["characters"] += len(row["body"])
        data["words"] += len(analyticsmod.WORD.findall(row["body"]))
    for data in daily.values():
        data["average_length"] = data["characters"] / data["messages"] if data["messages"] else None
    total = {key: sum(data[key] for data in daily.values()) for key in ("messages", "words", "characters")}
    return {**total, "average_length": total["characters"] / total["messages"] if total["messages"] else None,
            "daily": list(daily.values())}


def _analytics_files(conn, start: float, end: float) -> dict:
    rows = conn.execute("""SELECT uploader_id, COUNT(*) AS count, COALESCE(SUM(size), 0) AS bytes
                           FROM attachments WHERE published = 1 AND created_at >= ? AND created_at < ?
                           GROUP BY uploader_id ORDER BY bytes DESC, uploader_id""", (start, end))
    people = [dict(_brief(conn, row["uploader_id"]), count=row["count"], bytes=row["bytes"]) for row in rows]
    return {"count": sum(item["count"] for item in people), "bytes": sum(item["bytes"] for item in people),
            "by_principal": people}


def _analytics_responses(conn, start: float, end: float) -> dict:
    # Each request/agent appears once even when a DM also mentions its recipient.
    # Indexed first-response lookups avoid joining every request to every later message.
    rows = conn.execute("""WITH requests AS (
        SELECT m.id, mm.principal_id AS target, m.channel_id, COALESCE(m.thread_id, m.id) AS thread,
               m.created_at, c.kind
        FROM messages m JOIN message_mentions mm ON mm.message_id = m.id
        JOIN principals p ON p.id = mm.principal_id JOIN channels c ON c.id = m.channel_id
        WHERE m.created_at >= :start AND m.created_at < :end AND p.identity_type != 'user'
              AND mm.principal_id != m.sender_id
        UNION
        SELECT m.id, cm.principal_id, m.channel_id, COALESCE(m.thread_id, m.id), m.created_at, c.kind
        FROM messages m JOIN channels c ON c.id = m.channel_id
        JOIN channel_members cm ON cm.channel_id = c.id JOIN principals p ON p.id = cm.principal_id
        WHERE c.kind = 'dm' AND m.created_at >= :start AND m.created_at < :end
              AND p.identity_type != 'user' AND cm.principal_id != m.sender_id
    ) SELECT q.target, q.created_at,
        CASE WHEN q.kind = 'dm' THEN (
            SELECT r.created_at FROM messages r WHERE r.channel_id = q.channel_id AND r.sender_id = q.target
                AND r.created_at >= q.created_at AND r.created_at < :end AND r.id > q.id
            ORDER BY r.created_at, r.id LIMIT 1)
        ELSE (
            SELECT r.created_at FROM messages r WHERE r.sender_id = q.target AND r.thread_id = q.thread
                AND r.created_at >= q.created_at AND r.created_at < :end AND r.id > q.id
            ORDER BY r.created_at, r.id LIMIT 1)
        END AS answered_at FROM requests q""", {"start": start, "end": end})
    agents = {}
    latencies = []
    requests = 0
    for row in rows:
        requests += 1
        agent = agents.setdefault(row["target"], {"requests": 0, "latencies": []})
        agent["requests"] += 1
        if row["answered_at"] is not None:
            latency = row["answered_at"] - row["created_at"]
            latencies.append(latency)
            agent["latencies"].append(latency)
    per_agent = [dict(_brief(conn, pid), **analyticsmod.response_summary(data["requests"], data["latencies"]))
                 for pid, data in agents.items()]
    return {"rule": "Mention or DM to an agent -> its first later message in that thread or DM, before the range ends. Reactions do not count.",
            **analyticsmod.response_summary(requests, latencies), "histogram": analyticsmod.response_histogram(latencies),
            "agents": sorted(per_agent, key=lambda item: (-item["requests"], item["id"]))}


def _analytics_interactions(conn, start: float, end: float, top_k: int) -> dict:
    rows = conn.execute("""WITH events AS (
        SELECT m.id, m.sender_id AS source, cm.principal_id AS target, 0 AS priority
        FROM messages m JOIN channels c ON c.id = m.channel_id
        JOIN channel_members cm ON cm.channel_id = m.channel_id
        WHERE c.kind = 'dm' AND m.created_at >= :start AND m.created_at < :end AND cm.principal_id != m.sender_id
        UNION ALL
        SELECT m.id, m.sender_id, parent.sender_id, 1
        FROM messages m JOIN messages parent ON parent.id = m.reply_to JOIN channels c ON c.id = m.channel_id
        WHERE c.kind != 'dm' AND m.created_at >= :start AND m.created_at < :end
        UNION ALL
        SELECT m.id, m.sender_id, mm.principal_id, 2
        FROM messages m JOIN message_mentions mm ON mm.message_id = m.id JOIN channels c ON c.id = m.channel_id
        WHERE c.kind != 'dm' AND m.created_at >= :start AND m.created_at < :end
    ), pairs AS (
        SELECT e.id, min(source, target) AS a, max(source, target) AS b, min(priority) AS priority
        FROM events e JOIN principals s ON s.id = e.source JOIN principals t ON t.id = e.target
        WHERE (s.identity_type = 'user') != (t.identity_type = 'user') GROUP BY e.id, a, b
    ) SELECT a, b, priority, COUNT(*) AS count FROM pairs GROUP BY a, b, priority""", {"start": start, "end": end})
    edges = {}
    weights = {}
    for row in rows:
        a, b, count = row["a"], row["b"], row["count"]
        edge = edges.setdefault((a, b), {"source": a, "target": b, "total": 0, "mentions": 0, "replies": 0, "dms": 0})
        edge[("dms", "replies", "mentions")[row["priority"]]] += count
        edge["total"] += count
        for pid in (a, b):
            weights[pid] = weights.get(pid, 0) + count
    selected = sorted(weights, key=lambda pid: (-weights[pid], pid))[:top_k]
    identities = {pid: _brief(conn, pid) for pid in selected}
    return analyticsmod.chord_graph(list(edges.values()), identities, top_k)


def _analytics_listening(conn, start: float, end: float, pending: dict) -> dict:
    first = conn.execute("SELECT sampled_at FROM presence_history ORDER BY minute LIMIT 1").fetchone()
    started_at = first[0] if first else None
    if pending:
        candidate = min(sample[0] for sample in pending.values())
        started_at = min(started_at, candidate) if started_at is not None else candidate
    rows = conn.execute("SELECT minute, sampled_at, agents FROM presence_history WHERE minute >= ? AND minute < ?",
                        (int(start // 60) * 60, end))
    samples = {row[0]: (row[1], row[2]) for row in rows}
    samples.update(pending)
    return analyticsmod.listening_series(start, end, samples, started_at)


# ------------------------------------------------------------------ search

SEARCH_OPS = {"from", "in", "before", "after", "on", "has", "is", "by", "to", "mentions"}
SEARCH_TOKEN = re.compile(r'(?P<op>[A-Za-z]+):(?P<val>"[^"]*"|\S+)|"(?P<phrase>[^"]*)"|(?P<word>\S+)')


def parse_search(q: str) -> dict:
    """Split a query into free text and filters. Filters: from:@name in:#channel before:/after:/on:DATE
    has:file|replies|mention is:reply|root by:agent|person to:@name ("mentions:" works too).
    Values with spaces go in quotes: from:"Ana Lopez". Unknown `word:` stays text (URLs keep working)."""
    out: dict = {"words": [], "phrases": [], "filters": []}
    for m in SEARCH_TOKEN.finditer(q or ""):
        op = (m.group("op") or "").lower()
        if op in SEARCH_OPS:
            val = m.group("val")
            out["filters"].append((("to" if op == "mentions" else op), val[1:-1] if val.startswith('"') else val))
        elif m.group("phrase") is not None:
            if m.group("phrase").strip():
                out["phrases"].append(m.group("phrase").strip())
        else:
            out["words"].append(m.group(0))
    return out


def _fts_query(words: list[str], phrases: list[str]) -> str | None:
    """Every word must appear (as a prefix, so `deplo` finds `deployed`); phrases must appear as written."""
    parts = []
    for w in words:
        tokens = re.findall(r"\w+", w)
        if tokens:
            parts.append('"' + " ".join(tokens) + '"*')
    for ph in phrases:
        tokens = re.findall(r"\w+", ph)
        if tokens:
            parts.append('"' + " ".join(tokens) + '"')
    return " AND ".join(parts) or None


def _search_date(value: str, now: float, end: bool = False) -> float:
    """YYYY-MM-DD (UTC), `today`, `yesterday`, or a relative age like 7d, 12h, 2w."""
    v = value.lower()
    day = int(now // 86400) * 86400
    rel = re.fullmatch(r"(\d+)([hdw])", v)
    if rel:
        return now - int(rel.group(1)) * {"h": 3600, "d": 86400, "w": 7 * 86400}[rel.group(2)]
    if v in ("today", "yesterday"):
        start = day - (86400 if v == "yesterday" else 0)
    else:
        m = re.fullmatch(r"(\d{4})-(\d{1,2})-(\d{1,2})", v)
        if not m:
            raise bad_request(f"dates look like 2026-10-13, today, yesterday or 7d (got {value!r})")
        import calendar
        try:
            start = calendar.timegm((int(m.group(1)), int(m.group(2)), int(m.group(3)), 0, 0, 0))
        except (ValueError, OverflowError):
            raise bad_request(f"not a date: {value!r}")
    return start + 86400 if end else start


def _resolve_people(conn, value: str) -> list[int]:
    """Who `from:` / `to:` means: a display name, handle or HF name (with or without @)."""
    name = value.lstrip("@").strip().lower()
    if not name:
        return []
    return [r["id"] for r in conn.execute("SELECT * FROM principals") if name in _mention_names(r)]


def search(conn, p: Principal, q: str = "", *, channel_id: int | None = None, sender_id: int | None = None,
           after: str | None = None, before: str | None = None, sort: str = "newest", limit: int = 20,
           offset: int = 0, now: float = 0.0) -> dict:
    """Messages matching `q` in channels the caller can read, plus channels and people whose names
    match its plain words. Plain parameters do the same as the in-query filters."""
    limit = max(1, min(int(limit), 100))
    offset = max(0, int(offset))
    if sort not in ("newest", "oldest", "relevance"):
        raise bad_request("sort must be newest, oldest or relevance")
    parsed = parse_search(q)
    where, args, applied = [], [], []
    visible = visible_channel_ids(conn, p)
    if visible is not None:
        if not visible:
            return {"messages": [], "channels": [], "people": [], "total": 0, "next_offset": None, "filters": []}
        where.append(f"m.channel_id IN ({','.join(str(int(i)) for i in visible)})")
    filters = list(parsed["filters"])
    if channel_id is not None:
        channel_for(conn, p, channel_id)
        where.append("m.channel_id = ?"); args.append(channel_id)
    if sender_id is not None:
        where.append("m.sender_id = ?"); args.append(sender_id)
    if after:
        filters.append(("after", after))
    if before:
        filters.append(("before", before))
    for op, val in filters:
        if op in ("from", "to"):
            ids = [p.id] if val.lower() in ("me", "@me") else _resolve_people(conn, val)
            if not ids:
                raise bad_request(f"nobody called {val!r}")
            marks = ",".join("?" * len(ids))
            if op == "from":
                where.append(f"m.sender_id IN ({marks})")
            else:
                where.append(f"m.id IN (SELECT message_id FROM message_mentions WHERE principal_id IN ({marks}))")
            args += ids
        elif op == "in":
            name = val.lstrip("#").lower()
            row = conn.execute("SELECT * FROM channels WHERE name = ?", (name,)).fetchone()
            if row is None or not can_see(conn, p, row):
                raise bad_request(f"no channel #{name} that you can read")
            where.append("m.channel_id = ?"); args.append(row["id"])
        elif op in ("after", "before", "on"):
            if op != "before":
                where.append("m.created_at >= ?"); args.append(_search_date(val, now))
            if op != "after":
                where.append("m.created_at < ?"); args.append(_search_date(val, now, end=(op == "on")))
        elif op == "has":
            v = val.lower()
            if v in ("file", "files", "attachment"):
                where.append("m.attachments IS NOT NULL")
            elif v in ("replies", "thread"):
                where.append("EXISTS (SELECT 1 FROM messages r WHERE r.thread_id = m.id)")
            elif v in ("mention", "mentions"):
                where.append("EXISTS (SELECT 1 FROM message_mentions mm WHERE mm.message_id = m.id)")
            elif v in ("link", "links"):
                where.append("(m.body LIKE '%http://%' OR m.body LIKE '%https://%')")
            else:
                raise bad_request("has: takes file, replies, mention or link")
        elif op == "is":
            v = val.lower()
            if v in ("reply", "replies"):
                where.append("m.thread_id IS NOT NULL")
            elif v in ("root", "top", "toplevel"):
                where.append("m.thread_id IS NULL")
            elif v in ("edited",):
                where.append("m.edited_at IS NOT NULL")
            else:
                raise bad_request("is: takes reply, root or edited")
        elif op == "by":
            v = val.lower().rstrip("s")
            kinds = {"agent": "('agent', 'system')", "bot": "('agent', 'system')", "person": "('user')",
                     "people": "('user')", "human": "('user')", "user": "('user')", "service": "('system')"}
            if v not in kinds and val.lower() not in kinds:
                raise bad_request("by: takes agent, person or service")
            where.append(f"m.sender_id IN (SELECT id FROM principals WHERE identity_type IN {kinds.get(v) or kinds[val.lower()]})")
        applied.append({"op": op, "value": val})
    fts = _fts_query(parsed["words"], parsed["phrases"])
    if not fts and not where[1 if visible is not None else 0:] and not applied:
        return {"messages": [], "channels": [], "people": [], "total": 0, "next_offset": None, "filters": []}
    base = "FROM messages m"
    if fts:
        base += " JOIN messages_fts ON messages_fts.rowid = m.id"
        # With words to match, the full-text index must drive the query. Left to itself SQLite may walk a
        # channel (or sender) index and re-run the MATCH once per message: minutes for a prefix query in
        # a 14k-message channel, which is what stalled the board on 2026-10-25. "+" turns those off.
        where = [re.sub(r"(?<![\w.+])m\.(channel_id|sender_id)\b", r"+m.\1", w) for w in where]
        where.insert(0, "messages_fts MATCH ?"); args.insert(0, fts)
    cond = " WHERE " + " AND ".join(where) if where else ""
    order = {"newest": "m.id DESC", "oldest": "m.id ASC", "relevance": "bm25(messages_fts), m.id DESC" if fts else "m.id DESC"}[sort]
    snip = "snippet(messages_fts, 0, char(2), char(3), '…', 24)" if fts else "NULL"
    try:
        total = conn.execute(f"SELECT COUNT(*) FROM (SELECT 1 {base}{cond} LIMIT 1000)", args).fetchone()[0]
        rows = conn.execute(f"SELECT m.id, {snip} {base}{cond} ORDER BY {order} LIMIT ? OFFSET ?",
                            (*args, limit, offset)).fetchall()
    except sqlite3.OperationalError as e:
        if "interrupt" in str(e):
            raise                                   # over the read time limit: the server answers 503
        raise bad_request(f"could not run this search: {e}")
    snippets = {r[0]: r[1] for r in rows}
    messages = []
    if rows:
        full = {r["id"]: r for r in conn.execute(
            MESSAGE_SELECT + f" WHERE m.id IN ({','.join(str(r[0]) for r in rows)})")}
        messages = [_message_json(full[r[0]]) for r in rows]
        _attach_mentions(conn, messages, p)
        _attach_reactions(conn, messages, p.id, p)
        _attach_pins(conn, messages, p)
        _attach_thread_summaries(conn, messages)
        channels = {}
        for m in messages:
            cid = m["channel_id"]
            if cid not in channels:
                c = _channel_json(conn, conn.execute("SELECT * FROM channels WHERE id = ?", (cid,)).fetchone())
                channels[cid] = {k: c[k] for k in ("id", "name", "kind")} | ({"members": c["members"]} if c["kind"] == "dm" else {})
            m["channel"] = channels[cid]
            m["snippet"] = snippets[m["id"]]
    # names: only for plain text, so "deploy" also finds #deploys and an agent called Deployer
    text = " ".join(parsed["words"] + parsed["phrases"]).strip().lower()
    found_channels, found_people = [], []
    if text and offset == 0:
        for row in conn.execute("SELECT * FROM channels WHERE kind != 'dm' ORDER BY archived, name"):
            if (text in row["name"] or text in (row["description"] or "").lower()) and can_see(conn, p, row):
                found_channels.append(_channel_json(conn, row))
            if len(found_channels) >= 8:
                break
        allowed = _directory_ids(conn, p)
        for row in conn.execute("SELECT * FROM principals WHERE disabled = 0 ORDER BY identity_type = 'user' DESC, display_name"):
            if (allowed is None or row["id"] in allowed) and any(text in n for n in _mention_names(row)):
                found_people.append(_brief(conn, row["id"]))
            if len(found_people) >= 8:
                break
    more = offset + len(messages) < total
    return {"messages": messages, "channels": found_channels, "people": found_people, "total": total,
            "total_capped": total >= 1000, "next_offset": offset + len(messages) if more else None, "filters": applied}


# ------------------------------------------------------------------ channel docs

MAX_DOC_BYTES = 200_000


def _doc_json(conn, p: Principal, channel) -> dict:
    row = conn.execute("SELECT * FROM channel_doc_versions WHERE channel_id = ? AND version = ?",
                       (channel["id"], channel["doc_version"])).fetchone()
    vis = _visible_id_set(conn, p)
    return {"channel_id": channel["id"], "version": channel["doc_version"], "body": row["body"] if row else "",
            "updated_by": _brief(conn, row["author_id"], vis) if row else None, "updated_at": row["created_at"] if row else None,
            "can_edit": can_post(conn, p, channel) and p.may_post and not channel["archived"]}


def _docs_enabled(conn) -> None:
    if not get_settings(conn)["channel_docs"]:
        raise forbidden("channel docs are switched off on this board (an admin can turn them on in Settings > Board)")


def get_doc(conn, p: Principal, channel_id: int) -> dict:
    """The channel's shared Markdown doc (version 0 and an empty body until someone writes it)."""
    _docs_enabled(conn)
    return _doc_json(conn, p, channel_for(conn, p, channel_id))


def save_doc(conn, p: Principal, channel_id: int, payload: Any, now: float) -> tuple[dict, bool]:
    """Replace the doc. `base_version` is the version the edit started from: if someone saved since,
    nothing is written and the 409 carries their version, so no change is ever lost silently."""
    if not isinstance(payload, dict) or not isinstance(payload.get("body"), str) or set(payload) - {"body", "base_version"}:
        raise bad_request('request body must be {"body": "...", "base_version": <version you edited>}')
    base = payload.get("base_version")
    if not isinstance(base, int) or isinstance(base, bool) or base < 0:
        raise bad_request("base_version is required: the version you started from (0 for a new doc)")
    _docs_enabled(conn)
    body = payload["body"]
    if len(body.encode()) > MAX_DOC_BYTES:
        raise ApiError(413, "too_large", f"the doc is limited to {MAX_DOC_BYTES // 1000} KB")
    channel = channel_for(conn, p, channel_id, "messages:write")
    if channel["archived"]:
        raise conflict("channel_archived", "channel is archived")
    current = _doc_json(conn, p, channel)
    if base != current["version"]:
        who = nameOf(current["updated_by"]) if current["updated_by"] else "someone"
        raise ApiError(409, "doc_conflict", f"{who} saved version {current['version']} after the version you edited "
                       f"({base}). Merge your change into theirs and save again with base_version={current['version']}.",
                       details={"current": current})
    if body == current["body"]:
        return current, False
    version = current["version"] + 1
    conn.execute("INSERT INTO channel_doc_versions (channel_id, version, body, author_id, created_at) VALUES (?, ?, ?, ?, ?)",
                 (channel_id, version, body, p.id, now))
    conn.execute("UPDATE channels SET doc_version = ? WHERE id = ?", (version, channel_id))
    audit(conn, p.id, "doc.save", f"channel:{channel_id}", {"version": version}, now)
    return _doc_json(conn, p, conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone()), True


def doc_versions(conn, p: Principal, channel_id: int) -> dict:
    """Every saved version, newest first (without bodies)."""
    _docs_enabled(conn)
    channel_for(conn, p, channel_id)
    vis = _visible_id_set(conn, p)
    return {"versions": [{"version": r["version"], "author": _brief(conn, r["author_id"], vis), "created_at": r["created_at"],
                          "size": len(r["body"].encode())}
                         for r in conn.execute("SELECT * FROM channel_doc_versions WHERE channel_id = ? ORDER BY version DESC",
                                               (channel_id,))]}


def doc_version(conn, p: Principal, channel_id: int, version: int) -> dict:
    _docs_enabled(conn)
    channel_for(conn, p, channel_id)
    vis = _visible_id_set(conn, p)
    r = conn.execute("SELECT * FROM channel_doc_versions WHERE channel_id = ? AND version = ?", (channel_id, version)).fetchone()
    if r is None:
        raise not_found("no such version")
    return {"version": r["version"], "body": r["body"], "author": _brief(conn, r["author_id"], vis), "created_at": r["created_at"]}


def nameOf(brief: dict | None) -> str:
    return (brief or {}).get("display_name") or (brief or {}).get("external_id") or "someone"


def get_message(conn, p: Principal, message_id: int) -> dict:
    """One message by id, with its channel (for links). 404 if it does not exist or you cannot read its channel."""
    if message_id < 1 or message_id > (1 << 63) - 1:
        raise not_found("no such message")
    row = conn.execute(MESSAGE_SELECT + " WHERE m.id = ?", (message_id,)).fetchone()
    if row is None:
        raise not_found("no such message")
    try:
        channel = channel_for(conn, p, row["channel_id"])
    except ApiError as e:
        if e.status == 404:
            raise not_found("no such message") from None
        raise
    out = _message_json(row)
    _attach_thread_subscriptions(conn, [out], p)
    _attach_mentions(conn, [out], p)
    _attach_reactions(conn, [out], p.id, p)
    _attach_pins(conn, [out], p)
    c = _channel_json(conn, channel)
    out["channel"] = {k: c[k] for k in ("id", "name", "kind")} | ({"members": c["members"]} if c["kind"] == "dm" else {})
    return out


def delete_channel(conn, p: Principal, channel_id: int, confirm, now: float) -> dict:
    """Delete a channel for good (admins): its messages, threads, reactions, files, doc and members.
    `confirm` must repeat the channel's name. Returns what went, plus the file keys to remove from disk."""
    if not p.is_admin:
        raise forbidden("only admins can delete channels")
    row = conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone()
    if row is None:
        raise not_found("channel not found")
    if row["kind"] == "dm":
        raise bad_request("direct messages cannot be deleted")
    if confirm != row["name"]:
        raise bad_request(f"to delete it, confirm with the channel's name ({row['name']!r})")
    in_channel = "SELECT id FROM messages WHERE channel_id = ?"
    counts = {"messages": conn.execute("SELECT COUNT(*) FROM messages WHERE channel_id = ?", (channel_id,)).fetchone()[0]}
    keys = [r[0] for r in conn.execute("SELECT storage_key FROM attachments WHERE channel_id = ?", (channel_id,))]
    counts["files"] = len(keys)
    for table in ("message_reactions", "message_mentions", "message_revisions"):
        conn.execute(f"DELETE FROM {table} WHERE message_id IN ({in_channel})", (channel_id,))
    conn.execute(f"DELETE FROM thread_reads WHERE thread_id IN ({in_channel})", (channel_id,))
    conn.execute("UPDATE messages SET reply_to = NULL, thread_id = NULL WHERE channel_id = ?", (channel_id,))
    conn.execute("DELETE FROM messages WHERE channel_id = ?", (channel_id,))
    for table in ("attachments", "channel_doc_versions", "channel_members", "channel_reads"):
        conn.execute(f"DELETE FROM {table} WHERE channel_id = ?", (channel_id,))
    for inv in conn.execute("SELECT id, channel_ids FROM invites WHERE channel_ids IS NOT NULL").fetchall():
        ids = [i for i in json.loads(inv["channel_ids"]) if i != channel_id]
        conn.execute("UPDATE invites SET channel_ids = ? WHERE id = ?", (json.dumps(ids) if ids else None, inv["id"]))
    conn.execute("DELETE FROM channels WHERE id = ?", (channel_id,))
    audit(conn, p.id, "channel.delete", f"channel:{channel_id}", {"name": row["name"], **counts}, now)
    return {"deleted": row["name"], **counts, "storage_keys": keys}


def delete_message(conn, p: Principal, channel_id: int, message_id: int, now: float) -> dict:
    """Delete a message for good (admins). A thread's first message takes its replies with it.
    Returns the ids removed and the file keys to remove from disk."""
    if not p.is_admin:
        raise forbidden("only admins can delete messages")
    channel_for(conn, p, channel_id)
    row = conn.execute("SELECT * FROM messages WHERE id = ? AND channel_id = ?", (message_id, channel_id)).fetchone()
    if row is None:
        raise not_found("no such message in this channel")
    ids = [message_id] + ([r[0] for r in conn.execute("SELECT id FROM messages WHERE thread_id = ?", (message_id,))]
                          if row["thread_id"] is None else [])
    marks = ",".join("?" * len(ids))
    att_ids = [a for r in conn.execute(f"SELECT attachments FROM messages WHERE id IN ({marks}) AND attachments IS NOT NULL", ids)
               for a in json.loads(r[0])]
    keys = []
    if att_ids:
        amarks = ",".join("?" * len(att_ids))
        keys = [r[0] for r in conn.execute(f"SELECT storage_key FROM attachments WHERE id IN ({amarks})", att_ids)]
        conn.execute(f"DELETE FROM attachments WHERE id IN ({amarks})", att_ids)
    for table in ("message_reactions", "message_mentions", "message_revisions"):
        conn.execute(f"DELETE FROM {table} WHERE message_id IN ({marks})", ids)
    conn.execute(f"DELETE FROM thread_reads WHERE thread_id IN ({marks})", ids)
    conn.execute(f"UPDATE messages SET reply_to = NULL, thread_id = NULL WHERE id IN ({marks})", ids)
    conn.execute(f"DELETE FROM messages WHERE id IN ({marks})", ids)
    audit(conn, p.id, "message.delete", f"message:{message_id}",
          {"channel": channel_id, "sender": row["sender_id"], "with_replies": len(ids) - 1}, now)
    return {"deleted": ids, "storage_keys": keys}


# ------------------------------------------------------------------ storage folders

_storage_markdown = MarkdownIt("commonmark")


@lru_cache(maxsize=256)
def _storage_references(body: str) -> tuple[tuple[str, str], ...]:
    found = []
    for block in _storage_markdown.parse(body):
        if block.type != "inline":
            continue
        for token in block.children or ():
            destination = (token.attrGet("src") if token.type == "image" else
                           token.attrGet("href") if token.type == "link_open" else None)
            if not destination:
                continue
            try:
                url = urlsplit(destination)
            except ValueError:
                continue
            prefix = "/v1/storage/"
            if url.scheme or url.netloc or not url.path.startswith(prefix):
                continue
            handle, _, path = url.path[len(prefix):].partition("/")
            if handle and path and not path.endswith("/"):
                found.append((unquote(handle), unquote(path)))
    return tuple(found)


STORAGE_SEGMENT = re.compile(r"^[^/\\\x00-\x1f]{1,128}$")


def storage_path(path) -> str:
    """A safe relative path: segments of up to 128 characters, no `.` or `..`, no control characters."""
    if not isinstance(path, str):
        raise bad_request("path must be text")
    path = path.strip("/")
    parts = path.split("/")
    if not path or len(path) > 512 or len(parts) > 24 or any(
            p in (".", "..") or not STORAGE_SEGMENT.match(p) for p in parts):
        raise bad_request("path must be like `runs/1/loss.png`: up to 24 folders, no `.`/`..`, at most 512 characters")
    return path


def storage_owner(conn, p: Principal, handle: str, write: bool, shared_path: str | None = None) -> sqlite3.Row:
    """Whose folder `handle` is, checked against what the caller may do. Owners, the person who owns an
    agent, and admins can write; guests read their own folders and individual shared files."""
    row = conn.execute("SELECT * FROM principals WHERE external_id = ? OR (hf_username IS NOT NULL AND hf_username = ?)",
                       (handle, handle)).fetchone()
    if row is None or (row["disabled"] and row["joined_via"] != "import"):
        raise not_found("no such storage folder")
    mine = row["id"] == p.id or row["owner_id"] == p.id
    if write:
        if not (mine and p.may_post) and not p.is_admin:
            raise forbidden("only the folder's owner (or an admin) can change it")
    elif p.role == "guest" and not mine and (shared_path is None or not _storage_shared(conn, p, row, shared_path)):
        raise not_found("no such storage folder")
    return row


def _storage_shared(conn, p: Principal, owner, path: str) -> bool:
    """A readable message shares one file, never its folder or its neighbours.

    The sharer must have folder read access independently of message links. Otherwise
    a guest could unlock a guessed path by posting it in their own channel or DM.
    Current messages/visibility are checked on every lookup, including download links.
    """
    rows = conn.execute(f"""SELECT m.body FROM messages m JOIN principals s ON s.id = m.sender_id
        WHERE m.channel_id IN ({VISIBLE_CHANNELS_SQL}) AND instr(m.body, '/v1/storage/') > 0
          AND (s.role != 'guest' OR s.id = :owner OR s.id = :human_owner)""",
        {"role": p.role, "pid": p.id, "owner": owner["id"], "human_owner": owner["owner_id"]})
    for message in rows:
        for handle, linked_path in _storage_references(message["body"]):
            try:
                if storage_path(linked_path) != path:
                    continue
            except ApiError:
                continue
            # Resolve aliases exactly as storage_owner does; a textual prefix is not a grant.
            linked_owner = conn.execute("SELECT id FROM principals WHERE external_id = ? "
                                        "OR (hf_username IS NOT NULL AND hf_username = ?)", (handle, handle)).fetchone()
            if linked_owner is not None and linked_owner["id"] == owner["id"]:
                return True
    return False


def storage_key(owner_id: int, path: str) -> str:
    return f"storage/{owner_id}/{path}"


def storage_usage(conn, owner_id: int) -> int:
    return conn.execute("SELECT COALESCE(SUM(size), 0) FROM storage_files WHERE owner_id = ?", (owner_id,)).fetchone()[0]


def storage_file_json(row, handle: str) -> dict:
    return {"path": row["path"], "size": row["size"], "sha256": row["sha256"], "content_type": row["content_type"],
            "updated_at": row["updated_at"], "url": f"/v1/storage/{handle}/{row['path']}"}


def _mb(n: int) -> str:
    return f"{n / 1024 ** 3:g} GB" if n >= 1024 ** 3 else f"{n / 1024 ** 2:g} MB"


def storage_check_quota(conn, owner_id: int, path: str, size: int) -> None:
    max_file, quota = storage_limits(conn)
    if size > max_file:
        raise ApiError(413, "too_large", f"files are limited to {_mb(max_file)} on this board")
    old = conn.execute("SELECT size FROM storage_files WHERE owner_id = ? AND path = ?", (owner_id, path)).fetchone()
    if storage_usage(conn, owner_id) - (old[0] if old else 0) + size > quota:
        raise ApiError(413, "quota_exceeded", f"this folder is limited to {_mb(quota)} in total on this board")
    folder = conn.execute("SELECT 1 FROM storage_files WHERE owner_id = ? AND path LIKE ? ESCAPE '\\' LIMIT 1",
                          (owner_id, path.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "/%")).fetchone()
    if folder:
        raise conflict("is_folder", f"`{path}` is a folder")


def storage_record(conn, p: Principal, owner_id: int, path: str, size: int, sha: str, content_type, now: float) -> dict:
    """Index a file that is already in the object store."""
    conn.execute("""INSERT INTO storage_files (owner_id, path, size, sha256, content_type, updated_at, updated_by)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                    ON CONFLICT (owner_id, path) DO UPDATE SET size = excluded.size, sha256 = excluded.sha256,
                    content_type = excluded.content_type, updated_at = excluded.updated_at, updated_by = excluded.updated_by""",
                 (owner_id, path, size, sha, content_type, now, p.id))
    row = conn.execute("SELECT * FROM storage_files WHERE owner_id = ? AND path = ?", (owner_id, path)).fetchone()
    handle = conn.execute("SELECT external_id FROM principals WHERE id = ?", (owner_id,)).fetchone()[0]
    return storage_file_json(row, handle)


def storage_record_checked(conn, p, owner_id, path, size, sha, content_type, now):
    # Check again on the serialized writer: parallel uploads to different paths
    # may both pass their preflight reads, but must not exceed the folder quota.
    storage_check_quota(conn, owner_id, path, size)
    return storage_record(conn, p, owner_id, path, size, sha, content_type, now)


def storage_list(conn, p: Principal, handle: str, prefix: str = "") -> dict:
    owner = storage_owner(conn, p, handle, write=False)
    prefix = storage_path(prefix) + "/" if prefix.strip("/") else ""
    rows = conn.execute("SELECT * FROM storage_files WHERE owner_id = ? AND substr(path, 1, ?) = ? ORDER BY path",
                        (owner["id"], len(prefix), prefix)).fetchall()
    return {"owner": _brief(conn, owner["id"], _visible_id_set(conn, p)), "prefix": prefix, "files": [storage_file_json(r, owner["external_id"]) for r in rows],
            "used_bytes": storage_usage(conn, owner["id"]), "quota_bytes": storage_limits(conn)[1],
            "max_file_bytes": storage_limits(conn)[0]}


def storage_lookup(conn, p: Principal, handle: str, path: str) -> tuple[dict, str]:
    path = storage_path(path)
    owner = storage_owner(conn, p, handle, write=False, shared_path=path)
    row = conn.execute("SELECT * FROM storage_files WHERE owner_id = ? AND path = ?", (owner["id"], path)).fetchone()
    if row is None:
        raise not_found(f"no file `{path}` in {handle}'s storage")
    return storage_file_json(row, owner["external_id"]), storage_key(owner["id"], path)


def storage_remove(conn, p: Principal, handle: str, path: str, now: float) -> dict:
    """Delete one file, or a whole folder (everything under `path/`). Returns the object keys to delete."""
    owner = storage_owner(conn, p, handle, write=True)
    path = storage_path(path)
    rows = conn.execute("SELECT path FROM storage_files WHERE owner_id = ? AND (path = ? OR substr(path, 1, ?) = ?)",
                        (owner["id"], path, len(path) + 1, path + "/")).fetchall()
    if not rows:
        raise not_found(f"no file or folder `{path}` in {handle}'s storage")
    paths = [r[0] for r in rows]
    conn.execute(f"DELETE FROM storage_files WHERE owner_id = ? AND path IN ({','.join('?' * len(paths))})", (owner["id"], *paths))
    audit(conn, p.id, "storage.delete", f"principal:{owner['id']}", {"path": path, "files": len(paths)}, now)
    return {"deleted": paths, "keys": [storage_key(owner["id"], x) for x in paths]}