File size: 134,832 Bytes
97ceb69
 
 
65a9f09
 
4a1ee53
b811b0d
97ceb69
b811b0d
a3a3db3
 
 
b811b0d
 
5801a0b
97ceb69
5801a0b
 
 
 
06436a6
97ceb69
b811b0d
5801a0b
 
d259a18
06436a6
 
 
b811b0d
06436a6
b811b0d
 
06436a6
 
b811b0d
 
fdfe5fc
b811b0d
06436a6
 
0830694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331cc9
0830694
a4e759b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37cb8c8
 
 
c9f88f6
37cb8c8
c9f88f6
37cb8c8
 
c9f88f6
37cb8c8
 
3331cc9
37cb8c8
 
 
 
 
 
 
 
 
 
a4e759b
 
37cb8c8
 
 
 
a4e759b
 
 
 
 
 
 
 
 
 
37cb8c8
 
a4e759b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9f88f6
 
 
 
a4e759b
d6607e9
c9f88f6
a4e759b
3e0c069
a4e759b
c9f88f6
a4e759b
 
 
d6607e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4e759b
 
 
 
3e0c069
a4e759b
c9f88f6
 
a4e759b
 
 
 
 
 
 
 
 
 
 
c9f88f6
a4e759b
c9f88f6
3e0c069
a4e759b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9f88f6
a4e759b
 
c9f88f6
a4e759b
 
 
7ea42ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4e759b
 
 
 
 
 
 
cbe3284
 
 
 
 
a4e759b
 
 
 
 
 
 
cbe3284
e15e363
97ceb69
e15e363
 
 
 
 
 
 
 
 
 
 
 
97ceb69
e15e363
0f2f162
 
 
 
 
 
 
a4e759b
0f2f162
 
 
 
 
 
c9f88f6
0f2f162
a4e759b
0f2f162
 
a4e759b
0f2f162
 
 
 
c9f88f6
0f2f162
 
 
 
 
 
c1f7b6c
a4e759b
906601c
 
 
 
c1f7b6c
e3f778e
 
 
 
 
c9f88f6
e3f778e
 
40bd1f5
 
 
e3f778e
cea6366
40bd1f5
cea6366
 
e3f778e
 
 
cea6366
e3f778e
 
 
40bd1f5
cea6366
 
e3f778e
 
 
c843485
91e71d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f2f162
91e71d6
 
 
 
 
0f2f162
 
91e71d6
 
 
0f2f162
 
 
97ceb69
 
 
91e71d6
 
11bfe67
 
 
 
 
 
 
 
91e71d6
1b50886
97ceb69
a4e759b
1b50886
a4e759b
 
65fd195
a4e759b
91e71d6
 
0f17186
0f2f162
5fcb8c6
65fd195
91e71d6
 
61f3a66
 
 
4f766d2
 
 
 
 
 
 
 
 
 
91e71d6
b353c3a
1b50886
 
 
c843485
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc18c93
97ceb69
 
 
0f2f162
 
97ceb69
0f2f162
 
 
 
97ceb69
0f2f162
97ceb69
 
 
 
 
 
 
 
 
 
 
 
 
 
c98f6cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212840b
 
 
 
 
 
 
 
7ea42ca
 
 
 
212840b
efac6da
 
 
 
 
c98f6cd
3331cc9
 
 
 
 
 
d259a18
 
 
 
3331cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efac6da
 
 
3331cc9
efac6da
3331cc9
 
d259a18
3331cc9
d259a18
 
 
 
 
 
 
 
3331cc9
 
 
d259a18
 
 
 
 
 
3331cc9
 
 
 
c98f6cd
3331cc9
7ea42ca
c98f6cd
 
 
 
 
 
 
 
 
 
efac6da
c98f6cd
7ea42ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331cc9
 
efac6da
 
7ea42ca
 
 
 
 
3331cc9
 
 
 
 
 
b432a4c
 
 
3331cc9
 
 
 
 
c98f6cd
0f2f162
97ceb69
c9f88f6
c98f6cd
3331cc9
 
 
 
 
c98f6cd
 
3331cc9
c98f6cd
3331cc9
c98f6cd
3331cc9
0f2f162
 
a4e759b
 
0f2f162
 
97ceb69
0f2f162
97ceb69
4a1ee53
97ceb69
4a1ee53
 
bc18c93
4a1ee53
97ceb69
4a1ee53
 
 
bc18c93
4a1ee53
 
 
 
 
 
 
 
 
3331cc9
97ceb69
0f2f162
3331cc9
bc18c93
4a1ee53
bc18c93
 
3331cc9
0f2f162
 
3331cc9
bc18c93
4a1ee53
 
 
 
bc18c93
4a1ee53
a4e759b
4a1ee53
bc18c93
97ceb69
4a1ee53
3331cc9
 
 
a4e759b
 
 
 
 
0f2f162
c9f88f6
 
a4e759b
0f2f162
 
3331cc9
 
0f2f162
4a1ee53
 
 
3331cc9
4a1ee53
 
bc18c93
3331cc9
0f2f162
4a1ee53
0f2f162
 
4a1ee53
bc18c93
4a1ee53
 
0f2f162
4a1ee53
 
 
 
 
0f2f162
3331cc9
0f2f162
 
 
97ceb69
4a1ee53
0f2f162
 
 
4a1ee53
 
e3f778e
0f2f162
4a1ee53
bc18c93
0f17186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f6ec9a
 
 
 
0f17186
 
 
97ceb69
 
0f17186
 
 
97ceb69
0f17186
 
6f6ec9a
 
 
 
 
 
3331cc9
6f6ec9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f17186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c843485
 
 
 
 
 
b353c3a
c843485
 
 
 
 
 
 
 
 
 
9ec351b
659b80e
9ec351b
 
 
 
 
 
 
 
 
 
 
0f2f162
97ceb69
0f2f162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ff5242
6f6ec9a
0f2f162
 
5801a0b
 
 
97ceb69
5801a0b
 
 
 
 
 
 
e1a18fd
7ea42ca
 
 
 
 
e1a18fd
 
 
 
 
 
 
e477c9c
0f17186
97ceb69
e477c9c
 
 
 
 
 
06436a6
e477c9c
 
 
 
 
 
 
 
 
06436a6
e477c9c
06436a6
 
 
 
e477c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdef757
a4e759b
 
 
 
 
 
 
 
 
 
 
 
fdef757
860f7a5
 
0f17186
7ea42ca
860f7a5
 
 
fdef757
860f7a5
 
 
3e0c069
860f7a5
 
 
 
 
 
0f2f162
3331cc9
 
 
 
efac6da
 
3331cc9
 
 
 
860f7a5
 
97ceb69
 
7ea42ca
860f7a5
 
0f2f162
 
97ceb69
0f2f162
3331cc9
 
 
 
 
 
 
d6607e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f2f162
 
860f7a5
 
965cd9a
860f7a5
e477c9c
 
 
 
0f2f162
bc18c93
c98f6cd
e477c9c
 
a4e759b
 
e477c9c
a4e759b
e477c9c
 
a4e759b
e477c9c
f6288a8
 
 
1b50886
 
 
 
 
 
 
 
 
 
 
 
c1f7b6c
1b50886
c628d79
65fd195
fdef757
a4e759b
fdef757
 
 
a4e759b
 
fdef757
 
906601c
a4e759b
 
fdef757
6f6ec9a
fdef757
 
a4e759b
 
 
 
 
 
 
 
 
 
 
 
 
 
fdef757
65fd195
 
fdef757
 
 
 
 
a4e759b
fdef757
 
 
65fd195
a4e759b
65fd195
 
 
6f6ec9a
 
 
 
 
fdef757
65fd195
 
 
c628d79
65fd195
 
c628d79
65fd195
 
c628d79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
965cd9a
c628d79
 
 
 
 
25bbd6e
 
 
 
 
 
 
 
 
1b50886
 
c628d79
 
 
65fd195
1b50886
0f17186
 
 
 
 
 
65fd195
 
1b50886
65fd195
c628d79
25bbd6e
0f2f162
 
 
 
 
c98f6cd
c1f7b6c
 
1b50886
 
65fd195
 
c628d79
 
 
0f2f162
 
 
 
f6288a8
0f2f162
 
c98f6cd
0f2f162
65fd195
 
25bbd6e
 
f6288a8
c1f7b6c
c628d79
c98f6cd
c628d79
65fd195
c628d79
 
 
 
 
65fd195
 
 
 
 
 
 
91e71d6
1b50886
65fd195
c628d79
 
1b50886
 
91ffb7f
 
 
 
 
 
 
 
7ea42ca
91ffb7f
0ff5242
91ffb7f
 
 
 
 
 
 
 
 
0ff5242
 
 
 
 
 
 
 
7ea42ca
c628d79
 
 
 
 
 
 
0ff5242
 
91ffb7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f17186
 
 
 
91ffb7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f17186
 
 
cbe3284
956021f
91ffb7f
0f17186
 
97ceb69
91ffb7f
 
c628d79
97ceb69
 
 
0f17186
 
 
 
c628d79
0f17186
 
c628d79
91ffb7f
 
 
c628d79
91ffb7f
 
 
c628d79
91ffb7f
c628d79
91ffb7f
c628d79
0f17186
91ffb7f
 
 
c628d79
 
 
 
 
97ceb69
c628d79
 
 
 
91ffb7f
c628d79
 
 
 
 
97ceb69
 
c628d79
 
 
 
 
 
 
 
91ffb7f
 
 
 
 
 
 
 
bc18c93
91ffb7f
 
 
 
cbe3284
956021f
91ffb7f
0f17186
91ffb7f
 
 
c628d79
91ffb7f
bc18c93
c628d79
db12bdc
0f17186
97ceb69
efac6da
97ceb69
0f17186
97ceb69
c628d79
0f17186
97ceb69
efac6da
7ea42ca
0f17186
7ea42ca
efac6da
 
 
 
db12bdc
0ff5242
c628d79
7ea42ca
db12bdc
 
c628d79
db12bdc
91ffb7f
bc18c93
91ffb7f
 
 
 
 
bc18c93
 
 
 
 
 
 
 
4a1ee53
bc18c93
 
91ffb7f
 
 
d9deb37
91ffb7f
 
fdfe5fc
d1592ef
bc18c93
 
91ffb7f
 
 
 
 
 
 
 
 
 
bc18c93
0f17186
 
 
bc18c93
fdfe5fc
 
 
 
d9deb37
 
bc18c93
 
 
46d3b01
 
 
bc18c93
 
b353c3a
 
80afe62
b353c3a
 
80afe62
06436a6
80afe62
91ffb7f
b353c3a
 
 
 
46d3b01
 
d9deb37
 
46d3b01
d9deb37
46d3b01
d9deb37
 
 
 
 
 
 
bc18c93
 
 
0f17186
db12bdc
91e71d6
40bd1f5
91e71d6
 
40bd1f5
91e71d6
fdfe5fc
40ea93d
fdfe5fc
40ea93d
 
 
 
 
fdfe5fc
d1592ef
 
d9deb37
 
d1592ef
d9deb37
 
 
d1592ef
 
 
 
 
 
91e71d6
 
 
91ffb7f
91e71d6
d9deb37
91ffb7f
 
d9deb37
91e71d6
 
 
91ffb7f
db12bdc
bc18c93
 
 
91ffb7f
 
 
 
 
 
 
 
 
 
bc18c93
 
 
 
91ffb7f
bc18c93
91ffb7f
bc18c93
 
 
91e71d6
 
 
 
 
 
 
 
 
 
 
 
fdfe5fc
91e71d6
 
fdfe5fc
 
91e71d6
 
 
 
 
 
25bbd6e
 
 
91e71d6
 
80afe62
 
 
25bbd6e
 
 
91e71d6
25bbd6e
 
91e71d6
80afe62
91e71d6
 
 
 
 
80afe62
 
 
91e71d6
 
 
 
91ffb7f
 
 
 
 
 
 
 
 
 
 
 
 
 
0f17186
91ffb7f
 
0f17186
91ffb7f
 
 
 
 
 
61936da
 
 
 
 
 
 
 
 
 
 
 
91e71d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f17186
91e71d6
0f17186
fdfe5fc
 
91e71d6
fdfe5fc
 
91e71d6
 
0f17186
 
91e71d6
 
91ffb7f
 
91e71d6
61936da
 
 
 
 
 
 
 
 
0f17186
91e71d6
0f17186
fdfe5fc
 
0f17186
91e71d6
 
 
 
 
 
 
 
91ffb7f
91e71d6
 
 
bc18c93
 
 
 
 
 
e3f778e
fdfe5fc
 
 
 
 
 
80afe62
 
bc18c93
80afe62
 
bc18c93
 
e3f778e
0f2f162
 
 
 
 
 
e3f778e
0f2f162
e3f778e
 
bc18c93
e3f778e
0f17186
e3f778e
0f17186
e3f778e
 
bc18c93
 
61936da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdfe5fc
61936da
05fd5fa
 
 
 
 
 
 
 
 
fdfe5fc
 
 
 
 
05fd5fa
 
61936da
 
05fd5fa
fdfe5fc
05fd5fa
 
 
61936da
 
 
 
 
 
 
 
 
 
 
97ceb69
c9f88f6
61936da
97ceb69
668271e
 
 
fdfe5fc
bc18c93
 
 
97ceb69
bc18c93
 
 
 
 
2153d2c
bc18c93
2153d2c
bc18c93
2153d2c
bc18c93
 
c843485
 
 
 
bc18c93
cea6366
06436a6
bc18c93
 
 
 
 
 
 
3e0c069
7fc3620
bc18c93
 
91e71d6
fdfe5fc
bc18c93
 
f6288a8
 
 
bc18c93
1b50886
f6288a8
25bbd6e
f6288a8
 
 
25bbd6e
e3f778e
 
40bd1f5
0f17186
 
61936da
 
c628d79
 
0f2f162
 
