File size: 107,052 Bytes
5b48487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
# ===== file: integrations/harbor/experimental/deepseek_server_readiness_subset.py =====
from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any

try:
    from statem.miniyaml import loads as _yaml_loads
except ImportError:  # Allow the public helper to be copied outside the StateM tree.
    import yaml

    _yaml_loads = yaml.safe_load


DEFAULT_RUNBOOK = (
    Path(__file__).resolve().parents[3]
    / "examples"
    / "terminal-bench-2.1-deepseek-server-readiness-subset.yaml"
)


def load_runbook(path: Path = DEFAULT_RUNBOOK) -> dict[str, Any]:
    value = _yaml_loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise ValueError("server-readiness runbook must be a YAML object")
    if value.get("schema_version") != 1:
        raise ValueError("server-readiness runbook schema_version must be 1")
    if value.get("policy_version") != 9:
        raise ValueError("server-readiness runbook policy_version must be 9")
    if value.get("family") != "server_readiness":
        raise ValueError("server-readiness runbook has the wrong family")

    selection = value.get("selection")
    lens = value.get("lens")
    runtime = value.get("runtime")
    if not all(isinstance(item, dict) for item in (selection, lens, runtime)):
        raise ValueError("server-readiness runbook is missing structured sections")
    if lens.get("id") != "service_lifecycle_readiness":
        raise ValueError("server-readiness runbook has the wrong lens id")
    groups = selection.get("require_all_groups")
    if not isinstance(groups, list) or [item.get("name") for item in groups] != [
        "service",
        "public_client",
        "persistence",
    ]:
        raise ValueError("server-readiness runbook requires exactly three trigger groups")
    for group in groups:
        patterns = group.get("any_regex") if isinstance(group, dict) else None
        if not isinstance(patterns, list) or not patterns or not all(
            isinstance(pattern, str) and pattern for pattern in patterns
        ):
            raise ValueError("every server-readiness trigger group needs regex patterns")
        for pattern in patterns:
            re.compile(pattern, flags=re.IGNORECASE)
    return value


def select_review_lens(task_text: str, runbook: dict[str, Any]) -> dict[str, Any]:
    normalized = re.sub(r"[ \t]+", " ", task_text.lower())
    selection = runbook["selection"]
    selected = all(
        any(
            re.search(pattern, normalized, flags=re.IGNORECASE)
            for pattern in group["any_regex"]
        )
        for group in selection["require_all_groups"]
    )
    if selected:
        lens = runbook["lens"]
        return {
            "version": runbook["policy_version"],
            "selected": True,
            "selection_basis": selection["selection_basis"],
            "applies_in_state": selection["applies_in_state"],
            "lens": {
                "id": lens["id"],
                "instruction": lens["instruction"],
                "receipt": {"required_fields": lens["receipt"]["required_fields"]},
            },
            "limits": lens["limits"],
        }
    non_match = runbook["non_match"]
    return {
        "version": runbook["policy_version"],
        "selected": False,
        "selection_basis": non_match["selection_basis"],
        "applies_in_state": non_match["applies_in_state"],
        "lens": None,
        "limits": non_match["limits"],
    }


def render_review_lens(selection: dict[str, Any], runbook: dict[str, Any]) -> str:
    if not selection.get("selected"):
        return ""
    binding_errors = _selection_binding_errors(selection, runbook)
    if binding_errors:
        raise ValueError("; ".join(binding_errors))
    lens = runbook["lens"]
    fields = ", ".join(lens["receipt"]["required_fields"])
    runtime = runbook["runtime"]
    return (
        "DeepSeek review adaptation (self_review only):\n"
        f"- {lens['id']}: {lens['instruction']}\n"
        "- Run only one bounded countercheck. Do not broaden the solve, invent "
        "an acceptance rule, or delay handoff after the deadline reserve begins.\n"
        f"- Record the bounded evidence receipt at {runtime['receipt_path']} with fields: "
        f"{fields}. Validate it with `python3 {runtime['validator_path']} "
        f"validate --selection {runtime['selection_path']} --receipt "
        f"{runtime['receipt_path']}`. A pending or failed receipt is a concrete issue, "
        "not a clean handoff."
    )


def receipt_template(
    selection: dict[str, Any], runbook: dict[str, Any]
) -> dict[str, Any] | None:
    lens = selection.get("lens")
    if not selection.get("selected") or not isinstance(lens, dict):
        return None
    binding_errors = _selection_binding_errors(selection, runbook)
    if binding_errors:
        raise ValueError("; ".join(binding_errors))
    lens = runbook["lens"]
    payload: dict[str, Any] = {
        "version": selection["version"],
        "lens_id": lens["id"],
        "status": "pending",
    }
    for field in lens["receipt"]["required_fields"]:
        payload.setdefault(field, None)
    return payload


def _selection_binding_errors(
    selection: dict[str, Any], runbook: dict[str, Any]
) -> list[str]:
    errors: list[str] = []
    expected_selection = runbook["selection"]
    expected_lens = runbook["lens"]
    if selection.get("version") != runbook["policy_version"]:
        errors.append("selection version does not match runbook")
    if selection.get("selection_basis") != expected_selection["selection_basis"]:
        errors.append("selection basis does not match runbook")
    if selection.get("applies_in_state") != expected_selection["applies_in_state"]:
        errors.append("selection state does not match runbook")
    if selection.get("limits") != expected_lens["limits"]:
        errors.append("selection limits do not match runbook")

    lens = selection.get("lens")
    if not isinstance(lens, dict) or lens.get("id") != expected_lens["id"]:
        errors.append("selection is not bound to the server-readiness lens")
        return errors
    if lens.get("instruction") != expected_lens["instruction"]:
        errors.append("selection instruction does not match runbook")
    contract = lens.get("receipt")
    if not isinstance(contract, dict) or contract.get(
        "required_fields"
    ) != expected_lens["receipt"]["required_fields"]:
        errors.append("selection receipt fields do not match runbook")
    return errors


def validate_receipt(
    selection: dict[str, Any], receipt: dict[str, Any], runbook: dict[str, Any]
) -> list[str]:
    lens = selection.get("lens")
    if not selection.get("selected") or not isinstance(lens, dict):
        return ["selection does not require a DeepSeek contract receipt"]
    binding_errors = _selection_binding_errors(selection, runbook)
    if binding_errors:
        return binding_errors

    errors: list[str] = []
    if receipt.get("lens_id") != lens["id"]:
        errors.append("receipt lens_id does not match selection")
    required_values = runbook["lens"]["receipt"]["required_values"]
    if receipt.get("status") != required_values["status"]:
        errors.append("receipt status must be passed")
    for field in runbook["lens"]["receipt"]["required_fields"]:
        value = receipt.get(field)
        if value is None or value == "" or value == [] or value == {}:
            errors.append(f"missing receipt field: {field}")
    if (
        receipt.get("detached_from_agent_session")
        is not required_values["detached_from_agent_session"]
    ):
        errors.append("service is not detached from the agent session")
    return errors


def _read_json(path: Path) -> dict[str, Any]:
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise ValueError(f"expected JSON object: {path}")
    return value


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Verify the public server-readiness subset.")
    parser.add_argument("--runbook", type=Path, default=DEFAULT_RUNBOOK)
    subparsers = parser.add_subparsers(dest="command", required=True)
    select_parser = subparsers.add_parser("select")
    select_parser.add_argument("--task-text", type=Path, required=True)
    validate_parser = subparsers.add_parser("validate")
    validate_parser.add_argument("--selection", type=Path, required=True)
    validate_parser.add_argument("--receipt", type=Path, required=True)
    args = parser.parse_args(argv)

    try:
        runbook = load_runbook(args.runbook)
        if args.command == "select":
            result = select_review_lens(
                args.task_text.read_text(encoding="utf-8"), runbook
            )
            print(json.dumps(result, indent=2, sort_keys=True))
            return 0
        selection = _read_json(args.selection)
        receipt = _read_json(args.receipt)
        errors = validate_receipt(selection, receipt, runbook)
    except (OSError, ValueError, json.JSONDecodeError, re.error) as exc:
        print(json.dumps({"status": "failed", "errors": [str(exc)]}))
        return 2
    status = "passed" if not errors else "failed"
    print(json.dumps({"status": status, "errors": errors}, sort_keys=True))
    return 0 if not errors else 1


if __name__ == "__main__":
    sys.exit(main())

# ===== file: integrations/harbor/experimental/git_webserver_deploy_family.py =====
from __future__ import annotations

import atexit
import argparse
import hashlib
import json
import os
import pwd
import shutil
import socket
import subprocess
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any


FAMILY = "git_webserver_deploy"
VERSION = 1
GATE_TIMEOUT_SECONDS = float(os.environ.get("STATEM_GIT_WEBSERVER_CHECK_TIMEOUT", "90"))
DEFAULT_TASK = Path("/tmp/statem-verification-checks/task.txt")
DEFAULT_SELECTION = Path("/tmp/statem-verification-checks/git-webserver-selection.json")
DEFAULT_CONTRACT = Path("/tmp/statem-verification-checks/task-contract-receipt.json")
DEFAULT_REVIEW = Path("/tmp/statem-verification-checks/self-review.json")
DEFAULT_RECEIPT = Path("/tmp/statem-verification-checks/git-webserver-receipt.json")
DEFAULT_DEADLINE = Path("/tmp/statem-verification-checks/deadline.json")
REQUIRED_HINTS = (
    "ssh_user",
    "repo_path",
    "branch",
    "web_file",
    "expected_content",
    "web_url",
)
PRACTICE = {
    "id": FAMILY,
    "role": "reviewer",
    "instruction": (
        "Review the exact consumer path, not just the local implementation: a fresh client must "
        "clone the configured bare repository over SSH as the named user, commit and push the "
        "requested branch, and then fetch the exact expected body from the public HTTP URL. "
        "Treat repository existence, an executable hook, an open port, a direct write into the web "
        "root, and a curl against pre-existing content as separate partial observations, not proof "
        "of the end-to-end deployment contract. Preserve a working candidate and repair a concrete "
        "broken link before considering rollback."
    ),
    "review_questions": [
        "Does the configured SSH user reach the exact bare repository path from the prompt?",
        "Does a new push to the requested branch trigger deployment without an agent-side copy?",
        "Does a fresh HTTP request observe the pushed file with byte-exact body content?",
        "Could the current evidence be stale, circular, or produced through a privileged shortcut?",
    ],
    "required_evidence": [
        "fresh SSH clone",
        "fresh commit and push to the requested branch",
        "post-push HTTP body equality",
        "post-check repository ref and HTTP freshness",
    ],
    "anti_patterns": [
        "writing directly to the web root",
        "testing only localhost content created before the push",
        "checking only that sshd, Git, a hook, or an HTTP port exists",
        "replacing a failed end-to-end check with a proxy assertion",
    ],
}


def extract_hints(task_text: str) -> dict[str, str]:
    import re

    hints: dict[str, str] = {}
    remote = re.search(r"\b([A-Za-z0-9._-]+)@([A-Za-z0-9._-]+):(/[^\s'\"`]+)", task_text)
    if remote:
        hints["ssh_user"] = remote.group(1)
        hints["prompt_host"] = remote.group(2)
        hints["repo_path"] = remote.group(3).rstrip(".,)")

    url = re.search(r"https?://[^\s'\"`]+", task_text)
    if url:
        hints["web_url"] = url.group(0).rstrip(".,)")

    echo = re.search(r"\becho\s+([\"'])(.*?)\1\s*>\s*([A-Za-z0-9_./-]+)", task_text)
    if echo:
        hints["expected_content"] = echo.group(2)
        hints["web_file"] = echo.group(3).rstrip(".,)")

    push = re.search(r"\bgit\s+push\s+origin\s+([A-Za-z0-9_./-]+)", task_text)
    if push:
        hints["branch"] = push.group(1).rstrip(".,)")
    return hints


def select_family(task_text: str) -> dict[str, Any]:
    lower = task_text.lower()
    hints = extract_hints(task_text)
    selected = bool(
        all(str(hints.get(key) or "").strip() for key in REQUIRED_HINTS)
        and "git clone" in lower
        and "git push" in lower
        and ("curl " in lower or "http request" in lower or "webserver" in lower)
    )
    basis = (
        "task_visible_git_ssh_push_http_contract"
        if selected
        else "no_high_confidence_git_ssh_push_http_contract"
    )
    payload: dict[str, Any] = {
        "version": VERSION,
        "selected": selected,
        "family": FAMILY,
        "selection_basis": basis,
        "applies_in_state": "self_review",
        "practice": PRACTICE if selected else None,
        "gate": {
            "name": FAMILY,
            "effect_scope": "stateful",
            "git_webserver_hints": hints if selected else {},
        },
        "limits": [
            "solve the visible task normally before loading family review practice",
            "execute at most one stateful family gate per evidence-state entry",
            "repair concrete failures non-destructively before considering rollback",
            "under handoff deadline pressure preserve the best runnable candidate",
        ],
    }
    payload["selection_fingerprint"] = _selection_fingerprint(payload)
    return payload


def validate_selection(selection: Any, task_text: str) -> list[str]:
    expected = select_family(task_text)
    if not isinstance(selection, dict):
        return ["family selection must be a JSON object"]
    if selection != expected:
        return [
            "family selection does not exactly match the task-visible contract; "
            "regenerate it instead of editing routes, hints, practice, or limits"
        ]
    return []


def render_practice(selection: dict[str, Any], task_text: str) -> str:
    _raise_errors(validate_selection(selection, task_text))
    if not selection["selected"]:
        return ""
    practice = selection["practice"]
    lines = [
        "Selected reviewer practice: git_webserver_deploy",
        str(practice["instruction"]),
        "Review questions:",
    ]
    lines.extend(f"- {item}" for item in practice["review_questions"])
    lines.append("Required evidence:")
    lines.extend(f"- {item}" for item in practice["required_evidence"])
    lines.append("Reject these proxy checks:")
    lines.extend(f"- {item}" for item in practice["anti_patterns"])
    return "\n".join(lines)


def initial_contract() -> dict[str, Any]:
    return {
        "version": 1,
        "source": "agent",
        "status": "pending",
        "artifact_or_service_identity": "",
        "checks": [],
        "remaining_risk": "",
        "next_action": "",
    }


def validate_contract(receipt: Any) -> list[str]:
    if not isinstance(receipt, dict):
        return ["task contract receipt must be a JSON object"]
    problems: list[str] = []
    if not str(receipt.get("source") or "").startswith("agent"):
        problems.append("task contract receipt source must start with 'agent'")
    status = str(receipt.get("status") or "").strip().lower()
    if status not in {"passed", "failed"}:
        problems.append("task contract receipt status must be passed or failed")
    checks = receipt.get("checks")
    if not isinstance(checks, list) or not any(_meaningful(item) for item in checks):
        problems.append("task contract receipt needs at least one concrete current check")
    if status == "passed":
        if not _meaningful(receipt.get("artifact_or_service_identity")):
            problems.append("passed task contract receipt needs artifact_or_service_identity")
        if receipt.get("next_action") != "self_review":
            problems.append("passed task contract receipt next_action must be self_review")
    if status == "failed" and receipt.get("next_action") != "repair":
        problems.append("failed task contract receipt next_action must be repair")
    return problems


def initial_review(selection: dict[str, Any]) -> dict[str, Any]:
    lenses = {
        "task_contract": {"evidence": ""},
        "evidence_freshness": {"evidence": ""},
        "edge_risk": {"evidence": ""},
    }
    if selection.get("selected"):
        lenses["consumer_path"] = {"evidence": ""}
    return {
        "version": 1,
        "source": "agent",
        "mode": "bounded",
        "status": "pending",
        "family": FAMILY if selection.get("selected") else None,
        "lenses": lenses,
        "findings": [],
        "evidence_gaps": [],
        "next_fix": "",
        "residual_risk": "",
    }


def validate_review(review: Any, selection: Any, task_text: str) -> list[str]:
    problems = validate_selection(selection, task_text)
    safe_selection = selection if isinstance(selection, dict) else {}
    if not isinstance(review, dict):
        return problems + ["self-review must be a JSON object"]
    if not str(review.get("source") or "").startswith("agent"):
        problems.append("self-review source must start with 'agent'")
    if review.get("mode") not in {"bounded", "deadline_bounded"}:
        problems.append("self-review mode must be bounded or deadline_bounded")
    expected_family = FAMILY if safe_selection.get("selected") else None
    if review.get("family") != expected_family:
        problems.append("self-review family must match the immutable selection")

    status = str(review.get("status") or "").strip().lower()
    if status not in {"clean", "issues_found", "needs_evidence", "deadline_handoff"}:
        problems.append(
            "self-review status must be clean, issues_found, needs_evidence, or deadline_handoff"
        )
        return problems

    lenses = review.get("lenses") if isinstance(review.get("lenses"), dict) else {}
    required_lenses = ["task_contract", "evidence_freshness", "edge_risk"]
    if safe_selection.get("selected"):
        required_lenses.append("consumer_path")
    for name in required_lenses:
        lens = lenses.get(name) if isinstance(lenses, dict) else None
        evidence = lens.get("evidence") if isinstance(lens, dict) else ""
        if not _meaningful(evidence, minimum=12):
            problems.append(f"self-review lens {name} needs concrete evidence")

    findings = review.get("findings")
    gaps = review.get("evidence_gaps")
    if status == "clean":
        if _has_open_items(findings) or _has_open_items(gaps):
            problems.append("clean self-review cannot retain open findings or evidence gaps")
    elif status == "issues_found":
        if not _has_open_items(findings):
            problems.append("issues_found self-review needs at least one concrete finding")
        if not _meaningful(review.get("next_fix"), minimum=8):
            problems.append("issues_found self-review needs a concrete next_fix")
    elif status == "needs_evidence":
        if not safe_selection.get("selected"):
            problems.append("needs_evidence requires a selected fixed family gate")
        if not _has_open_items(gaps):
            problems.append("needs_evidence self-review needs at least one concrete evidence gap")
    else:
        if review.get("mode") != "deadline_bounded":
            problems.append("deadline_handoff self-review mode must be deadline_bounded")
        if not _meaningful(review.get("residual_risk"), minimum=12):
            problems.append("deadline_handoff self-review needs specific residual_risk")
    return problems


def run_gate(
    selection: Any,
    task_text: str,
    receipt_path: Path,
) -> tuple[bool, dict[str, Any]]:
    selection_errors = validate_selection(selection, task_text)
    safe_selection = selection if isinstance(selection, dict) else {}
    messages: list[str] = []
    passed = False
    if selection_errors:
        messages.extend(selection_errors)
    elif not safe_selection.get("selected"):
        messages.append("git_webserver_deploy is not selected for this task")
    else:
        try:
            passed, raw_messages = run_git_webserver_check(
                {"git_webserver_hints": safe_selection["gate"]["git_webserver_hints"]}
            )
            messages.extend(str(item)[:500] for item in raw_messages[:30])
        except Exception as exc:  # The failed receipt must survive an unexpected checker error.
            messages.append(f"git_webserver_deploy checker raised {type(exc).__name__}: {exc}")
            passed = False

    hints = safe_selection.get("gate", {}).get("git_webserver_hints", {})
    branch_head = _branch_head(hints) if passed else ""
    observed_url, observed_body, observation_error = _observe_http(hints) if passed else ("", "", "")
    expected = str(hints.get("expected_content") or "") if isinstance(hints, dict) else ""
    if passed and (not branch_head or observation_error or observed_body != expected):
        passed = False
        if not branch_head:
            messages.append("post-gate freshness check could not resolve the deployed branch head")
        if observation_error:
            messages.append(observation_error)
        elif observed_body != expected:
            messages.append(
                f"post-gate HTTP body was {observed_body!r}, expected {expected!r}"
            )

    receipt = {
        "version": 1,
        "source": "statem_fixed_family_gate",
        "family": FAMILY,
        "gate": FAMILY,
        "effect_scope": "stateful",
        "status": "passed" if passed else "failed",
        "selection_fingerprint": safe_selection.get("selection_fingerprint"),
        "gate_implementation_sha256": _implementation_sha256(),
        "recorded_at_epoch": time.time(),
        "branch_head": branch_head,
        "observed_url": observed_url,
        "observed_body": observed_body,
        "messages": messages,
    }
    _write_json(receipt_path, receipt)
    return passed, receipt


def validate_receipt(
    receipt: Any,
    selection: Any,
    task_text: str,
    *,
    max_age_seconds: int = 900,
    now: float | None = None,
) -> list[str]:
    problems = validate_selection(selection, task_text)
    safe_selection = selection if isinstance(selection, dict) else {}
    if not safe_selection.get("selected"):
        problems.append("a family gate receipt is invalid when the family route is not selected")
    if not isinstance(receipt, dict):
        return problems + ["family gate receipt must be a JSON object"]
    expected_fields = {
        "source": "statem_fixed_family_gate",
        "family": FAMILY,
        "gate": FAMILY,
        "effect_scope": "stateful",
        "status": "passed",
        "selection_fingerprint": safe_selection.get("selection_fingerprint"),
    }
    for key, expected in expected_fields.items():
        if receipt.get(key) != expected:
            problems.append(f"family gate receipt {key} must equal {expected!r}")

    current_gate_hash = _implementation_sha256()
    if not current_gate_hash or receipt.get("gate_implementation_sha256") != current_gate_hash:
        problems.append("family gate receipt does not match the current fixed gate implementation")

    recorded = _as_float(receipt.get("recorded_at_epoch"))
    current_time = time.time() if now is None else now
    if recorded is None:
        problems.append("family gate receipt needs recorded_at_epoch")
    elif recorded > current_time + 5:
        problems.append("family gate receipt timestamp is in the future")
    elif current_time - recorded > max_age_seconds:
        problems.append("family gate receipt is older than the allowed freshness window")

    hints = safe_selection.get("gate", {}).get("git_webserver_hints", {})
    current_head = _branch_head(hints)
    if not current_head:
        problems.append("current deployed branch head is unavailable")
    elif receipt.get("branch_head") != current_head:
        problems.append("deployed branch changed after the family gate receipt")

    observed_url, observed_body, observation_error = _observe_http(hints)
    expected_body = str(hints.get("expected_content") or "") if isinstance(hints, dict) else ""
    if observation_error:
        problems.append(observation_error)
    elif observed_body != expected_body:
        problems.append(
            f"current HTTP body was {observed_body!r}, expected {expected_body!r}"
        )
    if receipt.get("observed_url") != observed_url:
        problems.append("family gate receipt URL does not match the current consumer URL")
    if receipt.get("observed_body") != expected_body:
        problems.append("family gate receipt does not record the expected HTTP body")
    return problems