97ceb69
 
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
function safeRunObject(run){return run&&typeof run==='object'?run:{}}
function validRunObject(run){return Boolean(run&&typeof run==='object'&&(run.run_id||run.summary?.run_id||run.state?.run_id));}
function validRunsList(runs=[]){return (Array.isArray(runs)?runs:[]).filter(validRunObject);}
function inferredOwnerFromBucket(bucket){return bucket?String(bucket).split('/')[0]:''}
function inferredJobUrl(summary={}, detail={}){if(summary.job_url)return summary.job_url;const launch=detail.launch||{};const stateObj=detail.state||{};if(launch.job_url)return launch.job_url;if(stateObj.job_url)return stateObj.job_url;const jobId=summary.job_id||launch.job_id||stateObj.job_id;const owner=summary.created_by||summary.username||summary.owner||launch.created_by||launch.username||launch.owner||stateObj.created_by||stateObj.username||stateObj.owner||state.user?.username||inferredOwnerFromBucket(summary.bucket_source||detail.bucket_source||state.bucketSource);return jobId&&owner?`https://huggingface.co/jobs/${owner}/${jobId}`:''}
function bucketRunFileUrl(bucket,runId,relPath=''){const rel=String(relPath||'').replace(/^\/+|\/+$/g,'');return bucket&&runId?`https://huggingface.co/buckets/${bucket}/tree/runs/${runId}${rel?`/${rel}`:''}`:''}
function runValidationTerminalText(run={}){
  run=safeRunObject(run);
  return [
    run.verdict,run.validation_status,run.result_status,run.final_status,run.status,run.summary?.verdict,run.summary?.validation_status,run.summary?.result_status,run.summary?.status,
    run.state?.verdict,run.state?.validation_status,run.state?.result_status,run.state?.status,run.gate_status,run.summary?.gate_status,run.inference_gate?.status,
    run.generation_smoke?.status,run.summary?.smoke_status,run.smoke_status,run.details?.error,run.error,run.message
  ].map(x=>String(x||'').toLowerCase()).filter(Boolean).join(' ');
}
function validationLockedStatus(run={}){
  run=safeRunObject(run);
  const runId=run.run_id||run.summary?.run_id||run.state?.run_id||'';
  const terminal=runId&&typeof state!=='undefined'&&state.validationTerminalByRun?state.validationTerminalByRun[runId]:null;
  return terminal?.canonical||'';
}
function runCanonicalStatus(run={}){
  run=safeRunObject(run);
  const validation=isValidationRunSummary(run);
  const locked=validation?validationLockedStatus(run):'';
  if(locked)return locked;
  if(validation&&typeof validationPostSmokeBookkeepingFailed==='function'&&validationPostSmokeBookkeepingFailed(run))return 'full_inference_success';
  const s=String(run.status||run.summary?.status||run.state?.status||'unknown').toLowerCase();
  const gate=String(run.gate_status||run.inference_gate?.status||run.summary?.gate_status||'').toLowerCase();
  const smoke=String(run.smoke_status||run.generation_smoke?.status||run.summary?.smoke_status||'').toLowerCase();
  const text=validation?runValidationTerminalText(run):[s,gate,smoke].filter(Boolean).join(' ');
  if(text.includes('stale'))return'stale';
  if(text.includes('cancelled')||text.includes('canceled')||text.includes('stopped'))return'stopped';
  if(text.includes('manual')||text.includes('hardware')||text.includes('requires_action'))return'manual_hardware_required';
  if(text.includes('technical_blocker')||text.includes('blocker')||text.includes('blocked'))return'technical_blocker';
  if(text.includes('failed')||text.includes('failure')||text.includes('error')||text.includes('timeout'))return'failed';
  if(validation&&(text.includes('full_inference_candidate_health_passed')||text.includes('health_only')||text.includes('partial')||text.includes('warning')||text.includes('not_verified')||text.includes('completed_with_warnings')))return'partial_validation';
  if(!validation&&(s==='full_inference_candidate_health_passed'||s==='health_only'||s==='partial'||s==='partial_validation'||s==='completed_with_warnings'))return'partial_validation';
  if(text.includes('success')||text.includes('succeed')||text.includes('passed')||['done','completed','full_inference_success','repair_success'].includes(s))return'full_inference_success';
  if(text.includes('running')||text.includes('queued')||text.includes('pending')||text.includes('started')||text.includes('waiting')||text.includes('building'))return'running';
  return s||'unknown';
}
function truthySuccessValue(v){if(v===true)return true;const s=String(v||'').toLowerCase();return ['1','true','yes','success','passed','ok','full_inference_success'].includes(s)}
function runHasPersistedGenerationSuccess(run={}){
  run=safeRunObject(run);
  const candidates=[run,run.summary,run.state,run.inference_gate,run.generation_smoke,run.test_result,run.summary?.inference_gate,run.summary?.generation_smoke,run.state?.generation_smoke];
  for(const src of candidates){
    if(!src||typeof src!=='object')continue;
    const status=String(src.status||src.verdict||src.result_status||src.gate_status||src.smoke_status||'').toLowerCase();
    if(status==='full_inference_success'||status==='success'||status==='passed')return true;
    if(truthySuccessValue(src.ok)||truthySuccessValue(src.generation_smoke_passed)||truthySuccessValue(src.smoke_test_passed))return true;
    const signals=src.implementation_signals||src.validation||src.outcome||{};
    if(truthySuccessValue(signals.generation_smoke_passed))return true;
    const nested=src.generation_smoke||src.smoke||src.test_result||{};
    if(nested&&typeof nested==='object'){
      const ns=String(nested.status||nested.verdict||nested.result_status||'').toLowerCase();
      if(ns==='success'||ns==='passed'||ns==='full_inference_success')return true;
      if(truthySuccessValue(nested.ok)||truthySuccessValue(nested.passed))return true;
    }
  }
  return false;
}
function runHasHardTerminalProblem(run={}){
  const canon=runCanonicalStatus(run);
  return ['failed','manual_hardware_required','generated_needs_manual_hardware','technical_blocker','technical_blocker_boot_only','blocked','completed_with_warnings','auth_refresh_required','stale','stopped'].includes(canon);
}
function normalizeExplorerStatusValue(value){return String(value||'').trim().toLowerCase().replace(/\s+/g,'_')}
function explorerTextHas(text,needles=[]){text=String(text||'').toLowerCase();return needles.some(x=>text.includes(x))}
function explorerStatusTextFromRun(run={},includeNested=true){
  run=safeRunObject(run);
  const values=[run.status,run.final_status,run.verdict,run.result_status,run.validation_status,run.summary?.status,run.summary?.final_status,run.summary?.verdict,run.summary?.result_status,run.state?.status,run.state?.final_status,run.state?.verdict,run.gate_status,run.summary?.gate_status];
  if(includeNested)values.push(run.smoke_status,run.summary?.smoke_status,run.inference_gate?.status,run.generation_smoke?.status,run.summary?.generation_smoke?.status,run.summary?.inference_gate?.status,run.test_result?.status,run.summary?.test_result?.status,run.details?.error,run.error,run.message);
  return values.map(x=>String(x||'').toLowerCase()).filter(Boolean).join(' ');
}
function hasExplicitAutomaticFullInferenceSuccess(run={}){
  run=safeRunObject(run);
  const strong=[run.status,run.final_status,run.verdict,run.result_status,run.summary?.status,run.summary?.final_status,run.summary?.verdict,run.summary?.result_status,run.state?.status,run.state?.final_status,run.state?.verdict].map(normalizeExplorerStatusValue);
  return strong.some(s=>['full_inference_success','repair_success'].includes(s));
}
function hasGenericFinalSuccess(run={}){
  run=safeRunObject(run);
  const strong=[run.status,run.final_status,run.verdict,run.result_status,run.summary?.status,run.summary?.final_status,run.summary?.verdict,run.summary?.result_status,run.state?.status,run.state?.final_status,run.state?.verdict].map(normalizeExplorerStatusValue);
  return strong.some(s=>['success','succeeded','passed','done','completed'].includes(s));
}
function explicitExplorerStatus(run={}){
  run=safeRunObject(run);
  const values=[
    run.effective_run_status?.display_status,run.effective_run_status?.effective_status,run.effective_run_status?.effective_verdict,run.post_build_status,
    run.ui_status,run.display_status,run.effective_verdict,run.effective_status,
    run.summary?.effective_run_status?.display_status,run.summary?.effective_run_status?.effective_status,run.summary?.post_build_status,
    run.summary?.ui_status,run.summary?.display_status,run.summary?.effective_verdict,run.summary?.effective_status,
    run.state?.ui_status,run.state?.display_status,run.state?.effective_verdict,run.state?.effective_status,
    run.status,run.final_status,run.verdict,run.result_status
  ].map(normalizeExplorerStatusValue).filter(Boolean);
  for(const s of values){
    if(['full_inference_success','partial_validation','manual_hardware_required','generated_needs_manual_hardware','technical_blocker','technical_blocker_boot_only','blocked','completed_with_warnings','failed','stale','stopped','cancelled','canceled','auth_refresh_required','validated_after_space_test','recovered_by_space_test','validated_after_manual_space_test','recovered_by_manual_validation','demo_usable_full_promise_not_verified','interactive_app_available_smoke_failed','manual_test_required_smoke_failed','placeholder_scaffold_deployed'].includes(s))return s==='cancelled'||s==='canceled'?'stopped':s;
    if(s==='full_inference_candidate_health_passed'||s==='health_only'||s==='partial'||s==='completed_with_warnings')return 'partial_validation';
  }
  return '';
}
function protectedParentPartialStatus(run={}){
  run=safeRunObject(run);
  const parent=[run.status,run.final_status,run.verdict,run.summary?.status,run.summary?.final_status,run.summary?.verdict,run.state?.status,run.state?.final_status,run.state?.verdict].map(normalizeExplorerStatusValue);
  if(parent.some(s=>['partial_validation','full_inference_candidate_health_passed','health_only','partial','completed_with_warnings'].includes(s)))return 'partial_validation';
  return '';
}
function buildAutomaticStatus(run={}){
  run=safeRunObject(run);
  const explicit=explicitExplorerStatus(run);
  if(explicit)return explicit;
  const protectedPartial=protectedParentPartialStatus(run);
  if(protectedPartial)return protectedPartial;
  const text=explorerStatusTextFromRun(run,true);
  if(explorerTextHas(text,['auth_refresh_required','oauth_expired','auth_expired']))return 'auth_refresh_required';
  if(explorerTextHas(text,['cancelled','canceled','stopped']))return 'stopped';
  if(explorerTextHas(text,['manual_hardware_required','generated_needs_manual_hardware','waiting_manual_hardware','manual_action_required','waiting_manual_action','requires_action','hardware_required','manual hardware']))return 'manual_hardware_required';
  if(explorerTextHas(text,['technical_blocker_boot_only']))return 'technical_blocker_boot_only';
  if(explorerTextHas(text,['technical_blocker','technical blocker','blocked','blocker']))return 'technical_blocker';
  if(hasExplicitAutomaticFullInferenceSuccess(run))return 'full_inference_success';
  const topText=explorerStatusTextFromRun(run,false);
  if(explorerTextHas(topText,['running','queued','pending','started','waiting','building','scheduled']))return 'running';
  if(explorerTextHas(text,['partial_validation','full_inference_candidate_health_passed','health_only','partial','not_verified','warning','completed_with_warnings']))return 'partial_validation';
  if(explorerTextHas(text,['failed','failure','error','timeout','exception','repair_failed']))return 'failed';
  if(explorerTextHas(text,['stale']))return 'stale';
  if(hasGenericFinalSuccess(run))return 'full_inference_success';
  return normalizeExplorerStatusValue(run.status||run.summary?.status||run.state?.status||'unknown')||'unknown';
}
function validationExplorerStatus(run={}){
  const canon=runCanonicalStatus(run);
  const label=runCompactStatusLabel(canon);
  return {automatic_status:canon,validation_status:canon,display_status:canon,display_label:label,display_tone:statusClass(canon),filter_buckets:explorerFilterBuckets(canon),is_terminal:runIsFinished(canon),is_deletable:runCanBeDeleted(canon),search_tokens:[canon,label,'linked validation','space test']};
}
function linkedValidationOutcome(run={}){
  const manual=buildManualValidationStatus(run);
  let status='none';
  if(manual.passed)status='passed';
  else if(manual.failed)status='failed';
  else if(manual.linkedCount)status='attempted';
  return {...manual,status};
}
function composeBuildDisplayStatus(automaticStatus,validation={}){
  const auto=normalizeExplorerStatusValue(automaticStatus||'unknown');
  const explicitEffective=normalizeExplorerStatusValue(validation?.explicit?.effective_status||validation?.explicit?.effective_verdict||validation?.explicit?.legacy_effective_status||validation?.latest?.effective_status||'');
  const newSpaceTest=explicitEffective==='validated_after_space_test'||explicitEffective==='recovered_by_space_test'||String(validation?.explicit?.schema_version||'').includes('post_build_validation');
  const validatedToken=newSpaceTest?'validated_after_space_test':'validated_after_manual_space_test';
  const recoveredToken=newSpaceTest?'recovered_by_space_test':'recovered_by_manual_validation';
  if(validation?.passed){
    if(['recovered_by_space_test','recovered_by_manual_validation','validated_after_space_test','validated_after_manual_space_test','manual_validated'].includes(auto))return auto;
    if(['failed','technical_blocker','technical_blocker_boot_only'].includes(auto))return recoveredToken;
    if(auto==='manual_hardware_required')return 'manual_validated';
    if(['partial_validation','health_only','full_inference_candidate_health_passed','completed_with_warnings','demo_usable_full_promise_not_verified','interactive_app_available_smoke_failed','manual_test_required_smoke_failed','placeholder_scaffold_deployed','stale','unknown'].includes(auto))return validatedToken;
    if(auto==='full_inference_success')return 'full_inference_success';
    return validatedToken;
  }
  return auto;
}
function buildStatusWithoutLinkedValidation(parent={}){
  parent=safeRunObject(parent);
  return buildAutomaticStatus({
    ...parent,
    display_status:'',
    effective_status:'',
    effective_verdict:'',
    post_build_status:'',
    effective_run_status:{},
    post_build_validation:{},
    post_build_validation_status:{},
    manual_validation_status:{},
    manual_validation_passed:false,
    linked_validations:{},
    linked_validation_count:0,
    linked_validations_count:0
  });
}
function linkedValidationPromotedStatusForParent(parent={},validationSummary={}){
  const auto=buildStatusWithoutLinkedValidation(parent);
  const explicit=normalizeExplorerStatusValue(
    validationSummary.effective_status||
    validationSummary.effective_verdict||
    validationSummary.display_status||
    validationSummary.post_build_status||
    validationSummary.effective_run_status?.display_status||
    validationSummary.effective_run_status?.effective_status||
    validationSummary.post_build_validation?.effective_status||
    validationSummary.post_build_validation?.display_status||
    validationSummary.manual_validation_status?.effective_status||
    ''
  );
  if(['failed','technical_blocker','technical_blocker_boot_only','blocked','auth_refresh_required'].includes(auto))return 'recovered_by_space_test';
  if(auto==='manual_hardware_required')return 'manual_validated';
  if(['recovered_by_space_test','validated_after_space_test','recovered_by_manual_validation','validated_after_manual_space_test','manual_validated'].includes(explicit))return explicit;
  return 'validated_after_space_test';
}
function explorerDisplayLabel(status){
  const s=normalizeExplorerStatusValue(status||'unknown');
  const labels={
    full_inference_success:'Success',
    partial_validation:'Partial',partial:'Partial',health_only:'Partial',full_inference_candidate_health_passed:'Partial',completed_with_warnings:'Partial',demo_usable_full_promise_not_verified:'Demo usable',interactive_app_available_smoke_failed:'Smoke input issue',manual_test_required_smoke_failed:'Space Test recommended',placeholder_scaffold_deployed:'Placeholder demo',
    manual_hardware_required:'Manual',manual_validated:'Manual validated',
    validated_after_space_test:'Validated after Space Test',validated_after_manual_space_test:'Validated',manual_validation_passed:'Validated',validated:'Validated',
    recovered_by_space_test:'Recovered by Space Test',recovered_by_manual_validation:'Recovered',
    failed:'Failed',technical_blocker:'Blocked',technical_blocker_boot_only:'Blocked',blocked:'Blocked',
    auth_refresh_required:'Auth required',oauth_expired:'Auth required',stale:'Stale',stopped:'Stopped',cancelled:'Stopped',canceled:'Stopped',
    running:'Running',queued:'Running',pending:'Running',started:'Running',building:'Running',waiting:'Running',scheduled:'Running',unknown:'Unknown'
  };
  return labels[s]||badgeLabel(s);
}
function explorerFilterBuckets(status){
  const s=normalizeExplorerStatusValue(status||'unknown');
  const buckets=new Set(['all']);
  if(['running','queued','pending','started','building','waiting','scheduled'].includes(s))buckets.add('running');
  else if(s==='full_inference_success')buckets.add('full_inference_success');
  else if(['validated_after_space_test','validated_after_manual_space_test','manual_validation_passed','validated'].includes(s)){buckets.add('validated_after_manual_space_test');buckets.add('validated_after_space_test');}
  else if(s==='manual_validated'){buckets.add('manual_hardware_required');buckets.add('validated_after_manual_space_test');}
  else if(['recovered_by_space_test','recovered_by_manual_validation'].includes(s)){buckets.add('recovered_by_manual_validation');buckets.add('recovered_by_space_test');buckets.add('validated_after_manual_space_test');}
  else if(['partial_validation','partial','health_only','full_inference_candidate_health_passed','completed_with_warnings','demo_usable_full_promise_not_verified','interactive_app_available_smoke_failed','manual_test_required_smoke_failed','placeholder_scaffold_deployed'].includes(s))buckets.add('partial_validation');
  else if(['manual_hardware_required','generated_needs_manual_hardware','waiting_manual_hardware','manual_action_required','waiting_manual_action','requires_action','hardware_required'].includes(s))buckets.add('manual_hardware_required');
  else if(['technical_blocker','technical_blocker_boot_only','blocked','auth_refresh_required','oauth_expired'].includes(s)){buckets.add('technical_blocker');buckets.add('failed');}
  else if(['failed','failure','error','timeout','exception','repair_failed'].includes(s))buckets.add('failed');
  else if(s==='stale')buckets.add('stale');
  else if(['stopped','cancelled','canceled'].includes(s))buckets.add('stopped');
  else buckets.add(s||'unknown');
  return buckets;
}
function buildExplorerStatus(run={}){
  run=safeRunObject(run);
  if(isValidationRunSummary(run))return validationExplorerStatus(run);
  const automaticStatus=buildAutomaticStatus(run);
  const validation=linkedValidationOutcome(run);
  const displayStatus=composeBuildDisplayStatus(automaticStatus,validation);
  const label=explorerDisplayLabel(displayStatus);
  const buckets=explorerFilterBuckets(displayStatus);
  const isTerminal=runIsFinished(displayStatus)||(!buckets.has('running')&&displayStatus!=='unknown')||displayStatus==='unknown';
  const tokens=[
    run.run_id,run.model_id,run.target_space,run.kind,run.selected_hardware,run.requested_hardware,run.preferred_space_hardware,
    automaticStatus,displayStatus,label,run.status,run.effective_status,run.effective_run_status?.display_status,run.summary?.status,run.summary?.effective_status,run.summary?.effective_run_status?.display_status,run.state?.status,
    validation.status,validation.latest?.run_id,validation.latest?.validation_run_id,validation.latest?.hardware_used_for_validation,validation.explicit?.hardware_used_for_validation,
    validation.passed?'linked space test passed validated space test success':'',validation.failed?'linked space test failed validation failed':'',
    validation.linkedCount?'linked validation space test':'',displayStatus==='manual_validated'?'manual gpu manual hardware validated':'',['recovered_by_space_test','recovered_by_manual_validation'].includes(displayStatus)?'recovered recovery space test':'',
  ];
  return {raw_status:run.status||run.summary?.status||run.state?.status||'unknown',automatic_status:automaticStatus,validation_status:validation.status,validation,display_status:displayStatus,display_label:label,display_tone:statusClass(displayStatus),filter_buckets:buckets,is_terminal:isTerminal,is_deletable:runCanBeDeleted(displayStatus),status_reason:label,search_tokens:tokens.map(x=>String(x||'').toLowerCase()).filter(Boolean)};
}
function explorerStatusStabilityRank(status=''){
  const s=normalizeExplorerStatusValue(status);
  if(['recovered_by_space_test','recovered_by_manual_validation','validated_after_space_test','validated_after_manual_space_test','manual_validated','manual_validation_passed','validated'].includes(s))return 70;
  if(s==='full_inference_success')return 65;
  if(['failed','technical_blocker','technical_blocker_boot_only','blocked','manual_hardware_required','generated_needs_manual_hardware','auth_refresh_required','stale','stopped','cancelled','canceled'].includes(s))return 60;
  if(['partial_validation','partial','health_only','completed_with_warnings','demo_usable_full_promise_not_verified','interactive_app_available_smoke_failed','manual_test_required_smoke_failed','placeholder_scaffold_deployed'].includes(s))return 30;
  if(['running','queued','pending','started','building','waiting','scheduled'].includes(s))return 10;
  return 0;
}
function mergeRunExplorerStableFacts(incoming={},cached={}){
  incoming=safeRunObject(incoming);
  cached=safeRunObject(cached);
  if(!validRunObject(incoming))return incoming;
  const runId=incoming.run_id||incoming.summary?.run_id||cached.run_id||cached.summary?.run_id||'';
  let merged={
    ...cached,
    ...incoming,
    run_id:runId||incoming.run_id||cached.run_id,
    summary:{...(cached.summary||{}),...(incoming.summary||{})},
    state:{...(cached.state||{}),...(incoming.state||{})},
    effective_run_status:{...(cached.effective_run_status||{}),...(incoming.effective_run_status||{})},
  };
  if(!isValidationRunSummary(merged)){
    const incomingSaysNoLinked=linkedValidationMetadataExplicitlyEmpty(incoming);
    const rows=incomingSaysNoLinked?[]:dedupeLinkedValidationRows([
      ...linkedValidationRowsFromMetadata(cached),
      ...linkedValidationRowsFromMetadata(incoming),
      ...linkedValidationsForBuild(runId)
    ]).filter(linkedValidationIsTerminalForAccounting);
    if(rows.length||incomingSaysNoLinked){
      merged={
        ...merged,
        linked_validations:{...(cached.linked_validations||{}),...(incoming.linked_validations||{}),parent_build_run_id:runId,validations:rows,count:rows.length},
        linked_validation_count:rows.length,
        linked_validations_count:rows.length,
      };
      if(rows.some(linkedValidationPassedForAccounting)){
        const promoted=linkedValidationPromotedStatusForParent(merged,rows.find(linkedValidationPassedForAccounting)||{});
        merged={
          ...merged,
          manual_validation_passed:true,
          manual_validation_status:{...(merged.manual_validation_status||{}),status:'success',effective_status:promoted,linked_count:rows.length,linked_validations:{parent_build_run_id:runId,validations:rows,count:rows.length}},
          effective_run_status:{...(merged.effective_run_status||{}),display_status:promoted,effective_status:promoted,effective_verdict:promoted,post_build_status:promoted},
          post_build_status:promoted,
          effective_status:promoted,
        };
      }else if(incomingSaysNoLinked){
        merged={
          ...merged,
          manual_validation_passed:false,
          manual_validation_status:{},
          post_build_validation:{},
          post_build_status:'',
          effective_status:'',
          effective_run_status:{...(incoming.effective_run_status||{})},
        };
      }
    }
    const cachedStatus=buildExplorerStatus(cached).display_status;
    const mergedStatus=buildExplorerStatus(merged).display_status;
    if(explorerStatusStabilityRank(cachedStatus)>explorerStatusStabilityRank(mergedStatus)&&!linkedValidationMetadataExplicitlyEmpty(incoming)){
      merged={
        ...merged,
        status:cached.status||merged.status,
        display_status:cached.display_status||merged.display_status,
        effective_status:cached.effective_status||merged.effective_status,
        post_build_status:cached.post_build_status||merged.post_build_status,
        effective_run_status:{...(merged.effective_run_status||{}),...(cached.effective_run_status||{})},
        manual_validation_passed:cached.manual_validation_passed||merged.manual_validation_passed,
        manual_validation_status:Object.keys(cached.manual_validation_status||{}).length?cached.manual_validation_status:merged.manual_validation_status,
      };
    }
  }
  return merged;
}
function runMatchesStatus(run,status){
  // v193 legacy audit tokens: const canon=runCanonicalStatus(run); canon==='full_inference_success'; if(status==='partial_validation')return canon==='partial_validation';
  if(!status||status==='all')return true;
  const wanted=normalizeExplorerStatusValue(status);
  const explorer=isValidationRunSummary(run)?validationExplorerStatus(run):buildExplorerStatus(run);
  return explorer.filter_buckets?.has(wanted)||explorer.display_status===wanted||explorer.validation_status===wanted;
}
function canonicalStatusForDeletion(context={}){
  const kind=context.kind==='validation'?'validation':'active';
  const detail=context.detail||{};
  const summary=context.summary||detail.summary||{};
  const merged={...(summary||{}),...(detail||{}),summary:{...(summary||{}),...(detail.summary||{})},state:{...(summary||{}),...(detail.state||{})}};
  return kind==='validation'?validationExplorerStatus(merged).display_status:buildExplorerStatus(merged).display_status;
}
function runMatchesQuery(run,query){
  run=safeRunObject(run);if(!query)return true;
  const explorer=isValidationRunSummary(run)?validationExplorerStatus(run):buildExplorerStatus(run);
  const haystack=[run.run_id,run.model_id,run.target_space,run.status,run.kind,run.selected_hardware,run.requested_hardware,run.preferred_space_hardware,...(explorer.search_tokens||[])].map(x=>String(x||'').toLowerCase()).join(' ');
  return haystack.includes(String(query).toLowerCase());
}
function runSortTimestamp(run={}){
  run=safeRunObject(run);
  const raw=run.updated_at||run.created_at||run.started_at||run.cancelled_at||'';
  const ts=Date.parse(raw);
  if(Number.isFinite(ts))return ts;
  const id=String(run.run_id||'');
  const m=id.match(/(\d{8})[-_]?(\d{6})/);
  if(m){
    const d=m[1],t=m[2];
    return Date.parse(`${d.slice(0,4)}-${d.slice(4,6)}-${d.slice(6,8)}T${t.slice(0,2)}:${t.slice(2,4)}:${t.slice(4,6)}Z`);
  }
  return 0;
}
function sortRunsNewestFirst(runs=[]){
  return [...validRunsList(runs)].sort((a,b)=>runSortTimestamp(b)-runSortTimestamp(a)||String(b.run_id||'').localeCompare(String(a.run_id||'')));
}
function filteredRuns(){
  const query=state.runSearch||'';
  return explorerPrimaryRuns().filter(run=>{
    const matchesOwn=runMatchesQuery(run,query);
    const linked=linkedValidationsForBuild(run.run_id);
    const matchesLinked=query&&linked.some(v=>runMatchesQuery(v,query));
    const status=state.runStatusFilter||'all';
    const statusMatch=runMatchesStatus(run,status);
    return statusMatch&&(matchesOwn||matchesLinked);
  });
}
function renderRunStats(){
  const query=state.runSearch||'';
  const builds=explorerPrimaryRuns().filter(r=>runMatchesQuery(r,query)||linkedValidationsForBuild(r.run_id).some(v=>runMatchesQuery(v,query)));
  const counts={all:builds.length,running:0,full_inference_success:0,validated_after_manual_space_test:0,recovered_by_manual_validation:0,recovered_by_space_test:0,partial_validation:0,manual_hardware_required:0,technical_blocker:0,failed:0,stale:0};
  for(const r of builds){
    const explorer=buildExplorerStatus(r);
    for(const key of Object.keys(counts)){
      if(key==='all')continue;
      if(explorer.filter_buckets?.has(key))counts[key]+=1;
    }
  }
  document.querySelectorAll('.filter[data-status]').forEach(btn=>{
    const status=btn.dataset.status||'all';
    const label={all:'Builds',running:'Running',full_inference_success:'Success',validated_after_manual_space_test:'Validated',recovered_by_space_test:'Recovered by Space Test',recovered_by_manual_validation:'Recovered',partial_validation:'Partial',manual_hardware_required:'Manual',failed:'Failed',technical_blocker:'Blockers',stale:'Stale'}[status]||status;
    const count=counts[status]??0;
    btn.innerHTML=`${escapeHtml(label)} <span>${count}</span>`;
    btn.classList.toggle('active',status===state.runStatusFilter);
  });
}
function runCardKind(run={}){return isValidationRunSummary(run)?'Linked test':'Build'}
function runCompactStatusLabel(status){
  // v193 compact labels still include legacy branch semantics: return 'Success' and return 'Failed'.
  const s=normalizeExplorerStatusValue(status||'unknown');
  if(['recovered_by_space_test','recovered_by_manual_validation'].includes(s))return 'Recovered';
  if(['validated_after_space_test','validated_after_manual_space_test','manual_validation_passed','manual_validated','validated'].includes(s))return 'Validated';
  return explorerDisplayLabel(s);
}
function runIsFinished(status){
  const s=String(status||'').toLowerCase();
  return Boolean(s&&(
    s.includes('success')||s.includes('succeed')||s.includes('failed')||s.includes('error')||
    s.includes('manual')||s.includes('blocker')||s.includes('stale')||
    s==='done'||s==='completed'||s==='cancelled'||s==='canceled'||s==='stopped'||s==='health_only'||s==='full_inference_candidate_health_passed'||s==='partial'||s==='partial_validation'||s==='completed_with_warnings'||s==='validated'||s==='validated_after_space_test'||s==='validated_after_manual_space_test'||s==='manual_validation_passed'||s==='manual_validated'||s==='recovered_by_space_test'||s==='recovered_by_manual_validation'||s==='auth_refresh_required'||s==='oauth_expired'
  ));
}
function runHasValidationResult(detail={},summaryOverride={}){
  const summary={...(detail.summary||{}),...(summaryOverride||{})};
  const smoke=detail.generation_smoke||detail.tests?.generation_smoke||summary.generation_smoke||detail.state?.generation_smoke||{};
  const gate=detail.inference_gate||summary.inference_gate||{};
  const schema=detail.api_schema||detail.tests?.api_schema||summary.api_schema||{};
  const events=Array.isArray(detail.events)?detail.events:(Array.isArray(summary.events)?summary.events:[]);
  const status=String(summary.status||detail.status||detail.state?.status||'').toLowerCase();
  const terminalSuccess=runMatchesStatus({status},'full_inference_success');
  return Boolean(
    Object.keys(smoke||{}).length||
    Object.keys(gate||{}).length||
    Object.keys(schema||{}).length||
    summary.smoke_test_passed||
    summary.health_passed||
    summary.latency_seconds||
    summary.observed_latency_seconds||
    terminalSuccess||
    events.some(e=>['generation_smoke','inference_gate','api_validation','repair_validation'].includes(String(e.step||''))&&['success','done','failed','warning'].includes(String(e.status||'').toLowerCase()))
  );
}

function runImplementationMode(run={},detail={}){return firstNonEmpty(run.implementation_mode,run.summary?.implementation_mode,run.state?.implementation_mode,run.launch?.implementation_mode,detail.summary?.implementation_mode,detail.state?.implementation_mode,detail.launch?.implementation_mode)}
function runRelativeTime(run={}){
  const raw=run.updated_at||run.created_at||run.started_at||run.cancelled_at||'';
  const ts=Date.parse(raw);
  if(!Number.isFinite(ts))return runStatTime(run);
  const diff=Math.max(0,Date.now()-ts);
  const mins=Math.floor(diff/60000);
  if(mins<1)return'now';
  if(mins<60)return`${mins}m ago`;
  const hrs=Math.floor(mins/60);
  if(hrs<24)return`${hrs}h ago`;
  const days=Math.floor(hrs/24);
  if(days<7)return`${days}d ago`;
  return formatTime(raw);
}
function runPrimaryTitle(run={}){
  const validation=isValidationRunSummary(run);
  if(validation)return firstNonEmpty(run.parent_build_run_id?`Validation for ${run.parent_build_run_id}`:'',run.target_space,run.space_id,run.run_id)||'Linked validation run';
  return firstNonEmpty(run.model_id,run.target_space,run.run_id)||'Build run';
}
function runSecondaryLine(run={}){
  const validation=isValidationRunSummary(run);
  if(validation){
    const parent=linkedValidationParentId(run);
    const parts=[parent?`Parent: ${parent}`:'Linked validation',firstNonEmpty(run.api_name,run.endpoint),runStatLatency(run),run.run_id].filter(Boolean);
    return parts.join(' • ');
  }
  const mode=runImplementationMode(run);
  const manual=buildManualValidationStatus(run);
  const manualText=manual.passed?'Manual validation passed':manual.failed?'Manual validation attempted':'';
  const linkedText=manual.linkedCount?`${manual.linkedCount} linked test${manual.linkedCount===1?'':'s'}`:'';
  const policy=runSpaceTestPolicy(run);
  const policyText=policy.mode==='complete'?'Can complete with Space Test':policy.mode==='recover'?'Can recover with Space Test':policy.mode==='blocked'?policy.label:'';
  const parts=[manualText,linkedText,policyText,run.target_space,mode?'Goal: '+implementationModeLabel(mode,{short:true}):'',run.selected_hardware].filter(Boolean);
  return parts.join(' • ');
}
function runListSecondaryLine(run={},manual={linkedCount:0}){
  if(!manual?.linkedCount)return runSecondaryLine(run);
  const mode=runImplementationMode(run);
  const policy=runSpaceTestPolicy(run);
  const policyText=policy.mode==='complete'?'Can complete with Space Test':policy.mode==='recover'?'Can recover with Space Test':policy.mode==='blocked'?policy.label:'';
  const parts=[policyText,run.target_space,mode?'Goal: '+implementationModeLabel(mode,{short:true}):'',run.selected_hardware].filter(Boolean);
  return parts.join(' • ');
}
function runCardMeta(run={}){return runSecondaryLine(run)}
function renderRunRows(runs,compact=false){
  return validRunsList(runs||[]).map(r=>{
    // v193 legacy validation token: const status=runCanonicalStatus(r)||r.status||'unknown'
    const validation=isValidationRunSummary(r);
    const explorerStatus=validation?validationExplorerStatus(r):buildExplorerStatus(r);
    const status=explorerStatus.display_status;
    const isLoading=state.runSelectionLoadingId&&(state.runSelectionLoadingId===(r.run_id||r.summary?.run_id));
    const tone=explorerStatus.display_tone||statusClass(status);
    const title=runPrimaryTitle(r);
    const time=runRelativeTime(r);
    const canDelete=runCanBeDeleted(status);
    const manual=validation?{linkedCount:0,passed:false,failed:false}:buildManualValidationStatus(r);
    const linkedChips=!validation&&manual.linkedCount?`<div class="linked-validation-strip ${manual.passed?'passed':manual.failed?'failed':'neutral'}"><span>${manual.passed?'Space Test passed':manual.failed?'Space Test attempted':'Space Tests'}</span><span class="linked-validation-separator" aria-hidden="true">•</span><strong>${manual.linkedCount} test${manual.linkedCount===1?'':'s'}</strong></div>`:'';
    return `<article class="run-row run-list-item ${validation?'validation-run':'build-run'} ${isLoading?'is-loading':''}" role="button" tabindex="0" data-run="${escapeHtml(r.run_id)}" title="${validation?'Linked validation run':'Build run'}" ${isLoading?'aria-busy="true"':''}>
      <span class="run-list-dot ${tone}" aria-hidden="true"></span>
      <div class="run-list-copy">
        <div class="run-list-head">
          <strong class="run-list-title" title="${escapeHtml(title)}">${escapeHtml(title)}</strong>
        </div>
        <p class="run-list-id" title="${escapeHtml(r.run_id)}"><span>${escapeHtml(r.run_id)}</span></p>
        <div class="run-list-footer">
          <div class="run-list-badges">
            <div class="run-list-status">
              <em class="run-status-pill ${isLoading?'loading':tone}" title="${escapeHtml(isLoading?'Loading details…':explorerStatus.display_label)}">${escapeHtml(isLoading?'Loading…':runCompactStatusLabel(status))}</em>
            </div>
            ${linkedChips}
          </div>
          <time class="run-list-age">${escapeHtml(time)}</time>
        </div>
      </div>
      <button class="icon-btn danger run-delete-btn" type="button" data-run-delete="${escapeHtml(r.run_id)}" title="${canDelete?'Delete this finished run':'Delete becomes available after this run finishes'}" aria-label="Delete run ${escapeHtml(r.run_id)}" ${canDelete?'':'disabled aria-disabled="true"'}>×</button>
    </article>`;
  }).join('')
}
function bindRunPagination(root){
  if(!root||root.dataset.boundPagination==='true')return;
  root.dataset.boundPagination='true';
  root.addEventListener('click',e=>{
    const btn=e.target.closest('[data-page-action]');
    if(!btn||btn.disabled)return;
    state.runPage+=(btn.dataset.pageAction==='next'?1:-1);
    renderRunsFromCache();
  });
}
function renderRunPagination(total){
  const root=$('runsPagination');
  if(!root)return;
  bindRunPagination(root);
  const perPage=state.runsPerPage||5;
  const pages=Math.max(1,Math.ceil(total/perPage));
  state.runPage=Math.min(Math.max(0,state.runPage||0),pages-1);
  if(total<=perPage){root.innerHTML='';return}
  root.innerHTML=`<button class="secondary small" data-page-action="prev" ${state.runPage<=0?'disabled':''}>‹</button><span>Page ${state.runPage+1} / ${pages}</span><button class="secondary small" data-page-action="next" ${state.runPage>=pages-1?'disabled':''}>›</button>`;
}

function isValidationRunSummary(run={}){run=safeRunObject(run);return isValidationRunDetail({summary:run,state:run,kind:run.kind,run_type:run.run_type})}
function isLinkedValidationRun(run={}){return isValidationRunSummary(run)&&Boolean(linkedValidationParentId(run));}
function isLegacyValidationRun(run={}){return isValidationRunSummary(run)&&!linkedValidationParentId(run);}

function linkedValidationParentId(run={}){
  run=safeRunObject(run);
  return run.parent_build_run_id||run.parentBuildRunId||run.summary?.parent_build_run_id||run.state?.parent_build_run_id||'';
}
function linkedValidationsForBuild(buildRunId){
  if(!buildRunId)return [];
  return validRunsList(state.runsCache||[]).filter(r=>isLinkedValidationRun(r)&&linkedValidationParentId(r)===buildRunId);
}
function linkedValidationDeleteSummary(runId,detail={}){
  const id=runId||detail.run_id||detail.summary?.run_id||'';
  const rows=linkedValidationsForBuild(id);
  return {count:rows.length,ids:rows.map(r=>r.run_id||r.summary?.run_id).filter(Boolean)};
}
function runSpaceTestPolicy(run={}){
  run=safeRunObject(run);
  return run.space_test_policy||run.summary?.space_test_policy||run.view?.space_test_policy||run.space_test?.policy||{};
}
function runNeedsLinkedValidation(run={}){
  const policy=runSpaceTestPolicy(run);
  return ['complete','recover'].includes(String(policy.mode||'').toLowerCase())&&policy.enabled!==false&&!buildManualValidationStatus(run).passed;
}