def _selection_fingerprint(payload: dict[str, Any]) -> str:
    canonical = {key: value for key, value in payload.items() if key != "selection_fingerprint"}
    encoded = json.dumps(canonical, sort_keys=True, separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()


def _implementation_sha256() -> str:
    path = Path(__file__)
    if not path.is_file():
        return ""
    return hashlib.sha256(path.read_bytes()).hexdigest()


def run_git_webserver_check(selection: dict[str, Any]) -> tuple[bool, list[str]]:
    hints = selection.get("git_webserver_hints") if isinstance(selection, dict) else {}
    hints = hints if isinstance(hints, dict) else {}
    ssh_user = str(hints.get("ssh_user") or "").strip()
    repo_path = str(hints.get("repo_path") or "").strip()
    branch = str(hints.get("branch") or "").strip()
    web_file = str(hints.get("web_file") or "").strip()
    expected = str(hints.get("expected_content") or "").strip()
    raw_web_url = str(hints.get("web_url") or "").strip()
    web_url = _local_web_url(raw_web_url)
    prompt_host = str(hints.get("prompt_host") or "").strip()

    messages = [
        f"ssh_user={ssh_user}",
        f"repo_path={repo_path}",
        f"branch={branch}",
        f"web_url={web_url}",
    ]
    problems: list[str] = []
    for key, value in (
        ("ssh_user", ssh_user),
        ("repo_path", repo_path),
        ("branch", branch),
        ("web_file", web_file),
        ("expected_content", expected),
        ("web_url", raw_web_url),
    ):
        if not value:
            problems.append(f"missing required git_webserver_hints.{key}")
    for command in ("git", "ssh", "ssh-keygen"):
        if shutil.which(command) is None:
            problems.append(f"missing required command: {command}")
    if problems:
        return False, messages + problems

    try:
        user_info = pwd.getpwnam(ssh_user)
    except KeyError:
        return False, messages + [f"SSH user does not exist: {ssh_user!r}"]
    repo_check = _run_command(
        ["git", f"--git-dir={repo_path}", "rev-parse", "--is-bare-repository"]
    )
    if repo_check.returncode != 0:
        return False, messages + [
            f"{repo_path} is not a readable bare Git repository: {_command_output(repo_check)}"
        ]

    with tempfile.TemporaryDirectory(prefix="statem-git-webserver-check-") as temp_dir:
        root = Path(temp_dir)
        key_path = root / "id_ed25519"
        problems.extend(_prepare_ssh_key(ssh_user, user_info, key_path))
        if problems:
            return False, messages + problems

        ssh_env = os.environ.copy()
        ssh_env["GIT_SSH_COMMAND"] = (
            f"ssh -i {key_path} -o StrictHostKeyChecking=no "
            "-o UserKnownHostsFile=/dev/null -o BatchMode=yes"
        )
        clone_dir = root / "repo"
        clone_url = f"{ssh_user}@localhost:{repo_path}"
        clone = _run_command(
            ["git", "clone", clone_url, str(clone_dir)],
            env=ssh_env,
            timeout=GATE_TIMEOUT_SECONDS,
        )
        if clone.returncode != 0:
            return False, messages + [
                f"SSH git clone failed for {clone_url}: {_command_output(clone)}"
            ]

        _run_command(["git", "config", "user.email", "statem@example.com"], cwd=clone_dir)
        _run_command(["git", "config", "user.name", "statem deploy check"], cwd=clone_dir)
        target_path = clone_dir / web_file
        target_path.parent.mkdir(parents=True, exist_ok=True)
        target_path.write_text(expected + "\n", encoding="utf-8")
        probe_name = f".statem-deploy-check-{int(time.time())}-{os.getpid()}.txt"
        probe_path = clone_dir / probe_name
        probe_path.write_text("statem git webserver deployment check\n", encoding="utf-8")

        add = _run_command(["git", "add", web_file, probe_name], cwd=clone_dir)
        if add.returncode != 0:
            return False, messages + [f"git add failed in SSH clone: {_command_output(add)}"]
        commit = _run_command(
            ["git", "commit", "-m", "statem git webserver deployment check"],
            cwd=clone_dir,
        )
        if commit.returncode != 0:
            return False, messages + [
                f"git commit failed in SSH clone: {_command_output(commit)}"
            ]
        push = _run_command(
            ["git", "push", "origin", f"HEAD:{branch}"],
            cwd=clone_dir,
            env=ssh_env,
            timeout=GATE_TIMEOUT_SECONDS,
        )
        if push.returncode != 0:
            return False, messages + [f"git push over SSH failed: {_command_output(push)}"]

        body_problem = _wait_for_http_body(web_url, expected)
        if body_problem:
            return False, messages + [body_problem]

        cleanup = _run_command(["git", "rm", "--ignore-unmatch", probe_name], cwd=clone_dir)
        if cleanup.returncode != 0:
            return False, messages + [f"git cleanup failed: {_command_output(cleanup)}"]
        cleanup_status = _run_command(["git", "status", "--porcelain"], cwd=clone_dir)
        if cleanup_status.returncode != 0:
            return False, messages + [
                f"git cleanup status failed: {_command_output(cleanup_status)}"
            ]
        if cleanup_status.stdout.strip():
            cleanup_commit = _run_command(
                ["git", "commit", "-m", "statem git webserver deployment check cleanup"],
                cwd=clone_dir,
            )
            if cleanup_commit.returncode != 0:
                return False, messages + [
                    f"git cleanup commit failed: {_command_output(cleanup_commit)}"
                ]
            cleanup_push = _run_command(
                ["git", "push", "origin", f"HEAD:{branch}"],
                cwd=clone_dir,
                env=ssh_env,
                timeout=GATE_TIMEOUT_SECONDS,
            )
            if cleanup_push.returncode != 0:
                return False, messages + [
                    f"git cleanup push failed: {_command_output(cleanup_push)}"
                ]
            body_problem = _wait_for_http_body(web_url, expected)
            if body_problem:
                return False, messages + [f"post-cleanup web check failed: {body_problem}"]
            messages.append("temporary deploy probe cleaned")

        if raw_web_url != web_url and _host_resolves(_url_host(raw_web_url)):
            prompt_problem = _wait_for_http_body(raw_web_url, expected, attempts=3)
            if prompt_problem:
                return False, messages + [f"prompt URL check failed: {prompt_problem}"]
        elif prompt_host and prompt_host not in {"localhost", "127.0.0.1"}:
            messages.append(
                f"prompt_host={prompt_host} was not resolvable; localhost service check was used"
            )
    return True, messages + ["git_webserver_deploy_check passed"]


def _prepare_ssh_key(
    ssh_user: str,
    user_info: pwd.struct_passwd,
    key_path: Path,
) -> list[str]:
    keygen = _run_command(["ssh-keygen", "-t", "ed25519", "-f", str(key_path), "-N", "", "-q"])
    if keygen.returncode != 0:
        return [f"ssh-keygen failed: {_command_output(keygen)}"]
    ssh_dir = Path(user_info.pw_dir) / ".ssh"
    authorized_keys = ssh_dir / "authorized_keys"
    try:
        ssh_dir.mkdir(parents=True, exist_ok=True)
        public_key = key_path.with_suffix(".pub").read_text(encoding="utf-8").strip()
        existing = (
            authorized_keys.read_text(encoding="utf-8", errors="ignore")
            if authorized_keys.exists()
            else ""
        )
        added_key = public_key not in {line.strip() for line in existing.splitlines()}
        if added_key:
            with authorized_keys.open("a", encoding="utf-8") as handle:
                if existing and not existing.endswith("\n"):
                    handle.write("\n")
                handle.write(public_key + "\n")
        os.chown(ssh_dir, user_info.pw_uid, user_info.pw_gid)
        os.chown(authorized_keys, user_info.pw_uid, user_info.pw_gid)
        ssh_dir.chmod(0o700)
        authorized_keys.chmod(0o600)
        if added_key:
            atexit.register(
                _remove_authorized_key,
                authorized_keys,
                public_key,
                user_info.pw_uid,
                user_info.pw_gid,
            )
    except OSError as exc:
        return [f"could not authorize SSH key for {ssh_user}: {exc}"]
    return []


def _remove_authorized_key(
    authorized_keys: Path,
    public_key: str,
    uid: int,
    gid: int,
) -> None:
    try:
        if not authorized_keys.exists():
            return
        remaining = [
            line
            for line in authorized_keys.read_text(encoding="utf-8", errors="ignore").splitlines()
            if line.strip() != public_key
        ]
        payload = "\n".join(remaining)
        authorized_keys.write_text(payload + ("\n" if payload else ""), encoding="utf-8")
        os.chown(authorized_keys, uid, gid)
        authorized_keys.chmod(0o600)
    except OSError:
        return


def _wait_for_http_body(url: str, expected: str, attempts: int = 12) -> str | None:
    last_error = ""
    for _ in range(attempts):
        _, body, error = _observe_url(url)
        if not error and body == expected:
            return None
        last_error = error or f"{url} returned {body!r}, expected {expected!r}"
        time.sleep(1)
    return last_error or f"{url} did not return expected content"


def _observe_url(url: str) -> tuple[str, str, str]:
    try:
        with urllib.request.urlopen(url, timeout=5) as response:
            status = int(getattr(response, "status", 200))
            body = response.read().decode("utf-8", errors="replace").rstrip("\r\n")
    except (urllib.error.URLError, TimeoutError, OSError, ValueError) as exc:
        return url, "", f"{url} request failed: {exc}"
    if status != 200:
        return url, body, f"{url} returned HTTP {status}"
    return url, body, ""


def _host_resolves(host: str) -> bool:
    if not host:
        return False
    try:
        socket.getaddrinfo(host, None)
    except OSError:
        return False
    return True


def _url_host(url: str) -> str:
    try:
        return urllib.parse.urlparse(url).hostname or ""
    except ValueError:
        return ""


def _run_command(
    command: list[str],
    *,
    cwd: Path | None = None,
    env: dict[str, str] | None = None,
    timeout: float = 30,
) -> subprocess.CompletedProcess[str]:
    try:
        return subprocess.run(
            command,
            cwd=str(cwd) if cwd else None,
            env=env,
            text=True,
            capture_output=True,
            timeout=timeout,
            check=False,
        )
    except subprocess.TimeoutExpired as exc:
        return subprocess.CompletedProcess(
            command,
            124,
            exc.stdout or "",
            (exc.stderr or "") + f"\ntimed out after {timeout:g}s",
        )


def _command_output(completed: subprocess.CompletedProcess[str]) -> str:
    return "\n".join(
        part.strip() for part in (completed.stdout, completed.stderr) if part.strip()
    )[:2000]


def _branch_head(hints: Any) -> str:
    if not isinstance(hints, dict):
        return ""
    repo_path = str(hints.get("repo_path") or "").strip()
    branch = str(hints.get("branch") or "").strip()
    if not repo_path or not branch:
        return ""
    try:
        completed = subprocess.run(
            ["git", f"--git-dir={repo_path}", "rev-parse", f"refs/heads/{branch}"],
            capture_output=True,
            check=False,
            text=True,
            timeout=10,
        )
    except (OSError, subprocess.TimeoutExpired):
        return ""
    return completed.stdout.strip() if completed.returncode == 0 else ""


def _observe_http(hints: Any) -> tuple[str, str, str]:
    if not isinstance(hints, dict):
        return "", "", "missing git webserver hints"
    raw_url = str(hints.get("web_url") or "").strip()
    if not raw_url:
        return "", "", "missing consumer HTTP URL"
    url = _local_web_url(raw_url)
    try:
        with urllib.request.urlopen(url, timeout=5) as response:
            status = int(getattr(response, "status", 200))
            body = response.read().decode("utf-8", errors="replace").rstrip("\r\n")
    except (urllib.error.URLError, TimeoutError, OSError, ValueError) as exc:
        return url, "", f"current HTTP request failed: {exc}"
    if status != 200:
        return url, body, f"current HTTP request returned status {status}"
    return url, body, ""


def _local_web_url(url: str) -> str:
    parsed = urllib.parse.urlparse(url)
    if not parsed.scheme or not parsed.netloc:
        return url
    if parsed.hostname in {"localhost", "127.0.0.1", "::1"}:
        return url
    netloc = "localhost" + (f":{parsed.port}" if parsed.port else "")
    return urllib.parse.urlunparse(parsed._replace(netloc=netloc))


def _meaningful(value: Any, *, minimum: int = 4) -> bool:
    if isinstance(value, dict):
        return any(_meaningful(item, minimum=minimum) for item in value.values())
    if isinstance(value, list):
        return any(_meaningful(item, minimum=minimum) for item in value)
    return len(str(value or "").strip()) >= minimum


def _has_open_items(value: Any) -> bool:
    if not isinstance(value, list):
        return False
    for item in value:
        if isinstance(item, dict):
            status = str(item.get("status") or "open").strip().lower()
            if status not in {"fixed", "resolved", "not_applicable"} and _meaningful(item):
                return True
        elif _meaningful(item):
            return True
    return False


def _as_float(value: Any) -> float | None:
    try:
        return float(value)
    except (TypeError, ValueError):
        return None


def _read_text(path: Path) -> str:
    return path.read_text(encoding="utf-8")


def _read_json(path: Path) -> Any:
    return json.loads(path.read_text(encoding="utf-8"))


def _write_json(path: Path, payload: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    temporary.replace(path)


def _raise_errors(problems: list[str]) -> None:
    if problems:
        raise ValueError("; ".join(problems))


def _print_errors(problems: list[str]) -> int:
    for problem in problems:
        print(problem)
    return 1 if problems else 0


def deadline_status(path: Path, *, now: float | None = None) -> dict[str, Any]:
    try:
        payload = _read_json(path)
    except (OSError, json.JSONDecodeError):
        payload = {}
    if not isinstance(payload, dict) or not payload.get("deadline_at_epoch"):
        return {
            "configured": False,
            "mode": "unbounded",
            "remaining_seconds": None,
        }
    current = time.time() if now is None else now
    deadline_at = _as_float(payload.get("deadline_at_epoch"))
    if deadline_at is None:
        return {
            "configured": False,
            "mode": "unbounded",
            "remaining_seconds": None,
        }
    handoff_buffer = _positive_int(payload.get("handoff_buffer_seconds"), 120)
    heavy_buffer = _positive_int(payload.get("heavy_work_buffer_seconds"), 240)
    remaining = int(deadline_at - current)
    if remaining <= 0:
        mode = "expired"
    elif remaining <= handoff_buffer:
        mode = "handoff_due"
    elif remaining <= heavy_buffer:
        mode = "heavy_work_closed"
    else:
        mode = "normal"
    return {
        "configured": True,
        "mode": mode,
        "remaining_seconds": remaining,
        "handoff_buffer_seconds": handoff_buffer,
        "heavy_work_buffer_seconds": heavy_buffer,
    }


def validate_deadline_predicate(
    status: dict[str, Any],
    *,
    required_modes: set[str] | None = None,
    min_remaining: int | None = None,
    handoff_due_or_expired: bool = False,
    heavy_work_closed_or_worse: bool = False,
) -> list[str]:
    if not status.get("configured"):
        return []
    mode = str(status.get("mode") or "")
    remaining = status.get("remaining_seconds")
    problems: list[str] = []
    if required_modes and mode not in required_modes:
        problems.append(f"deadline mode {mode!r} is not one of {sorted(required_modes)!r}")
    if min_remaining is not None and isinstance(remaining, int) and remaining < min_remaining:
        problems.append(
            f"deadline remaining_seconds={remaining} is below required {min_remaining}"
        )
    if handoff_due_or_expired and mode not in {"handoff_due", "expired"}:
        problems.append("deadline is not handoff_due or expired")
    if heavy_work_closed_or_worse and mode not in {
        "heavy_work_closed",
        "handoff_due",
        "expired",
    }:
        problems.append("deadline has not closed heavy work")
    return problems


def _positive_int(value: Any, default: int) -> int:
    try:
        parsed = int(value)
    except (TypeError, ValueError):
        return default
    return parsed if parsed > 0 else default


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description="Standalone git_webserver_deploy family router, reviewer, and receipt gate."
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    select_parser = subparsers.add_parser("select")
    select_parser.add_argument("--task", type=Path, default=DEFAULT_TASK)
    select_parser.add_argument("--selection", type=Path, default=DEFAULT_SELECTION)
    select_parser.add_argument("--quiet", action="store_true")

    for name in ("validate-selection", "render-practice"):
        command = subparsers.add_parser(name)
        command.add_argument("--task", type=Path, default=DEFAULT_TASK)
        command.add_argument("--selection", type=Path, default=DEFAULT_SELECTION)

    route_parser = subparsers.add_parser("route")
    route_parser.add_argument("--task", type=Path, default=DEFAULT_TASK)
    route_parser.add_argument("--selection", type=Path, default=DEFAULT_SELECTION)
    route_parser.add_argument("--target", choices=("family_evidence", "handoff"), required=True)

    contract_init = subparsers.add_parser("init-contract")
    contract_init.add_argument("--contract", type=Path, default=DEFAULT_CONTRACT)
    contract_check = subparsers.add_parser("validate-contract")
    contract_check.add_argument("--contract", type=Path, default=DEFAULT_CONTRACT)
    contract_status = subparsers.add_parser("contract-status")
    contract_status.add_argument("--contract", type=Path, default=DEFAULT_CONTRACT)
    contract_status.add_argument("--status", choices=("passed", "failed"), required=True)

    review_init = subparsers.add_parser("init-review")
    review_init.add_argument("--task", type=Path, default=DEFAULT_TASK)
    review_init.add_argument("--selection", type=Path, default=DEFAULT_SELECTION)
    review_init.add_argument("--review", type=Path, default=DEFAULT_REVIEW)
    review_check = subparsers.add_parser("validate-review")
    review_check.add_argument("--task", type=Path, default=DEFAULT_TASK)
    review_check.add_argument("--selection", type=Path, default=DEFAULT_SELECTION)
    review_check.add_argument("--review", type=Path, default=DEFAULT_REVIEW)
    review_status = subparsers.add_parser("review-status")
    review_status.add_argument("--task", type=Path, default=DEFAULT_TASK)
    review_status.add_argument("--selection", type=Path, default=DEFAULT_SELECTION)
    review_status.add_argument("--review", type=Path, default=DEFAULT_REVIEW)
    review_status.add_argument(
        "--target", choices=("repair", "family_evidence", "handoff", "deadline_handoff"), required=True
    )

    gate_run = subparsers.add_parser("run-gate")
    gate_run.add_argument("--task", type=Path, default=DEFAULT_TASK)
    gate_run.add_argument("--selection", type=Path, default=DEFAULT_SELECTION)
    gate_run.add_argument("--receipt", type=Path, default=DEFAULT_RECEIPT)
    receipt_check = subparsers.add_parser("validate-receipt")
    receipt_check.add_argument("--task", type=Path, default=DEFAULT_TASK)
    receipt_check.add_argument("--selection", type=Path, default=DEFAULT_SELECTION)
    receipt_check.add_argument("--receipt", type=Path, default=DEFAULT_RECEIPT)
    receipt_check.add_argument("--max-age-seconds", type=int, default=900)
    receipt_status = subparsers.add_parser("receipt-status")
    receipt_status.add_argument("--receipt", type=Path, default=DEFAULT_RECEIPT)
    receipt_status.add_argument("--status", choices=("passed", "failed"), required=True)

    deadline_parser = subparsers.add_parser("deadline")
    deadline_parser.add_argument("--deadline", type=Path, default=DEFAULT_DEADLINE)
    deadline_parser.add_argument("--require-mode", default="")
    deadline_parser.add_argument("--min-remaining", type=int)
    deadline_parser.add_argument("--handoff-due-or-expired", action="store_true")
    deadline_parser.add_argument("--heavy-work-closed-or-worse", action="store_true")

    args = parser.parse_args(argv)
    try:
        if args.command == "select":
            selected = select_family(_read_text(args.task))
            if args.selection.exists():
                _raise_errors(validate_selection(_read_json(args.selection), _read_text(args.task)))
            else:
                _write_json(args.selection, selected)
            if not args.quiet:
                print(json.dumps(selected, indent=2, sort_keys=True))
            return 0
        if args.command in {"validate-selection", "render-practice", "route"}:
            task_text = _read_text(args.task)
            selection = _read_json(args.selection)
            problems = validate_selection(selection, task_text)
            if problems:
                return _print_errors(problems)
            if args.command == "validate-selection":
                print("git_webserver_deploy selection is valid")
                return 0
            if args.command == "render-practice":
                rendered = render_practice(selection, task_text)
                if rendered:
                    print(rendered)
                return 0
            expected_selected = args.target == "family_evidence"
            return 0 if bool(selection["selected"]) == expected_selected else 1
        if args.command == "init-contract":
            _write_json(args.contract, initial_contract())
            return 0
        if args.command in {"validate-contract", "contract-status"}:
            contract = _read_json(args.contract)
            problems = validate_contract(contract)
            if problems:
                return _print_errors(problems)
            if args.command == "validate-contract":
                print("task contract receipt is valid")
                return 0
            return 0 if contract.get("status") == args.status else 1
        if args.command == "init-review":
            selection = _read_json(args.selection)
            _raise_errors(validate_selection(selection, _read_text(args.task)))
            _write_json(args.review, initial_review(selection))
            return 0
        if args.command in {"validate-review", "review-status"}:
            task_text = _read_text(args.task)
            selection = _read_json(args.selection)
            review = _read_json(args.review)
            problems = validate_review(review, selection, task_text)
            if problems:
                return _print_errors(problems)
            if args.command == "validate-review":
                print("bounded self-review is valid")
                return 0
            status = review.get("status")
            allowed = {
                "repair": {"issues_found"},
                "family_evidence": {"clean", "needs_evidence"},
                "handoff": {"clean"},
                "deadline_handoff": {"deadline_handoff"},
            }[args.target]
            return 0 if status in allowed else 1
        if args.command == "run-gate":
            passed, receipt = run_gate(
                _read_json(args.selection), _read_text(args.task), args.receipt
            )
            for message in receipt["messages"]:
                print(message)
            return 0 if passed else 1
        if args.command == "validate-receipt":
            problems = validate_receipt(
                _read_json(args.receipt),
                _read_json(args.selection),
                _read_text(args.task),
                max_age_seconds=args.max_age_seconds,
            )
            if problems:
                return _print_errors(problems)
            print("git_webserver_deploy receipt is current and valid")
            return 0
        if args.command == "receipt-status":
            try:
                status = str(_read_json(args.receipt).get("status") or "failed")
            except (OSError, json.JSONDecodeError, AttributeError):
                status = "failed"
            return 0 if status == args.status else 1
        if args.command == "deadline":
            status = deadline_status(args.deadline)
            print(
                "deadline_status "
                f"mode={status.get('mode')} "
                f"remaining_seconds={status.get('remaining_seconds')} "
                f"configured={str(bool(status.get('configured'))).lower()}"
            )
            required_modes = {
                item.strip()
                for item in str(args.require_mode or "").split(",")
                if item.strip()
            }
            return _print_errors(
                validate_deadline_predicate(
                    status,
                    required_modes=required_modes,
                    min_remaining=args.min_remaining,
                    handoff_due_or_expired=args.handoff_due_or_expired,
                    heavy_work_closed_or_worse=args.heavy_work_closed_or_worse,
                )
            )
    except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc:
        print(f"git_webserver_deploy family error: {exc}")
        return 1
    return 2


if __name__ == "__main__":
    raise SystemExit(main())

# ===== file: integrations/harbor/statem_codex_git_webserver_deploy.py =====
from __future__ import annotations

import base64
import hashlib
import json
import os
import re
import shlex
import tempfile
import time
from pathlib import Path, PurePosixPath
from typing import Any

from harbor.agents.installed.codex import Codex
from harbor.environments.base import BaseEnvironment
from harbor.models.agent.context import AgentContext
from harbor.models.trial.paths import EnvironmentPaths


FAMILY_METADATA = {
    "name": "git_webserver_deploy",
    "policy_surface": "single_family",
    "selection_basis": "task_visible_contract",
}


class GitWebserverDeployFamilyStatemCodex(Codex):
    """Self-contained Harbor adapter for one executable StateM task family."""

    _PINNED_CODEX_VERSION = "0.146.0"
    _REMOTE_STATEM_SRC = PurePosixPath("/tmp/statem-src")
    _REMOTE_RUNBOOK_DIR = PurePosixPath("/tmp/statem-runbooks")
    _REMOTE_STATE_DIR = PurePosixPath("/tmp/statem-state")
    _REMOTE_CHECKS = PurePosixPath("/tmp/statem-verification-checks")
    _REMOTE_RUNBOOK = _REMOTE_RUNBOOK_DIR / "git-webserver-family.yaml"
    _REMOTE_HELPER = _REMOTE_CHECKS / "git_webserver_deploy_family.py"
    _REMOTE_STOP_HOOK = _REMOTE_CHECKS / "statem_stop_hook.py"
    _REMOTE_ADAPTER = _REMOTE_CHECKS / "git-webserver-family-adapter.py"
    _PUBLIC_STATEM_FILES = (
        "__init__.py",
        "__main__.py",
        "cli.py",
        "core.py",
        "miniyaml.py",
    )

    def __init__(
        self,
        *args: Any,
        statem_source_dir: str | None = None,
        runbook_path: str | None = None,
        run_id_prefix: str = "tb21-git-webserver-deploy",
        final_state: str = "handoff",
        enforce_final_state: bool = True,
        agent_deadline_seconds: int = 900,
        handoff_buffer_seconds: int = 120,
        heavy_work_buffer_seconds: int = 240,
        **kwargs: Any,
    ) -> None:
        requested_version = kwargs.get("version")
        if requested_version not in (None, self._PINNED_CODEX_VERSION):
            raise ValueError(
                "git_webserver_deploy family reproduction requires Codex "
                f"{self._PINNED_CODEX_VERSION}, got {requested_version}"
            )
        kwargs["version"] = self._PINNED_CODEX_VERSION
        super().__init__(*args, **kwargs)
        repo_root = Path(__file__).resolve().parents[2]
        self._statem_source_dir = (
            Path(statem_source_dir).expanduser().resolve()
            if statem_source_dir
            else repo_root
        )
        self._runbook_path = (
            Path(runbook_path).expanduser().resolve()
            if runbook_path
            else repo_root
            / "examples"
            / "terminal-bench-2.1-git-webserver-deploy-family.yaml"
        )
        self._helper_path = (
            repo_root
            / "integrations"
            / "harbor"
            / "experimental"
            / "git_webserver_deploy_family.py"
        )
        self._stop_hook_path = (
            repo_root / "integrations" / "hooks" / "statem_stop_hook.py"
        )
        self._adapter_path = Path(__file__).resolve()
        self._run_id_prefix = run_id_prefix
        self._final_state = final_state
        self._enforce_final_state = bool(enforce_final_state)
        self._agent_deadline_seconds = max(1, int(agent_deadline_seconds))
        self._handoff_buffer_seconds = max(1, int(handoff_buffer_seconds))
        self._heavy_work_buffer_seconds = max(1, int(heavy_work_buffer_seconds))
        self._source_manifest: dict[str, Any] | None = None

    @staticmethod
    def name() -> str:
        return "statem-codex-git-webserver-deploy-family"

    def build_cli_flags(self) -> str:
        flags = super().build_cli_flags()
        if self._get_env("CODEX_AUTH_JSON_PATH"):
            flags = f"{flags} -c cli_auth_credentials_store=file".strip()
        return f"{flags} --dangerously-bypass-hook-trust".strip()

    async def setup(self, environment: BaseEnvironment) -> None:
        await super().setup(environment)
        await self._install_family_runtime(environment)

    async def _install_family_runtime(self, environment: BaseEnvironment) -> None:
        required = [
            self._runbook_path,
            self._helper_path,
            self._stop_hook_path,
            self._adapter_path,
            *[
                self._statem_source_dir / "statem" / name
                for name in self._PUBLIC_STATEM_FILES
            ],
        ]
        missing = [str(path) for path in required if not path.is_file()]
        if missing:
            raise FileNotFoundError(
                "single-family publication is missing required files: "
                + ", ".join(missing)
            )

        await self.exec_as_root(
            environment,
            command=(
                "if command -v python3 >/dev/null 2>&1; then python3 --version; "
                "elif [ -f /etc/alpine-release ]; then apk add --no-cache python3; "
                "elif command -v apt-get >/dev/null 2>&1; then "
                "DEBIAN_FRONTEND=noninteractive apt-get update && "
                "DEBIAN_FRONTEND=noninteractive apt-get install -y python3; "
                "else echo 'python3 is required for statem' >&2; exit 1; fi"
            ),
        )
        await self.exec_as_root(
            environment,
            command=(
                f"rm -rf {shlex.quote(self._REMOTE_STATEM_SRC.as_posix())} "
                f"{shlex.quote(self._REMOTE_RUNBOOK_DIR.as_posix())} "
                f"{shlex.quote(self._REMOTE_STATE_DIR.as_posix())} "
                f"{shlex.quote(self._REMOTE_CHECKS.as_posix())} && "
                f"mkdir -p {shlex.quote((self._REMOTE_STATEM_SRC / 'statem').as_posix())} "
                f"{shlex.quote(self._REMOTE_RUNBOOK_DIR.as_posix())} "
                f"{shlex.quote(self._REMOTE_STATE_DIR.as_posix())} "
                f"{shlex.quote(self._REMOTE_CHECKS.as_posix())} && "
                f"chmod -R 777 {shlex.quote(self._REMOTE_STATEM_SRC.as_posix())} "
                f"{shlex.quote(self._REMOTE_RUNBOOK_DIR.as_posix())} "
                f"{shlex.quote(self._REMOTE_STATE_DIR.as_posix())} "
                f"{shlex.quote(self._REMOTE_CHECKS.as_posix())}"
            ),
        )

        for name in self._PUBLIC_STATEM_FILES:
            await environment.upload_file(
                self._statem_source_dir / "statem" / name,
                (self._REMOTE_STATEM_SRC / "statem" / name).as_posix(),
            )
        for local_path, remote_path in (
            (self._runbook_path, self._REMOTE_RUNBOOK),
            (self._helper_path, self._REMOTE_HELPER),
            (self._stop_hook_path, self._REMOTE_STOP_HOOK),
            (self._adapter_path, self._REMOTE_ADAPTER),
        ):
            await environment.upload_file(local_path, remote_path.as_posix())

        manifest = self._build_source_manifest()
        self._source_manifest = manifest
        await self._write_remote_text(
            environment,
            (self._REMOTE_CHECKS / "source-manifest.json").as_posix(),
            json.dumps(manifest, indent=2, sort_keys=True) + "\n",
        )
        await self.exec_as_root(
            environment,
            command=(
                "cat >/usr/local/bin/statem <<'SH'\n"
                "#!/bin/sh\n"
                f"PYTHONPATH={shlex.quote(self._REMOTE_STATEM_SRC.as_posix())} "
                "exec python3 -m statem.cli \"$@\"\n"
                "SH\n"
                "chmod +x /usr/local/bin/statem\n"
                f"statem validate {shlex.quote(self._REMOTE_RUNBOOK.as_posix())} "
                "--json >/tmp/statem-family-validate.json"
            ),
        )

    def _build_source_manifest(self) -> dict[str, Any]:
        entries: list[dict[str, Any]] = []
        for name in self._PUBLIC_STATEM_FILES:
            local = self._statem_source_dir / "statem" / name
            entries.append(
                self._manifest_entry(
                    "statem",
                    local,
                    self._REMOTE_STATEM_SRC / "statem" / name,
                )
            )
        entries.extend(
            [
                self._manifest_entry("runbook", self._runbook_path, self._REMOTE_RUNBOOK),
                self._manifest_entry("family_helper", self._helper_path, self._REMOTE_HELPER),
                self._manifest_entry("stop_hook", self._stop_hook_path, self._REMOTE_STOP_HOOK),
                self._manifest_entry("family_adapter", self._adapter_path, self._REMOTE_ADAPTER),
            ]
        )
        payload: dict[str, Any] = {
            "version": 1,
            "agent": self.name(),
            "family": FAMILY_METADATA,
            "runbook": self._local_relative(self._runbook_path),
            "file_count": len(entries),
            "files": entries,
        }
        encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
        payload["manifest_sha256"] = hashlib.sha256(encoded).hexdigest()
        return payload

    def _manifest_entry(
        self,
        group: str,
        path: Path,
        remote_path: PurePosixPath,
    ) -> dict[str, Any]:
        return {
            "group": group,
            "local_relative_path": self._local_relative(path),
            "remote_path": remote_path.as_posix(),
            "size_bytes": path.stat().st_size,
            "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
        }

    def _local_relative(self, path: Path) -> str:
        try:
            return path.relative_to(self._statem_source_dir).as_posix()
        except ValueError:
            return path.name

    async def _write_remote_text(
        self,
        environment: BaseEnvironment,
        remote_path: str,
        text: str,
    ) -> None:
        encoded = base64.b64encode(text.encode("utf-8")).decode("ascii")
        await self.exec_as_root(
            environment,
            command=(
                "python3 -c "
                + shlex.quote(
                    "import base64, pathlib; "
                    f"pathlib.Path({remote_path!r}).write_bytes(base64.b64decode({encoded!r}))"
                )
            ),
        )

    def _run_id(self, environment: BaseEnvironment) -> str:
        raw = f"{self._run_id_prefix}-{environment.session_id}"
        return re.sub(r"[^A-Za-z0-9_.-]+", "-", raw).strip("-") or self._run_id_prefix

    def _statem_env(self, run_id: str) -> dict[str, str]:
        return {
            "STATEM_STATE_DIR": self._REMOTE_STATE_DIR.as_posix(),
            "STATEM_AGENT_ID": self.name(),
            "STATEM_AGENT_ROLE": "benchmark-agent",
            "STATEM_RUN_ID": run_id,
            "STATEM_DEADLINE_FILE": (self._REMOTE_CHECKS / "deadline.json").as_posix(),
        }

    async def _write_task_and_deadline(
        self,
        environment: BaseEnvironment,
        run_id: str,
        instruction: str,
    ) -> None:
        await self._write_remote_text(
            environment,
            (self._REMOTE_CHECKS / "task.txt").as_posix(),
            instruction,
        )
        started = time.time()
        deadline = {
            "version": 1,
            "source": "git_webserver_deploy_family_adapter",
            "run_id": run_id,
            "started_at_epoch": started,
            "deadline_at_epoch": started + self._agent_deadline_seconds,
            "agent_deadline_seconds": self._agent_deadline_seconds,
            "handoff_buffer_seconds": self._handoff_buffer_seconds,
            "heavy_work_buffer_seconds": self._heavy_work_buffer_seconds,
        }
        await self._write_remote_text(
            environment,
            (self._REMOTE_CHECKS / "deadline.json").as_posix(),
            json.dumps(deadline, indent=2, sort_keys=True) + "\n",
        )

    async def _start_statem(self, environment: BaseEnvironment, run_id: str) -> None:
        result = await self.exec_as_agent(
            environment,
            command=(
                f"statem start {shlex.quote(self._REMOTE_RUNBOOK.as_posix())} "
                f"--state-dir {shlex.quote(self._REMOTE_STATE_DIR.as_posix())} "
                f"--run-id {shlex.quote(run_id)} "
                f"--agent-id {shlex.quote(self.name())} "
                "--agent-role benchmark-agent"
            ),
            env=self._statem_env(run_id),
        )
        return_code = getattr(
            result,
            "return_code",
            getattr(result, "returncode", 0),
        )
        if return_code not in (None, 0):
            raise RuntimeError(f"could not start StateM family run: {result.stderr}")

    async def _current_context(self, environment: BaseEnvironment, run_id: str) -> str:
        result = await self.exec_as_agent(
            environment,
            command=(
                "statem cur "
                f"--state-dir {shlex.quote(self._REMOTE_STATE_DIR.as_posix())} "
                f"--run-id {shlex.quote(run_id)} --json"
            ),
            env=self._statem_env(run_id),
        )
        return (result.stdout or "").strip()

    def _augment_instruction(
        self,
        instruction: str,
        run_id: str,
        current_context: str,
    ) -> str:
        state_dir = self._REMOTE_STATE_DIR.as_posix()
        return f"""You are {self.name()}, a Codex agent using one executable StateM task-family runbook.

Required StateM protocol:
- Inspect the current state before substantive work with:
  `statem cur --state-dir {state_dir} --run-id {run_id}`
- Follow the current state's prompt and hooks. Inspect the graph with:
  `statem state --state-dir {state_dir} --run-id {run_id}`
- Move only through explicit transitions with `statem goto TARGET --state-dir {state_dir} --run-id {run_id}`.
- Use `--yes` only after satisfying a transition's checklist and machine checks.
- If a transition fails, remain in the current state, repair the recorded issue, and retry it.
- Keep progress.md current with the visible contract, candidate identity, checks, and residual risk.
- The graph is `direct_solve -> task_contract_check -> self_review`, followed by a selected
  `family_evidence_check`, targeted `repair`, ordinary non-match `handoff`, or explicit
  `deadline_handoff`. There is no broad catalog or unrelated family route.
- Solve normally before self_review. Only the immutable task-visible selector may expose the
  git_webserver_deploy reviewer practice. A selected task normally requires the fixed stateful
  gate receipt before handoff; do not replace it with proxy evidence or rerun it at final handoff.
- Do not inspect benchmark answers, hidden tests, verifier internals, credentials, or unrelated files.

Current StateM state:
{current_context}

Benchmark task:
{instruction}
"""

    def _codex_stop_hook_payload(self) -> dict[str, Any]:
        command = (
            f"STATEM_STATE_DIR={shlex.quote(self._REMOTE_STATE_DIR.as_posix())} "
            "STATEM_COMMAND=statem STATEM_HOST=codex "
            f"python3 {shlex.quote(self._REMOTE_STOP_HOOK.as_posix())}"
        )
        return {
            "hooks": {
                "Stop": [
                    {
                        "hooks": [
                            {
                                "type": "command",
                                "command": command,
                                "timeout": 15,
                                "statusMessage": "Checking active StateM run",
                            }
                        ]
                    }
                ]
            }
        }

    async def _install_codex_stop_hook(self, environment: BaseEnvironment) -> None:
        await self.exec_as_agent(
            environment,
            command=f"mkdir -p {shlex.quote(self._REMOTE_CODEX_HOME.as_posix())}",
            env={"CODEX_HOME": self._REMOTE_CODEX_HOME.as_posix()},
        )
        await self._write_remote_text(
            environment,
            (self._REMOTE_CODEX_HOME / "hooks.json").as_posix(),
            json.dumps(self._codex_stop_hook_payload(), indent=2, sort_keys=True) + "\n",
        )

    async def _effective_agent_user(self, environment: BaseEnvironment) -> str | int:
        if environment.default_user is not None:
            return environment.default_user
        result = await self.exec_as_agent(environment, command="id -u")
        user = (result.stdout or "").strip()
        if not user.isdigit():
            raise RuntimeError(f"could not resolve container agent uid: {user!r}")
        return int(user)

    async def run(
        self,
        instruction: str,
        environment: BaseEnvironment,
        context: AgentContext,
    ) -> None:
        run_id = self._run_id(environment)
        await self._write_task_and_deadline(environment, run_id, instruction)
        await self._start_statem(environment, run_id)
        current_context = await self._current_context(environment, run_id)
        augmented = self._augment_instruction(instruction, run_id, current_context)
        await self._install_codex_stop_hook(environment)
        try:
            if environment.default_user is None:
                effective_user = await self._effective_agent_user(environment)
                with environment.with_default_user(effective_user):
                    await super().run(augmented, environment, context)
            else:
                await super().run(augmented, environment, context)
        finally:
            try:
                Codex.populate_context_post_run(self, context)
            finally:
                await self._remove_session_logs(environment)
                await self._collect_family_artifacts(environment, context, run_id)

    async def _remove_session_logs(self, environment: BaseEnvironment) -> None:
        try:
            await self.exec_as_agent(
                environment,
                command=(
                    f"rm -rf {shlex.quote((EnvironmentPaths.agent_dir / 'sessions').as_posix())}"
                ),
            )
        except Exception:
            return

    async def _collect_family_artifacts(
        self,
        environment: BaseEnvironment,
        context: AgentContext,
        run_id: str,
    ) -> None:
        current: dict[str, Any] | None = None
        try:
            current_raw = await self._current_context(environment, run_id)
            current = json.loads(current_raw)
        except (OSError, json.JSONDecodeError, TypeError, ValueError):
            current = None
        agent_statem = (EnvironmentPaths.agent_dir / "statem").as_posix()
        copy_names = (
            "git-webserver-selection.json",
            "task-contract-receipt.json",
            "self-review.json",
            "git-webserver-receipt.json",
            "task.txt",
            "deadline.json",
            "source-manifest.json",
        )
        commands = [f"mkdir -p {shlex.quote(agent_statem)}"]
        commands.extend(
            f"cp {shlex.quote((self._REMOTE_CHECKS / name).as_posix())} "
            f"{shlex.quote(f'{agent_statem}/{name}')} || true"
            for name in copy_names
        )
        commands.extend(
            [
                f"statem cur --state-dir {shlex.quote(self._REMOTE_STATE_DIR.as_posix())} "
                f"--run-id {shlex.quote(run_id)} --json >"
                f"{shlex.quote(f'{agent_statem}/current.json')} || true",
                f"statem history --state-dir {shlex.quote(self._REMOTE_STATE_DIR.as_posix())} "
                f"--run-id {shlex.quote(run_id)} --limit 100 --json >"
                f"{shlex.quote(f'{agent_statem}/history.json')} || true",
                f"cp -R {shlex.quote(self._REMOTE_STATE_DIR.as_posix())} "
                f"{shlex.quote(f'{agent_statem}/state')} || true",
            ]
        )
        await self.exec_as_agent(
            environment,
            command="\n".join(commands),
            env=self._statem_env(run_id),
        )
        context.metadata = dict(context.metadata or {})
        context.metadata["statem"] = {
            "run_id": run_id,
            "agent": self.name(),
            "family": FAMILY_METADATA,
            "current": current.get("current") if current else None,
            "current_entry_id": current.get("current_entry_id") if current else None,
            "source_manifest_sha256": (
                self._source_manifest.get("manifest_sha256")
                if self._source_manifest
                else None
            ),
            "family_artifacts": list(copy_names),
        }
        if self._enforce_final_state and (
            not current or current.get("current") != self._final_state
        ):
            raise RuntimeError(
                f"statem final state is {(current or {}).get('current')!r}, "
                f"expected {self._final_state!r}"
            )


class DeepSeekGitWebserverDeployFamilyStatemCodex(
    GitWebserverDeployFamilyStatemCodex
):
    """Self-contained family adapter with DeepSeek's official Codex config."""

    _EXPECTED_MODEL = "deepseek-v4-flash"

    def __init__(
        self,
        *args: Any,
        deepseek_config_home: str | None = None,
        **kwargs: Any,
    ) -> None:
        config_home = deepseek_config_home or os.environ.get(
            "DEEPSEEK_CODEX_CONFIG_HOME", ""
        )
        if not config_home:
            raise ValueError(
                "deepseek_config_home or DEEPSEEK_CODEX_CONFIG_HOME is required"
            )
        self._deepseek_config_home = Path(config_home).expanduser().resolve()
        self._deepseek_config = self._deepseek_config_home / "config.toml"
        self._deepseek_models = self._deepseek_config_home / "models.json"
        self._validate_deepseek_config()
        super().__init__(*args, **kwargs)

    @staticmethod
    def name() -> str:
        return "statem-deepseek-git-webserver-deploy-family"

    def _validate_deepseek_config(self) -> None:
        if not self._deepseek_config.is_file() or not self._deepseek_models.is_file():
            raise FileNotFoundError(
                "DeepSeek Codex config home must contain config.toml and models.json"
            )
        models = json.loads(self._deepseek_models.read_text(encoding="utf-8"))
        slugs = {
            str(item.get("slug"))
            for item in models.get("models", [])
            if isinstance(item, dict)
        }
        if self._EXPECTED_MODEL not in slugs:
            raise ValueError(f"DeepSeek model catalog is missing {self._EXPECTED_MODEL}")
        config_text = self._deepseek_config.read_text(encoding="utf-8")
        required_fragments = (
            'model_provider = "deepseek"',
            'base_url = "https://api.deepseek.com/"',
            'wire_api = "responses"',
            "experimental_bearer_token",
        )
        if any(fragment not in config_text for fragment in required_fragments):
            raise ValueError("DeepSeek config.toml is not an official provider config")

    @classmethod
    def _container_config_text(cls, source: str) -> str:
        catalog_path = cls._REMOTE_CODEX_HOME / "models.json"
        replacement = f'model_catalog_json = "{catalog_path}"'
        rendered, count = re.subn(
            r"(?m)^\s*model_catalog_json\s*=\s*[^\n]+$",
            replacement,
            source,
            count=1,
        )
        if count != 1:
            raise ValueError("DeepSeek config.toml must contain one model_catalog_json")
        return rendered

    async def _stage_deepseek_config(self, environment: BaseEnvironment) -> None:
        remote_home = self._REMOTE_CODEX_HOME.as_posix()
        await self.exec_as_agent(
            environment,
            command=f"mkdir -p {shlex.quote(remote_home)} && chmod 700 {shlex.quote(remote_home)}",
        )
        rendered = self._container_config_text(
            self._deepseek_config.read_text(encoding="utf-8")
        )
        temporary_name = ""
        try:
            with tempfile.NamedTemporaryFile(
                mode="w",
                encoding="utf-8",
                prefix="statem-deepseek-family-",
                suffix=".toml",
                delete=False,
            ) as handle:
                temporary_name = handle.name
                handle.write(rendered)
            os.chmod(temporary_name, 0o600)
            await environment.upload_file(
                Path(temporary_name),
                (self._REMOTE_CODEX_HOME / "config.toml").as_posix(),
            )
            await environment.upload_file(
                self._deepseek_models,
                (self._REMOTE_CODEX_HOME / "models.json").as_posix(),
            )
            if environment.default_user is not None:
                await self.exec_as_root(
                    environment,
                    command=(
                        f"chown {environment.default_user} "
                        f"{remote_home}/config.toml {remote_home}/models.json && "
                        f"chmod 600 {remote_home}/config.toml {remote_home}/models.json"
                    ),
                )
        finally:
            if temporary_name:
                Path(temporary_name).unlink(missing_ok=True)

    async def run(
        self,
        instruction: str,
        environment: BaseEnvironment,
        context: AgentContext,
    ) -> None:
        await self._stage_deepseek_config(environment)
        await super().run(instruction, environment, context)

# ===== file: integrations/hooks/statem_stop_hook.py =====
#!/usr/bin/env python3
"""Host Stop hook adapter for statem-managed runs.

Works with hosts whose Stop hook supports `{"decision": "block", "reason": ...}`
continuations, including Codex and Claude Code. This script intentionally does
not advance statem state. It only nudges the agent to inspect statem and keep
working when a run is active.
"""

from __future__ import annotations

import json
import os
import shlex
import subprocess
import sys
from pathlib import Path
from typing import Any


DEFAULT_STOP_STATES = {"handoff", "done", "complete", "completed", "finished"}


def main() -> int:
    payload = _read_payload()
    if payload.get("stop_hook_active") is True:
        return _allow()

    cwd = Path(str(payload.get("cwd") or os.getcwd())).expanduser().resolve()
    state_dir = Path(os.environ.get("STATEM_STATE_DIR", cwd / ".statem")).expanduser()
    if not state_dir.is_absolute():
        state_dir = (cwd / state_dir).resolve()

    if not (state_dir / "active_run").exists():
        return _allow()

    statem_cmd = os.environ.get("STATEM_COMMAND", f"{sys.executable} -m statem")
    cur = _run_statem_json(statem_cmd, cwd, state_dir, "cur")
    if cur is None:
        return _allow(
            system_message="statem Stop hook found an active run but could not read it; allowing stop."
        )

    current = str(cur.get("current") or "")
    stop_states = _stop_states()
    next_states = cur.get("next") or []
    if current in stop_states or not next_states:
        return _allow()

    reason = _continuation_reason(statem_cmd, state_dir, current, next_states)
    return _continue(reason)


def _read_payload() -> dict[str, Any]:
    try:
        raw = sys.stdin.read()
        return json.loads(raw) if raw.strip() else {}
    except json.JSONDecodeError:
        return {}


def _stop_states() -> set[str]:
    raw = os.environ.get("STATEM_AUTOLOOP_STOP_STATES")
    if not raw:
        return DEFAULT_STOP_STATES
    return {part.strip() for part in raw.split(",") if part.strip()}


def _run_statem_json(statem_cmd: str, cwd: Path, state_dir: Path, command: str) -> dict[str, Any] | None:
    try:
        argv = [*shlex.split(statem_cmd), command, "--state-dir", str(state_dir), "--json"]
        completed = subprocess.run(
            argv,
            cwd=cwd,
            text=True,
            capture_output=True,
            check=False,
            timeout=10,
        )
    except (OSError, ValueError, subprocess.TimeoutExpired):
        return None
    if completed.returncode != 0:
        return None
    try:
        return json.loads(completed.stdout)
    except json.JSONDecodeError:
        return None


def _continuation_reason(statem_cmd: str, state_dir: Path, current: str, next_states: list[Any]) -> str:
    next_names = ", ".join(str(edge.get("to")) for edge in next_states if isinstance(edge, dict)) or "(none)"
    return "\n".join(
        [
            "Continue the active statem-managed run instead of stopping.",
            "",
            "First inspect durable state:",
            f"{statem_cmd} cur --state-dir {sh_quote(str(state_dir))} --json",
            f"{statem_cmd} next --state-dir {sh_quote(str(state_dir))} --json",
            "",
            f"Current state: {current}",
            f"Allowed next states: {next_names}",
            "",
            "Follow the current node prompt. Move only with `statem goto <next-state>`.",
            "If the current node requires user input or is ready for handoff, explain that and stop.",
        ]
    )


def _allow(*, system_message: str | None = None) -> int:
    if system_message:
        print(json.dumps({"systemMessage": system_message}))
    return 0


def _continue(reason: str) -> int:
    print(json.dumps({"decision": "block", "reason": reason}))
    return 0


def sh_quote(value: str) -> str:
    return "'" + value.replace("'", "'\"'\"'") + "'"


if __name__ == "__main__":
    raise SystemExit(main())

# ===== file: statem/__init__.py =====
"""Command line state machine for agent long runs."""

__version__ = "0.1.0"


# ===== file: statem/__main__.py =====
from .cli import main


if __name__ == "__main__":
    raise SystemExit(main())


# ===== file: statem/cli.py =====
from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path
from typing import Any

from .core import RunOptions, StatemError, StatemRuntime, validate_spec


def main(argv: list[str] | None = None) -> int:
    parser = _build_parser()
    args = parser.parse_args(argv)
    if not hasattr(args, "handler"):
        parser.print_help()
        return 1

    options = RunOptions(
        state_dir=Path(args.state_dir),
        yes=bool(args.yes),
        json_mode=bool(args.json),
        run_id=args.run_id,
        agent_id=args.agent_id,
        agent_role=args.agent_role,
    )
    try:
        payload = args.handler(args, options)
    except StatemError as exc:
        if getattr(args, "json", False):
            error_payload: dict[str, Any] = {"ok": False, "error": str(exc)}
            if exc.details:
                error_payload["details"] = exc.details
            print(json.dumps(error_payload, indent=2, sort_keys=True))
        else:
            print(f"statem: {exc}", file=sys.stderr)
        return getattr(exc, "exit_code", 1)

    if args.json:
        print(json.dumps(payload, indent=2, sort_keys=True))
    else:
        _print_payload(args.command, payload)
    return 0


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="statem",
        description="Command line state machine for agent long runs.",
        epilog=(
            "Loop hygiene: for cyclic runbooks, model compaction as an explicit node "
            "and use 'statem compact-prompt' to generate a safe /compact instruction."
        ),
    )
    subparsers = parser.add_subparsers(dest="command")

    common = argparse.ArgumentParser(add_help=False)
    common.add_argument(
        "--state-dir",
        default=os.environ.get("STATEM_STATE_DIR", ".statem"),
        help="runtime state directory (default: $STATEM_STATE_DIR or .statem)",
    )
    common.add_argument("--run-id", help="run id to use instead of the active run")
    common.add_argument("--agent-id", default=os.environ.get("STATEM_AGENT_ID"), help="agent instance id for dynamic checks")
    common.add_argument("--agent-role", default=os.environ.get("STATEM_AGENT_ROLE"), help="agent role metadata for dynamic checks")
    common.add_argument("--yes", action="store_true", help="auto-confirm manual checks and checklists")
    common.add_argument("--json", action="store_true", help="emit machine-readable JSON")

    start = subparsers.add_parser("start", parents=[common], help="create or resume a run from a spec")
    start.add_argument("spec", help="spec file")
    start.add_argument("--fresh", action="store_true", help="force a new run even if an active run exists")
    start.set_defaults(handler=_cmd_start)

    cur = subparsers.add_parser("cur", parents=[common], help="show current state")
    cur.set_defaults(handler=_cmd_cur)

    state = subparsers.add_parser("state", parents=[common], help="list states and edges")
    state.set_defaults(handler=_cmd_state)

    show = subparsers.add_parser("ls", parents=[common], help="show node details")
    show.add_argument("node")
    show.set_defaults(handler=_cmd_ls)

    next_cmd = subparsers.add_parser("next", parents=[common], help="show next states")
    next_cmd.set_defaults(handler=_cmd_next)

    goto = subparsers.add_parser("goto", parents=[common], help="move to a next state")
    goto.add_argument("target")
    goto.set_defaults(handler=_cmd_goto)

    transfer = subparsers.add_parser("transfer", parents=[common], help="alias for goto")
    transfer.add_argument("target")
    transfer.set_defaults(handler=_cmd_goto)

    save = subparsers.add_parser("save", parents=[common], help="persist state and run current out_hook")
    save.add_argument("--skip-hooks", action="store_true", help="persist runtime state without running out_hook")
    save.set_defaults(handler=_cmd_save)

    history = subparsers.add_parser("history", parents=[common], help="show run history")
    history.add_argument("--limit", "--tail", dest="limit", type=int, help="show only the last N events")
    history.set_defaults(handler=_cmd_history)

    prompt = subparsers.add_parser("prompt", parents=[common], help="print a post-clear resume prompt")
    prompt.add_argument(
        "--command",
        dest="statem_command",
        default="statem",
        help="statem command to embed in the prompt",
    )
    prompt.set_defaults(handler=_cmd_prompt)

    compact_prompt = subparsers.add_parser(
        "compact-prompt",
        parents=[common],
        help="print a safe /compact prompt for loop hygiene",
    )
    compact_prompt.add_argument(
        "--command",
        dest="statem_command",
        default="statem",
        help="statem command to embed in the prompt",
    )
    compact_prompt.set_defaults(handler=_cmd_compact_prompt)

    validate = subparsers.add_parser("validate", parents=[common], help="validate a spec")
    validate.add_argument("spec")
    validate.add_argument(
        "--strict",
        action="store_true",
        help="reject unknown runbook keywords at every supported schema level",
    )
    validate.set_defaults(handler=_cmd_validate)

    dynamic = subparsers.add_parser("dynamic", parents=[common], help="manage current-entry dynamic checks")
    dynamic_subparsers = dynamic.add_subparsers(dest="dynamic_command")

    dynamic_path = dynamic_subparsers.add_parser("path", parents=[common], help="show dynamic check directory")
    dynamic_path.set_defaults(handler=_cmd_dynamic_path)

    dynamic_write = dynamic_subparsers.add_parser("write", parents=[common], help="write checks for this agent")
    dynamic_write.add_argument("checks_file", help="JSON or mini-YAML dynamic checks file")
    dynamic_write.add_argument("--role", help="producer role metadata")
    dynamic_write.set_defaults(handler=_cmd_dynamic_write)

    dynamic_list = dynamic_subparsers.add_parser("list", parents=[common], help="list current dynamic check producers")
    dynamic_list.set_defaults(handler=_cmd_dynamic_list)

    dynamic_show = dynamic_subparsers.add_parser("show", parents=[common], help="alias for dynamic list")
    dynamic_show.set_defaults(handler=_cmd_dynamic_list)

    return parser


def _cmd_start(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).start(args.spec, fresh=args.fresh)


def _cmd_cur(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).cur()


def _cmd_state(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).graph_state()


def _cmd_ls(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).node_details(args.node)


def _cmd_next(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).next_states()


def _cmd_goto(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).goto(args.target)


def _cmd_save(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).save(skip_hooks=args.skip_hooks)


def _cmd_history(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).history(limit=args.limit)


def _cmd_prompt(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).prompt(command=args.statem_command)


def _cmd_compact_prompt(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).compact_prompt(command=args.statem_command)


def _cmd_validate(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return validate_spec(args.spec, strict=args.strict)


def _cmd_dynamic_path(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).dynamic_path()


def _cmd_dynamic_write(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).dynamic_write(args.checks_file, agent_id=args.agent_id, role=args.role)


def _cmd_dynamic_list(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]:
    return StatemRuntime(options).dynamic_list()


def _print_payload(command: str, payload: dict[str, Any]) -> None:
    if command in {"start", "cur"}:
        _print_cur(payload)
    elif command == "state":
        _print_state(payload)
    elif command == "ls":
        _print_node(payload)
    elif command == "next":
        _print_next(payload)
    elif command in {"goto", "transfer"}:
        _print_goto(payload)
    elif command == "save":
        _print_save(payload)
    elif command == "history":
        _print_history(payload)
    elif command in {"prompt", "compact-prompt"}:
        print(payload["prompt"], end="")
    elif command == "validate":
        _print_validate(payload)
    elif command == "dynamic":
        _print_dynamic(payload)
    else:
        print(json.dumps(payload, indent=2, sort_keys=True))


def _print_cur(payload: dict[str, Any]) -> None:
    print(f"Run: {payload['run_id']}")
    print(f"Spec: {payload['spec_name']} ({payload['spec']})")
    print(f"Current: {payload['current']}")
    if payload.get("current_entry_id"):
        print(f"Entry: {payload['current_entry_id']}")
    if payload.get("dynamic_before_transfer"):
        dynamic = payload["dynamic_before_transfer"]
        print(f"Dynamic checks: {dynamic.get('resolved_path') or dynamic.get('path')}")
    if payload.get("prompt"):
        print("\nPrompt:")
        print(payload["prompt"])
    if payload.get("before_transfer"):
        print("\nBefore transfer:")
        for item in payload["before_transfer"]:
            print(f"- {_summary_text(item)}")
    _print_next({"next": payload.get("next", [])})


def _print_state(payload: dict[str, Any]) -> None:
    print(f"Run: {payload['run_id']}")
    print(f"Current: {payload['current']}")
    print("\nStates:")
    for node in payload["nodes"]:
        marker = "*" if node["name"] == payload["current"] else "-"
        print(f"{marker} {node['name']}")
    print("\nEdges:")
    for edge in payload["edges"]:
        print(f"- {edge['from']} -> {edge['to']}")


def _print_node(payload: dict[str, Any]) -> None:
    current_marker = " (current)" if payload["node"] == payload["current"] else ""
    print(f"Node: {payload['node']}{current_marker}")
    if payload.get("prompt"):
        print("\nPrompt:")
        print(payload["prompt"])
    for key, title in [("in_hook", "In hook"), ("before_transfer", "Before transfer"), ("out_hook", "Out hook")]:
        if payload.get(key):
            print(f"\n{title}:")
            for item in payload[key]:
                print(f"- {_summary_text(item)}")
    if payload.get("dynamic_before_transfer"):
        dynamic = payload["dynamic_before_transfer"]
        print("\nDynamic before transfer:")
        print(f"- path: {dynamic.get('resolved_path') or dynamic.get('path')}")
        print(f"- allow_types: {', '.join(dynamic.get('allow_types', []))}")
    _print_next({"next": payload.get("next", [])})


def _print_next(payload: dict[str, Any]) -> None:
    print("\nNext:")
    if not payload.get("next"):
        print("- (none)")
        return
    for edge in payload["next"]:
        condition = ""
        if edge.get("condition"):
            condition = " | condition: " + "; ".join(_summary_text(item) for item in edge["condition"])
        attempts = f" | max_attempts: {edge['max_attempts']}" if "max_attempts" in edge else ""
        print(f"- {edge['to']}{attempts}{condition}")


def _print_goto(payload: dict[str, Any]) -> None:
    print(f"Moved: {payload['from']} -> {payload['to']}")
    _print_results(payload.get("results", []))


def _print_save(payload: dict[str, Any]) -> None:
    print(f"Saved run {payload['run_id']} at {payload['current']}")
    _print_results(payload.get("results", []))


def _print_history(payload: dict[str, Any]) -> None:
    print(f"Run: {payload['run_id']}")
    print(f"Current: {payload['current']}")
    for event in payload.get("history", []):
        if event["event"] == "goto":
            detail = f"{event.get('from')} -> {event.get('to')}"
        elif event["event"] in {"goto_blocked", "save", "save_blocked"}:
            detail = event.get("stage") or event.get("node") or ""
        else:
            detail = event.get("current") or event.get("node") or ""
        print(f"- {event['ts']} {event['event']} {detail}".rstrip())


def _print_validate(payload: dict[str, Any]) -> None:
    print(f"Valid spec: {payload['name']}")
    if payload.get("strict"):
        print("Strict keywords: yes")
    print(f"Initial: {payload['initial']}")
    print(f"Nodes: {', '.join(payload['nodes'])}")
    print(f"Edges: {len(payload['edges'])}")


def _print_dynamic(payload: dict[str, Any]) -> None:
    print(f"Run: {payload['run_id']}")
    print(f"Current: {payload['current']}")
    print(f"Entry: {payload.get('current_entry_id')}")
    if payload.get("agent_id"):
        print(f"Agent: {payload['agent_id']}")
    if payload.get("path"):
        print(f"Path: {payload['path']}")
    if "checks" in payload:
        print(f"Checks: {payload['checks']}")
    for producer in payload.get("producers", []):
        details = producer.get("producer", {})
        label = details.get("agent_id") or producer.get("path")
        print(f"- {label}: {producer.get('checks', 0)} check(s)")


def _print_results(results: list[dict[str, Any]]) -> None:
    interesting = [result for result in results if not result["passed"] or result.get("continued")]
    if not interesting:
        return
    print("\nChecks:")
    for result in interesting:
        status = "continued" if result.get("continued") else "failed"
        print(f"- {result['purpose']} {result['type']} {status}: {result.get('output', '')}")


def _summary_text(item: dict[str, Any]) -> str:
    item_type = item.get("type")
    if item_type == "command":
        return f"command: {item.get('run')}"
    if item_type == "llm_review":
        command = item.get("run") or "$STATEM_LLM_REVIEW_CMD"
        return f"llm_review: {item.get('prompt')} via {command}"
    if item_type == "predicate":
        bits = [f"predicate: {item.get('path')}"]
        for key in ("exists", "non_empty", "contains", "matches", "json_path", "equals"):
            if key in item:
                bits.append(f"{key}={item[key]!r}")
        return ", ".join(bits)
    if item_type == "checklist":
        return "checklist: " + ", ".join(str(value) for value in item.get("items", []))
    return f"{item_type}: {item.get('text')}"


if __name__ == "__main__":
    raise SystemExit(main())

# ===== file: statem/core.py =====
from __future__ import annotations

import difflib
import hashlib
import json
import os
import re
import shlex
import subprocess
import sys
import time
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from . import miniyaml


class StatemError(Exception):
    exit_code = 1

    def __init__(self, message: str, *, details: dict[str, Any] | None = None) -> None:
        super().__init__(message)
        self.details = details or {}


class TransitionBlocked(StatemError):
    exit_code = 2


DYNAMIC_PURPOSE = "dynamic_before_transfer"
GATING_PURPOSES = {"condition", "before_transfer", DYNAMIC_PURPOSE}
HOOK_KEYS = {"in_hook", "before_transfer", "out_hook", "condition", "hook"}
CHECK_TYPES = {"message", "manual", "checklist", "command", "predicate", "llm_review"}

STRICT_ROOT_KEYS = {"name", "initial", "start", "nodes", "edges"}
STRICT_NODE_KEYS = {
    "name",
    "prompt",
    "pre_request",
    "pre-request",
    "next",
    "next_states",
    "in_hook",
    "before_transfer",
    DYNAMIC_PURPOSE,
    "out_hook",
}
STRICT_EDGE_KEYS = {
    "from",
    "source",
    "node1",
    "to",
    "target",
    "node2",
    "condition",
    "hook",
    "max_attempts",
}
STRICT_NESTED_EDGE_KEYS = {"to", "target", "name", "condition", "hook", "max_attempts"}
STRICT_DYNAMIC_CONFIG_KEYS = {
    "path",
    "required",
    "min_items",
    "require_reason",
    "require_basis",
    "merge",
    "refresh",
    "stale_policy",
    "allow_types",
}
STRICT_CHECK_COMMON_KEYS = {"type", "blocking", "on_failure"}
STRICT_CHECK_KEYS = {
    "message": STRICT_CHECK_COMMON_KEYS | {"text", "prompt"},
    "manual": STRICT_CHECK_COMMON_KEYS | {"prompt", "text", "name", "confirmation", "confirm"},
    "checklist": STRICT_CHECK_COMMON_KEYS | {"items", "checks", "confirmation", "confirm"},
    "command": STRICT_CHECK_COMMON_KEYS | {"run", "cmd", "command", "timeout", "cwd"},
    "predicate": STRICT_CHECK_COMMON_KEYS
    | {
        "path",
        "cwd",
        "exists",
        "non_empty",
        "contains",
        "not_contains",
        "matches",
        "json_path",
        "equals",
        "one_of",
    },
    "llm_review": STRICT_CHECK_COMMON_KEYS
    | {
        "run",
        "cmd",
        "command",
        "prompt",
        "text",
        "name",
        "timeout",
        "cwd",
        "stdin",
        "accept_contains",
        "reject_contains",
        "accept_regex",
        "reject_regex",
    },
}


@dataclass
class RunOptions:
    state_dir: Path
    yes: bool = False
    json_mode: bool = False
    run_id: str | None = None
    agent_id: str | None = None
    agent_role: str | None = None

    def emit(self, message: str) -> None:
        if message and not self.json_mode:
            print(message)


@dataclass
class StatemSpec:
    path: Path
    raw: dict[str, Any]
    name: str
    initial: str
    nodes: dict[str, dict[str, Any]]
    edges: list[dict[str, Any]]
    outgoing: dict[str, list[dict[str, Any]]]
    spec_hash: str

    @classmethod
    def load(cls, path: str | os.PathLike[str], *, strict: bool = False) -> "StatemSpec":
        spec_path = Path(path).expanduser().resolve()
        if not spec_path.exists():
            raise StatemError(f"Spec file not found: {spec_path}")
        text = spec_path.read_text(encoding="utf-8")
        raw = _load_mapping(text, spec_path)
        if strict:
            strict_errors = _strict_keyword_errors(raw)
            if strict_errors:
                raise StatemError("Invalid spec:\n" + "\n".join(f"- {error}" for error in strict_errors))
        name = str(raw.get("name") or spec_path.stem)
        nodes = _normalize_nodes(raw.get("nodes"))
        if not nodes:
            raise StatemError("Spec must define at least one node")
        initial = str(raw.get("initial") or raw.get("start") or next(iter(nodes)))
        edges = _normalize_edges(raw, nodes)
        outgoing: dict[str, list[dict[str, Any]]] = {name: [] for name in nodes}
        for edge in edges:
            outgoing.setdefault(edge["from"], []).append(edge)
        spec = cls(
            path=spec_path,
            raw=raw,
            name=name,
            initial=initial,
            nodes=nodes,
            edges=edges,
            outgoing=outgoing,
            spec_hash=_sha256_text(text),
        )
        errors = spec.validation_errors()
        if errors:
            raise StatemError("Invalid spec:\n" + "\n".join(f"- {error}" for error in errors))
        return spec

    def validation_errors(self) -> list[str]:
        errors: list[str] = []
        if self.initial not in self.nodes:
            errors.append(f"initial node '{self.initial}' is not defined")

        seen_edges: set[tuple[str, str]] = set()
        for index, edge in enumerate(self.edges, start=1):
            source = edge.get("from")
            target = edge.get("to")
            if source not in self.nodes:
                errors.append(f"edge {index} source '{source}' is not a node")
            if target not in self.nodes:
                errors.append(f"edge {index} target '{target}' is not a node")
            edge_key = (str(source), str(target))
            if edge_key in seen_edges:
                errors.append(f"duplicate edge '{source}' -> '{target}' makes goto ambiguous")
            seen_edges.add(edge_key)
            errors.extend(_validate_edge_max_attempts(edge, f"edge {source}->{target}"))
            errors.extend(_validate_items(edge.get("condition"), "condition", f"edge {source}->{target} condition"))
            errors.extend(_validate_items(edge.get("hook"), "hook", f"edge {source}->{target} hook"))

        for name, node in self.nodes.items():
            errors.extend(_validate_items(node.get("in_hook"), "in_hook", f"node {name} in_hook"))
            errors.extend(_validate_items(node.get("before_transfer"), "before_transfer", f"node {name} before_transfer"))
            errors.extend(_validate_items(node.get("out_hook"), "out_hook", f"node {name} out_hook"))
            errors.extend(_validate_dynamic_config(node.get(DYNAMIC_PURPOSE), f"node {name} {DYNAMIC_PURPOSE}"))
        return errors

    def node_prompt(self, name: str) -> str:
        node = self.nodes[name]
        return str(node.get("prompt") or node.get("pre_request") or node.get("pre-request") or "")

    def edge_to(self, source: str, target: str) -> dict[str, Any] | None:
        matches = [edge for edge in self.outgoing.get(source, []) if edge.get("to") == target]
        if not matches:
            return None
        return matches[0]


class StatemRuntime:
    def __init__(self, options: RunOptions) -> None:
        self.options = options
        self.state_dir = options.state_dir.expanduser().resolve()

    def start(self, spec_path: str, *, fresh: bool = False) -> dict[str, Any]:
        spec = StatemSpec.load(spec_path)
        self.state_dir.mkdir(parents=True, exist_ok=True)
        (self.state_dir / "runs").mkdir(parents=True, exist_ok=True)

        requested_run_id = _clean_run_id(self.options.run_id) if self.options.run_id else None
        run_id = requested_run_id
        if run_id is None and not fresh:
            run_id = self._active_run_for_spec(spec)
        if run_id is None:
            run_id = _new_run_id()

        state_path = self._state_path(run_id)
        is_new = fresh or not state_path.exists()
        if is_new:
            state = {
                "version": 1,
                "run_id": run_id,
                "spec_path": str(spec.path),
                "spec_hash": spec.spec_hash,
                "current": spec.initial,
                "current_entry_id": _new_entry_id(),
                "created_at": _now(),
                "updated_at": _now(),
                "history": [],
            }
            self._ensure_agent_identity(state)
            self._ensure_entry_manifest(spec, state, spec.initial)
            _append_event(state, "start", {"current": spec.initial, "spec": str(spec.path)})
        else:
            state = _read_json(state_path)
            self._ensure_agent_identity(state)
            previous_current = str(state.get("current"))
            if previous_current not in spec.nodes:
                state["current"] = spec.initial
                state["current_entry_id"] = _new_entry_id()
                self._ensure_entry_manifest(spec, state, spec.initial)
                _append_event(
                    state,
                    "migrate_current",
                    {
                        "from": previous_current,
                        "to": spec.initial,
                        "reason": "current state missing from updated spec",
                    },
                )
            state["spec_path"] = str(spec.path)
            state["spec_hash"] = spec.spec_hash
            self._ensure_current_entry(spec, state)
            _append_event(state, "resume", {"current": state["current"], "spec": str(spec.path)})

        self._write_active(run_id)
        self._write_state(state)
        results = self._run_node_items(spec, state, str(state["current"]), "in_hook")
        _append_event(
            state,
            "in_hook",
            {"node": state["current"], "reason": "start" if is_new else "resume", "results": results},
        )
        self._write_state(state)
        _raise_if_blocked(
            results,
            f"Run '{run_id}' started, but in_hook failed for '{state['current']}'",
            details={
                "run_id": run_id,
                "current": state["current"],
                "stage": "in_hook",
                "results": results,
            },
        )

        return self.cur(run_id=run_id)

    def cur(self, *, run_id: str | None = None) -> dict[str, Any]:
        spec, state = self._load_runtime(run_id)
        current = state["current"]
        return {
            "run_id": state["run_id"],
            "spec": str(spec.path),
            "spec_name": spec.name,
            "current": current,
            "current_entry_id": state.get("current_entry_id"),
            "agent_id": self._ensure_agent_identity(state),
            "dynamic_before_transfer": _dynamic_summary(
                spec.nodes[current].get(DYNAMIC_PURPOSE),
                self._dynamic_dir(state, current, str(state.get("current_entry_id"))),
            ),
            "prompt": spec.node_prompt(current),
            "before_