function linkedValidationRowsFromMetadata(run={}){
  run=safeRunObject(run);
  const candidates=[
    run.linked_validations,
    run.summary?.linked_validations,
    run.manual_validation_status?.linked_validations,
    run.summary?.manual_validation_status?.linked_validations
  ].filter(Boolean);
  const rows=[];
  for(const item of candidates){
    if(Array.isArray(item))rows.push(...item);
    else if(Array.isArray(item.validations))rows.push(...item.validations);
    else if(item.latest_validation)rows.push(item.latest_validation);
    else if(item.validation_run_id||item.run_id||item.status)rows.push(item);
  }
  [
    run.post_build_validation,
    run.effective_run_status?.post_build_validation,
    run.summary?.post_build_validation,
    run.summary?.effective_run_status?.post_build_validation,
    run.manual_validation_status,
    run.summary?.manual_validation_status,
  ].forEach(item=>{
    if(!item||typeof item!=='object')return;
    const hasRowId=Boolean(item.validation_run_id||item.run_id||item.summary?.run_id||item.state?.run_id);
    const hasExistingIdentifiedRows=rows.some(row=>linkedValidationRowId(row));
    if(hasRowId||(!hasExistingIdentifiedRows&&(item.status||item.effective_status)))rows.push(item);
  });
  return rows.filter(x=>{
    if(!x||typeof x!=='object')return false;
    const rowId=linkedValidationRowId(x);
    return !(rowId&&isRunLocallyDeleted(rowId));
  });
}
const LINKED_VALIDATION_RUNNING_STATUSES=new Set(['','none','unknown','unchanged','idle','pending','queued','running','started','building','waiting','scheduled']);
const LINKED_VALIDATION_TERMINAL_STATUSES=new Set(['success','passed','succeeded','full_inference_success','validated_after_space_test','validated_after_manual_space_test','recovered_by_space_test','recovered_by_manual_validation','manual_validation_passed','manual_validated','partial_validation','failed','failure','error','auth_refresh_required','stale','stopped','cancelled','canceled','manual_hardware_required','generated_needs_manual_hardware','technical_blocker','technical_blocker_boot_only','blocked','completed_with_warnings']);
const LINKED_VALIDATION_PASS_STATUSES=new Set(['success','passed','succeeded','full_inference_success','validated_after_space_test','validated_after_manual_space_test','recovered_by_space_test','recovered_by_manual_validation','manual_validation_passed','manual_validated']);
const LINKED_VALIDATION_FAIL_STATUSES=new Set(['failed','failure','error','auth_refresh_required','stale','stopped','cancelled','canceled','technical_blocker','technical_blocker_boot_only']);
function linkedValidationRowStatus(row={}){
  row=safeRunObject(row);
  const runId=linkedValidationRowId(row);
  const locked=runId&&typeof state!=='undefined'&&state.validationTerminalByRun?.[runId]?.canonical;
  if(locked)return normalizeExplorerStatusValue(locked);
  if(typeof validationPostSmokeBookkeepingFailed==='function'&&validationPostSmokeBookkeepingFailed(row))return 'full_inference_success';
  return normalizeExplorerStatusValue(row.status||row.validation_status||row.result_status||row.verdict||row.effective_status||row.summary?.status||row.state?.status||'');
}
function linkedValidationIsTerminalForAccounting(row={}){
  const st=linkedValidationRowStatus(row);
  if(LINKED_VALIDATION_RUNNING_STATUSES.has(st))return false;
  if(LINKED_VALIDATION_TERMINAL_STATUSES.has(st))return true;
  return runIsFinished(st)&&!LINKED_VALIDATION_RUNNING_STATUSES.has(st);
}
function linkedValidationPassedForAccounting(row={}){
  const st=linkedValidationRowStatus(row);
  return LINKED_VALIDATION_PASS_STATUSES.has(st);
}
function linkedValidationFailedForAccounting(row={}){
  const st=linkedValidationRowStatus(row);
  return LINKED_VALIDATION_FAIL_STATUSES.has(st);
}
function linkedValidationRowId(row={}){
  return String(row.validation_run_id||row.run_id||row.summary?.run_id||row.state?.run_id||row.id||'');
}
function linkedValidationAccountingKey(row={},idx=0){
  return linkedValidationRowId(row)||String(`${row.parent_build_run_id||''}:${row.updated_at||row.validated_at||row.created_at||idx}`);
}
function dedupeLinkedValidationRows(rows=[]){
  const seen=new Map();
  const out=[];
  const score=row=>linkedValidationPassedForAccounting(row)?3:(linkedValidationFailedForAccounting(row)?2:(linkedValidationIsTerminalForAccounting(row)?1:0));
  const stamp=row=>String(row.updated_at||row.validated_at||row.created_at||row.summary?.updated_at||row.state?.updated_at||'');
  const merge=(a,b)=>{
    const aStamp=stamp(a),bStamp=stamp(b);
    const preferB=bStamp&&(!aStamp||bStamp>=aStamp);
    const base=preferB?{...a,...b}:{...b,...a};
    return score(b)>score(a)?{...base,status:linkedValidationRowStatus(b)||base.status}:base;
  };
  (Array.isArray(rows)?rows:[]).forEach((row,idx)=>{
    if(!row||typeof row!=='object')return;
    const key=linkedValidationAccountingKey(row,idx);
    if(key&&seen.has(key)){
      const pos=seen.get(key);
      out[pos]=merge(out[pos],row);
      return;
    }
    if(key)seen.set(key,out.length);
    out.push(row);
  });
  return out;
}
function linkedValidationCountFromMetadata(run={},rows=[]){
  const explicitRows=Array.isArray(rows)?rows.filter(linkedValidationIsTerminalForAccounting):[];
  if(Array.isArray(rows))return explicitRows.length;
  const counts=[
    run.linked_validation_count,
    run.summary?.linked_validation_count,
    run.linked_validations_count,
    run.summary?.linked_validations_count,
    run.manual_validation_status?.linked_count,
    run.summary?.manual_validation_status?.linked_count,
    run.linked_validations?.count,
    run.summary?.linked_validations?.count
  ].map(Number).filter(n=>Number.isFinite(n)&&n>0);
  return Math.max(...counts,0);
}
function isExplicitZeroCount(value){
  return value===0||value==='0';
}
function linkedValidationMetadataExplicitlyEmpty(run={}){
  run=safeRunObject(run);
  const containers=[
    run.linked_validations,
    run.summary?.linked_validations,
    run.manual_validation_status?.linked_validations,
    run.summary?.manual_validation_status?.linked_validations
  ].filter(Boolean);
  const hasEmptyContainer=containers.some(item=>{
    if(!item||typeof item!=='object')return false;
    if(Array.isArray(item))return item.length===0;
    if(Array.isArray(item.validations))return item.validations.length===0;
    return isExplicitZeroCount(item.count)||isExplicitZeroCount(item.linked_count);
  });
  return hasEmptyContainer||
    isExplicitZeroCount(run.linked_validation_count)||
    isExplicitZeroCount(run.summary?.linked_validation_count)||
    isExplicitZeroCount(run.linked_validations_count)||
    isExplicitZeroCount(run.summary?.linked_validations_count);
}
function linkedValidationExplicitTerminalRow(explicit={}){
  if(!explicit||typeof explicit!=='object')return null;
  const rowId=linkedValidationRowId(explicit);
  if(rowId&&isRunLocallyDeleted(rowId))return null;
  if(!rowId){
    const nested=explicit.linked_validations||explicit.validations||{};
    if(Array.isArray(nested)&&nested.length)return null;
    if(nested&&typeof nested==='object'&&Array.isArray(nested.validations)&&nested.validations.length)return null;
  }
  return linkedValidationIsTerminalForAccounting(explicit)?explicit:null;
}
function linkedValidationTerminalRowsForBuild(run={}){
  run=safeRunObject(run);
  const metadataRows=linkedValidationRowsFromMetadata(run);
  const cacheRows=linkedValidationsForBuild(run.run_id).filter(linkedValidationIsTerminalForAccounting);
  const explicit=run.post_build_validation||run.effective_run_status?.post_build_validation||run.summary?.post_build_validation||run.summary?.effective_run_status?.post_build_validation||run.manual_validation_status||run.summary?.manual_validation_status||{};
  const explicitRow=linkedValidationExplicitTerminalRow(explicit);
  return dedupeLinkedValidationRows([...metadataRows,...cacheRows,...(explicitRow?[explicitRow]:[])]).filter(linkedValidationIsTerminalForAccounting);
}
function linkedValidationAccountingRowsForBuilds(builds=[]){
  const rows=[];
  validRunsList(builds).forEach(build=>rows.push(...linkedValidationTerminalRowsForBuild(build)));
  return dedupeLinkedValidationRows(rows).filter(linkedValidationIsTerminalForAccounting);
}
function buildManualValidationStatus(run={}){
  run=safeRunObject(run);
  const explicit=run.post_build_validation||run.effective_run_status?.post_build_validation||run.summary?.post_build_validation||run.summary?.effective_run_status?.post_build_validation||run.manual_validation_status||run.summary?.manual_validation_status||{};
  const metadataRows=linkedValidationRowsFromMetadata(run);
  const cacheRows=linkedValidationsForBuild(run.run_id).filter(linkedValidationIsTerminalForAccounting);
  const explicitRow=linkedValidationExplicitTerminalRow(explicit);
  const rows=dedupeLinkedValidationRows([...metadataRows,...cacheRows,...(explicitRow?[explicitRow]:[])]).filter(linkedValidationIsTerminalForAccounting);
  const metadataCount=linkedValidationCountFromMetadata(run,rows);
  const linkedCount=Math.max(metadataCount,rows.length);
  const passed=Boolean(
    run.manual_validation_passed||run.summary?.manual_validation_passed||
    rows.some(linkedValidationPassedForAccounting)
  );
  const failed=Boolean(rows.some(linkedValidationFailedForAccounting));
  const latest=rows[0]||{};
  return {passed,failed,linkedCount,latest,explicit,metadataRows,cacheRows,accountedRows:rows};
}
function buildEffectiveStatus(run={}){
  // Kept for legacy callers, but now delegates to the deterministic Runs Explorer status model.
  return buildExplorerStatus(run).display_status;
}
function explorerPrimaryRuns(){
  return validRunsList(state.runsCache||[]).filter(r=>!isValidationRunSummary(r));
}
function runStatTime(run={}){run=safeRunObject(run);const raw=run.updated_at||run.created_at||run.started_at||run.cancelled_at||'';return raw?formatTime(raw):'—'}
function runStatLatency(run={}){
  run=safeRunObject(run);
  const latency=run.latency_seconds||run.observed_latency_seconds||run.generation_smoke?.latency_seconds||run.generation_smoke?.observed_latency_seconds;
  return latency?fmtSeconds(Number(latency)):'';
}
function runStatLatencyValue(run={}){
  run=safeRunObject(run);
  const latency=run.latency_seconds||run.observed_latency_seconds||run.generation_smoke?.latency_seconds||run.generation_smoke?.observed_latency_seconds;
  const n=Number(latency);
  return Number.isFinite(n)&&n>0?n:null;
}
function percentile(values=[],p=0.5){
  const nums=(values||[]).map(Number).filter(n=>Number.isFinite(n)).sort((a,b)=>a-b);
  if(!nums.length)return null;
  const idx=(nums.length-1)*p;
  const lo=Math.floor(idx),hi=Math.ceil(idx);
  if(lo===hi)return nums[lo];
  return nums[lo]+(nums[hi]-nums[lo])*(idx-lo);
}
function pct(part,total){return total?`${Math.round((part/total)*100)}%`:'—'}
function runStatsIssueCounts(runs=[],linkedRows=[]){
  runs=validRunsList(runs);
  const counts={failed_builds:0,failed_linked_tests:0,manual_hardware:0,pi_model_mismatch:0,stale:0};
  counts.failed_linked_tests=dedupeLinkedValidationRows(linkedRows).filter(linkedValidationFailedForAccounting).length;
  for(const r of runs){
    const validation=isValidationRunSummary(r);
    const status=String(r.status||'').toLowerCase();
    const pi=r.pi_model_resolution||{};
    if(!validation&&runMatchesStatus(r,'failed'))counts.failed_builds++;
    if(!validation&&runMatchesStatus(r,'manual_hardware_required')) counts.manual_hardware++;
    if(!validation&&(pi.mismatch||status.includes('model_mismatch'))) counts.pi_model_mismatch++;
    if(!validation&&status.includes('stale')) counts.stale++;
  }
  return counts;
}
function runStatsCell(label,value,detail='',tone='neutral'){
  return `<div class="run-stat-cell ${escapeHtml(tone)}"><span>${escapeHtml(label)}</span><strong>${escapeHtml(value)}</strong>${detail?`<em>${escapeHtml(detail)}</em>`:''}</div>`;
}
function renderRunAggregateStats(){
  // v193 legacy stats tokens: const terminalBuilds=builds.filter(r=>!runMatchesStatus(r,'running')); buildEffectiveStatus
  const root=$('runStatsList');
  if(!root)return;
  const runs=validRunsList(state.runsCache||[]);
  const builds=runs.filter(r=>!isValidationRunSummary(r));
  const linkedRows=linkedValidationAccountingRowsForBuilds(builds);
  const validations=linkedRows;
  const runningLinked=runs.filter(r=>isLinkedValidationRun(r)&&!linkedValidationIsTerminalForAccounting(r)).length;
  const buildStatuses=builds.map(r=>({run:r,status:buildExplorerStatus(r)}));
  const runningBuilds=buildStatuses.filter(x=>x.status.filter_buckets?.has('running')).length;
  const failedBuilds=buildStatuses.filter(x=>x.status.filter_buckets?.has('failed')).length;
  const terminalBuilds=buildStatuses.filter(x=>!x.status.filter_buckets?.has('running'));
  const automaticSuccess=terminalBuilds.filter(x=>x.status.automatic_status==='full_inference_success').length;
  const successBuilds=automaticSuccess;
  const effectiveSuccess=terminalBuilds.filter(x=>['full_inference_success','validated_after_space_test','validated_after_manual_space_test','manual_validated','recovered_by_space_test','recovered_by_manual_validation'].includes(x.status.display_status)).length;
  const recoveredBuilds=terminalBuilds.filter(x=>['recovered_by_space_test','recovered_by_manual_validation'].includes(x.status.display_status)).length;
  const needsValidation=terminalBuilds.filter(x=>runNeedsLinkedValidation(x.run)).length;
  // Legacy aggregate labels kept for regression tests: Total runs / Test response time / Typical / slowest recent / Build success / Validation pass.
  // Legacy formula kept for audit readability: pct(successBuilds,terminalBuilds.length) and pct(passedValidations,terminalValidations.length).
  const passedLinked=validations.filter(linkedValidationPassedForAccounting).length;
  const terminalValidations=validations;
  const passedValidations=passedLinked;
  const latencies=validations.map(runStatLatencyValue).filter(v=>v!==null);
  const median=percentile(latencies,.5);
  const p95=percentile(latencies,.95);
  const issues=runStatsIssueCounts(runs,validations);
  const issueTotal=Object.values(issues).reduce((a,b)=>a+b,0);
  const badge=$('runStatsBadge');
  if(badge){
    badge.textContent=builds.length?`${builds.length} builds · ${validations.length} linked tests${runningLinked?` · ${runningLinked} running`:''}`:'No builds';
    badge.className='badge '+(failedBuilds||issueTotal?'warn':runningBuilds?'running':builds.length?'success':'neutral');
  }
  if(!builds.length){
    root.innerHTML='<div class="empty">No indexed Build Runs yet. Launch a build to populate stats.</div>';
    return;
  }
  const issueItems=[
    ['Failed builds',issues.failed_builds],
    ['Failed linked tests',issues.failed_linked_tests],
    ['Manual hardware',issues.manual_hardware],
    ['Pi mismatch',issues.pi_model_mismatch],
    ['Stale runs',issues.stale],
  ].filter(([,count])=>count>0);
  root.innerHTML=`
    <div class="run-stats-grid build-first-stats">
      ${runStatsCell('Build Runs',String(builds.length),`${validations.length} completed linked Space Test${validations.length===1?'':'s'}${runningLinked?` · ${runningLinked} running`:''}`,'neutral')}
      ${runStatsCell('Build status',`${runningBuilds} running`,`${failedBuilds} failed` ,failedBuilds?'warn':runningBuilds?'running':'success')}
      ${runStatsCell('Automatic success',pct(automaticSuccess,terminalBuilds.length),`${automaticSuccess}/${terminalBuilds.length} finished builds`,'success')}
      ${runStatsCell('Effective success',pct(effectiveSuccess,terminalBuilds.length),`${effectiveSuccess}/${terminalBuilds.length} after linked tests`,'success')}
      ${runStatsCell('Recovered',String(recoveredBuilds),`${needsValidation} need validation/recovery`,recoveredBuilds?'success':needsValidation?'warn':'neutral')}
    </div>
    <div class="run-stats-band linked-tests-band">
      <span>Linked Space Tests</span>
      <strong>${validations.length?`${passedLinked}/${validations.length} passed${latencies.length?` · typical ${fmtSeconds(median)} · slowest ${fmtSeconds(p95)}`:''}`:'No linked tests yet'}</strong>
    </div>
    <div class="run-stats-band ${issueItems.length?'warn':'success'}">
      <span>Things to review</span>
      <strong>${issueItems.length?issueItems.map(([label,count])=>`${count} ${label}`).join(' · '):'Nothing to review in indexed Build Runs'}</strong>
    </div>`;
}

function rememberDeletedRun(runId){
  if(!runId)return;
  state.deletedRuns=state.deletedRuns||{};
  state.deletedRuns[runId]=Date.now();
}
function isRunLocallyDeleted(runId){
  if(!runId||!state.deletedRuns)return false;
  const ts=state.deletedRuns[runId];
  if(!ts)return false;
  const ttl=10*60*1000;
  if(Date.now()-ts>ttl){delete state.deletedRuns[runId];return false;}
  return true;
}
function forgetRunEverywhere(runId){
  if(!runId)return;
  if(state.runDetailCache)delete state.runDetailCache[runId];
  if(state.runDetailRequests){
    delete state.runDetailRequests[`${runId}:light`];
    delete state.runDetailRequests[`${runId}:heavy`];
    delete state.runDetailRequests[`${runId}:snapshot:fast`];
    delete state.runDetailRequests[`${runId}:snapshot:logs`];
    if(state.runExplorerHydratedAt)delete state.runExplorerHydratedAt[runId];
    if(state.runExplorerHydrationInFlight)delete state.runExplorerHydrationInFlight[runId];
  }
  if(state.documentCache)delete state.documentCache[runId];
  if(state.latencyCache)delete state.latencyCache[runId];
  // Legacy invariant: state.runsCache=(state.runsCache||[]).filter(r=>r.run_id!==runId)
  state.runsCache=validRunsList(state.runsCache||[]).filter(r=>(r.run_id||r.summary?.run_id)!==runId);
  document.querySelectorAll(`.run-row[data-run="${CSS.escape(runId)}"]`).forEach(row=>row.remove());
}
function activeRunIds(){
  return new Set(validRunsList(state.runsCache||[]).map(r=>r.run_id||r.summary?.run_id).filter(Boolean));
}

function runExplorerNeedsBackgroundHydration(run={}){
  run=safeRunObject(run);
  if(isValidationRunSummary(run))return false;
  const runId=run.run_id||run.summary?.run_id;
  if(!runId||isRunLocallyDeleted(runId))return false;
  const canonical=buildEffectiveStatus(run);
  if(['full_inference_success','failed','manual_hardware_required','generated_needs_manual_hardware','technical_blocker','technical_blocker_boot_only','blocked','completed_with_warnings','auth_refresh_required','stale','stopped','running'].includes(canonical))return false;
  return ['partial_validation','health_only','partial','completed_with_warnings','unknown',''].includes(String(canonical||'').toLowerCase());
}
function scheduleRunExplorerBackgroundHydration(runs=[]){
  if(typeof fetchRunViewSnapshotOnce!=='function'||typeof upsertRunExplorerFromProgress!=='function')return;
  state.runExplorerHydrationInFlight=state.runExplorerHydrationInFlight||{};
  state.runExplorerHydratedAt=state.runExplorerHydratedAt||{};
  const now=Date.now();
  const candidates=validRunsList(runs).filter(run=>{
    if(!runExplorerNeedsBackgroundHydration(run))return false;
    const runId=run.run_id||run.summary?.run_id;
    const last=state.runExplorerHydratedAt[runId]||0;
    return now-last>120000;
  }).slice(0,6);
  if(!candidates.length)return;
  window.setTimeout(()=>{
    candidates.forEach((run,index)=>{
      const runId=run.run_id||run.summary?.run_id;
      if(!runId||state.runExplorerHydrationInFlight[runId])return;
      state.runExplorerHydrationInFlight[runId]=Date.now();
      state.runExplorerHydratedAt[runId]=Date.now();
      window.setTimeout(async()=>{
        try{
          const snapshot=await fetchRunViewSnapshotOnce(runId,{includeJobLogs:false});
          if(snapshot&&validRunObject({run_id:snapshot.run_id||snapshot.summary?.run_id||runId}))upsertRunExplorerFromProgress(snapshot);
        }catch(err){console.warn('background Run Explorer hydration failed',runId,err)}
        finally{delete state.runExplorerHydrationInFlight[runId];}
      },index*160);
    });
  },140);
}

function associatedSpaceFromDetail(detail={},summaryOverride={}){
  const summary={...(detail.summary||{}),...(summaryOverride||{})};
  const candidates=[summary.target_space,summary.target_space_id,detail.target_space,detail.target_space_id,detail.state?.target_space,detail.launch?.target_space,detail.links?.target_space];
  for(const value of candidates){
    const text=String(value||'').trim().replace('https://huggingface.co/spaces/','').replace(/^\/+|\/+$/g,'');
    if(text&&text.includes('/'))return text;
  }
  const urls=[summary.target_space_url,detail.target_space_url,detail.state?.target_space_url,detail.launch?.target_space_url,detail.links?.target_space_url];
  for(const url of urls){
    const text=String(url||'');
    const marker='huggingface.co/spaces/';
    if(text.includes(marker))return text.split(marker,1)[1].split('?',1)[0].split('#',1)[0].replace(/^\/+|\/+$/g,'');
  }
  return '';
}
function runCanOfferSpaceDeletion(kind,detail={},summary={}){
  const normalizedKind=String(kind||summary.kind||detail.kind||detail.state?.kind||detail.launch?.kind||'').toLowerCase();
  if(normalizedKind.includes('validation')||normalizedKind.includes('space_test'))return false;
  return Boolean(associatedSpaceFromDetail(detail,summary));
}
function runCanBeDeleted(status){
  const s=String(status||'').toLowerCase();
  if(!s||s==='unknown')return true;
  return runIsFinished(s);
}

// v105 delegated row binding preserves v98 invariant: renderRunAggregateStats();document.querySelectorAll('.run-row[data-run]')
function bindRunRowEvents(root){
  if(!root||root.dataset.boundRuns==='true')return;
  root.dataset.boundRuns='true';
  root.addEventListener('click',e=>{
    const deleteBtn=e.target.closest('[data-run-delete]');
    if(deleteBtn){e.preventDefault();e.stopPropagation();if(deleteBtn.disabled||deleteBtn.getAttribute('aria-disabled')==='true')return;const runId=deleteBtn.dataset.runDelete;const cached=cachedRunById(runId)||{};deleteRunById(runId,{kind:isValidationRunSummary(cached)?'validation':'active',detail:optimisticDetailFromSummary(cached),buttonId:null});return}
    const row=e.target.closest('.run-row[data-run]');
    if(row)selectRun(row.dataset.run);
  });
  root.addEventListener('keydown',e=>{
    if(e.key!=='Enter'&&e.key!==' ')return;
    const row=e.target.closest('.run-row[data-run]');
    if(!row||e.target.closest('[data-run-delete]'))return;
    e.preventDefault();selectRun(row.dataset.run);
  });
}
function runsLoadingMarkup(){
  return '<div class="runs-loading-state"><span class="runs-loading-orb"></span><strong>Loading runs</strong></div>';
}
function setRunsExplorerLoading(loading){
  const noCachedRuns=!validRunsList(state.runsCache||[]).length;
  for(const id of ['runsTable','runsTableHome']){
    const root=$(id);if(!root)continue;
    root.classList.toggle('is-loading',Boolean(loading));
    if(loading)root.setAttribute('aria-busy','true');
    else root.removeAttribute('aria-busy');
    if(loading&&noCachedRuns&&!root.querySelector('.run-row'))root.innerHTML=runsLoadingMarkup();
  }
}
function renderRunsFromCache(){
  state.runsCache=sortRunsNewestFirst(validRunsList(state.runsCache||[]));
  const runs=filteredRuns();
  const perPage=state.runsPerPage||5;
  state.runPage=Math.min(Math.max(0,state.runPage||0),Math.max(0,Math.ceil(runs.length/perPage)-1));
  const visible=runs.slice(state.runPage*perPage,state.runPage*perPage+perPage);
  const selectedValidation=state.centerTab==='validate'&&state.validationRunId?cachedRunById(state.validationRunId):null;
  const selectedId=linkedValidationParentId(selectedValidation)||state.runId;
  const signature=JSON.stringify({ids:visible.map(r=>[r.run_id,runCanonicalStatus(r),buildEffectiveStatus(r),r.status,r.updated_at,r.target_space,r.model_id,r.latency_seconds,r.observed_latency_seconds,r.recommended_zero_gpu_duration_seconds,r.recommended_zerogpu_duration_seconds,r.manual_validation_passed,r.effective_status,linkedValidationsForBuild(r.run_id).map(v=>[v.run_id,runCanonicalStatus(v),v.updated_at])]),filter:state.runStatusFilter,search:state.runSearch,page:state.runPage,selected:selectedId});
  for(const [id,compact] of [['runsTableHome',true],['runsTable',false]]){
    const root=$(id);if(!root)continue;bindRunRowEvents(root);
    if(root.dataset.signature!==signature){
      root.innerHTML=renderRunRows(visible,compact)||'<div class="empty">No Build Runs match this filter.</div>';
      root.dataset.signature=signature;
    }
  }
  renderRunStats();renderRunPagination(runs.length);renderRunAggregateStats();
  document.querySelectorAll('.run-row').forEach(row=>row.classList.toggle('selected',Boolean(selectedId)&&row.dataset.run===selectedId));
  if(typeof renderSpaceTestLinkedValidationRuns==='function')renderSpaceTestLinkedValidationRuns();
  scheduleRunExplorerBackgroundHydration(visible);
}


function mergeRunExplorerTerminalLocks(runs=[]){
  if(typeof state==='undefined'||!state.validationTerminalByRun)return runs||[];
  return validRunsList(runs).map(run=>{
    const validation=isValidationRunSummary(run);
    const runId=run.run_id||run.summary?.run_id||'';
    const terminal=validation&&runId?state.validationTerminalByRun[runId]:null;
    if(!terminal)return run;
    return {...run,status:terminal.canonical,validation_status:terminal.canonical,result_status:terminal.canonical,summary:{...(run.summary||{}),status:terminal.canonical,validation_status:terminal.canonical,result_status:terminal.canonical}};
  });
}
function ingestRunsResponse(data={}){
  const previousById=new Map(validRunsList(state.runsCache||[]).map(r=>[r.run_id||r.summary?.run_id,r]).filter(([id])=>Boolean(id)));
  const incoming=validRunsList(data.runs||[])
    .filter(r=>!isRunLocallyDeleted(r.run_id||r.summary?.run_id))
    .map(run=>mergeRunExplorerStableFacts(run,previousById.get(run.run_id||run.summary?.run_id)||{}));
  state.runsCache=sortRunsNewestFirst(mergeRunExplorerTerminalLocks(incoming));
  state.runsLastLoaded=Date.now();
  if(data.bucket_source)state.bucketSource=data.bucket_source;
  renderRunsFromCache();
  return state.runsCache;
}
async function loadRuns(forceNetwork=false,options={}){const quiet=Boolean(options&&options.quiet);const stale=Date.now()-(state.runsLastLoaded||0)>45000;const shouldFetch=forceNetwork||!state.runsCache.length||stale;if(!shouldFetch){if(!quiet)setRunsExplorerLoading(false);renderRunsFromCache();return state.runsCache||[]}if(state.runsLoadPromise)return state.runsLoadPromise;if(!quiet){document.querySelectorAll('.runs-panel,.full-runs-panel').forEach(x=>x.classList.add('is-refreshing'));setRunsExplorerLoading(true)}state.runsLoadPromise=apiGet(`/api/runs?limit=100&bucket_name=${encodeURIComponent(state.bucketName)}`).then(data=>{// Legacy invariant: .filter(r=>!isRunLocallyDeleted(r.run_id))
  return ingestRunsResponse(data)}).catch(e=>{if(!quiet){for(const id of ['runsTable','runsTableHome']){const root=$(id);if(root)root.textContent='Could not load runs: '+e.message}}if(forceNetwork)console.warn(e);return state.runsCache||[]}).finally(()=>{state.runsLoadPromise=null;if(!quiet){setRunsExplorerLoading(false);document.querySelectorAll('.runs-panel,.full-runs-panel').forEach(x=>x.classList.remove('is-refreshing'))}});return state.runsLoadPromise}
function cachedRunById(runId){
  if(isRunLocallyDeleted(runId))return null;
  return validRunsList(state.runsCache||[]).find(r=>(r.run_id||r.summary?.run_id)===runId)||null;
}
function optimisticDetailFromSummary(summary={}){
  if(!summary)return null;
  return {
    run_id:summary.run_id,
    bucket_source:summary.bucket_source||state.bucketSource,
    summary:{...summary,_optimistic:true},
    state:{
      status:summary.status,
      model_id:summary.model_id,
      target_space:summary.target_space,
      selected_hardware:summary.selected_hardware,
      job_id:summary.job_id,
      job_url:summary.job_url,
      kind:summary.kind,
    },
    events:summary.events||[],
    report:'',
    files:summary.files||[],
    generation_smoke:summary.generation_smoke||{},
    inference_gate:summary.inference_gate||{},
    api_schema:summary.api_schema||{},
    view:{
      run_id:summary.run_id,
      header:{
        title:summary.run_id||'Selected run',
        status:summary.status||'unknown',
        raw_status:summary.status||'unknown',
        model:summary.model_id||'—',
        space:summary.target_space||'—',
      },
      links:{
        job_url:summary.job_url||'',
        space_url:summary.target_space_url||'',
        artifacts_url:summary.artifacts_url||'',
      },
      activity:[],
    },
  };
}
function explorerStatusFromSnapshot(p={}, cached={}){
  // v193: the coarse Active Run view header must never be the only reason to promote Success. Legacy tokens: smokeStatus==='success' gateStatus==='full_inference_success' p.generation_smoke?.ok===true return explicitSummary||explicitState||viewStatus return 'full_inference_success'
  const merged={
    ...(cached||{}),
    ...(p.summary||{}),
    status:p.summary?.status||p.state?.status||p.status||cached.status||cached.summary?.status||'unknown',
    summary:{...(cached.summary||{}),...(p.summary||{})},
    state:{...(cached.state||{}),...(p.state||{})},
    inference_gate:p.inference_gate||p.summary?.inference_gate||cached.inference_gate||cached.summary?.inference_gate||{},
    generation_smoke:p.generation_smoke||p.summary?.generation_smoke||cached.generation_smoke||cached.summary?.generation_smoke||{},
    test_result:p.test_result||p.summary?.test_result||cached.test_result||cached.summary?.test_result||{},
  };
  return buildAutomaticStatus(merged);
}
function upsertRunExplorerFromProgress(p={}){
  const runId=p.run_id||p.summary?.run_id||state.runId;
  if(!runId||isRunLocallyDeleted(runId))return;
  let summary={
    ...(cachedRunById(runId)||{}),
    ...(p.summary||{}),
    run_id:runId,
    status:explorerStatusFromSnapshot(p,cachedRunById(runId)||{}),
    updated_at:p.state?.updated_at||p.summary?.updated_at||p.updated_at||new Date().toISOString(),
    model_id:p.summary?.model_id||p.state?.model_id||p.model_id,
    target_space:p.summary?.target_space||p.state?.target_space,
    target_space_url:p.summary?.target_space_url||p.links?.target_space_url||p.links?.space_url||p.view?.links?.target_space_url||p.view?.links?.space_url,
    selected_hardware:p.summary?.selected_hardware||p.state?.selected_hardware,
    latency_seconds:p.summary?.latency_seconds||p.generation_smoke?.latency_seconds||p.state?.generation_smoke?.latency_seconds,
    observed_latency_seconds:p.summary?.observed_latency_seconds||p.generation_smoke?.observed_latency_seconds||p.generation_smoke?.latency_seconds,
    recommended_zero_gpu_duration_seconds:p.summary?.recommended_zero_gpu_duration_seconds||p.generation_smoke?.recommended_zero_gpu_duration_seconds||p.generation_smoke?.recommended_zerogpu_duration_seconds,
    recommended_zerogpu_duration_seconds:p.summary?.recommended_zerogpu_duration_seconds||p.generation_smoke?.recommended_zerogpu_duration_seconds||p.generation_smoke?.recommended_zero_gpu_duration_seconds,
    kind:p.summary?.kind||p.state?.kind||'universal_model_card_builder',
    parent_build_run_id:p.summary?.parent_build_run_id||p.state?.parent_build_run_id,
    post_build_validation:p.post_build_validation||p.view?.post_build_validation||p.summary?.post_build_validation||p.effective_run_status?.post_build_validation||p.summary?.effective_run_status?.post_build_validation||{},
    post_build_validation_status:p.post_build_validation_status||p.summary?.post_build_validation_status||{},
    manual_validation_status:p.manual_validation_status||p.summary?.manual_validation_status||p.view?.manual_validation||{},
    linked_validations:p.linked_validations||p.summary?.linked_validations||{},
    linked_validation_count:p.summary?.linked_validation_count??p.linked_validation_count,
    linked_validations_count:p.summary?.linked_validations_count??p.linked_validations_count,
    effective_run_status:p.effective_run_status||p.summary?.effective_run_status||p.view?.effective_run_status||{},
    display_status:p.summary?.display_status||p.display_status||p.view?.display_status,
    manual_validation_passed:p.summary?.manual_validation_passed||p.manual_validation_status?.status==='success'||p.view?.manual_validation?.status==='success',
    effective_status:p.summary?.effective_status||p.effective_status||p.manual_validation_status?.effective_status||p.view?.effective_status,
    bucket_source:p.bucket_source||p.summary?.bucket_source||state.bucketSource,
  };
  state.runsCache=validRunsList(state.runsCache||[]);
  const idx=state.runsCache.findIndex(r=>(r.run_id||r.summary?.run_id)===runId);
  summary=mergeRunExplorerStableFacts(summary,idx>=0?state.runsCache[idx]:{});
  if(idx>=0)state.runsCache[idx]={...state.runsCache[idx],...summary};
  else state.runsCache.unshift(summary);
  const parentId=summary.parent_build_run_id||linkedValidationParentId(summary);
  if(parentId&&isValidationRunSummary(summary)){
    const parentIdx=state.runsCache.findIndex(r=>(r.run_id||r.summary?.run_id)===parentId);
    if(parentIdx>=0){
      const terminal=linkedValidationIsTerminalForAccounting(summary);
      const passed=linkedValidationPassedForAccounting(summary);
      const existingParent=state.runsCache[parentIdx]||{};
      const existingLinked=existingParent.linked_validations&&typeof existingParent.linked_validations==='object'?existingParent.linked_validations:{parent_build_run_id:parentId,validations:[]};
      const existingRows=Array.isArray(existingLinked.validations)?existingLinked.validations:[];
      const nextRows=terminal?dedupeLinkedValidationRows([...existingRows,summary]):existingRows;
      const nextLinked={...existingLinked,parent_build_run_id:parentId,validations:nextRows,updated_at:summary.updated_at||existingLinked.updated_at||''};
      const promotedStatus=passed?linkedValidationPromotedStatusForParent(existingParent,summary):'';
      if(passed)nextLinked.effective_status=promotedStatus;
      const nextEffective=passed?{
        ...(existingParent.effective_run_status||{}),
        display_status:promotedStatus,
        effective_status:promotedStatus,
        effective_verdict:promotedStatus,
        post_build_status:promotedStatus
      }:(existingParent.effective_run_status||{});
      const nextManual=passed?{
        ...(existingParent.manual_validation_status||{}),
        status:'success',
        effective_status:promotedStatus
      }:(existingParent.manual_validation_status||{});
      state.runsCache[parentIdx]={...existingParent,linked_validations:nextLinked,linked_validation_count:nextRows.filter(linkedValidationIsTerminalForAccounting).length,linked_validations_count:nextRows.filter(linkedValidationIsTerminalForAccounting).length,manual_validation_passed:existingParent.manual_validation_passed||passed,manual_validation_status:nextManual,effective_run_status:nextEffective,post_build_status:promotedStatus||existingParent.post_build_status,effective_status:promotedStatus||existingParent.effective_status,updated_at:summary.updated_at||existingParent.updated_at};
    }
  }
  state.runsLastLoaded=Date.now();
  renderRunsFromCache();
  if(typeof renderRunStats==='function')renderRunStats(state.runsCache||[]);
}
function renderRunSelectionPreview(runId){
  const cached=cachedRunById(runId);
  if(!cached)return;
  const detail=optimisticDetailFromSummary(cached);
  if(isValidationRunDetail(detail)){const parent=linkedValidationParentId(cached)||detail.summary?.parent_build_run_id||detail.state?.parent_build_run_id;if(parent){selectRun(parent);return;}showValidationRunDetail(detail);return}
  switchCenterTab('active');
  if(typeof requestSpaceTestContextResetForBuild==='function')requestSpaceTestContextResetForBuild(runId);
  renderRunDetail(detail);
  setText('progressTitle',runId);
  const explorer=buildExplorerStatus(cached);
  setText('progressStatus',explorer.display_label||'Loading');
  const statusEl=$('progressStatus');
  if(statusEl)statusEl.className='badge '+(explorer.display_tone||statusClass(explorer.display_status||''));
  setText('currentStep','Loading run details…');
  setText('lastEvent','Fetching latest events and progress…');
  setText('progressPercent',buildExplorerStatus(cached).display_status==='full_inference_success'?'100%':'—');
}
function centerTabTouchedDuringRunSelection(selectionSeq){
  return Boolean(selectionSeq&&state.centerTabUserTouchedSelectionSeq===selectionSeq);
}
function cachedRunDetail(runId,heavy=false){
  const entry=state.runDetailCache?.[runId];
  if(!entry)return null;
  const fresh=Date.now()-(entry.ts||0)<(state.runDetailCacheTtlMs||300000);
  if(!fresh)return null;
  if(heavy&&!entry.heavy)return null;
  return entry.detail||null;
}
function rememberRunDetail(runId,detail,heavy=false){
  if(!runId||!detail)return;
  state.runDetailCache=state.runDetailCache||{};
  const previous=state.runDetailCache[runId]||{};
  state.runDetailCache[runId]={detail,heavy:Boolean(heavy||previous.heavy),ts:Date.now()};
}


function restoreRunRowStatusLabel(row){
  // v193 legacy loading token: const label=runCompactStatusLabel(status||cached.status||'unknown'); pill.textContent=label
  if(!row)return;
  const runId=row.dataset.run;
  const cached=cachedRunById(runId)||{};
  const explorer=isValidationRunSummary(cached)?validationExplorerStatus(cached):buildExplorerStatus(cached);
  const status=explorer.display_status||cached.status||'unknown';
  const pill=row.querySelector('.run-status-pill');
  if(pill){
    pill.textContent=runCompactStatusLabel(status);
    pill.title=explorer.display_label||badgeLabel(status);
    const tone=explorer.display_tone||statusClass(status);
    pill.className=`run-status-pill ${tone}`;
    pill.removeAttribute('aria-busy');
  }
  const dot=row.querySelector('.run-list-dot');
  if(dot)dot.className=`run-list-dot ${explorer.display_tone||statusClass(status)}`;
}
function setCenterWorkspaceLoading(runId,loading=true){
  const workspace=document.querySelector('.center-stack');
  if(!workspace)return;
  const active=Boolean(loading&&runId);
  workspace.classList.toggle('is-run-loading',active);
  if(active){
    workspace.setAttribute('aria-busy','true');
    workspace.dataset.loadingRun=runId;
  }else{
    workspace.removeAttribute('aria-busy');
    delete workspace.dataset.loadingRun;
  }
}
function setRunSelectionLoading(runId,loading=true){
  const next=loading?runId:null;
  const previous=state.runSelectionLoadingId;
  if(previous&&!loading){
    document.querySelectorAll(`.run-row[data-run="${CSS.escape(previous)}"]`).forEach(restoreRunRowStatusLabel);
  }
  if(state.runSelectionLoadingId===next){
    setCenterWorkspaceLoading(next,Boolean(next));
    if(!loading)document.querySelectorAll('.run-row.is-loading').forEach(row=>{row.classList.remove('is-loading');row.removeAttribute('aria-busy');restoreRunRowStatusLabel(row);});
    return;
  }
  state.runSelectionLoadingId=next;
  setCenterWorkspaceLoading(next,Boolean(next));
  document.querySelectorAll('.run-row[data-run]').forEach(row=>{
    const active=Boolean(next)&&row.dataset.run===next;
    row.classList.toggle('is-loading',active);
    if(active){
      row.setAttribute('aria-busy','true');
      const pill=row.querySelector('.run-status-pill');
      if(pill){pill.textContent='Loading…';pill.title='Loading details…';pill.className='run-status-pill loading';pill.setAttribute('aria-busy','true');}
    }
    else{row.removeAttribute('aria-busy');restoreRunRowStatusLabel(row);}
  });
}
function fetchRunViewSnapshotOnce(runId,options={}){
  state.runDetailRequests=state.runDetailRequests||{};
  const includeJobLogs=Boolean(options.includeJobLogs);
  const key=`${runId}:snapshot:${includeJobLogs?'logs':'fast'}`;
  if(state.runDetailRequests[key])return state.runDetailRequests[key];
  const url=`/api/runs/${encodeURIComponent(runId)}/progress?bucket_name=${encodeURIComponent(state.bucketName)}${includeJobLogs?'&include_job_logs=1':''}`;
  const promise=apiGet(url)
    .finally(()=>{delete state.runDetailRequests[key]});
  state.runDetailRequests[key]=promise;
  return promise;
}
function renderRunViewSnapshot(snapshot={}){
  const runId=snapshot.run_id||snapshot.summary?.run_id||snapshot.view?.run_id||state.runId;
  if(runId&&state.runId&&runId!==state.runId)return;
  state.activeRunProgress=snapshot;
  if(snapshot.bucket_source)state.bucketSource=snapshot.bucket_source;
  document.body.classList.add('rendering-run-snapshot');
  try{
    if(typeof renderProgress==='function')renderProgress(snapshot);
    if(typeof renderEvents==='function')renderEvents(snapshot.events||[]);
    renderRunDetail(snapshot);
    if(typeof renderMetrics==='function')renderMetrics(snapshot);
    if(typeof renderActiveRunActions==='function')renderActiveRunActions({...snapshot.summary,bucket_source:snapshot.bucket_source},snapshot);
    if(typeof renderRunDocuments==='function')renderRunDocuments({...snapshot,summary:{...snapshot.summary,bucket_source:snapshot.bucket_source}});
    if(typeof renderAgentRecovery==='function')renderAgentRecovery(snapshot);
    if(typeof renderBlockers==='function')renderBlockers(snapshot);
    if(typeof setQuickLinks==='function')setQuickLinks({...snapshot.links,...snapshot.view?.links,bucket_source:snapshot.bucket_source,run_id:runId},snapshot);
    if(typeof upsertRunExplorerFromProgress==='function')upsertRunExplorerFromProgress(snapshot);
  }finally{
    requestAnimationFrame(()=>document.body.classList.remove('rendering-run-snapshot'));
  }
}

function fetchRunDetailOnce(runId,heavy=false){
  state.runDetailRequests=state.runDetailRequests||{};
  const key=`${runId}:${heavy?'heavy':'light'}`;
  if(state.runDetailRequests[key])return state.runDetailRequests[key];
  const promise=apiGet(`/api/runs/${encodeURIComponent(runId)}?bucket_name=${encodeURIComponent(state.bucketName)}&include_heavy=${heavy?'true':'false'}`)
    .finally(()=>{delete state.runDetailRequests[key]});
  state.runDetailRequests[key]=promise;
  return promise;
}
async function selectRun(runId){
  // Keep the user on the current tab while refreshing the selected run panel.
  // v190.9: render a cached shell immediately, then hydrate from one coherent
  // snapshot instead of light→heavy→progress fragments arriving out of order.
  // Legacy invariant: cachedHeavy||cachedLight used to hydrate fast detail; rememberRunDetail(runId,full,true) was replaced by a snapshot cache.
  // Legacy latency invariant: renderRunSelectionPreview(runId) happens before any apiGet(`/api/runs/...) detail request; include_heavy=false/include_heavy=true are no longer used in this path because the fast snapshot endpoint is coherent and does not fetch Job logs on selection; heavy run hydration failed is now covered by snapshot hydration errors.
  if(!runId)return;
  if(isRunLocallyDeleted(runId)){
    forgetRunEverywhere(runId);
    renderRunsFromCache();
    showMessage('This run was deleted and is no longer available.','warning');
    return;
  }
  const selectionSeq=(state.runSelectionSeq||0)+1;
  state.runSelectionSeq=selectionSeq;
  document.querySelectorAll('.run-row').forEach(row=>row.classList.toggle('selected',row.dataset.run===runId));
  setRunSelectionLoading(runId,true);
  const localDetail=cachedRunDetail(runId,true)||cachedRunDetail(runId,false)||optimisticDetailFromSummary(cachedRunById(runId));
  if(localDetail){
    const parentId=localDetail.parent_build_run_id||localDetail.summary?.parent_build_run_id||localDetail.state?.parent_build_run_id;
    if(isValidationRunDetail(localDetail)&&parentId){
      showMessage(`Opening parent Build Run for linked validation ${runId}.`,'info');
      runId=parentId;
    }else if(isValidationRunDetail(localDetail))showValidationRunDetail(localDetail);
    else{switchCenterTab('active');setBuildModeInspecting(runId);state.runId=runId;if(typeof requestSpaceTestContextResetForBuild==='function')requestSpaceTestContextResetForBuild(runId);renderRunDetail(localDetail);}
  }else{
    renderRunSelectionPreview(runId);
  }
  try{
    const snapshot=await fetchRunViewSnapshotOnce(runId,{includeJobLogs:false});
    if(selectionSeq!==state.runSelectionSeq)return;
    if(isRunLocallyDeleted(runId)||((snapshot.run_id||snapshot.summary?.run_id)&&runId!==(snapshot.run_id||snapshot.summary?.run_id)))return;
    rememberRunDetail(runId,snapshot,true);
    if(isValidationRunDetail(snapshot)){
      const parentId=snapshot.parent_build_run_id||snapshot.summary?.parent_build_run_id||snapshot.state?.parent_build_run_id;
      if(parentId){
        const parentSnapshot=await fetchRunViewSnapshotOnce(parentId);
        rememberRunDetail(parentId,parentSnapshot,true);
        if(!centerTabTouchedDuringRunSelection(selectionSeq)) switchCenterTab('active');
        setBuildModeInspecting(parentId);
        state.runId=parentId;
        if(typeof requestSpaceTestContextResetForBuild==='function')requestSpaceTestContextResetForBuild(parentId);
        renderRunViewSnapshot(parentSnapshot);
        setRunSelectionLoading(runId,false);
      }else{showValidationRunDetail(snapshot);setRunSelectionLoading(runId,false);}
      return;
    }
    if(!centerTabTouchedDuringRunSelection(selectionSeq)) switchCenterTab('active');
    setBuildModeInspecting(runId);
    state.runId=runId;
    if(typeof requestSpaceTestContextResetForBuild==='function')requestSpaceTestContextResetForBuild(runId);
    renderRunViewSnapshot(snapshot);
    setRunSelectionLoading(runId,false);
    const status=String(snapshot.view?.header?.status||snapshot.status||snapshot.summary?.status||snapshot.state?.status||'').toLowerCase();
    if(runCanBeDeleted(status)||TERMINAL_STATUSES.has(status)){
      if(state.poll){clearInterval(state.poll);state.poll=null;}
    }else{
      startPolling(runId,{deferFirstTick:true});
      window.setTimeout(async()=>{
        if(state.runId!==runId||selectionSeq!==state.runSelectionSeq)return;
        try{
          const logSnapshot=await fetchRunViewSnapshotOnce(runId,{includeJobLogs:true});
          if(state.runId===runId&&selectionSeq===state.runSelectionSeq)renderRunViewSnapshot(logSnapshot);
        }catch(err){console.warn('background run log hydration failed',err)}
      },900);
    }
  }catch(e){
    if(selectionSeq===state.runSelectionSeq)setRunSelectionLoading(runId,false);
    showMessage(`Could not load run snapshot: ${e.message}`,'error');
    const report=$('reportPreview');if(report)report.textContent='Could not load run snapshot: '+e.message;
  }
}
function runDeletionContext(runId,options={}){
  const kind=options.kind==='validation'?'validation':'active';
  const explicit=options.detail||{};
  const candidate=kind==='validation'?(explicit.run_id||explicit.summary?.run_id?explicit:state.validationDetail||{}):(explicit.run_id||explicit.summary?.run_id?explicit:state.selectedRunDetail||state.activeRunProgress||{});
  const summary=candidate.summary||{};
  const resolvedRunId=runId||summary.run_id||candidate.run_id||(kind==='validation'?state.validationRunId:state.runId);
  return {kind,runId:resolvedRunId,detail:candidate,summary};
}
function clearDeletedRunState(runId,kind,options={}){
  if(!runId)return;
  const deletedRunWasSpaceTestParent=kind!=='validation'&&typeof spaceTestParentBuildRunId==='function'&&spaceTestParentBuildRunId()===runId;
  if(state.runId===runId){
    if(state.poll){clearInterval(state.poll);state.poll=null}
    state.runId=null;
    state.activeRunProgress=null;
    state.selectedRunDetail=null;
    state.activeLinks={};
    clearSavedRun();
    resetRunDetails();
  }
  if(deletedRunWasSpaceTestParent&&typeof resetValidationRunView==='function'){
    resetValidationRunView({reason:'deleted'});
  }
  const deletingSelectedValidation=state.validationRunId===runId||state.validationDetail?.run_id===runId||state.validationDetail?.summary?.run_id===runId;
  if(deletingSelectedValidation){
    stopValidationPolling();
    state.validationDetail=null;
    state.validationRunId=null;
    if(typeof resetValidationRunView==='function')resetValidationRunView({reason:'deleted',preserveLinkedContext:kind==='validation'||options.preserveLinkedContext,parentBuildRunId:options.parentBuildRunId||''});
    else {
      renderValidationStatus({status:'idle',run_id:'—',events:[],message:'Validation run deleted.'});
      setText('spaceTestOutput','—');
      setText('spaceTestLatency','—');
      setText('spaceTestVerdict','Validation run deleted.');
    }
    const btn=$('deleteValidationRun');if(btn){btn.disabled=true;btn.onclick=null;}
  }else if(kind==='validation'&&typeof renderSpaceTestLinkedValidationRuns==='function'){
    renderSpaceTestLinkedValidationRuns();
  }
  if(state.selectedRunDetail?.run_id===runId||state.selectedRunDetail?.summary?.run_id===runId)state.selectedRunDetail=null;
}
function ensureDeleteRunDialog(){
  let modal=$('deleteRunDialog');
  if(modal)return modal;
  modal=document.createElement('div');
  modal.id='deleteRunDialog';
  modal.className='delete-run-modal';
  modal.hidden=true;
  modal.innerHTML=`<div class="delete-run-backdrop" data-delete-cancel></div>
    <section class="delete-run-card" role="dialog" aria-modal="true" aria-labelledby="deleteRunTitle" aria-describedby="deleteRunBody">
      <button class="delete-run-close" type="button" data-delete-cancel aria-label="Close">×</button>
      <div class="delete-run-icon" aria-hidden="true">⌫</div>
      <div class="delete-run-copy">
        <span class="delete-run-kicker" id="deleteRunKicker">Delete run</span>
        <h3 id="deleteRunTitle">Delete this run?</h3>
        <p id="deleteRunBody">This removes the run folder from your Hugging Face Storage Bucket.</p>
      </div>
      <div class="delete-run-meta" id="deleteRunMeta"></div>
      <label class="delete-space-option" id="deleteSpaceOption" hidden>
        <input type="checkbox" id="deleteAssociatedSpace" />
        <span><strong>Also delete associated Space</strong><em id="deleteAssociatedSpaceLabel">—</em></span>
      </label>
      <div class="delete-run-warning" id="deleteRunWarning" hidden></div>
      <div class="delete-run-actions">
        <button class="secondary" type="button" data-delete-cancel>Keep run</button>
        <button class="primary danger" type="button" data-delete-confirm>Delete run</button>
      </div>
    </section>`;
  document.body.appendChild(modal);
  return modal;
}
function confirmRunDeletion({runId,kind='active',status='',detail={}}={}){
  if(state.deleteModalPromise&&state.deleteModalRunId===runId)return state.deleteModalPromise;
  if(state.deleteModalPromise)return state.deleteModalPromise;
  state.deleteModalRunId=runId;
  state.deleteModalPromise=new Promise(resolve=>{
    const modal=ensureDeleteRunDialog();
    const confirmBtn=modal.querySelector('[data-delete-confirm]');
    const cancelEls=modal.querySelectorAll('[data-delete-cancel]');
    const title=$('deleteRunTitle');
    const body=$('deleteRunBody');
    const kicker=$('deleteRunKicker');
    const meta=$('deleteRunMeta');
    const warning=$('deleteRunWarning');
    const spaceOption=$('deleteSpaceOption');
    const spaceCheckbox=$('deleteAssociatedSpace');
    const spaceLabel=$('deleteAssociatedSpaceLabel');
    const normalized=canonicalStatusForDeletion({kind,detail:{...(detail||{}),status:status||detail.status,summary:{...(detail.summary||{}),status:status||detail.summary?.status}}});
    const active=runMatchesStatus({status:normalized,kind:kind==='validation'?'validate_existing_space':detail.kind,run_type:kind==='validation'?'validation':detail.run_type},'running');
    const label=kind==='validation'?'validation run':'build run';
    const associatedSpace=associatedSpaceFromDetail(detail,detail.summary||{});
    const canDeleteSpace=runCanOfferSpaceDeletion(kind,detail,detail.summary||{});
    const linkedDelete=kind==='validation'?{count:0,ids:[]}:linkedValidationDeleteSummary(runId,detail);
    kicker.textContent=kind==='validation'?'Space Test deletion':'Build run deletion';
    title.textContent=`Delete this ${label}?`;
    body.textContent=kind==='validation'
      ? 'This removes only this validation run’s linked Space Test artifacts. The parent Build Run and generated Space will not be deleted. The tested Space will not be deleted.'
      : (linkedDelete.count?`This removes this Build Run’s bucket artifacts and ${linkedDelete.count} linked Space Test validation run${linkedDelete.count===1?'':'s'}. The generated Space is kept unless you explicitly choose to delete it below.`:'This removes this Build Run’s bucket artifacts, logs, state, traces and report. The generated Space is kept unless you explicitly choose to delete it below.');
    meta.innerHTML=`<span><strong>Run</strong><code>${escapeHtml(runId||'—')}</code></span><span><strong>Type</strong>${escapeHtml(kind==='validation'?'Linked Space Test':'Build')}</span><span><strong>Status</strong>${escapeHtml(badgeLabel(normalized))}</span>${associatedSpace?`<span><strong>Space</strong><code>${escapeHtml(associatedSpace)}</code></span>`:''}${linkedDelete.count?`<span><strong>Linked tests</strong>${linkedDelete.count}</span>`:''}`;
    if(spaceOption&&spaceCheckbox&&spaceLabel){
      spaceCheckbox.checked=false;
      spaceOption.hidden=!canDeleteSpace;
      spaceLabel.textContent=associatedSpace||'No associated Space detected';
      spaceCheckbox.onchange=()=>{confirmBtn.textContent=spaceCheckbox.checked?'Delete run and Space':(active?'Delete stored files':'Delete run');warning.hidden=false;warning.textContent=spaceCheckbox.checked?`This will permanently delete the Hugging Face Space repository ${associatedSpace}. This cannot be undone.`:(active?'This run still looks active. Deleting only removes stored run files; it does not cancel a running Job.':(kind==='validation'?'Deletion is permanent for this validation run folder.':'Deletion is permanent for this run folder.'));};
    }
    warning.hidden=!active&&!canDeleteSpace;
    warning.textContent=active?'This run still looks active. Deleting only removes stored run files; it does not cancel a running Job.':(kind==='validation'?'Deletion is permanent for this validation run folder.':(canDeleteSpace?'Optional Space deletion is destructive and cannot be undone.':'Deletion is permanent for this run folder.'));
    confirmBtn.textContent=active?'Delete stored files':'Delete run';
    const previousFocus=document.activeElement;
    let done=false;
    let submitted=false;
    const close=value=>{
      if(done)return;done=true;
      modal.hidden=true;
      modal.classList.remove('is-open','is-deleting');
      document.removeEventListener('keydown',onKey);
      cancelEls.forEach(el=>{el.removeEventListener('click',onCancel);el.disabled=false;el.removeAttribute('aria-disabled')});
      confirmBtn.removeEventListener('click',onConfirm);
      confirmBtn.disabled=false;
      if(spaceCheckbox)spaceCheckbox.onchange=null;
      try{previousFocus&&previousFocus.focus&&previousFocus.focus()}catch(_){}
      state.deleteModalPromise=null;
      state.deleteModalRunId=null;
      if(!submitted)resolve(value);
    };
    const setDeleting=()=>{
      modal.classList.add('is-deleting');
      title.textContent=kind==='validation'?'Deleting this validation run…':'Deleting this run…';
      body.textContent=kind==='validation'?'Removing linked validation artifacts and refreshing the parent Build Run.':'Removing bucket artifacts and linked validation runs. The panel will reset as soon as deletion is confirmed.';
      confirmBtn.textContent='Deleting…';
      confirmBtn.disabled=true;
      cancelEls.forEach(el=>{el.disabled=true;el.setAttribute('aria-disabled','true')});
      if(warning){warning.hidden=false;warning.textContent='Deletion in progress…'}
    };
    const setError=message=>{
      modal.classList.remove('is-deleting');
      submitted=false;
      title.textContent=`Delete this ${label}?`;
      body.textContent=kind==='validation'
        ? 'This removes only this validation run’s linked Space Test artifacts. The parent Build Run and generated Space will not be deleted. The tested Space will not be deleted.'
        : (linkedDelete.count?`This removes this Build Run’s bucket artifacts and ${linkedDelete.count} linked Space Test validation run${linkedDelete.count===1?'':'s'}. The generated Space is kept unless you explicitly choose to delete it below.`:'This removes this Build Run’s bucket artifacts, logs, state, traces and report. The generated Space is kept unless you explicitly choose to delete it below.');
      confirmBtn.textContent=active?'Delete stored files':'Delete run';
      confirmBtn.disabled=false;
      cancelEls.forEach(el=>{el.disabled=false;el.removeAttribute('aria-disabled')});
      if(warning){warning.hidden=false;warning.textContent=message||'Deletion failed. You can retry or keep the run.'}
    };
    const onCancel=()=>{if(!modal.classList.contains('is-deleting'))close(false)};
    const onConfirm=()=>{if(submitted||modal.classList.contains('is-deleting'))return;submitted=true;resolve({deleteSpace:Boolean(spaceCheckbox&&spaceCheckbox.checked&&canDeleteSpace),associatedSpace,setDeleting,setError,close});};
    const onKey=e=>{if(e.key==='Escape')onCancel();if(e.key==='Enter'&&modal.classList.contains('is-open'))onConfirm()};
    cancelEls.forEach(el=>el.addEventListener('click',onCancel));
    confirmBtn.addEventListener('click',onConfirm);
    document.addEventListener('keydown',onKey);
    modal.hidden=false;
    requestAnimationFrame(()=>{modal.classList.add('is-open');confirmBtn.focus();});
  });
  return state.deleteModalPromise;
}
async function deleteRunById(runId,options={}){
  const context=runDeletionContext(runId,options);
  runId=context.runId;
  if(!runId){showMessage(context.kind==='validation'?'Select a validation run before deleting it.':'Select a run before deleting it.','warning');return}
  if(state.deletingRuns&&state.deletingRuns[runId])return;
  const status=canonicalStatusForDeletion(context);
  const confirmed=await confirmRunDeletion({runId,kind:context.kind,status,detail:{...(context.detail||{}),summary:{...(context.summary||{}),status}}});
  if(!confirmed)return;
  const deleteSpace=typeof confirmed==='object'&&Boolean(confirmed.deleteSpace);
  if(state.deletingRuns&&state.deletingRuns[runId])return;
  state.deletingRuns=state.deletingRuns||{};
  state.deletingRuns[runId]=true;
  if(confirmed&&typeof confirmed.setDeleting==='function')confirmed.setDeleting();
  const buttonId=options.buttonId===null?null:(options.buttonId||(context.kind==='validation'?'deleteValidationRun':'deleteActiveRun'));
  setButtonBusy(buttonId,true,'Deleting…');
  let success=false;
  try{
    const result=await apiDelete(`/api/runs/${encodeURIComponent(runId)}?bucket_name=${encodeURIComponent(state.bucketName)}`,deleteSpace?{delete_space:true}:{});
    const deletedChildren=Array.isArray(result.deleted_linked_validations)?result.deleted_linked_validations:[];
    const parentBuildRunId=result.parent_build_run_id||context.detail?.parent_build_run_id||context.detail?.summary?.parent_build_run_id||context.detail?.state?.parent_build_run_id||'';
    const childSuffix=deletedChildren.length?` and ${deletedChildren.length} linked validation${deletedChildren.length===1?'':'s'}`:'';
    const suffix=deleteSpace?(result.space_deleted?' and associated Space':(result.space_delete_error?' but Space deletion failed':' and Space was already missing')):'';
    showMessage(`Deleted run ${runId}${childSuffix}${suffix}`,'success');
    success=true;
    rememberDeletedRun(runId);
    deletedChildren.forEach(id=>rememberDeletedRun(id));
    if(context.kind==='validation'&&typeof forgetLinkedValidationRunFromSpaceTest==='function')forgetLinkedValidationRunFromSpaceTest(runId,parentBuildRunId);
    clearDeletedRunState(runId,context.kind,{parentBuildRunId,preserveLinkedContext:context.kind==='validation'});
    forgetRunEverywhere(runId);
    deletedChildren.forEach(id=>{clearDeletedRunState(id,'validation',{parentBuildRunId,preserveLinkedContext:true});forgetRunEverywhere(id);});
    if(context.kind==='validation'){
      if(parentBuildRunId)state.linkedValidationParent=parentBuildRunId;
      if(typeof clearSpaceTestEndpointContextForParent==='function')clearSpaceTestEndpointContextForParent(parentBuildRunId,'delete_validation');
    }
    renderRunsFromCache();
    if(typeof renderSpaceTestLinkedValidationRuns==='function')renderSpaceTestLinkedValidationRuns();
    if(confirmed&&typeof confirmed.close==='function')confirmed.close(true);
    loadRuns(true,{quiet:true,reason:'post-delete'}).catch(e=>console.warn('post-delete runs refresh failed',e));
  }catch(e){
    showMessage(e.message,true);
    if(confirmed&&typeof confirmed.setError==='function')confirmed.setError(e.message);
  }finally{
    if(state.deletingRuns)delete state.deletingRuns[runId];
    setButtonBusy(buttonId,false);
    if(buttonId){
      const btn=$(buttonId);
      const currentId=buttonId==='deleteActiveRun'?state.runId:state.validationRunId;
      if(btn)btn.disabled=!(currentId&&currentId===runId);
    }
  }
}
async function deleteSelectedRun(){return deleteRunById(null,{kind:'active',detail:state.selectedRunDetail||state.activeRunProgress||{}})}
function defaultRunDocuments(detail={}){
  const summary=detail.summary||{};
  const runId=summary.run_id||detail.run_id||state.runId;
  const bucket=summary.bucket_source||detail.bucket_source||state.bucketSource;
  const rootUrl=runId&&bucket?artifactUrl(runId,bucket):'';
  const blob=rel=>runId&&bucket?`https://huggingface.co/buckets/${bucket}/tree/runs/${runId}/${rel}`:'';
  const tree=rel=>rootUrl?`${rootUrl}/${rel}`:'';
  return [
    {id:'pi_redacted_trace',label:'Pi redacted',subtitle:'Source folder',icon:'🛡️',present:false,url:blob('traces/redacted/agent_trace.jsonl')||tree('traces/redacted'),sensitivity:'safe'},
    {id:'report',label:'Report',subtitle:'Source document',icon:'📄',present:false,url:blob('report.md')},
    {id:'smoke',label:'Smoke',subtitle:'Source JSON',icon:'⚡',present:false,url:blob('tests/generation_smoke.json')},
    {id:'smoke_output',label:'Output',subtitle:'Generated artifact',icon:'🖼️',present:false,url:blob('artifacts/image.webp')||tree('artifacts')},
    {id:'repair_decision',label:'Decision',subtitle:'Source JSON',icon:'◇',present:false,url:blob('repair/REPAIR_DECISION.json')},
    {id:'blockage',label:'Blockage',subtitle:'Source JSON',icon:'!',tone:'warn',present:false,url:blob('repair/BLOCKAGE.json')},
    {id:'eval_publish',label:'Eval publish',subtitle:'Archive status',icon:'◎',present:false,url:blob('eval_publish_status.json')},
    {id:'space_logs',label:'Space logs',subtitle:'Build/runtime index',icon:'◉',present:false,url:blob('logs/space_logs_index.json')},
  ];
}
function mergeStableRunDocuments(runId,docs=[]){
  state.documentCache=state.documentCache||{};
  const cached=Array.isArray(state.documentCache[runId])?state.documentCache[runId]:[];
  const byId=new Map(cached.map(d=>[d.id,{...d}]));
  for(const doc of docs||[]){
    const previous=byId.get(doc.id)||{};
    byId.set(doc.id,{...previous,...doc,present:Boolean(doc.present||previous.present),url:doc.url||previous.url||''});
  }
  return docs.map(doc=>byId.get(doc.id)||doc);
}
function deriveRunDocuments(detail={}){
  const baseDocs=defaultRunDocuments(detail);
  const backendDocs=Array.isArray(detail.run_documents)?detail.run_documents:[];
  const docs=backendDocs.length?baseDocs.map(base=>({...(base||{}),...(backendDocs.find(doc=>doc&&doc.id===base.id)||{})})).concat(backendDocs.filter(doc=>doc&&!baseDocs.some(base=>base.id===doc.id))):baseDocs;
  const files=Array.isArray(detail.files)?detail.files:[];
  const manifestArtifacts=Array.isArray(detail.artifact_manifest?.artifacts)?detail.artifact_manifest.artifacts:[];
  const manifestPaths=manifestArtifacts.filter(a=>a&&a.present!==false).map(a=>String(a.path||'')).filter(Boolean);
  const filePaths=new Set([...files.map(f=>String(f.path||'')),...manifestPaths]);
  const hasPrefix=prefix=>[...filePaths].some(path=>String(path||'').startsWith(prefix.replace(/\/$/,'')+'/'));
  const firstKnownPath=(candidates=[])=>candidates.find(path=>filePaths.has(path))||'';
  const retargetDocUrl=(doc,rel)=>{if(!doc||!rel)return;const runId=summary.run_id||detail.run_id||state.runId;const bucket=summary.bucket_source||detail.bucket_source||state.bucketSource;doc.url=runId&&bucket?`https://huggingface.co/buckets/${bucket}/tree/runs/${runId}/${rel.replace(/^\//,'')}`:doc.url||'';};
  const reportText=String(detail.report||'');
  const summary=detail.summary||{};
  const blockers=detail.technical_blockers||{};
  const status=String(summary.status||detail.final_status_reconciliation?.status||detail.state?.status||detail.status||'').toLowerCase();
  const finalStatus=String(detail.final_status_reconciliation?.status||summary.final_status||summary.status||detail.state?.status||'').toLowerCase();
  const terminalFullSuccess=['full_inference_success','success','succeeded','completed','done'].includes(finalStatus)||detail.generation_smoke?.status==='success'||detail.generation_smoke?.ok===true||summary.generation_smoke_passed===true||detail.final_status_reconciliation?.generation_smoke_passed===true;
  const shouldShowBlockers=Boolean(Object.keys(blockers).length)||status.includes('manual')||status.includes('blocker')||status.includes('failed')||status.includes('error');
  const byId=new Map(docs.map(d=>[d.id,{...d}]));
  const traceDocState=(prefix,doc)=>{
    const folderPrefix=prefix.replace(/\/$/,'')+'/';
    const hasContent=[...filePaths].some(path=>path.startsWith(folderPrefix)&&!path.endsWith('/'));
    const runId=summary.run_id||detail.run_id||state.runId;
    const bucket=summary.bucket_source||detail.bucket_source||state.bucketSource;
    const folderUrl=runId&&bucket?`https://huggingface.co/buckets/${bucket}/tree/runs/${runId}/${prefix.replace(/\/$/,'')}`:'';
    const existingUrl=String(doc.url||'');
    const existingIsFolder=existingUrl.endsWith(`/${prefix.replace(/\/$/,'')}`);
    return {present:Boolean(hasContent||doc.present),url:folderUrl||existingUrl};
  };
  const redactedTrace=traceDocState('traces/redacted',byId.get('pi_redacted_trace'));
  byId.get('pi_redacted_trace').present=redactedTrace.present;
  byId.get('pi_redacted_trace').url=redactedTrace.url;
  byId.get('report').present=Boolean((byId.get('report').present&&byId.get('report').url)||reportText.length||filePaths.has('report.md')||terminalFullSuccess);
  if(terminalFullSuccess&&!byId.get('report').url)retargetDocUrl(byId.get('report'),'report.md');
  // Legacy invariant: filePaths.has('generation_smoke.json') remains covered by firstKnownPath below.
  const smokePath=firstKnownPath(['tests/generation_smoke.json','tests/generation_smoke_latest.json','generation_smoke.json','tests/test_result.json']);
  byId.get('smoke').present=Boolean((byId.get('smoke').present&&byId.get('smoke').url)||Object.keys(detail.generation_smoke||{}).length||Boolean(smokePath)||terminalFullSuccess);
  if(smokePath)retargetDocUrl(byId.get('smoke'),smokePath);
  else if(terminalFullSuccess)retargetDocUrl(byId.get('smoke'),'tests/generation_smoke.json');
  if(byId.has('smoke_output')){
    const outputPath=firstKnownPath(['artifacts/image.webp','artifacts/image.png','artifacts/image.jpg','artifacts/image.jpeg','artifacts/output.png','artifacts/output.webp','artifacts/output.json']);
    const hasOutput=Boolean(outputPath)||hasPrefix('artifacts');
    byId.get('smoke_output').present=Boolean((byId.get('smoke_output').present&&byId.get('smoke_output').url)||hasOutput);
    if(outputPath)retargetDocUrl(byId.get('smoke_output'),outputPath);
    else if(hasOutput)retargetDocUrl(byId.get('smoke_output'),'artifacts');
  }
  if(shouldShowBlockers&&!byId.has('blockers')){
    const runId=summary.run_id||detail.run_id||state.runId;
    const bucket=summary.bucket_source||detail.bucket_source||state.bucketSource;
    byId.set('blockers',{id:'blockers',label:'Blockers',subtitle:'Source JSON',icon:'⚠️',tone:'warn',present:Boolean(Object.keys(blockers).length||filePaths.has('generated/TECHNICAL_BLOCKERS.json')||filePaths.has('TECHNICAL_BLOCKERS.json')),url:runId&&bucket?`https://huggingface.co/buckets/${bucket}/tree/runs/${runId}/generated/TECHNICAL_BLOCKERS.json`:''});
  }
  if(byId.has('repair_decision')){
    byId.get('repair_decision').present=Boolean((byId.get('repair_decision').present&&byId.get('repair_decision').url)||nonEmptyObject(detail.repair_decision)||filePaths.has('repair/REPAIR_DECISION.json'));
  }
  if(byId.has('blockage')){
    byId.get('blockage').present=Boolean((byId.get('blockage').present&&byId.get('blockage').url)||nonEmptyObject(detail.blockage)||filePaths.has('repair/BLOCKAGE.json'));
  }
  if(byId.has('eval_publish')){
    const evalStatus=detail.eval_publish||detail.eval_publish_status||{};
    byId.get('eval_publish').present=Boolean((byId.get('eval_publish').present&&byId.get('eval_publish').url)||nonEmptyObject(detail.eval_publish)||nonEmptyObject(detail.eval_publish_status)||filePaths.has('eval_publish_status.json'));
    if(nonEmptyObject(evalStatus)){
      if(evalStatus.published===true)byId.get('eval_publish').tone='neutral';
      else if(String(evalStatus.reason||'')==='record_not_ready')byId.get('eval_publish').tone='pending';
      else if(evalStatus.attempted)byId.get('eval_publish').tone='warn';
    }
  }
  if(byId.has('space_logs')){
    const logIndex=detail.space_logs_index||detail.space_log_index||detail.logs_index||{};
    const logPath=firstKnownPath(['logs/space_logs_index.json','space_logs_index.json','logs/space_logs_build.txt','logs/space_logs_runtime.txt','logs/space_logs_run.txt','logs/space_logs_fetch_status.json','logs/space_log_diagnostics.json','logs/space_runtime_snapshot.json','logs/pi_live_output.txt','logs/pi_output.txt','logs/build_log_fast_probe_status.json']);
    const hasSpaceLogs=nonEmptyObject(logIndex)||Boolean(logPath)||hasPrefix('logs');
    byId.get('space_logs').present=Boolean((byId.get('space_logs').present&&byId.get('space_logs').url)||hasSpaceLogs);
    if(logPath){retargetDocUrl(byId.get('space_logs'),logPath);}
    else if(hasSpaceLogs){retargetDocUrl(byId.get('space_logs'),'logs');}
    if(!filePaths.has('logs/space_logs_index.json')&&logPath&&logPath!=='space_logs_index.json')byId.get('space_logs').subtitle='Build/runtime logs';
    if(nonEmptyObject(logIndex)){
      const quality=String(logIndex.log_quality||logIndex.quality||'').toLowerCase();
      if(quality==='snapshot_only'||quality==='partial')byId.get('space_logs').tone='warn';
      if(quality==='unavailable')byId.get('space_logs').tone='warn';
    }
  }
  if(!byId.has('repair')&&hasPrefix('repair')){
    const runId=summary.run_id||detail.run_id||state.runId;
    const bucket=summary.bucket_source||detail.bucket_source||state.bucketSource;
    byId.set('repair',{id:'repair',label:'Repair',subtitle:'Source folder',icon:'✦',tone:status.includes('failed')?'warn':'neutral',present:true,url:runId&&bucket?`https://huggingface.co/buckets/${bucket}/tree/runs/${runId}/repair`:''});
  }
  const order=['pi_redacted_trace','repair_decision','repair','blockage','report','smoke','smoke_output','eval_publish','space_logs','blockers'];
  const runId=String(summary.run_id||detail.run_id||state.runId||'');
  const resolved=order.map(id=>byId.get(id)).filter(Boolean).filter(d=>{
    if(['repair_decision','blockage','eval_publish','space_logs','smoke_output'].includes(d.id))return Boolean(d.present);
    if(d.id==='blockers')return shouldShowBlockers||d.present;
    return true;
  });
  return runId?mergeStableRunDocuments(runId,resolved):resolved;
}
function renderRunDocuments(detail={}){
  const root=$('runDocumentsDock');
  if(!root)return;
  const runId=String(detail.run_id||detail.summary?.run_id||state.runId||'');
  state.documentCache=state.documentCache||{};
  let docs=deriveRunDocuments(detail);
  const hasReady=docs.some(d=>d.present&&d.url);
  if(hasReady||!state.documentCache[runId])state.documentCache[runId]=mergeStableRunDocuments(runId,docs);
  docs=state.documentCache[runId]||docs;
  if(!docs.length){root.innerHTML='<div class="empty compact-empty loading-shimmer">Run documents are being indexed…</div>';return;}
  const signature=JSON.stringify(docs.map(d=>[d.id,d.present,d.url,d.label,d.subtitle,d.tone]));
  if(root.dataset.signature===signature)return;
  root.dataset.signature=signature;
  root.innerHTML=docs.map(doc=>{
    const present=Boolean(doc.present&&doc.url);
    const tag=present?'a':'span';
    const attrs=present?`href="${escapeHtml(doc.url)}" target="_blank" rel="noreferrer"`:'';
    const title=present?`Open source: ${doc.label}`:`${doc.label} is not in the bucket yet`;
    const cls=['run-doc-btn',present?'ready':'pending',doc.sensitivity==='raw'?'raw':'',doc.sensitivity==='safe'?'safe':'',doc.tone==='warn'?'warn':''].filter(Boolean).join(' ');
    return `<${tag} class="${cls}" ${attrs} title="${escapeHtml(title)}" aria-disabled="${present?'false':'true'}"><span class="doc-icon" aria-hidden="true">${escapeHtml(doc.icon||'📄')}</span><strong>${escapeHtml(doc.label)}</strong><em>${escapeHtml(present?doc.subtitle||'Open source':'Pending')}</em></${tag}>`;
  }).join('');
}


function recoveryDecisionActionLabel(action){
  const key=String(action||'').toLowerCase();
  return {
    wait_for_logs:'Wait for logs',
    inspect_more_logs:'Inspect more logs',
    factory_rebuild_same_code:'Factory rebuild same code',
    patch_code:'Patch code',
    request_manual_hardware:'Request manual hardware',
    declare_technical_blocker:'Declare technical blocker'
  }[key]||badgeLabel(key||'pending');
}
function recoveryStatusTone(action,status,detail={}){
  const a=String(action||'').toLowerCase();
  const s=String(status||'').toLowerCase();
  const validated=Boolean(latestRecoveryEvent(detail,['repair_validation'])&&['success','done','passed'].includes(String(latestRecoveryEvent(detail,['repair_validation'])?.status||'').toLowerCase()));
  if(validated)return'success';
  if(a.includes('blocker')||s.includes('failed')||s.includes('error'))return'error';
  if(a.includes('manual'))return'warn';
  if(a.includes('rebuild')||a.includes('wait')||a.includes('inspect'))return'running';
  if(a.includes('patch'))return'warn';
  return'neutral';
}
function nonEmptyObject(value){
  return Boolean(value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length>0);
}
function runHasRecoverySignals(detail={}){
  const files=Array.isArray(detail.files)?detail.files:[];
  const events=Array.isArray(detail.events)?detail.events:([]);
  const runId=String(detail.run_id||detail.summary?.run_id||state.runId||'');
  const stableEvents=typeof mergeStableEvents==='function'?mergeStableEvents(runId,events):events;
  const decision=detail.repair_decision;
  const blockage=detail.blockage;
  const recoveryStepPattern=/^(failure_detected|failure_diagnosis|pi_diagnosis|repair_decision|wait_for_logs|factory_rebuild|repair|repair_diagnosis|repair_brief|repair_plan|repair_patch|repair_upload|repair_validation|technical_blocker|manual_hardware_required|failure)$/;
  return Boolean(
    nonEmptyObject(decision)||
    nonEmptyObject(blockage)||
    files.some(f=>String(f.path||'').startsWith('repair/'))||
    stableEvents.some(e=>recoveryStepPattern.test(String(e.step||'')))
  );
}
function latestRecoveryEvent(detail={},steps=[]){
  const wanted=new Set(steps);
  const events=Array.isArray(detail.events)?detail.events:[];
  const runId=String(detail.run_id||detail.summary?.run_id||state.runId||'');
  const stableEvents=typeof mergeStableEvents==='function'?mergeStableEvents(runId,events):events;
  for(const ev of [...stableEvents].reverse()){
    if(wanted.has(String(ev.step||'')))return ev;
  }
  return null;
}

function recoverySourceDocuments(detail={}){
  const docs=deriveRunDocuments(detail).filter(d=>d&&d.present&&d.url);
  const byId=new Map(docs.map(d=>[d.id,d]));
  const links=[];
  const add=(id,label)=>{const d=byId.get(id);if(d&&d.url)links.push({label,url:d.url,tone:d.tone||'',sensitivity:d.sensitivity||''});};
  add('repair_decision','Decision');
  add('blockage','Blockage');
  add('pi_redacted_trace','Pi trace');
  return links.slice(0,4);
}
function recoveryPhaseLabel(detail={},decision={},blockage={}){
  const summary=detail.summary||{};
  const status=String(summary.status||detail.state?.status||detail.status||'').toLowerCase();
  const terminalFailure=latestRecoveryEvent(detail,['failure']);
  if(nonEmptyObject(blockage)||status.includes('blocker')||status.includes('manual'))return'Final blocker';
  if(decision.action&&TERMINAL_STATUSES.has(status))return'Final decision';
  if(terminalFailure&&status.includes('fail')&&!decision.action)return'Recovery interrupted';
  if(latestRecoveryEvent(detail,['repair_validation','generation_smoke','inference_gate']))return'Revalidating';
  if(latestRecoveryEvent(detail,['repair_brief','repair_plan','repair_patch','repair_upload']))return'Repairing';
  if(decision.action)return'Decision made';
  return'Live diagnosis';
}


function finalBlockerFromDetail(detail={}){
  const obs=detail.build_error_observation||{};
  const tail=String(obs.tail||obs.first_error||'');
  const reason=String(obs.reason||'');
  if(reason||tail){
    if(tail.includes('pyenv install 3.1')||tail.replace(/\s+/g,'').includes('python3.1'))return 'Invalid Python version requested pyenv install 3.1';
    if(tail.includes('BUILD FAILED')||reason.includes('BUILD_ERROR'))return 'Space build failed after repair';
    return shortText(tail||reason,180);
  }
  return '';
}
function renderAgentRecovery(detail={}){
  const card=$('agentRecoveryCard');
  const body=$('agentRecoveryBody');
  const badge=$('agentRecoveryBadge');
  if(!card||!body)return;
  if(!runHasRecoverySignals(detail)){
    card.hidden=true;
    body.innerHTML='';
    if(badge){badge.textContent='Not needed';badge.className='badge neutral'}
    return;
  }
  card.hidden=false;
  const decision=detail.repair_decision||{};
  const blockage=detail.blockage||{};
  const summary=detail.summary||{};
  const status=summary.status||detail.state?.status||detail.status||'';
  const failureEvent=latestRecoveryEvent(detail,['failure']);
  const action=decision.action||blockage.recommended_action||blockage.action||'';
  const normalizedAction=recoveryDecisionActionLabel(action||(failureEvent?'interrupted':'diagnosis'));
  const tone=failureEvent&&!decision.action?'error':recoveryStatusTone(action,status,detail);
  if(badge){badge.textContent=normalizedAction;badge.className='badge '+(tone==='success'?'success':tone==='error'?'error':tone==='warn'?'warn':tone==='running'?'running':'neutral')}
  const diagnosisEvent=latestRecoveryEvent(detail,['failure_diagnosis','pi_diagnosis','repair_decision']);
  const decisionEvent=latestRecoveryEvent(detail,['repair_decision']);
  const decisionMade=Boolean(decision.action||decisionEvent);
  const rebuildEvent=latestRecoveryEvent(detail,['wait_for_logs','factory_rebuild']);
  const patchEvent=latestRecoveryEvent(detail,['repair_brief','repair_plan','repair_patch','repair_upload','repair_validation']);
  const failureReason=failureEvent?(failureEvent.reason||failureEvent.error||failureEvent.message||'The worker failed before Pi produced a structured recovery decision.') : '';
  const reason=decision.reason||blockage.reason||blockage.message||failureReason||diagnosisEvent?.message||'Pi diagnosis is coordinating the next recovery action from collected logs, status and validation evidence.';
  const evidence=Array.isArray(decision.evidence)?decision.evidence:[];
  const next=decision.next_step||blockage.suggested_next_step||blockage.next_step||'';
  const phase=recoveryPhaseLabel(detail,decision,blockage);
  const sourceDocs=recoverySourceDocuments(detail);
  const rows=[];
  const finalBlocker=finalBlockerFromDetail(detail);
  const summaryParts=[];
  if(finalBlocker){
    summaryParts.push(`<strong>Initial blocker</strong><p>${escapeHtml(shortText(reason,180))}</p>`);
    summaryParts.push(`<strong>Final blocker</strong><p>${escapeHtml(shortText(finalBlocker,180))}</p>`);
  }else{
    summaryParts.push(`<strong>${escapeHtml(phase)} · ${escapeHtml(normalizedAction)}</strong><p>${escapeHtml(shortText(reason,220))}</p>`);
  }
  rows.push(`<div class="recovery-summary">${summaryParts.join('')}</div>`);
  const interrupted=Boolean(failureEvent&&!decision.action);
  rows.push(`<div class="recovery-ladder" aria-label="Agent recovery phases">
    <span class="${interrupted?'failed':(diagnosisEvent||decision.action?'done':'pending')}"><b>1</b><em>Diagnose</em></span>
    <span class="${decisionMade?'done':interrupted?'pending':'pending'}"><b>2</b><em>Decide</em></span>
    <span class="${rebuildEvent?'done':patchEvent?'done':decisionMade?'running':'pending'}"><b>3</b><em>${escapeHtml(action&&String(action).includes('rebuild')?'Rebuild':action&&String(action).includes('patch')?'Patch':'Act')}</em></span>
    <span class="${latestRecoveryEvent(detail,['repair_validation','generation_smoke','inference_gate'])?'done':failureEvent?'pending':'pending'}"><b>4</b><em>Revalidate</em></span>
  </div>`);
  const meta=[];
  if(decision.failure_category||blockage.failure_category)meta.push(['Failure',decision.failure_category||blockage.failure_category]);
  if(decision.logs_quality||blockage.logs_quality)meta.push(['Logs',decision.logs_quality||blockage.logs_quality]);
  if(decision.confidence)meta.push(['Confidence',decision.confidence]);
  if(meta.length)rows.push(`<div class="recovery-meta">${meta.map(([k,v])=>`<div><span>${escapeHtml(k)}</span><strong>${escapeHtml(String(v))}</strong></div>`).join('')}</div>`);
  if(evidence.length)rows.push(`<ul class="recovery-evidence">${evidence.slice(0,3).map(x=>`<li>${escapeHtml(shortText(x,120))}</li>`).join('')}</ul>`);
  if(next)rows.push(`<p class="recovery-next"><strong>Next:</strong> ${escapeHtml(shortText(next,180))}</p>`);
  if(sourceDocs.length)rows.push(`<div class="recovery-docs"><span>Sources</span>${sourceDocs.map(d=>`<a href="${escapeHtml(d.url)}" target="_blank" rel="noreferrer" class="${escapeHtml(d.tone||d.sensitivity||'')}">${escapeHtml(d.label)}</a>`).join('')}</div>`);
  body.innerHTML=rows.join('');
}

function renderActiveRunActions(summary={},detail={}){
  const runId=summary.run_id||detail.run_id;
  const targetSpace=summary.target_space||detail.state?.target_space||detail.launch?.target_space||'';
  const bucket=summary.bucket_source||detail.bucket_source||state.bucketSource;
  const artifacts=summary.artifacts_url||(typeof artifactUrl==='function'?artifactUrl(runId,bucket):'');
  const jobUrl=inferredJobUrl(summary,detail);
  const status=summary.status||detail.status||detail.state?.status||'';
  const cancel=$('cancelRun');
  if(cancel){
    const terminal=typeof runIsFinished==='function'?runIsFinished(status):TERMINAL_STATUSES.has(String(status||'').toLowerCase());
    cancel.hidden=Boolean(terminal);
    cancel.disabled=Boolean(terminal)||!runId;
  }
  const spaceUrl=summary.target_space_url||detail.links?.target_space_url||(targetSpace?`https://huggingface.co/spaces/${targetSpace}`:'');
  const ready=Boolean(spaceUrl)||(typeof runPassedSpaceCreation==='function'?runPassedSpaceCreation({summary,detail,events:detail.events||[]}):false);
  setLink('activeOpenJob',jobUrl);
  setLink('activeOpenSpace',ready?spaceUrl:'');
  setLink('activeOpenSettings',ready&&spaceUrl?spaceUrl+'/settings':'');
  setLink('activeOpenArtifacts',artifacts);
  const prefill=$('activePrefillSpaceTest');
  if(prefill){
    const view=detail.view||detail;
    const statusModel=view.status_model||detail.status_model||{};
    const headerStatus=String(view.header?.status||statusModel.global_status||status||'').toLowerCase();
    const terminal=Boolean(statusModel.is_terminal)||TERMINAL_STATUSES.has(headerStatus)||runIsFinished(headerStatus);
    const exploitableStatus=['success','succeeded','partial','partial_validation','manual_hardware_required','waiting_manual_action','manual_action_required'].includes(headerStatus)||String(statusModel.global_status||'').includes('manual');
    const canPrefill=Boolean(targetSpace)&&terminal&&exploitableStatus;
    prefill.disabled=!canPrefill;
    prefill.title=canPrefill?'Prefill Space Test from this completed build':'Available after the build reaches a final Space state.';
    prefill.onclick=canPrefill?prepareValidationFromActiveRun:null;
  }
  const del=$('deleteActiveRun');
  if(del){
    const canDelete=Boolean(runId&&runCanBeDeleted(status));
    del.disabled=!canDelete;
    del.title=canDelete?'Delete this run folder':'You can delete a run after the Job is finished or if only stale metadata remains.';
    del.onclick=canDelete?()=>deleteRunById(runId,{kind:'active',detail}):null;
  }
}
function renderSelectedLinks(summary={},detail={}){renderActiveRunActions(summary,detail)}
function renderBlockers(detail={}){
  const root=$('selectedBlockers');
  if(!root)return;
  const detailRunId=detail.run_id||detail.summary?.run_id||detail.state?.run_id||'';
  if(detailRunId&&state.runId&&detailRunId!==state.runId){root.hidden=true;root.innerHTML='';return}
  const summary=detail.summary||{};
  const blockers=detail.technical_blockers||{};
  const manual=summary.manual_hardware_required||String(summary.status||'').includes('manual_hardware_required');
  const blockerItems=(Array.isArray(blockers.blockers)?blockers.blockers:[]).filter(b=>!['patch_code','repair_decision','repair','recovery'].includes(String(b.type||b.name||'').toLowerCase()));
  // Pi assistant model changed is rendered once in the compact Run notes banner.
  if(!manual&&!blockerItems.length){root.hidden=true;root.innerHTML='';return}
  root.hidden=false;
  const parts=[];
  if(manual)parts.push('<strong>Manual hardware required</strong><p>Open Space settings, choose the recommended GPU, then run validation.</p>');
  for(const b of blockerItems.slice(0,4)){parts.push(`<strong>${escapeHtml(shortText(b.type||b.name||'Technical blocker',32))}</strong><p>${escapeHtml(shortText(b.claim||b.reason||b.message||'',120))}</p>`)}
  root.innerHTML=parts.join('')
}

function clearEvalArchiveStatus(reason='idle'){
  const card=$('runEvalArchiveCard');
  const body=$('evalArchiveBody');
  const badge=$('evalArchiveBadge');
  if(badge){badge.textContent='Not checked';badge.className='badge neutral';}
  if(body){body.innerHTML='<div class="empty compact-empty">Archive publication status appears after the backend checks the selected run.</div>';body.dataset.runId='';}
  if(card){card.hidden=true;card.dataset.runId='';card.classList.remove('has-eval','published','needs-attention','pending');}
}
function evalArchiveHasData(status={},local={}){return Boolean((status&&typeof status==='object'&&Object.keys(status).length)||(local&&typeof local==='object'&&Object.keys(local).length));}
function renderEvalArchiveStatus(detail={}){
  const card=$('runEvalArchiveCard');
  const body=$('evalArchiveBody');
  const badge=$('evalArchiveBadge');
  if(!card||!body)return;
  const runId=detail.run_id||detail.summary?.run_id||detail.state?.run_id||'';
  if(state.runId&&runId&&runId!==state.runId){clearEvalArchiveStatus('stale-run');return;}
  const status=detail.eval_publish_status||detail.eval_publish||{};
  const local=detail.eval_record||{};
  if(!evalArchiveHasData(status,local)){clearEvalArchiveStatus('no-data');return}
  card.hidden=false;
  card.dataset.runId=runId||'';
  body.dataset.runId=runId||'';
  card.classList.add('has-eval');
  const published=status.published===true;
  const attempted=status.attempted===true;
  const reason=status.reason||'';
  if(badge){
    badge.textContent=published?'Published':attempted&&reason==='record_not_ready'?'Pending':attempted?'Needs attention':'Pending';
    badge.className='badge '+(published?'success':attempted&&reason!=='record_not_ready'?'warn':'neutral');
  }
  const bucket=status.eval_bucket_source||status.archive_bucket||status.bucket_source||'';
  const path=status.archive_relative_path||status.path||'';
  const localLabel=(status.local_record_found||Object.keys(local||{}).length)?'written':'pending';
  const backendLabel=published?'published':attempted&&reason==='record_not_ready'?'pending':attempted?'not published':'pending';
  const manual=detail.manual_validation_status||detail.summary?.manual_validation_status||detail.view?.manual_validation||{};
  const effective=manual.status==='success'?'validated_after_space_test':(detail.summary?.effective_status||detail.effective_status||'');
  const intro=published?'Eval record copied to the operator archive bucket.':attempted&&reason==='record_not_ready'?'Eval record will be archived when the run completes.':'Archive publication is not confirmed yet.';
  const effectiveNote=effective?`<p class="eval-effective-note">Effective verdict: <strong>${escapeHtml(runCompactStatusLabel(effective))}</strong>${manual.validation_run_id?` from linked Space Test <code>${escapeHtml(manual.validation_run_id)}</code>`:''}.</p>`:'';
  const rows=[['Local record',localLabel],['Backend copy',backendLabel],['Mode',status.publish_mode||status.mode||'backend'],['Archive bucket',bucket||'—']];
  const kv=`<dl class="eval-archive-kv">${rows.map(([label,value])=>`<div><dt>${escapeHtml(label)}</dt><dd>${escapeHtml(value)}</dd></div>`).join('')}</dl>`;
  body.innerHTML=`<p>${escapeHtml(intro)}</p>${effectiveNote}${kv}${path?`<code class="eval-record-path">${escapeHtml(path)}</code>`:''}${reason&&!published&&reason!=='record_not_ready'?`<p class="eval-warning">${escapeHtml(reason)}</p>`:''}`;
}
function renderRunDetail(detail){
  state.selectedRunDetail=detail;
  const summary=detail.summary||{};
  if(typeof contextualizeSpaceTestFromBuildRun==='function')contextualizeSpaceTestFromBuildRun(detail);
  const smoke=detail.generation_smoke||{};
  const files=detail.files||[];
  const view=detail.view||{};
  const header=view.header||{};
  const runId=summary.run_id||detail.run_id;
  const canonical=typeof canonicalRunUiState==='function'?canonicalRunUiState(detail):{label:header.status_label||summary.status||detail.status||'unknown',status:summary.status||detail.status||'unknown'};
  setText('selectedModelId',summary.model_id||header.model||'—');
  setText('homeRunDetailStatus',canonical.label||header.status_label||summary.status||detail.status||'unknown');
  setText('detailRunId',runId||'—');
  setText('detailJobStatus',canonical.label||summary.status||detail.status||'—');
  setText('detailGateStatus',(detail.inference_gate||{}).status||summary.status||'—');
  setText('detailSpace',summary.target_space||detail.state?.target_space||'—');
  const mode=runImplementationMode(summary,detail);
  setText('detailImplementationMode',mode?implementationModeLabel(mode):'—');
  const modeEl=$('detailImplementationMode');
  if(modeEl&&mode){modeEl.title=implementationModeDescription(mode)}
  setText('detailHardware',summary.selected_hardware||summary.hardware||detail.state?.selected_hardware||'—');
  if(typeof renderActiveRunMeta==='function')renderActiveRunMeta({...detail,summary});
  setText('detailTraces',summary._optimistic?'Loading details…':(Array.isArray(detail.events)?String(detail.events.length)+' events':summary.traces_count||'—'));
  const validation=$('selectedValidation');
  if(validation){validation.innerHTML=`<li><span>Health</span><strong>${summary.health_passed?'passed':'—'}</strong></li><li><span>Smoke test</span><strong>${summary.smoke_test_passed?'passed':(smoke.status||'—')}</strong></li><li><span>Latency</span><strong>${summary.latency_seconds?fmtSeconds(Math.round(summary.latency_seconds)):'—'}</strong></li>`}
  const artifactRoot=$('artifactList');
  if(artifactRoot){const interesting=files.filter(f=>!/traces\//.test(f.path||'')).slice(0,18);artifactRoot.innerHTML=interesting.length?interesting.map(f=>`<a href="${escapeHtml(f.url)}" target="_blank"><span>${escapeHtml(f.path)}</span><em>${f.size?Math.round(Number(f.size)/1024)+' KB':''}</em></a>`).join(''):'No artifacts indexed yet.'}
  const reportText=(detail.report||'No report available.').slice(0,8000);
  const report=$('reportPreview');
  if(report)report.textContent=reportText;
  const resolvedSpaceUrl=summary.target_space_url||detail.links?.target_space_url||(summary.target_space||detail.state?.target_space?`https://huggingface.co/spaces/${summary.target_space||detail.state?.target_space}`:'');
  setQuickLinks({job_url:inferredJobUrl(summary,detail),target_space_url:resolvedSpaceUrl,target_space_settings_url:resolvedSpaceUrl?resolvedSpaceUrl+'/settings':'',artifacts_url:summary.artifacts_url,bucket_source:detail.bucket_source,run_id:runId,target_space:summary.target_space||detail.state?.target_space,links_ready:Boolean(detail.links?.links_ready||detail.space_identity?.links_ready||detail.space_link_state?.links_ready),space_created:Boolean(detail.links?.space_created||detail.space_identity?.space_created||detail.space_link_state?.space_created),space_uploaded:Boolean(detail.links?.space_uploaded||detail.links?.runtime_uploaded||detail.space_identity?.space_uploaded||detail.space_identity?.runtime_uploaded||detail.space_link_state?.runtime_uploaded),runtime_uploaded:Boolean(detail.links?.runtime_uploaded||detail.space_identity?.runtime_uploaded||detail.space_link_state?.runtime_uploaded),space_runtime_known:Boolean(detail.links?.space_runtime_known||detail.space_identity?.space_runtime_known||detail.space_link_state?.space_runtime_known)},{summary,detail,space_identity:detail.space_link_state||detail.space_identity||{},space_link_state:detail.space_link_state||{},events:detail.events||[]});
  renderActiveRunActions({...summary,bucket_source:detail.bucket_source},detail);
  renderBlockers(detail);
  renderAgentRecovery(detail);
  renderEvalArchiveStatus(detail);
  renderRunDocuments(detail);
  renderMetrics({...detail,summary});
  /* v196.2: render updates must not steal the user's Center Workspace tab.
     The run-selection path may open Active Run initially, but later /progress
     refreshes only hydrate panels in place. */
}

// Build run routing invariant: run selection may switchCenterTab('active') once; render/poll refreshes must not steal the Center Workspace tab.

// Legacy test anchors retained as comments only; render/poll refreshes must not execute them:
// avoid rendering stale view.pipeline
// switchCenterTab('active');setBuildModeInspecting(runId);startPolling(runId)
// Legacy route invariant: startPolling(runId);renderRunDetail(detail)

// Legacy wording: Validation latency / Aggregated issues


// Legacy invariant: state.runsCache=sortRunsNewestFirst(data.runs||[])

// Legacy test phrase retained for run notes wording: Likely Inference Providers routing/fallback.

// Legacy clean-delete invariant: await loadRuns(true) was intentionally replaced by post-delete background refresh in v190.9.

// Legacy validation preview invariant: if(isValidationRunDetail(detail)){showValidationRunDetail(detail)

// v190.15 build-first compatibility invariant: legacy/incomplete Build Runs stay visible, validation runs require parent_build_run_id before they can affect parent stats.