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

One mechanism for every environment: receive the goal -> inspect the environment -> compose the work -> execute -> check the
actual result -> repair, or ask for the one missing detail -> continue with the task intact.

The environment is a folder on this machine or a host reached over ssh (its alias), chosen per conversation, with the
authority to change it held per conversation (read only until the operator says "allow changes"). Each conversation owns
its environment, its pending offers and its last operation, so "here", "it", "that" and "go" never cross conversations.

  open <folder>  /  connect to <host> [read only]          the environment for this conversation
  allow changes  /  read only                               this conversation's authority over it
  ls, read <file> [lines a-b], grep <text> [in <path>], files named <pattern>
  run `command`  /  call `command` the <name> [alone]  /  the <name> passes when it says "..."  /  run the <name>  /  run it again
  where are we, what failed, did that solve it, what changed, undo, todo <text>, tasks, done <n>, go [n], cancel
  in <file> replace "a" with "b"   /   write <file> + body   exact edits the operator gives
  <a described change>  ("the addition function subtracts; correct it and run the tests", "fix that",
                         "handle the empty case too")    repair.py finds the code, composes candidate changes, and the
                                                           project's own checks decide; or it names the missing step
  audit / check the ssh (nginx, ports, logs) config       findings.py: findings with evidence, a prepared correction,
  fix <n>                                                  applied only with authority, verified by checking again

Every reply carries an execution receipt (started, finished, exit, timeout, check, files) and its status follows the
receipt: a failed run is never marked answered. Nothing here writes a sentence of its own; no language model. Secret-shaped
files are never read, searched or shown."""
import difflib
import fnmatch
import hashlib
import json
import os
import py_compile
import re
import secrets
import shlex
import shutil
import subprocess
import sys
import time
from pathlib import Path

NL = chr(10)
HOME = Path(os.environ.get("ORACLE7_BENCH_HOME") or (Path(os.environ.get("ORACLE7_STATE") or Path.home() / ".oracle7") / "bench"))
SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", "env", ".mypy_cache", ".pytest_cache", "dist", "build",
             ".next", ".cache", "target"}
SECRET = re.compile(r"(?i)(secret|credential|wallet|password|passwd|\.env$|^\.env|token|key_guard|keys\.py|\.pem$|\.key$|id_rsa|"
                    r"id_ed25519|^auth(?!\.log)|hugs\.txt|keypair|shadow$)")
SECRET_TEXT = re.compile(r"(hf_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9_-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{30,})")
DANGER = re.compile(r"(?i)(\brm\s+-[a-z]*[rf]|\bmkfs|\bdd\s+if=|\bshutdown\b|\breboot\b|\bgit\s+push\b.*--force|\bgit\s+reset\s+--hard|"
                    r">\s*/dev/sd|\bchmod\s+-R\s+777|\bkill\s+-9|\bpkill\b|\bsystemctl\s+(stop|disable|restart|reload)|\bdrop\s+table|"
                    r"\btruncate\b|\bcurl\b.*\|\s*(ba)?sh|\bwget\b.*\|\s*(ba)?sh|\biptables\b|\bufw\s+(deny|reset|disable))")
QUICK = 20
SSH = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10"]
RUNNER = r'''import json, os, signal, subprocess, sys, time
from pathlib import Path
d, lock = Path(sys.argv[1]), sys.argv[2]
owner = json.loads((d / "owner.json").read_text())
held = False
handled = None
started = False
stopped = None
child = None
rc = -1

def put(name, value):
    target = d / name
    temp = d / (name + ".runner-new")
    temp.write_text(value)
    os.replace(temp, target)

def stop_request():
    try:
        request = json.loads((d / "stop.json").read_text())
        if request.get("id") == handled or not request.get("id"):
            return None
        if all(request.get(k) == owner.get(k) for k in ("token", "sid", "env", "job")):
            return request
    except (OSError, ValueError, TypeError):
        pass
    return None

def stop_child():
    # The owning Popen retains its process handle. No stored/user-supplied PID
    # is signalled; the child must still be live in this runner.
    if child.poll() is not None:
        return False
    if os.name == "nt":
        result = subprocess.run(["taskkill", "/PID", str(child.pid), "/T", "/F"],
                                capture_output=True, timeout=10)
        if result.returncode and child.poll() is None:
            raise RuntimeError(result.stderr.decode(errors="replace")[-500:])
    else:
        os.killpg(child.pid, signal.SIGTERM)
        # Do not reap the session leader before the final group signal: its
        # unreaped PID cannot be reused for an unrelated process group.
        time.sleep(.25)
        try:
            os.killpg(child.pid, signal.SIGKILL)
        except ProcessLookupError:
            pass
    child.wait(timeout=5)
    return True

put("pid", str(os.getpid()))
with (d / "log").open("wb") as lg:
    try:
        while lock != "-" and not held:
            stopped = stop_request()
            if stopped:
                break
            try:
                with open(lock, "x") as stream:
                    stream.write(str(d))
                held = True
            except FileExistsError:
                time.sleep(.1)
        stopped = stopped or stop_request()
        if stopped:
            rc = 130
        else:
            cmd = (d / "cmd").read_text()
            kwargs = {"creationflags": 0x00000200} if os.name == "nt" else {"start_new_session": True}
            child = subprocess.Popen(cmd, shell=True, stdout=lg, stderr=subprocess.STDOUT,
                                     stdin=subprocess.DEVNULL, **kwargs)
            started = True
            put("started", str(time.time()))
            put("child_pid", str(child.pid))
            while child.poll() is None:
                request = stop_request()
                if request:
                    try:
                        if stop_child():
                            stopped = request
                            break
                    except Exception as error:
                        handled = request["id"]
                        put("stop_error.json", json.dumps({"id": handled, "error": repr(error)}))
                time.sleep(.1)
            rc = child.wait()
    except Exception as error:
        lg.write((repr(error) + "\n").encode()); lg.flush()
        if child is not None and child.poll() is None:
            try:
                stop_child()
            except Exception:
                pass
        rc = -1
    finally:
        if stopped:
            lg.write(b"\n[Oracle7] stopped by this conversation's request.\n"); lg.flush()
            put("stopped.json", json.dumps({"state": "stopped", "started": started,
                "request": stopped["id"], "sid": owner["sid"], "env": owner["env"], "job": owner["job"]}))
        put("exit", str(rc))
        if held:
            try:
                if Path(lock).read_text() == str(d):
                    os.remove(lock)
            except OSError:
                pass
'''


GUARD = r'''"""Oracle7 network scope: Python programs run for a conversation may connect only to loopback and to the hosts the
conversation allowed ("allow network to <host>"). A guard inside Python processes, not a jail: a program started with -I or
-S, or not written in Python, is not covered."""
import os
import socket

_SCOPE = {h.strip().lower() for h in os.environ.get("O7_NET_SCOPE", "").split(",") if h.strip()}
_DENY = {int(p) for p in os.environ.get("O7_DENY_PORTS", "").split(",") if p.strip().isdigit()}
_IPS = set()
for _h in list(_SCOPE):
    try:
        for _fam, _t, _p, _c, _sa in socket.getaddrinfo(_h, None):
            _IPS.add(str(_sa[0]).lower())
    except Exception:
        pass


def _o7_check(addr):
    if not isinstance(addr, tuple) or not addr:
        return                                        # a local (unix) socket
    host = str(addr[0]).lower()
    loop = host in ("localhost", "::1", "0.0.0.0") or host.startswith("127.")
    if loop and len(addr) > 1 and addr[1] in _DENY:
        raise PermissionError("Oracle7: a run of project code may not reach Oracle7's own port %s." % addr[1])
    if loop or host in _SCOPE or host in _IPS:
        return
    raise PermissionError("Oracle7: %s is outside this conversation's network scope (allowed: loopback%s). Say \"allow "
                          "network to %s\" to reach it." % (host, "".join(", " + h for h in sorted(_SCOPE)), host))


_o7_connect, _o7_connect_ex, _o7_sendto = socket.socket.connect, socket.socket.connect_ex, socket.socket.sendto


def _connect(self, addr):
    _o7_check(addr)
    return _o7_connect(self, addr)


def _connect_ex(self, addr):
    _o7_check(addr)
    return _o7_connect_ex(self, addr)


def _sendto(self, data, *rest):
    _o7_check(rest[-1] if rest else None)
    return _o7_sendto(self, data, *rest)


socket.socket.connect, socket.socket.connect_ex, socket.socket.sendto = _connect, _connect_ex, _sendto
'''


def _guard_env(env):
    """the environment a conversation's runs get: the scope guard first on the path, its hosts named"""
    import runjail                                 # round-3 R2: no Oracle7 state, private home/temp, head port refused
    return runjail.env(root=getattr(env, "root", None), net_scope=getattr(env, "net_scope", []) or [])


def _authority(turn):
    """the authority a turn's work runs under, as a dependency of its attempts (12.0 C31)"""
    return {"net_scope": sorted(turn.s.get("net_scope") or []), "may_change": bool(_may_change(turn))}


def net_scope(turn, host):
    """'allow network to <host>' / 'no network': which hosts this conversation's runs and examples may reach"""
    if turn.env is None:
        return None
    sc = list(turn.s.get("net_scope", []))
    if host is None:
        turn.s["net_scope"] = []
        turn.save()
        return _r("This conversation's runs may now reach loopback only; no example pages are fetched.", "done", "netscope",
                  scope=[])
    host = host.strip().strip("`'\".,").lower()
    if host not in sc:
        sc.append(host)
    turn.s["net_scope"] = sc
    turn.save()
    return _r("This conversation may now reach %s over the network: example pages there are read once each while composing, "
              "and this project's runs may connect to it. Every other host stays outside the scope (loopback is always "
              "inside). The scope is a guard in the Python programs run here, not a jail." % host, "done", "netscope", scope=sc)


_NET = re.compile(r"(?i)^\s*(?:allow|permit|open)\s+(?:the\s+)?network\s+(?:access\s+)?(?:to|for)\s+([\w.:-]+)\s*[.!]*$")
_NONET = re.compile(r"(?i)^\s*(?:no network|close the network|network off|block (?:the )?network)\s*[.!]*$")


# ---------------------------------------------------------------- state
def _p(name):
    HOME.mkdir(parents=True, exist_ok=True)
    return HOME / name


def _load(name, default):
    try:
        return json.load(open(_p(name)))
    except Exception:  # noqa: BLE001
        return default


def _save(name, obj):
    p = _p(name)
    tmp = p.with_suffix(".tmp%d" % os.getpid())
    json.dump(obj, open(tmp, "w"), indent=1)
    os.replace(tmp, p)


def _sidf(sid):
    return "sid_%s.json" % re.sub(r"[^A-Za-z0-9_-]", "", str(sid))[:60]


class Turn:
    """one conversation's view: its environment, authority, offers and last operation"""

    def __init__(self, sid):
        self.sid = sid
        self.s = _load(_sidf(sid), {})

    def save(self):
        _save(_sidf(self.sid), self.s)

    @property
    def env(self):
        e = self.s.get("env")
        if not e:
            return None
        env = Env(e)
        env.net_scope = list(self.s.get("net_scope", []))
        return env

    def offer(self, o):
        """12.5 step 8 (held register, design 1.3): one row set keyed by id. A new offer never drops an older one of the same
        kind (a second `cmd` used to replace the first silently); only a row offering the very same thing is replaced by
        the newer. Each row carries born, owner, env, the file's sha and the test verdict where they apply."""
        offers = [x for x in self.s.get("offers", []) if _same_offer(x) != _same_offer(o)]
        self.s["offer_seq"] = int(self.s.get("offer_seq") or 0) + 1
        o["id"] = self.s["offer_seq"]
        o.setdefault("owner", "bench")
        o["t"] = time.time()
        o["born"] = _delivered_seq(self.sid)          # 12.5 step 7: the turn it was offered on (the one exit's own count)
        if o.get("file") and self.env is not None:   # 12.5 step 8: what the offer rests on, to be found unchanged at go
            try:
                o["file_sha"] = hashlib.sha256((self.env.read(o["file"]) or "").encode("utf-8", "replace")).hexdigest()
            except Exception:  # noqa: BLE001
                o["file_sha"] = None
        o["env"] = self.s.get("env")
        offers.append(o)
        self.s["offers"] = offers[-8:]
        self.save()

    def last(self, **kw):
        if kw:
            self.s["last"] = dict(kw, t=time.time(), env=self.s.get("env"))
            self.save()
        return self.s.get("last") or {}


class Env:
    """a folder here, or a host over ssh; root is where paths start"""

    def __init__(self, d):
        self.d = d
        self.net_scope = []
        self.kind, self.root, self.host = d["kind"], d["root"], d.get("host")
        self.key = hashlib.sha256(json.dumps([self.kind, self.host, self.root]).encode()).hexdigest()[:12]

    def label(self):
        return ("host %s:%s" % (self.host, self.root)) if self.kind == "host" else self.root

    def path(self, name):
        name = name.strip().strip("`'\"")
        if self.kind == "host":
            return name if name.startswith("/") else (self.root.rstrip("/") + "/" + name)
        p = Path(os.path.expanduser(name))
        return str(p if p.is_absolute() else Path(self.root) / name)

    def sh(self, cmd, timeout=60):
        """(exit or None on timeout, output)"""
        if self.kind == "host":
            argv = SSH + [self.host, "cd %s && %s" % (shlex.quote(self.root), cmd)]
            kw = {}
        else:
            argv, kw = cmd, {"shell": True, "cwd": self.root, "env": _guard_env(self)}
        try:
            r = subprocess.run(argv, capture_output=True, text=True, timeout=timeout, errors="replace", **kw)
            return r.returncode, (r.stdout or "") + (r.stderr or "")
        except subprocess.TimeoutExpired:
            return None, "ran past %d s and was stopped" % timeout

    def read(self, path, cap=2_000_000):
        if SECRET.search(os.path.basename(path)):
            return None
        if self.kind == "host":
            code, out = self.sh("test -f %s && head -c %d %s" % (shlex.quote(path), cap, shlex.quote(path)), 30)
            s = out if code == 0 else None
        else:
            p = Path(path)
            if not p.is_file() or p.stat().st_size > cap:
                return None
            b = p.read_bytes()
            if b"\0" in b[:4096]:
                return None
            s = b.decode("utf-8", "replace")
        return None if s is None or SECRET_TEXT.search(s) else s

    def write(self, path, text):
        if self.kind == "host":
            q = shlex.quote(path)
            r = subprocess.run(SSH + [self.host, "cat > %s.o7new && mv %s.o7new %s" % (q, q, q)], input=text, text=True,
                               capture_output=True, timeout=30)
            if r.returncode != 0:
                raise OSError(r.stderr.strip()[:200])
            return
        p = Path(path)
        base = Path(self.root).resolve()
        p = p.resolve()
        if p != base and base not in p.parents:
            raise ValueError("The write is outside the open folder. Open the intended project folder first.")
        import work_tasks as _work
        _work.guard_write(p)
        before_bytes = p.read_bytes() if p.is_file() else None
        if p.is_file():
            os.unlink(p)                                   # never through a hardlink into another tree
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(text, encoding="utf-8", newline="")  # exactly the text given: read() keeps \r\n, so no translation
        _work.note_write(p, before_bytes, p.read_bytes())
        import repair as _rp
        _rp.drop_bytecode(p)                               # no later run uses the old compiled code

    def exists(self, path):
        if self.kind == "host":
            return self.sh("test -e %s" % shlex.quote(path), 20)[0] == 0
        return os.path.exists(path)

    def isdir(self, path):
        if self.kind == "host":
            return self.sh("test -d %s" % shlex.quote(path), 20)[0] == 0
        return os.path.isdir(path)

    def walk(self, sub="", limit=60000):
        """file paths under the root (or sub), skipping build and vendor folders"""
        base = self.path(sub) if sub else self.root
        if self.kind == "host":
            prune = " -o ".join("-name %s" % d for d in sorted(SKIP_DIRS))
            code, out = self.sh("find %s \\( %s \\) -prune -o -type f -print 2>/dev/null | head -n %d" % (
                shlex.quote(base), prune, limit), 60)
            for ln in out.splitlines():
                yield ln
            return
        if os.path.isfile(base):
            yield base
            return
        n = 0
        for dp, dns, fns in os.walk(base):
            dns[:] = sorted(d for d in dns if d not in SKIP_DIRS and not d.startswith("."))
            for f in sorted(fns):
                n += 1
                if n > limit:
                    return
                yield os.path.join(dp, f)

    def rel(self, path):
        r = self.root.rstrip("/\\")
        return path[len(r) + 1:].replace(os.sep, "/") if path.startswith(r + os.sep) or path.startswith(r + "/") else path

    def resolve(self, name):
        p = self.path(name)
        if self.exists(p):
            return [p]
        name = name.strip().strip("`'\"").lstrip("./")
        hits = []
        for q in self.walk():
            if os.path.basename(q) == name or q.replace(os.sep, "/").endswith("/" + name):
                hits.append(q)
                if len(hits) > 8:
                    break
        return hits


def _ago(t):
    s = int(time.time() - t)
    return "%ds" % s if s < 90 else "%dm" % (s // 60) if s < 5400 else "%.1fh" % (s / 3600)


def _r(text, state, path, **rec):
    """a reply and its receipt; the status follows the receipt"""
    st = {"passed": "answered", "read": "answered", "changed-checked": "answered", "done": "answered",
          "failed": "hole", "refused": "hole", "blocked": "hole", "missing": "hole",
          "running": "offered", "queued": "offered", "changed-untested": "offered", "waiting": "offered",
          "interrupted": "hole", "stopped": "answered"}[state]
    rec["state"] = state
    return {"status": st, "path": "bench:" + path, "response": text, "execution": rec}


def _e(env, name):
    return "%s.%s" % (env.key, name)


# ---------------------------------------------------------------- environment
def open_env(turn, arg, host=False, readonly=False):
    arg = arg.strip().strip("`'\"")
    windows_path = bool(re.match(r"^[A-Za-z]:[/\\]", arg))
    if host or (not windows_path and re.match(r"^[\w.-]+:(/.*)?$", arg)):
        h, _, root = arg.partition(":")
        root = root or "/"
        code, out = subprocess.run(SSH + [h, "test -d %s && hostname" % shlex.quote(root)], capture_output=True, text=True,
                                   timeout=25).returncode, ""
        if code != 0:
            return _r("I could not reach %s over ssh (or %s is not a folder there). The host must be an ssh alias this "
                      "machine can log in to with a key." % (h, root), "blocked", "open:host", started=False)
        d = {"kind": "host", "host": h, "root": root}
    else:
        p = Path(os.path.expanduser(arg)).resolve()
        if not p.is_dir():
            return None
        d = {"kind": "folder", "root": str(p)}
    try:                                               # C11: the project goes with its environment, both ways
        import continuation as CT
        CT.switch(turn, d)
    except Exception:  # noqa: BLE001
        turn.s["project"] = None
    turn.s["env"] = d
    turn.s["authority"] = "read" if (readonly or d["kind"] == "host") else "change"
    turn.s["offers"] = []
    turn.s["last"] = {}
    turn.save()
    env = Env(d)
    kinds, n = {}, 0
    for q in env.walk(limit=20000):
        n += 1
        s = os.path.splitext(q)[1] or os.path.basename(q)
        kinds[s] = kinds.get(s, 0) + 1
    top = sorted(kinds.items(), key=lambda kv: -kv[1])[:8]
    out = ["Working in %s: %d files (%s)." % (env.label(), n, ", ".join("%s %d" % kv for kv in top))]
    for f in ("README.md", "package.json", "pyproject.toml", "Makefile", "requirements.txt", "setup.py"):
        if env.exists(env.path(f)):
            out.append("Has " + f + ".")
    names = _load(_e(env, "names.json"), {})
    if names:
        out.append("Named commands here: " + ", ".join(sorted(names)) + ".")
    out.append("This conversation may %s." % ("read here, not change anything (say \"allow changes\")" if
                                               turn.s["authority"] == "read" else "read and change files here"))
    return _r(" ".join(out), "read", "open", env=env.label())


def authority(turn, change):
    if turn.env is None:
        return None
    turn.s["authority"] = "change" if change else "read"
    turn.save()
    return _r("This conversation may now %s %s." % ("read and change" if change else "only read", turn.env.label()), "done",
              "authority", authority=turn.s["authority"])


def _may_change(turn):
    return turn.s.get("authority") == "change"


# ---------------------------------------------------------------- reading
def ls(turn, arg):
    env = turn.env
    d = env.path(arg) if arg.strip() else env.root
    if not env.isdir(d):
        return None
    if env.kind == "host":
        code, out = env.sh("ls -la %s" % shlex.quote(d), 20)
        return _r(out.strip(), "read", "ls")
    es = sorted(Path(d).iterdir(), key=lambda q: (not q.is_dir(), q.name.lower()))
    out = [q.name + "/" if q.is_dir() else "%s  (%d B)" % (q.name, q.stat().st_size) for q in es[:150] if q.name not in SKIP_DIRS]
    return _r("%s:%s%s" % (env.rel(d) if d != env.root else env.root, NL, NL.join(out)), "read", "ls")


def files_named(turn, pat):
    pat = pat.strip().strip("`'\"")
    if not any(c in pat for c in "*?["):
        pat = "*" + pat + "*"
    hits = [turn.env.rel(q) for q in turn.env.walk() if fnmatch.fnmatch(os.path.basename(q).lower(), pat.lower())][:60]
    return _r(NL.join(hits) if hits else "No file named like %s here." % pat, "read", "files")


def read(turn, arg):
    env = turn.env
    m = re.match(r"(?is)^(.+?)(?:\s+(?:lines?|from line)\s+(\d+)\s*(?:-|to|\.\.)?\s*(\d+)?)?\s*$", arg.strip())
    name, a, b = m.group(1), m.group(2), m.group(3)
    hits = env.resolve(name)
    if not hits:
        return None
    if len(hits) > 1:
        return _r("Several files are called that:" + NL + NL.join(env.rel(h) for h in hits[:8]), "read", "read:which")
    p = hits[0]
    if SECRET.search(os.path.basename(p)):
        return _r("%s looks like it holds a secret, so I don't open it." % env.rel(p), "refused", "read:secret")
    s = env.read(p)
    if s is None:
        return _r("%s is not text I can show (a folder, binary, too large, or it carries a secret)." % env.rel(p), "refused",
                  "read:binary")
    lines = s.splitlines()
    i = max(1, int(a)) if a else 1
    j = int(b) if b else (i + 199 if a else 200)
    body = NL.join("%5d  %s" % (k, lines[k - 1]) for k in range(i, min(j, len(lines)) + 1))
    more = "" if j >= len(lines) else NL + "... (%d lines in all; say \"read %s lines %d-%d\")" % (len(lines), env.rel(p), j + 1, j + 200)
    turn.last(kind="read", file=p)
    return _r("%s (%d lines)%s```%s%s%s```%s" % (env.rel(p), len(lines), NL, NL, body, NL, more), "read", "read", files=[env.rel(p)])


def grep(turn, pat, where=None):
    env = turn.env
    pat = pat.strip().strip("`'\"")
    if env.kind == "host":
        tgt = env.path(where) if where else env.root
        code, out = env.sh("grep -rIn --exclude-dir=.git -i -- %s %s 2>/dev/null | head -40" % (shlex.quote(pat), shlex.quote(tgt)), 60)
        lines = [ln for ln in out.splitlines() if not SECRET.search(ln.split(":", 1)[0].rsplit("/", 1)[-1])]
        return _r(NL.join(ln[:220] for ln in lines) if lines else "No line there has %s." % pat, "read", "grep")
    files = []
    if where:
        for h in env.resolve(where):
            files += list(env.walk(env.rel(h))) if os.path.isdir(h) else [h]
        if not files:
            return _r("There is no %s here." % where, "missing", "grep")
    else:
        files = env.walk()
    out, low = [], pat.lower()
    for p in files:
        s = env.read(p, 1_000_000)
        if s is None or low not in s.lower():
            continue
        for i, ln in enumerate(s.splitlines(), 1):
            if low in ln.lower():
                out.append("%s:%d  %s" % (env.rel(p), i, ln.strip()[:170]))
                if len(out) >= 40:
                    break
        if len(out) >= 40:
            break
    return _r(NL.join(out) if out else "No line here has %s." % pat, "read", "grep")


# ---------------------------------------------------------------- edits (hash-checked)
def _sha(s):
    return hashlib.sha256((s or "").encode("utf-8")).hexdigest()[:16]


def _record_edit(turn, path, before, after, how):
    env = turn.env
    log = _load(_e(env, "edits.json"), [])
    eid = 1 + len(log)
    d = _p(_e(env, "edits"))
    d.mkdir(exist_ok=True)
    if before is not None:
        (d / ("%d.before" % eid)).write_bytes(before.encode("utf-8"))     # kept exactly, line endings included
    log.append({"id": eid, "file": path, "t": time.time(), "existed": before is not None, "before": _sha(before),
                "after": _sha(after), "how": how, "sid": turn.sid})
    _save(_e(env, "edits.json"), log)
    return eid


def _compiles(path, new):
    if not path.endswith(".py"):
        return None
    try:
        compile(new, path, "exec")
        return None
    except SyntaxError as e:
        return "%s (line %s)" % (e.msg, e.lineno)


def _diff(env, path, a, b, tag=("before", "after")):
    d = list(difflib.unified_diff((a or "").splitlines(), b.splitlines(), "%s/%s" % (tag[0], env.rel(path)),
                                  "%s/%s" % (tag[1], env.rel(path)), n=2, lineterm=""))
    return "```diff" + NL + NL.join(d[:80] + (["... (%d more lines)" % (len(d) - 80)] if len(d) > 80 else [])) + NL + "```"


def _apply(turn, path, before, after, how):
    """write a change the conversation has authority for; returns the edit id"""
    turn.env.write(path, after)
    return _record_edit(turn, path, before, after, how)


def _check_name(env):
    names = _load(_e(env, "names.json"), {})
    return next((n for n in ("test", "tests", "check", "gate", "build") if n in names), None)


_EDIT = (re.compile(r"(?is)^(?:please\s+)?in\s+(\S+?)\s*,?\s*(?:replace|change)\s+(```\w*\n?|`|\")(.+?)\2\s+(?:with|to|by|into)\s+(```\w*\n?|`|\")(.*?)\4\s*\.?$"),
         re.compile(r"(?is)^(?:please\s+)?(?:replace|change)\s+(```\w*\n?|`|\")(.+?)\1\s+(?:with|to|by|into)\s+(```\w*\n?|`|\")(.*?)\3\s+in\s+(\S+?)\s*\.?$"))


def edit(turn, text):
    m = _EDIT[0].match(text.strip())
    if m:
        f, a, b = m.group(1), m.group(3), m.group(5)
    else:
        m = _EDIT[1].match(text.strip())
        if not m:
            return None
        a, b, f = m.group(2), m.group(4), m.group(5)
    env = turn.env
    a, b = a.strip(NL), b.strip(NL)
    hits = env.resolve(f)
    if len(hits) != 1:
        return _r("%s names %s here." % (f, "no file" if not hits else "%d files: %s" % (len(hits), ", ".join(env.rel(h) for h in hits[:5]))),
                  "missing", "edit:file", started=False)
    p = hits[0]
    if not _may_change(turn):
        return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused", "edit:authority",
                  started=False)
    s = env.read(p)
    if s is None:
        return _r("%s is not a text file I edit." % env.rel(p), "refused", "edit:file", started=False)
    n = s.count(a)
    if n != 1:
        return _r("The text to replace occurs %d times in %s; it must occur exactly once." % (n, env.rel(p)), "missing",
                  "edit:match", started=False)
    new = s.replace(a, b)
    bad = _compiles(p, new)
    if bad:
        return _r("Not made: %s would not compile after it: %s" % (env.rel(p), bad), "failed", "edit:compile", started=False)
    eid = _apply(turn, p, s, new, "exact")
    return _after_change(turn, p, s, new, eid, "Edit %d made to %s as you gave it." % (eid, env.rel(p)))


def write(turn, text):
    m = re.match(r"(?is)^(?:please\s+)?(?:write|create|save)\s+(?:the\s+|a\s+)?(?:file\s+)?([\w./~-]+\.\w{1,8})\s*:?\s*\n(.*)$", text.strip())
    if not m:
        return None
    env = turn.env
    name, body = m.group(1), m.group(2)
    f = re.match(r"(?s)^\s*```[\w+-]*\n(.*?)\n?```\s*$", body)
    body = (f.group(1) if f else body.rstrip()) + NL
    if not body.strip():
        return None
    p = env.path(name)
    if SECRET.search(os.path.basename(p)):
        return _r("%s is named like a secret file; I don't write those." % name, "refused", "write:secret", started=False)
    if not _may_change(turn):
        return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused", "write:authority",
                  started=False)
    bad = _compiles(p, body)
    if bad:
        return _r("Not written: it would not compile: %s" % bad, "failed", "write:compile", started=False)
    old = env.read(p) if env.exists(p) else None
    eid = _apply(turn, p, old, body, "write")
    return _after_change(turn, p, old or "", body, eid, "Edit %d wrote %s." % (eid, env.rel(p)))


def _after_change(turn, p, s, new, eid, head):
    env = turn.env
    chk = _check_name(env)
    tail = NL + head + " Backup kept; \"undo\" takes it back."
    if chk:
        turn.offer({"kind": "run", "name": chk, "why": "check edit %d" % eid})
        tail += " Run the %s on it? Say go." % chk
    turn.last(kind="edit", edit=eid, file=p)
    return _r(_diff(env, p, s, new) + tail, "changed-untested", "edit", files=[env.rel(p)], edit=eid)


def undo(turn):
    env = turn.env
    log = _load(_e(env, "edits.json"), [])
    live = [e for e in log if not e.get("undone")]
    if not live:
        return _r("There is no edit to take back.", "done", "undo")
    e = live[-1]
    cur = env.read(e["file"]) if env.exists(e["file"]) else None
    if _sha(cur) != e["after"]:
        return _r("Edit %d to %s was not taken back: the file has changed since (its content is not what that edit left), so "
                  "undoing would lose the later work. \"what changed\" shows the difference." % (e["id"], env.rel(e["file"])),
                  "blocked", "undo:conflict", started=False)
    if e.get("existed", True):
        env.write(e["file"], (_p(_e(env, "edits")) / ("%d.before" % e["id"])).read_bytes().decode("utf-8"))
    elif env.kind == "folder":
        os.unlink(e["file"])
    else:
        env.sh("rm -f %s" % shlex.quote(e["file"]), 20)
    e["undone"] = time.time()
    _save(_e(env, "edits.json"), log)
    return _r("Edit %d to %s taken back." % (e["id"], env.rel(e["file"])), "done", "undo", files=[env.rel(e["file"])])


def changed(turn):
    env = turn.env
    log = [e for e in _load(_e(env, "edits.json"), []) if not e.get("undone")]
    if not log:
        return _r("No file has been changed here from the chat.", "read", "diff")
    first = {}
    for e in log:
        first.setdefault(e["file"], e)
    out = []
    for f, e in first.items():
        bp = _p(_e(env, "edits")) / ("%d.before" % e["id"])
        a = bp.read_bytes().decode("utf-8") if e.get("existed", True) and bp.is_file() else ""
        b = env.read(f) if env.exists(f) else ""
        out.append(_diff(env, f, a, b or "", ("before", "now")))
    return _r("%d file(s) changed here from the chat:%s%s" % (len(first), NL, NL.join(out)), "read", "diff",
              files=[env.rel(f) for f in first])


# ---------------------------------------------------------------- commands and jobs
def _jobs(env):
    jobs = _load(_e(env, "jobs.json"), [])
    ch = False
    for j in jobs:
        if j["state"] in ("running", "queued"):
            d = Path(j["dir"])
            if (d / "started").is_file() and j["state"] == "queued":
                j["state"], j["t"] = "running", os.path.getmtime(d / "started")
                ch = True
            if not (d / "exit").is_file() and (d / "pid").is_file() and not _alive((d / "pid").read_text().strip()):
                time.sleep(0.3)                          # Amendment 15: the runner is gone and left no exit: the outcome is
                if not (d / "exit").is_file():           # not known, and it is said so (never "running" for ever, never a guess)
                    j["state"], j["t_end"] = "interrupted", time.time()
                    j["result"] = "interrupted: the run stopped without an exit status; what it did is not known"
                    ch = True
                    continue
            if (d / "exit").is_file():
                if (d / "pid").is_file():
                    _reap((d / "pid").read_text().strip())   # the finished runner collected, so none are left behind
                stopped = _load_stop_receipt(j, env)
                j["state"] = "stopped" if stopped else "finished"
                try:
                    j["exit"] = int((d / "exit").read_text().strip())
                except ValueError:
                    j["exit"] = -1
                j["t_end"] = os.path.getmtime(d / "exit")
                log = (d / "log").read_text(errors="replace").splitlines() if (d / "log").is_file() else []
                rule = j.get("passes")
                hits = [ln for ln in log if rule and re.search(re.escape(rule), ln, re.I)]
                j["passed"] = not stopped and j["exit"] == 0 and (bool(hits) if rule else True)
                j["result"] = "stopped as requested; log preserved" if stopped else ((hits[-1] if hits else (log[-1] if log else "(no output)")))[:300]
                if stopped:
                    j["stopped"], j["started"] = True, bool(stopped["started"])
                ch = True
    if ch:
        _save(_e(env, "jobs.json"), jobs)
    return jobs


def _load_stop_receipt(job, env):
    try:
        receipt = json.loads((Path(job["dir"]) / "stopped.json").read_text())
        if receipt.get("state") == "stopped" and all(receipt.get(k) == v for k, v in
                (("job", job["id"]), ("sid", job.get("sid")), ("env", env.key))) and isinstance(receipt.get("started"), bool):
            return receipt
    except (OSError, ValueError, TypeError):
        pass
    return None


def _alive(pid):
    try:
        pid = int(pid)
    except ValueError:
        return False
    if os.name == "nt":
        r = subprocess.run(["tasklist", "/FI", "PID eq %d" % pid], capture_output=True, text=True)
        return str(pid) in r.stdout
    _reap(pid)                                         # a runner the server started and never collected is a zombie:
    try:                                               # os.kill(pid, 0) succeeds on it (acceptance I1, run 1)
        with open("/proc/%d/stat" % pid) as fh:
            if fh.read().rsplit(")", 1)[-1].split()[0] == "Z":
                return False
    except FileNotFoundError:
        return False
    except Exception:  # noqa: BLE001
        pass
    try:
        os.kill(pid, 0)
    except ProcessLookupError:
        return False
    except PermissionError:
        return True
    return True


def _reap(pid):
    """collect one of the bench's own runners if it has ended (only that pid: other children are their owners' to collect)"""
    if os.name == "nt":
        return
    try:
        os.waitpid(int(pid), os.WNOHANG)
    except (ChildProcessError, OSError, ValueError):
        pass


def changed_since(env, t, limit=12):
    """files of the environment changed after a moment: what an interrupted run may have done"""
    out = []
    if env.kind != "folder":
        code, o = env.sh("find . -newermt @%d -type f 2>/dev/null | head -n %d" % (int(t), limit), 30)
        return [x for x in o.splitlines() if x.strip()]
    for p in env.walk(limit=20000):
        try:
            if os.path.getmtime(p) > t:
                out.append(env.rel(p))
        except OSError:
            continue
        if len(out) >= limit:
            break
    return out


def interrupted_check(turn, j):
    """before anything is run again after an interruption: what the environment shows now, and a go to repeat"""
    env = turn.env
    log = (Path(j["dir"]) / "log").read_text(errors="replace").splitlines() if (Path(j["dir"]) / "log").is_file() else []
    ch = changed_since(env, j["t"])
    turn.offer({"kind": "cmd", "cmd": j["cmd"], "name": j.get("name")})
    return _r("Job %d (`%s`) was interrupted: it stopped without an exit status, so whether it finished its work is not known. "
              "Before running it again, what the environment shows now:%s- files changed since it started: %s%s- the last lines it "
              "wrote:%s%s%sIf it is safe to repeat, say go; otherwise tell me what to check first." % (
                  j["id"], j["cmd"][:100], NL, ", ".join(ch) if ch else "none", NL, NL,
                  NL.join("    " + ln[:200] for ln in log[-6:]) or "    (nothing)", NL),
              "waiting", "run:interrupted", job=j["id"], files=ch)


def _receipt(j):
    if j["state"] == "stopped":
        return "stopped", {"job": j["id"], "started": j.get("started", True), "finished": True,
                           "exit": j.get("exit"), "stopped": True, "passed": False}
    if j["state"] == "interrupted":
        return "interrupted", {"job": j["id"], "started": True, "finished": False, "exit": None}
    if j["state"] in ("running", "queued"):
        return j["state"], {"job": j["id"], "started": j["state"] == "running", "finished": False}
    return ("passed" if j.get("passed") else "failed"), {"job": j["id"], "started": True, "finished": True,
                                                        "exit": j.get("exit"), "check": j.get("passes"),
                                                        "timeout": False}


def run_cmd(turn, cmd, name=None, confirmed=False):
    env = turn.env
    names = _load(_e(env, "names.json"), {})
    alone = bool(name and names.get(name, {}).get("alone"))
    if DANGER.search(cmd) and not confirmed:
        turn.offer({"kind": "cmd", "cmd": cmd, "name": name})
        return _r("That command can destroy, stop or restart things on %s:%s```%s%s%s```%sSay go to run it, or cancel." % (
            env.label(), NL, NL, cmd, NL, NL), "waiting", "run:confirm", started=False)
    if env.kind == "host" and not _may_change(turn) and not re.match(
            r"^\s*(?:ls|cat|head|tail|grep|find|ps|ss|netstat|df|du|free|uptime|uname|whoami|id|systemctl\s+(?:status|is-active|"
            r"list-units)|journalctl|stat|wc|sha256sum|nginx\s+-t|sshd\s+-t|git\s+(?:status|log|diff))\b", cmd):
        return _r("This conversation may only read %s, and that command is not one I know to be read-only. Say \"allow "
                  "changes\" to run it." % env.label(), "refused", "run:authority", started=False)
    if os.environ.get("ORACLE7_BENCH_DRY") == "1":
        return _r("Would run on %s: %s (dry run)." % (env.label(), cmd), "waiting", "run", started=False)
    jobs = _jobs(env)
    if name:
        live = [j for j in jobs if j.get("name") == name and j["state"] in ("running", "queued")]
        if live:
            return _r("The %s is already %s (job %d, %s)." % (name, live[0]["state"], live[0]["id"], _ago(live[0]["t"])),
                      live[0]["state"], "run:already", job=live[0]["id"])
    jid = 1 + max([j["id"] for j in jobs] or [0])
    d = _p(_e(env, "jobs")) / str(jid)
    d.mkdir(parents=True, exist_ok=True)
    full = cmd if env.kind == "folder" else " ".join(shlex.quote(x) for x in SSH + [env.host, "cd %s && %s" % (shlex.quote(env.root), cmd)])
    (d / "cmd").write_text(full + NL)
    (d / "owner.json").write_text(json.dumps({"token": secrets.token_urlsafe(32), "sid": turn.sid,
        "env": env.key, "job": jid, "command_sha256": hashlib.sha256((full + NL).encode()).hexdigest()}))
    rp = _p("runner.py")
    if not rp.is_file() or rp.read_text() != RUNNER:
        rp.write_text(RUNNER)
    lock = _p("alone.lock")
    busy = alone and lock.is_file()
    kw = {"start_new_session": True} if os.name != "nt" else {"creationflags": 0x00000008 | 0x00000200}
    own = Path(__file__).resolve().parent              # Oracle7's own tools (its judges over its own candidates) run as
    if env.kind == "folder" and not (name == "judge" and str(own / "judge") in cmd):   # Oracle7; project code is jailed
        kw["env"] = _guard_env(env)                    # the conversation's network scope holds in what it runs
    subprocess.Popen([sys.executable, str(rp), str(d), str(lock) if alone else "-"], cwd=env.root if env.kind == "folder" else None,
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, **kw)
    rule = names.get(name, {}).get("passes") if name else None
    jobs.append({"id": jid, "name": name, "cmd": cmd, "dir": str(d), "t": time.time(), "sid": turn.sid,
                 "state": "queued" if busy else "running", "passes": rule, "control_version": 1})
    _save(_e(env, "jobs.json"), jobs)
    turn.last(kind="job", job=jid, cmd=cmd, name=name)
    if not busy:
        t0 = time.time()
        while time.time() - t0 < QUICK and not (d / "exit").is_file():
            time.sleep(0.3)
        if (d / "exit").is_file():
            time.sleep(0.05)
            j = [x for x in _jobs(env) if x["id"] == jid][0]
            log = (d / "log").read_text(errors="replace")
            body = log[-6000:]
            st, rec = _receipt(j)
            verdict = "exit %d" % j["exit"] + ("" if not rule else (", passed" if j["passed"] else ", did not pass (looked for: %s)" % rule))
            return _r("```%s$ %s%s%s%s```%s%s" % (NL, cmd, NL, body.rstrip(), NL, NL, verdict), st, "run", **rec)
    label = ("the " + name) if name else "`%s`" % cmd[:80]
    return _r("%s is %s as job %d. \"where are we\" or \"is it done\" shows how it stands; \"what failed\" reads its log." % (
        label[:1].upper() + label[1:], "waiting its turn (one at a time)" if busy else "running (still going after %ds)" % QUICK, jid),
        "queued" if busy else "running", "run:job", job=jid, started=not busy, finished=False)


def stop_job(turn, number=None):
    """Ask this local job's owning runner to stop; never signal a stored PID."""
    env = turn.env
    if env is None or env.kind != "folder":
        return _r("Stopping an app needs its local project folder open in this conversation.", "missing", "stop", started=False)
    if not _may_change(turn):
        return _r("This conversation may only read this folder. Say \"allow changes\" before stopping its app.",
                  "refused", "stop:authority", started=False)
    jobs = _jobs(env)
    mine = [j for j in jobs if j.get("sid") == turn.sid]
    if number is not None:
        job = next((j for j in jobs if j["id"] == int(number)), None)
        if job is None or job.get("sid") != turn.sid:
            return _r("Job %s is not a job of this conversation in the currently open folder." % number,
                      "refused", "stop:ownership", started=False)
    else:
        live = [j for j in mine if j["state"] in ("running", "queued")]
        if len(live) > 1:
            return _r("Several jobs are running here. Say stop job %s to choose one." %
                      " or stop job ".join(str(j["id"]) for j in live), "missing", "stop:scope", started=False)
        job = live[0] if live else mine[-1] if mine else None
        if job is None:
            return _r("This conversation has no app job in the currently open folder.", "missing", "stop", started=False)
    if job["state"] == "stopped":
        state, receipt = _receipt(job)
        return _r("Job %d is already stopped. Its log is kept." % job["id"], state, "stop", **receipt)
    if job["state"] not in ("running", "queued"):
        return _r("Job %d is already %s; no process was stopped." % (job["id"], job["state"]),
                  "read", "stop", job=job["id"], job_state=job["state"], finished=True, stopped=False)
    directory = Path(job["dir"]).resolve()
    expected = (_p(_e(env, "jobs")) / str(job["id"])).resolve()
    if directory != expected or job.get("control_version") != 1:
        return _r("This older job has no owned stop control. Its process identity cannot safely be inferred; its log is kept.",
                  "missing", "stop:binding", job=job["id"], started=False)
    try:
        owner = json.loads((directory / "owner.json").read_text())
        command = (directory / "cmd").read_text()
        if not owner.get("token") or any(owner.get(k) != v for k, v in
                (("sid", turn.sid), ("env", env.key), ("job", job["id"]))) or \
                owner.get("command_sha256") != hashlib.sha256(command.encode()).hexdigest():
            raise ValueError("the job's owner or command receipt changed")
    except (OSError, ValueError, TypeError) as error:
        return _r("This job's stop binding could not be checked: %s" % error,
                  "missing", "stop:binding", job=job["id"], started=False)
    request = {k: owner[k] for k in ("token", "sid", "env", "job")}
    request.update(id=secrets.token_urlsafe(20), requested=time.time())
    temporary = directory / ("stop." + secrets.token_hex(6) + ".new")
    try:
        temporary.write_text(json.dumps(request)); os.replace(temporary, directory / "stop.json")
    finally:
        temporary.unlink(missing_ok=True)
    deadline = time.monotonic() + 8
    while time.monotonic() < deadline:
        current = next(j for j in _jobs(env) if j["id"] == job["id"])
        if current["state"] == "stopped":
            state, receipt = _receipt(current)
            return _r("Stopped job %d%s. Its log is kept; the run is marked stopped, not passed." %
                      (job["id"], " before it started" if not current.get("started") else ""), state, "stop", **receipt)
        if current["state"] not in ("running", "queued"):
            return _r("Job %d %s before the stop was acknowledged; its recorded result and log are kept." %
                      (job["id"], current["state"]), "read", "stop", job=job["id"],
                      job_state=current["state"], finished=True, stopped=False)
        error_file = directory / "stop_error.json"
        if error_file.is_file():
            try:
                error = json.loads(error_file.read_text())
                if error.get("id") == request["id"]:
                    return _r("The owning runner could not finish stopping job %d: %s. The job remains observable; say stop job %d to retry." %
                              (job["id"], error.get("error"), job["id"]), "failed", "stop",
                              job=job["id"], finished=False, stopped=False)
            except (OSError, ValueError):
                pass
        time.sleep(.1)
    return _r("Job %d's owning runner received a stop request; it has not acknowledged stopping yet." % job["id"],
              "running", "stop", job=job["id"], stop_requested=True, finished=False, stopped=False)


def name_cmd(turn, cmd, name, alone):
    env = turn.env
    names = _load(_e(env, "names.json"), {})
    old = names.get(name, {})
    names[name] = {"cmd": cmd, "alone": alone or old.get("alone", False), "passes": old.get("passes")}
    _save(_e(env, "names.json"), names)
    return _r("\"run the %s\" now runs `%s` on %s%s." % (name, cmd, env.label(), ", one at a time" if names[name]["alone"] else ""),
              "done", "name")


def name_rule(turn, name, rule):
    env = turn.env
    names = _load(_e(env, "names.json"), {})
    if name not in names:
        return _r("There is no command called the %s here. Name one: call `command` the %s." % (name, name), "missing", "name")
    names[name]["passes"] = rule
    _save(_e(env, "names.json"), names)
    return _r("The %s passes when its output says \"%s\" and it exits 0." % (name, rule), "done", "name")


def status(turn):
    env = turn.env
    jobs = _jobs(env)
    out = ["Environment: %s (this conversation may %s)" % (env.label(), "change it" if _may_change(turn) else "only read it")]
    if turn.s.get("goal"):
        out.append("Goal: " + turn.s["goal"])
    pj = turn.s.get("project")
    if pj and pj.get("env") in (None, env.key):      # C11: the project of this environment, from its own record
        att = pj.get("attempts") or []
        try:                                         # C31: the record is history; say when what it rested on has changed
            import continuation as _ct
            if att and env.kind == "folder" and att[-1].get("fp") and att[-1]["fp"] != _ct.fingerprint(pj, env.root, _authority(turn)):
                out.append("Note: attempt %d's result rests on inputs or authority that have changed since (files, words or "
                           "permissions); it was true then and needs a fresh run to count now." % att[-1]["seq"])
        except Exception:  # noqa: BLE001
            pass
        out.append("Project %s (id %s): %s after attempt %d; your words kept: %d turn%s%s." % (
            pj.get("module") or "(no module yet)", pj.get("pid", "?"), pj.get("status"), att[-1]["seq"] if att else 0,
            len(pj.get("clauses") or []), "" if len(pj.get("clauses") or []) == 1 else "s",
            ("; open holes: " + " | ".join(h.get("text", "")[:120] for h in pj.get("holes_kept") or [])) if pj.get("holes_kept") else ""))
    others = [k for k in (turn.s.get("projects") or {}) if k != env.key and turn.s["projects"][k]]
    if others:
        out.append("Projects kept in other environments of this conversation: %s." % ", ".join(
            "%s (%s)" % (turn.s["projects"][k].get("module") or "?", turn.s["projects"][k].get("env_root") or k) for k in others))
    run = [j for j in jobs if j["state"] in ("running", "queued")]
    fin = [j for j in jobs if j["state"] in ("finished", "interrupted", "stopped")][-6:]
    if run or fin:
        out += ["", "Jobs:"]
    seen = turn.s.setdefault("log_seen", {})
    for j in run:                                    # C11: a job whose log grows is progressing; one whose log is still is not
        lp = Path(j["dir"]) / "log"
        size, mt = (lp.stat().st_size, lp.stat().st_mtime) if lp.is_file() else (0, j["t"])
        before = seen.get(str(j["id"]))
        how = ("progressing: %d bytes of output since you last asked" % (size - before) if before is not None and size > before
               else "no new output since you last asked (last output %s ago)" % _ago(mt) if before is not None
               else "%d bytes of output so far, the last %s ago" % (size, _ago(mt)))
        seen[str(j["id"])] = size
        out.append("- %d %s: %s, %s; %s" % (j["id"], j.get("name") or j["cmd"][:60], j["state"], _ago(j["t"]), how))
    if run:
        turn.save()
    for j in reversed(fin):
        mark = "STOPPED (as requested)" if j["state"] == "stopped" else "INTERRUPTED (outcome not known)" if j["state"] == "interrupted" else "passed" if j.get("passed") else \
            "FAILED (exit %s)" % j.get("exit")
        out.append("- %d %s: %s %s ago: %s" % (j["id"], j.get("name") or j["cmd"][:60], mark, _ago(j["t_end"]), j["result"]))
    eds = [e for e in _load(_e(env, "edits.json"), []) if not e.get("undone")]
    if eds:
        out += ["", "Changed from the chat: " + ", ".join(sorted({env.rel(e["file"]) for e in eds})[:10])]
    fs = turn.s.get("findings")
    if fs:
        out += ["", "Findings open: " + ", ".join("%d %s" % (i + 1, f["rule"]) for i, f in enumerate(fs) if not f.get("fixed"))]
    offers = turn.s.get("offers", [])
    if offers:
        out += ["", "Waiting for your go:"] + ["- go %d: %s" % (i + 1, _offer_text(o)) for i, o in enumerate(offers)]
    ts = [t for t in _load(_e(env, "tasks.json"), []) if not t.get("done")]
    if ts:
        out += ["", "Open tasks:"] + ["- %d. %s" % (t["id"], t["text"]) for t in ts[-8:]]
    names = _load(_e(env, "names.json"), {})
    if names:
        out += ["", "Named commands: " + ", ".join(sorted(names))]
    return _r(NL.join(out), "read", "status")


def _offer_text(o):
    k = o.get("kind")
    if k == "run":
        return "run the %s (%s)" % (o["name"], o.get("why", ""))
    if k == "cmd":
        return "run `%s`" % o["cmd"][:80]
    if k == "repair_value":
        return "finish the change to %s() once you say what it gives for an empty %s" % (o["function"], o["param"])
    if k == "fix":
        return "apply the correction for finding %d (%s)" % (o["n"], o["rule"])
    if k == "resolved":
        return "`%s` (how I read your words)" % o["sent"]
    if k == "selfdev_build":
        return "build the proposed change to myself (%s) as a candidate and judge it" % ", ".join("%s = %s" % kv for kv in sorted(o["new"].items()))
    if k == "selfdev_adopt":
        return "adopt the candidate the judge passed"
    if k == "project_go":
        return "go on with the project"
    return k


_FAILLINE = re.compile(r"(?i)(error|fail|traceback|exception|assert|fatal|denied|not found|no such)")


def _job_for(turn, text):
    env = turn.env
    jobs = _jobs(env)
    m = re.search(r"\bjob\s*(\d+)\b|\blog of (\d+)\b", text)
    names = _load(_e(env, "names.json"), {})
    nm = next((n for n in sorted(names, key=len, reverse=True) if re.search(r"\b" + re.escape(n) + r"\b", text.lower())), None)
    if m:
        return next((j for j in jobs if j["id"] == int(m.group(1) or m.group(2))), None)
    if nm:
        js = [j for j in jobs if j.get("name") == nm]
        return js[-1] if js else None
    last = turn.last()
    if last.get("job"):
        return next((j for j in jobs if j["id"] == last["job"]), None)
    mine = [j for j in jobs if j.get("sid") == turn.sid]
    return mine[-1] if mine else None


def log_of(turn, text):
    j = _job_for(turn, text)
    if not j:
        return _r("This conversation has not run anything here yet.", "missing", "log")
    log = (Path(j["dir"]) / "log").read_text(errors="replace").splitlines() if (Path(j["dir"]) / "log").is_file() else []
    st, rec = _receipt(j)
    out = ["Job %d %s: %s%s" % (j["id"], j.get("name") or "", j["state"],
                               "" if j["state"] != "finished" else ", exit %s, %s" % (j["exit"], "passed" if j.get("passed") else "FAILED"))]
    out.append("$ " + j["cmd"])
    bad = [ln for ln in log if _FAILLINE.search(ln)]
    if bad and not j.get("passed"):
        out += ["", "Lines that report a failure (%d):" % len(bad)] + ["  " + ln[:220] for ln in bad[-15:]]
    out += ["", "Last lines of the log (%d in all):" % len(log)] + ["  " + ln[:220] for ln in log[-25:]]
    return _r(NL.join(out), "read", "log", job=j["id"], job_state=st)


def solved(turn):
    """did that solve it: the check run after the last change, or the offer to run it"""
    env = turn.env
    last = turn.last()
    chk = _check_name(env)
    eds = [e for e in _load(_e(env, "edits.json"), []) if not e.get("undone")]
    after = max([e["t"] for e in eds] or [0])
    js = [j for j in _jobs(env) if j["t"] >= after and (not chk or j.get("name") == chk)]
    if js and js[-1]["state"] == "finished":
        j = js[-1]
        return _r("After the last change, %s %s: %s" % (j.get("name") or "`%s`" % j["cmd"], "passed" if j["passed"] else
                                                       "FAILED (exit %s)" % j["exit"], j["result"]), *_receipt(j)[:1], "solved",
                  **_receipt(j)[1])
    if last.get("kind") == "repair" and last.get("checked"):
        return _r("Yes: the change to %s() was kept because the check passed (%s)." % (last["function"], last.get("check")),
                  "passed", "solved")
    if chk:
        turn.offer({"kind": "run", "name": chk, "why": "see whether the last change solved it"})
        return _r("Nothing has checked it since the last change. Run the %s? Say go." % chk, "waiting", "solved")
    return _r("Nothing has checked it since the last change, and no check is named here (call `command` the test).",
              "missing", "solved")


# ---------------------------------------------------------------- described changes
def repair_turn(turn, text, value=None):
    import repair as R
    env = turn.env
    if env.kind != "folder":
        return _r("Described code changes work on a folder; for %s, read the file and give the change, or audit it." % env.label(),
                  "missing", "repair", started=False)
    if not _may_change(turn):
        return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused", "repair:authority",
                  started=False)
    req = R.read_request(text)
    if value:
        req["value"], req["empty"] = value, True
    log_text = ""
    j = _job_for(turn, "")
    if j and j["state"] == "finished" and not j.get("passed"):
        lp = Path(j["dir"]) / "log"
        log_text = lp.read_text(errors="replace") if lp.is_file() else ""
    prev = turn.s.get("repair_text")
    if re.match(r"(?i)^\s*(?:ok(?:ay)?\s*,?\s*)?(?:fix|repair|correct)\s+(?:that|it|this)\b", text) and prev and not log_text:
        req = R.read_request(prev)
    names = _load(_e(env, "names.json"), {})
    chk = _check_name(env)
    cmd = names[chk]["cmd"] if chk else R.test_command(env.root)
    last = turn.last()
    prefer = (last["file"], last["function"]) if last.get("function") and last.get("file") else None
    turn.s["goal"] = " ".join(text.split())[:200] if not re.match(r"(?i)^\s*(fix|repair|correct)\s+(that|it|this)\b", text) else turn.s.get("goal")
    turn.s["repair_text"] = text
    turn.save()
    res = R.attempt(env.root, req, cmd, log_text, prefer=prefer)
    if not res["done"] and res.get("missing") == "change" and cmd:
        rc = recompose(turn, text, req, log_text, cmd, res)   # CODE_SPEC C3: repair is composition aimed at the failing check
        if rc:
            return rc
    if not res["done"]:
        if res.get("missing") == "value":
            turn.offer({"kind": "repair_value", "function": res["function"], "param": res["param"], "text": text})
        why = ""
        if res.get("considered"):
            why = NL + "Looked at: " + "; ".join(res["considered"][:4])
        if res.get("caps"):                          # the search reached its own limits: what reproduces this, for the judge
            why += NL + "Ask \"propose an improvement to yourself\" to have that limit changed in a candidate and judged."
        return _r(res["say"] + why, "waiting" if res.get("missing") == "value" else "missing", "repair:" + res["missing"],
                  started=bool(res.get("tried")), tried=res.get("tried", 0), caps=res.get("caps") or {},
                  request={"text": text, "root": env.root, "check": cmd, "log": log_text[-4000:] if log_text else ""})
    p = str(res["file"])
    eid = _record_edit(turn, p, res["before"], res["after"], "repair: " + res["what"])
    turn.last(kind="repair", edit=eid, file=p, function=res["function"], checked=res["checked"], check=cmd)
    head = "In %s(), %s, %s." % (res["function"], env.rel(p), res["what"])
    if res["checked"] and res.get("partial"):
        tail = ("%s ran the check `%s` after it: the tests that were failing on this now pass, and none that passed fails. "
                "Still failing, as before this change: %s (%d candidate change%s tried). Edit %d; \"undo\" takes it back." % (
                    NL, cmd, ", ".join(res["partial"]), res["tried"], "" if res["tried"] == 1 else "s", eid))
        out = (res.get("check_out") or "").strip().splitlines()[-4:]
        return _r(head + NL + _diff(env, p, res["before"], res["after"]) + tail + NL + "```" + NL + NL.join(out) + NL + "```",
                  "changed-checked", "repair", files=[env.rel(p)], edit=eid, check="better", started=True, finished=True,
                  exit=1, function=res["function"], what=res["what"], tried=res["tried"], still_failing=res["partial"])
    if res["checked"]:
        tail = "%s ran the check `%s` after it and it passed (%d candidate change%s tried). Edit %d; \"undo\" takes it back." % (
            NL, cmd, res["tried"], "" if res["tried"] == 1 else "s", eid)
        out = (res.get("check_out") or "").strip().splitlines()[-4:]
        return _r(head + NL + _diff(env, p, res["before"], res["after"]) + tail + NL + "```" + NL + NL.join(out) + NL + "```",
                  "changed-checked", "repair", files=[env.rel(p)], edit=eid, check="passed", started=True, finished=True, exit=0,
                  function=res["function"], what=res["what"], tried=res["tried"])
    env.write(p, res["after"])
    if res.get("still_passes"):
        note = ("Edit %d. The check `%s` passed before this change and still passes after it, so it does not test what you "
                "asked: this is changed, and not yet checked for the new behaviour. Add a test for it, or try it with  "
                "run `command`." % (eid, cmd))
    else:
        note = "Edit %d. There is no check here to run, so this is changed but untested: name one with  call `command` the test." % eid
    return _r(head + NL + _diff(env, p, res["before"], res["after"]) + NL + note, "changed-untested", "repair",
              files=[env.rel(p)], edit=eid, check="not testing this" if res.get("still_passes") else None,
              function=res["function"], what=res["what"], tried=1)


# ---------------------------------------------------------------- code written by composition (CODE_SPEC.md, C1-C3)
def _module_of(env, p):
    rel = os.path.relpath(p, env.root)
    return ".".join(Path(rel).with_suffix("").parts)


def _with_functions(old, sources, imports):
    """the file with the composed functions appended and their imports added after the file's own"""
    new = old or ""
    have = set(re.findall(r"(?m)^(?:import|from) .+$", new))
    add = ["import %s" % i for i in imports if "import %s" % i not in have]
    if add:
        lines = new.splitlines()
        at = 0
        for i, ln in enumerate(lines):
            if re.match(r"^(?:import|from) ", ln):
                at = i + 1
        if at == 0 and lines and lines[0].startswith(('"""', "'''")):    # after a module docstring
            j = 0
            q = lines[0][:3]
            if not (lines[0].count(q) >= 2 and len(lines[0]) > 3):
                j = next((k for k in range(1, len(lines)) if q in lines[k]), 0)
            at = j + 1
        lines[at:at] = add
        new = NL.join(lines) + NL
    out, have_defs = [], set(re.findall(r"(?m)^def (\w+)\(", new))
    for s in sources:                                  # a part already in the file (or already added) is not written twice
        m = re.search(r"(?m)^def (\w+)\(", s)
        if m and m.group(1) in have_defs:
            continue
        if m:
            have_defs.add(m.group(1))
        out.append(s)
    if not out:
        return new
    return new.rstrip(NL) + (NL + NL + NL if new.strip() else "") + (NL + NL + NL).join(s.rstrip(NL) for s in out) + NL


def _srcs(r):
    """a composed function's source, with the parts from outside the project it calls written before it"""
    return list(r.get("support") or []) + [r["source"]]


def _how(r):
    m = r.get("moves") or []
    return "%s (%d move%s; %s; %d example%s, read back by a separate interpreter: %s)" % (
        " -> ".join(m) if m else "composed", r.get("size") or len(m), "" if (r.get("size") or len(m)) == 1 else "s",
        "branches" if r.get("branches") else "one expression", r["examples"], "" if r["examples"] == 1 else "s",
        r["read_back"].replace("read back ", ""))


def _check_cmd(env):
    import repair as R
    names = _load(_e(env, "names.json"), {})
    chk = _check_name(env)
    return names[chk]["cmd"] if chk else R.test_command(env.root)


def _write_checked(turn, writes, how, head, ex_note=None):
    """write the files, run the project's check; kept (and recorded as edits) only if the check passes after it, else put
    back. writes: [(path, old or None, new)]"""
    import repair as R
    env = turn.env
    cmd = _check_cmd(env)
    for p, _old, new in writes:
        bad = _compiles(p, new)
        if bad:
            return _r(head + NL + "Not written: the file would not compile: %s" % bad, "failed", "compose:compile", started=False)
    before = R.run_check(cmd, env.root)[0] if cmd else None
    for p, _old, new in writes:
        env.write(p, new)
    diff = NL.join(_diff(env, p, old or "", new) for p, old, new in writes)
    if cmd:
        ok, out, code = R.run_check(cmd, env.root)
        if not ok:
            for p, old, _new in writes:
                if old is None:
                    os.remove(p)
                else:
                    env.write(p, old)
            return _r(head + NL + diff + NL + "The check `%s` FAILED after it, so it was put back:%s```%s%s%s```" % (
                cmd, NL, NL, out[-1200:], NL), "failed", "compose:check", started=True, finished=True, exit=code,
                files=[env.rel(p) for p, _o, _n in writes])
    eids = [_record_edit(turn, p, old, new, how) for p, old, new in writes]
    files = [env.rel(p) for p, _o, _n in writes]
    ed = "Edit%s %s; \"undo\" takes %s back." % ("s" if len(eids) > 1 else "", ", ".join(map(str, eids)), "them" if len(eids) > 1 else "it")
    if cmd:
        tail = "The check `%s` %s and passes now. %s" % (cmd, "failed before" if not before else "passed before", ed)
        if before and not ex_note:
            # round-3 R3, the witness rule: composed content under a check that passed before as well is not told apart
            return _r(head + NL + diff + NL + tail + " The check passed before this change as well, so it does not tell this "
                      "change apart: it is kept, not yet checked. Give an example or a test it must pass.", "changed-unwitnessed",
                      "compose", files=files, edit=eids[-1], check="passed before and after", started=True, finished=True, exit=0)
        return _r(head + NL + diff + NL + tail, "changed-checked", "compose", files=files, edit=eids[-1],
                  check="passed" if not before else "your examples, and the check still passes", started=True, finished=True, exit=0)
    if ex_note:
        return _r(head + NL + diff + NL + "There are no tests here; %s. %s" % (ex_note, ed), "changed-checked", "compose",
                  files=files, edit=eids[-1], check="your examples", started=True, finished=True, exit=0)
    return _r(head + NL + diff + NL + "There is no check here, so this is changed, not yet checked. " + ed, "changed-untested",
              "compose", files=files, edit=eids[-1])


def _gap_text(rs):
    return NL.join("  - %s: %s" % (r["name"], r.get("gap") or r.get("status")) for r in rs)


_TGOAL_VERB = re.compile(r"(?i)\b(?:make|get|write|create|implement|build|fill in|add)\b")
_TGOAL_PASS = re.compile(r"(?i)\b(?:pass|passes|passing|green|needs?|expects?|calls?|wants?)\b")


def project_turn(turn, text):
    """a project described as a whole (project.py): read into a ledger of requirements, planned over shapes from its
    outcomes back to its tables, written from parts, and judged requirement by requirement against what it does. A hole
    (a word nobody owns, a table not there, a value no part makes) keeps the project as it is, in the conversation and in
    the project's .oracle7 folder; the next turn's example, file, explanation or "drop" fills it and the build goes on,
    after a restart too. A value made from a column comes from Oracle7's code store (by its sha) or is composed from
    examples and kept once the project's judges pass with it."""
    import project as PJ
    import continuation as CT
    env = turn.env
    if env is None or env.kind != "folder":
        return None
    kept = CT.bind(turn, env)                      # C11: only the project of the environment that is open
    if turn.s.get("focus") == "work" and not PJ.is_project(text, None):
        return None                              # a follow-up belongs to the active work record
    if kept is None and PJ.CONTINUE.match(text.strip()):
        kept = PJ.load_project(env.root)           # a project left unfinished, continued from its folder
    import language_bridge as language
    account = language.project_answer(text, kept)
    if account:
        return account
    if language.asks_about(text):
        return None                              # a question containing "now" is not a project revision
    fresh = bool(kept and re.match(
        r"(?i)^\s*(?:build|make|create|develop|start|set up)\s+(?:(?:a|an)\s+)?(?:new|separate)\s+"
        r"(?:project|app|application|script|tool)\b", text))
    if not PJ.is_project(text, None if fresh else kept):
        return None
    if not _may_change(turn):
        return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused",
                  "project:authority", started=False)
    if fresh:
        # A separately requested project starts from its own clauses. The old
        # project remains available in the conversation record.
        turn.s.setdefault("project_history", []).append(kept)
        kept = None
    pre = []
    auth = _authority(turn)
    prev = CT.unchanged_retry(kept, env.root, text, auth) if kept else None
    if prev:                                       # going again on the same inputs would show the same: a different step
        step = CT.choose(turn, kept, env.root, kept.get("last_reply") or {}, CT.used_for(kept, prev["sig"]), _guard_env(env))
        if not step.get("rerun"):
            same = {"response": "", "execution": dict((kept.get("last_reply") or {}).get("execution") or {})}
            a = CT.record(kept, text, same, prev["fp"], cont=step["kind"])
            a["sig"] = prev["sig"]
            turn.s["project"] = kept
            turn.save()
            try:
                PJ.save_project(env.root, kept)
            except OSError:
                pass
            return _r("Nothing this project depends on has changed since attempt %d (the same words, meanings and examples, "
                      "the same files, the same store), so going again would show what it showed then. Instead: %s" % (
                          prev["seq"], step["text"]), prev.get("state") or "missing", "project:continue:" + step["kind"],
                      started=False, continuation={"attempt": a["seq"], "same_inputs_as": prev["seq"], "step": step["kind"],
                                                   "pid": kept.get("pid")})
        pre.append(step["text"])
    r = _project_core(turn, text, kept, env)
    shape = turn.s.get("project")
    st = (r.get("execution") or {}).get("state")
    if shape is not None and st == "missing":      # a missing table an adopted capability of mine makes: made, and on
        step = None
        for h in shape.get("holes_kept") or []:
            got = CT._parts_for(h, shape) if h.get("kind") == "world" and h.get("file") else None
            if got and got[0] == "capability":
                step = CT.choose(turn, shape, env.root, r, (), _guard_env(env))
                break
        if step and step.get("rerun"):
            pre.append(step["text"])
            r = _project_core(turn, "continue", shape, env)
            shape = turn.s.get("project")
    if shape is None:
        return r
    a = CT.record(shape, text, r, CT.fingerprint(shape, env.root, _authority(turn)))
    n_same = CT.same_outcome_run(shape)
    if (r.get("execution") or {}).get("state") in CT.UNFINISHED and n_same >= 2:
        step = CT.choose(turn, shape, env.root, r, CT.used_for(shape, a["sig"]), _guard_env(env))
        a["cont"] = step["kind"]
        r["response"] += NL + "This ended as attempt %d did (nothing new came of it), so this time, differently: %s" % (
            shape["attempts"][-2]["seq"], step["text"])
    if pre:
        r["response"] = NL.join(pre) + NL + r["response"]
    r.setdefault("execution", {})["continuation"] = {"attempt": a["seq"], "pid": shape.get("pid"), "env": env.key,
                                                     "same_outcome_as_before": n_same - 1, "step": a.get("cont")}
    ex = r.get("execution") or {}
    shape["last_reply"] = {"response": (r.get("response") or "")[-6000:],
                           "execution": {k: ex.get(k) for k in ("state", "requirements", "holes") if k in ex}}
    turn.s["project"] = shape
    turn.s["focus"] = "project"
    turn.save()
    try:
        PJ.save_project(env.root, shape)
    except OSError:
        pass
    return r


def _project_core(turn, text, kept, env):
    """one attempt of a project turn: received, planned, composed, written, judged (stages a turn job shows)"""
    import project as PJ
    import continuation as CT
    CT.stage("receiving")
    shape = CT.stamp(PJ.receive(text, env.root, kept), env)
    pipes, holes, reqs, world = PJ.plan(shape, env.root)
    CT.stage("composing")
    composed = PJ.compose_holes(env.root, shape, holes, env.net_scope)
    if composed:
        pipes, holes, reqs, world = PJ.plan(shape, env.root)
    CT.stage("planned")
    # C15: a correction must change the project. One whose requirements come out exactly as before was not understood -
    # it is a named hole, never a rebuild reported as done ("No, I meant above 200" read as nothing to change)
    if kept and not holes and len(shape.get("clauses") or []) > len(kept.get("clauses") or []) and \
            (PJ.REVISE.search(text) or re.match(r"(?i)^\s*(?:actually|no\b|wait|rather|sorry|i meant)", text)):
        before = PJ.plan(json.loads(json.dumps(kept)), env.root)[2]

        def _sig(rs):
            return sorted((r["id"], r["kind"], r["status"], json.dumps(
                {k: v for k, v in r.items() if k not in ("from", "clause", "evidence", "status", "superseded", "_carriers")},
                sort_keys=True, default=str)) for r in rs)
        if _sig(before) == _sig(reqs):
            return _r("I read \"%s\" as a change to %s, but it changes none of its requirements, so nothing was rebuilt. "
                      "The requirements stay:%s%s%sSay what it changes with its column or value (for example \"%s\"), "
                      "or \"drop\" with a requirement's number." % (
                          text.strip()[:160], shape.get("module"), NL, NL.join("  " + x for x in PJ.ledger_lines(before)), NL,
                          next(("%s above 10 instead" % r["op"]["col"] for r in before if r["kind"] == "op" and
                                r["op"].get("op") == "filter"), "save to other.csv instead")),
                      "missing", "project:revision-unread", started=False,
                      holes=["the change \"%s\" names nothing to change" % text.strip()[:120]])
    head = ("I changed the project %s (\"%s\")." % (shape["module"], text.strip()[:160]) if kept
            else "I read the request as a project: %s." % shape["module"])
    prop = [n for n, e in shape["entries"].items() if e.get("proposed")]
    if prop:
        head += " The request names no command%s for %s, so I propose %s." % (
            "" if len(prop) == 1 else "s", "it" if not kept else "this", ", ".join(
                "`python3 %s %s%s`" % (shape["module"], n, "".join(" " + a for a in shape["entries"][n]["args"])) for n in prop))
    store_lines = ["  %s made from %s: Oracle7's kept function %s (sha %s, kept from %s; its evidence replayed and holding)" % (
        d["name"], d["col"], d["fn"], d["sha256"][:16], d.get("project") or "earlier work")
        for d in (shape.get("derived") or {}).values() if d.get("from") == "store"]
    probing = any(p["source"] == "probe" for p in pipes.values())
    if world and probing and not holes:
        scope = set(h.lower() for h in env.net_scope)
        outside = [h for h in world.get("hosts", []) if not (h in ("localhost", "::1") or h.startswith("127.") or
                                                              h.lower() in scope)]
        if outside:
            holes.append({"kind": "netscope", "text": "the servers in %s include host%s outside this conversation's network "
                                                      "scope: %s. Say \"allow network to %s\" for each, then \"continue\"." % (
                                                          world["file"], "" if len(outside) == 1 else "s", ", ".join(outside),
                                                          outside[0])})
            shape["status"] = "blocked"
            shape["holes_kept"] = holes
    turn.s["project"] = shape
    turn.save()
    try:
        PJ.save_project(env.root, shape)
    except OSError:
        pass
    ledger = PJ.ledger_lines(reqs)
    if holes:
        return _r(head + NL + "The requirements, as I read them:" + NL + NL.join("  " + x for x in ledger) +
                  ((NL + "Composed this turn:" + NL + NL.join("  " + c for c in composed)) if composed else "") + NL +
                  "Not all of it can be built yet, so nothing was written. What would fill each hole:" + NL +
                  NL.join("  - " + h["text"] for h in holes) + NL +
                  "The project is kept as it stands (here and in %s/.oracle7/project.json); the next turn goes on from it." % (
                      env.label()), "missing", "project:gap", started=False, holes=[h["text"] for h in holes],
                  requirements=[{"id": r["id"], "kind": r["kind"], "status": r["status"]} for r in reqs])
    CT.stage("writing")
    src = PJ.write(shape, pipes, reqs, world)
    p = env.path(shape["module"])
    old = env.read(p) if env.exists(p) else None
    bad = _compiles(p, src)
    if bad:
        return _r("Not written: the project's code would not compile: %s" % bad, "failed", "project:compile", started=False)
    eid = _apply(turn, p, old, src, "project")
    CT.stage("judging")
    ok, lines, jholes = PJ.judge(env.root, shape, pipes, reqs, world, _guard_env(env))
    kept_now = PJ.keep_derived(env.root, shape) if ok else []
    shape["status"] = "built" if ok else "failed"
    turn.s["project"] = shape
    turn.save()
    try:
        PJ.save_project(env.root, shape)
    except OSError:
        pass
    turn.last(kind="edit", edit=eid, file=p)
    pl = []
    for name, pp in pipes.items():
        e = shape["entries"][name]
        pl.append("  `python3 %s %s%s`: %s" % (shape["module"], name, "".join(" " + a for a in e["args"]),
                                                " -> ".join("%s (%s)" % (l["part"], l["why"]) for l in pp["links"])))
    body = (head + NL + "The plan, from what each command must do back to its table:" + NL + NL.join(pl) + NL +
            ((NL.join(store_lines) + NL) if store_lines else "") +
            (("Composed this turn:" + NL + NL.join("  " + c for c in composed) + NL) if composed else "") +
            _diff(env, p, old or "", src) + NL + "What happened when I ran it:" + NL + NL.join("  " + x for x in lines) + NL +
            "Every requirement against it:" + NL + NL.join("  " + x for x in PJ.ledger_lines(reqs)))
    rec = {"files": [env.rel(p)], "edit": eid, "requirements": [{"id": r["id"], "kind": r["kind"], "status": r["status"]}
                                                                 for r in reqs],
           "from_store": [{"name": d["fn"], "sha256": d["sha256"], "project": d.get("project")}
                          for d in (shape.get("derived") or {}).values() if d.get("from") == "store"]}
    if not ok:
        return _r(body + NL + "Not done - the requirements not met:" + NL + NL.join("  - " + h for h in jholes) + NL +
                  "Edit %d; \"undo\" takes it back." % eid, "failed", "project:judge", **rec)
    if kept_now:
        body += NL + "Kept in Oracle7's store for later work, with the examples they rest on: %s." % ", ".join(
            "%s (sha %s)" % (e["name"], e["sha256"][:16]) for e in kept_now)
        rec["kept"] = [e["id"] for e in kept_now]
    first = next((n for n in pipes if "PORT" not in shape["entries"][n]["args"]), next(iter(pipes)))
    return _r(body + NL + "Done: every requirement passed. Edit %d; \"undo\" takes it back. Run `python3 %s %s` again at "
              "any time." % (eid, shape["module"], first), "changed-checked", "project", **rec)


def _bound_record(goals, rs):
    """for self-development: the goals the composer declined at its own time or memory bound, kept with the receipt"""
    hit = [(g, r) for g, r in zip(goals, rs) if r["status"] != "composed" and
           re.search(r"reached its (?:time limit|memory bound)", r.get("gap") or "")]
    if not hit:
        return {}
    import compose_code as CC
    keep = []
    for g, _r_ in hit:
        try:
            json.dumps(g["examples"])
            keep.append({"name": g["name"], "params": g["params"], "examples": g["examples"]})
        except (TypeError, ValueError):
            continue
    if not keep:
        return {}
    return {"ccaps": {"GOAL_SECONDS": CC.GOAL_SECONDS, "CHAIN_SECONDS": CC.CHAIN_SECONDS}, "cgoals": keep}


def tests_goal(turn, text):
    """'make the tests in test_x.py pass', 'write x.py so that test_x.py passes': every function the tests call that the
    project does not have is a goal; each is composed from the tests' examples, round by round (a function composed in this
    turn is a part for the next), written, and the check decides"""
    t = text.strip()
    if not (_TGOAL_VERB.search(t) and _TGOAL_PASS.search(t)):
        return None
    import compose_code as CC
    named = re.findall(r"[\w./-]+\.py\b", t)
    tfiles = [x for x in named if CC.is_test_path(x)]
    if not tfiles and not re.search(r"(?i)\b(?:the|its|my|all|these)\s+tests?\b", t):
        return None
    env = turn.env
    if env.kind != "folder":
        return None
    if not _may_change(turn):
        return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused", "compose:authority",
                  started=False)
    tests = CC.read_tests(env.root, only=[os.path.basename(x) for x in tfiles] or None)
    ctests = CC.read_class_tests(env.root, only=[os.path.basename(x) for x in tfiles] or None)
    cmissing = {}
    for cname, d in ctests.items():
        mp = os.path.join(env.root, *d["module"].split(".")) + ".py"
        txt = env.read(mp) if os.path.isfile(mp) else ""
        if not re.search(r"(?m)^class %s\b" % re.escape(cname), txt or ""):
            cmissing[cname] = d
    tests = {n: d for n, d in tests.items() if n not in ctests}
    if cmissing and not any(not re.search(r"(?m)^def %s\(" % re.escape(n), (env.read(os.path.join(env.root, *d["module"].split(".")) + ".py")
                                                                         if os.path.isfile(os.path.join(env.root, *d["module"].split(".")) + ".py") else "") or "")
                            for n, d in tests.items()):
        return classes_goal(turn, t, cmissing)
    if not tests:
        return _r("I found no assertion in %s that calls a function of this project with values I can read, so there is "
                  "nothing to compose from." % (", ".join(tfiles) or "the tests"), "missing", "compose:evidence", started=False)
    missing, texts = [], {}
    for name, d in tests.items():
        mp = os.path.join(env.root, *d["module"].split(".")) + ".py"
        txt = env.read(mp) if os.path.isfile(mp) else ""
        texts[mp] = txt
        if not re.search(r"(?m)^def %s\(" % re.escape(name), txt or ""):
            missing.append((name, d, mp))
    if not missing:
        return repair_turn(turn, t)                  # everything the tests call exists: what fails is a change to make
    goals = [{"name": n, "params": CC.param_names(d["examples"]), "module": d["module"], "examples": d["examples"],
              "module_text": texts[mp]} for n, d, mp in missing]
    res = CC.run_job(env.root, goals, words=t, net_scope=env.net_scope) if goals else {"results": []}
    if "error" in res:
        return _r("The composer did not finish: %s" % res["error"], "failed", "compose:run", started=True)
    rs = res["results"]
    bad = [r for r in rs if r["status"] != "composed"]
    files = sorted({mp for _n, _d, mp in missing})
    if bad:
        done = [r for r in rs if r["status"] == "composed"]
        return _r("The tests call %d function%s this project does not have. I composed %d of them, but not %s, so nothing was "
                  "written:%s%s%s" % (len(rs), "" if len(rs) == 1 else "s", len(done), ", ".join(r["name"] for r in bad), NL,
                                      _gap_text(bad), (NL + "Composed: " + ", ".join(r["name"] for r in done)) if done else ""),
                  "missing", "compose:gap", started=False, gaps=[r.get("gap") for r in bad], **_bound_record(goals, rs))
    writes, lines = [], []
    for mp in files:
        mine = [(g, r) for g, r in zip(goals, rs) if os.path.join(env.root, *g["module"].split(".")) + ".py" == mp]
        imports = sorted({i for _g, r in mine for i in r["imports"] + r.get("support_imports", [])})
        old = texts[mp] if os.path.isfile(mp) else None
        writes.append((mp, old, _with_functions(old, [x for _g, r in mine for x in _srcs(r)], imports)))
        for g, r in mine:
            lines.append("  %s(%s): %s%s%s" % (g["name"], ", ".join(g["params"]), _how(r),
                                               (" - uses " + ", ".join(r["uses"])) if r.get("uses") else "", _store_note(r)))
    tf = sorted({f for _n, d, _mp in missing for f in d["files"]})
    head = "The tests in %s call %d function%s the project does not have. I composed each from the tests' examples and " \
           "wrote %s:%s%s" % (", ".join(tf), len(rs), "" if len(rs) == 1 else "s",
                              ", ".join("%s%s" % (env.rel(p), " (new file)" if o is None else "") for p, o, _n in writes),
                              NL, NL.join(lines))
    turn.last(kind="newfn", file=files[-1], function=rs[-1]["name"])
    reply = _write_checked(turn, writes, "composed from tests: " + ", ".join(r["name"] for r in rs), head)
    return _keep_composed(env, list(zip(goals, rs)), tf, reply)


def _keep_composed(env, pairs, files, reply):
    """the functions just written are kept in Oracle7's store only when the project's check passed with them (the tests
    decide); -> a line for the reply. When the project's check failed with a kept function inside what was written, that
    failure is evidence against the kept function: it is retired with the receipt, so no later goal reuses it (12.5 C32)"""
    if (reply.get("execution") or {}).get("state") != "changed-checked":
        used = [f for _g, r in pairs for f in (r.get("from_store") or []) if f.get("id")]
        if used and reply.get("path") == "bench:compose:check":
            try:
                import code_store as CS
                gone = CS.retire([f["id"] for f in used], "the check of %s failed with it inside %s (%s)" % (
                    ", ".join(files) or "the project", ", ".join(r["name"] for _g, r in pairs), env.root))
            except Exception:  # noqa: BLE001
                gone = []
            if gone:
                names = sorted({f["name"] for f in used if f["id"] in gone})
                reply["response"] += NL + "The check failed with %s from Oracle7's store inside, so %s no longer reused: " \
                    "a failed check is evidence against a kept function." % (", ".join(names), "it is" if len(names) == 1 else "they are")
                reply["execution"]["retired"] = gone
        return reply
    try:
        import code_store as CS
        added = CS.keep([CS.entry_for(r, g, env.root, files) for g, r in pairs])
    except Exception as e:  # noqa: BLE001
        reply["response"] += NL + "(Not kept in the store: %s)" % str(e)[:120]
        return reply
    if added:
        reply["response"] += NL + "Kept in Oracle7's store for later work, with the examples they rest on: %s." % (
            ", ".join(e["name"] for e in added))
        reply["execution"]["kept"] = [e["id"] for e in added]
    return reply


def _store_note(r):
    fs = r.get("from_store") or []
    return "".join(" - uses %s from Oracle7's store (kept from %s)" % (f["name"], f.get("project") or "earlier work") for f in fs)


def classes_goal(turn, t, cmissing):
    """classes the tests use: each query composed from what was done to the object and what it gave; written whole"""
    import compose_code as CC
    env = turn.env
    res = CC.run_job(env.root, [], words=t, net_scope=env.net_scope, classes=cmissing)
    if "error" in res:
        return _r("The composer did not finish: %s" % res["error"], "failed", "compose:run", started=True)
    rs = res["classes"]
    bad = [r for r in rs if r["status"] != "composed"]
    if bad:
        return _r("The tests use %d class%s this project does not have. %s, so nothing was written:%s%s" % (
            len(rs), "" if len(rs) == 1 else "es", "I composed %d of them, but not %s" % (len(rs) - len(bad), ", ".join(r["class"] for r in bad)),
            NL, NL.join("  - %s: %s" % (r["class"], r.get("gap", "")) for r in bad)),
                  "missing", "compose:gap", started=False, gaps=[r.get("gap") for r in bad])
    writes, lines, by = [], [], {}
    for r in rs:
        mp = os.path.join(env.root, *r["module"].split(".")) + ".py"
        by.setdefault(mp, []).append(r)
    for mp, group in by.items():
        old = env.read(mp) if os.path.isfile(mp) else None
        imports = sorted({i for r in group for i in r["imports"] + r.get("support_imports", [])})
        writes.append((mp, old, _with_functions(old, [x for r in group for x in _srcs(r)], imports)))
        for r in group:
            lines.append("  class %s: what is done to it (%s) is kept as its history; %s" % (
                r["class"], ", ".join(r["mutators"]) or "nothing", "; ".join(
                    "%s from %d examples (%s)" % (q["name"], q["examples"], " -> ".join(q["moves"] or [])) for q in r["queries"])))
    head = "The tests use %d class%s the project does not have. I composed each query from what the tests did to the object " \
           "and what it gave, and wrote %s:%s%s" % (len(rs), "" if len(rs) == 1 else "es",
                                                   ", ".join("%s%s" % (env.rel(p_), " (new file)" if o is None else "")
                                                             for p_, o, _n in writes), NL, NL.join(lines))
    turn.last(kind="newfn", file=list(by)[-1], function=rs[-1]["class"])
    return _write_checked(turn, writes, "composed classes: " + ", ".join(r["class"] for r in rs), head)


def compose_function(turn, name, params, p, words):
    """one named function, composed from the request's examples and the project's tests -> a reply, or (None, gap)"""
    import compose_code as CC
    env = turn.env
    ex = CC.examples_in(words, name)
    tests = CC.read_tests(env.root)
    src_files = []
    if name in tests:
        have = {repr((a, o)) for a, o, _t in ex}
        ex += [e for e in tests[name]["examples"] if repr((e[0], e[1])) not in have]
        src_files = tests[name]["files"]
    if params:
        ex = [e for e in ex if len(e[0]) == len(params)]
    if not ex:
        return None, None
    old = env.read(p) if env.exists(p) else None
    goal = {"name": name, "params": params or CC.param_names(ex), "module": _module_of(env, p), "examples": ex,
            "module_text": old or ""}
    res = CC.run_job(env.root, [goal], words=words, net_scope=env.net_scope)
    if "error" in res:
        return None, res["error"]
    r = res["results"][0]
    if r["status"] != "composed" and r.get("network"):   # outside the network scope: a hard stop, nothing else is tried
        return _r("Nothing was fetched and nothing was written: %s" % r["gap"], "missing", "newfn:netscope", started=False), None
    if r["status"] != "composed":
        return None, r["gap"]
    where = ("the tests in %s" % ", ".join(src_files)) if src_files else "your examples"
    head = "Composed %s(%s) from %s: %s%s. Put it in %s:" % (name, ", ".join(goal["params"]), where, _how(r), _store_note(r),
                                                            env.rel(p))
    turn.last(kind="newfn", file=p, function=name)
    new = _with_functions(old, _srcs(r), r["imports"] + r.get("support_imports", []))
    reply = _write_checked(turn, [(p, old, new)], "composed function " + name, head,
                           ex_note="your %d example%s were run on it by a separate interpreter and it gives each one (%s)" % (
                               r["examples"], "" if r["examples"] == 1 else "s", r["read_back"]))
    return _keep_composed(env, [(goal, r)], src_files, reply), None


def recompose(turn, text, req, log_text, cmd, res):
    """repair as composition: the located function composed again from its tests, its body replaced, the check decides"""
    import compose_code as CC
    import repair as R
    env = turn.env
    tests = CC.read_tests(env.root)
    for _score, p, fn, src in R.locate(env.root, req, log_text)[:3]:
        d = tests.get(fn.name)
        params = [a.arg for a in fn.args.args]
        if not d or len(d["examples"]) < 2 or fn.col_offset != 0 or fn.args.vararg or fn.args.kwarg:
            continue
        ex = [e for e in d["examples"] if len(e[0]) == len(params)]
        if len(ex) < 2:
            continue
        goal = {"name": fn.name, "params": params, "module": _module_of(env, str(p)), "examples": ex, "module_text": src}
        out = CC.run_job(env.root, [goal], words=text, exclude=[fn.name], net_scope=env.net_scope)
        if "error" in out or out["results"][0]["status"] != "composed":
            continue
        r = out["results"][0]
        lines = src.splitlines()
        b0 = fn.body[0]
        A = ast_mod()
        is_doc = isinstance(b0, A.Expr) and isinstance(getattr(b0, "value", None), A.Constant) and isinstance(b0.value.value, str)
        start = b0.end_lineno if is_doc else b0.lineno - 1
        body = r["source"].splitlines()[1:]
        new = NL.join(lines[:start] + body + lines[fn.end_lineno:]) + NL
        if r["imports"] or r.get("support"):
            new = _with_functions(new, r.get("support", []), r["imports"] + r.get("support_imports", [])).rstrip(NL) + NL
        head = ("%s; none made the check pass, so I composed %s() again from its %d tests in %s: %s." % (
            res["say"].split(";")[0], fn.name, r["examples"], ", ".join(d["files"]), _how(r)))
        rr = _write_checked(turn, [(str(p), src, new)], "repair by composition: " + fn.name, head)
        if rr["execution"]["state"] == "changed-checked":
            turn.last(kind="repair", edit=rr["execution"].get("edit"), file=str(p), function=fn.name, checked=True, check=cmd)
            return rr
    return None


def ast_mod():
    import ast as _a
    return _a


_FN = r"(\w+(?:\s*\([^)]*\))?)"      # a name, and its inputs if the operator names them: big_total(xs, limit)
_NEWFN = (re.compile(r"(?is)^(?:please\s+)?(?:add|write|create|make|build)\s+(?:a\s+)?(?:new\s+)?function\s+(?:called\s+|named\s+)?" + _FN +
                     r"\s+(?:to|in|into|inside)\s+([\w./~-]+\.py)\s*,?\s*(?:that|which|to|:|-)\s*(.+)$"),
          re.compile(r"(?is)^(?:please\s+)?(?:in|to|into)\s+([\w./~-]+\.py)\s*,?\s*(?:add|write|create|make|build)\s+(?:a\s+)?(?:new\s+)?"
                     r"function\s+(?:called\s+|named\s+)?" + _FN + r"\s*(?:that|which|to|:|-)\s*(.+)$"),
          re.compile(r"(?is)^(?:please\s+)?(?:create|make|write)\s+(?:a\s+)?(?:new\s+)?(?:file\s+)?([\w./~-]+\.py)\s+with\s+(?:a\s+)?"
                     r"function\s+(?:called\s+|named\s+)?" + _FN + r"\s*(?:that|which|to|:|-)\s*(.+)$"),
          # 12.0 C28: a name written with its inputs right after the verb is a function by its own form ("add double(x)
          # with these examples: ...", "write slug(title) to people.py: ..."); the file may be left to the project
          re.compile(r"(?is)^(?:please\s+)?(?:add|write|create|make|build)\s+(\w+\s*\([^)]*\))\s*(?:(?:to|in|into|inside)\s+"
                     r"([\w./~-]+\.py)\s*)?,?\s*(?:with\s+(?:these\s+|the\s+following\s+|its\s+)?examples?\s*:?|that|which|:|-)\s*(.+)$"))


def new_function(turn, text):
    """a function composed from described steps by the program builder (make.py's moves), put into a project file, and the
    project's checks run after it"""
    t = text.strip()
    m = _NEWFN[0].match(t)
    if m:
        name, f, steps = m.group(1), m.group(2), m.group(3)
    else:
        m = _NEWFN[1].match(t) or _NEWFN[2].match(t)
        if m:
            f, name, steps = m.group(1), m.group(2), m.group(3)
        else:
            m = _NEWFN[3].match(t)
            if not m:
                return None
            name, f, steps = m.group(1), m.group(2), m.group(3)
            if not f:                                   # no file named: the project's one source file, or ask which
                env0 = turn.env
                if env0 is None or env0.kind != "folder":
                    return None
                src = sorted(env0.rel(p) for p in env0.walk(limit=4000) if p.endswith(".py")
                             and not re.match(r"(?:test_|_)", os.path.basename(p)) and not os.path.basename(p).endswith("_test.py"))
                if len(src) != 1:
                    return _r("Which file should %s go into? %s" % (re.match(r"\w+", name).group(0),
                              ("This folder has %s." % ", ".join(src[:8])) if src else "This folder has no Python file yet; "
                              "name one, for example `add %s to calc.py: ...`." % name.strip()), "missing", "newfn:file", started=False)
                f = src[0]
    fsig = re.sub(r"\s+", "", name)                 # "big_total(xs,limit)" goes to the builder; the bare name everywhere else
    name = re.match(r"\w+", name).group(0)
    env = turn.env
    if env.kind != "folder":
        return _r("Composing functions works on a folder; %s is a host." % env.label(), "missing", "newfn", started=False)
    if not _may_change(turn):
        return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused", "newfn:authority",
                  started=False)
    hits0 = env.resolve(f)
    p0 = hits0[0] if len(hits0) == 1 else env.path(f)
    if env.exists(p0) and re.search(r"(?m)^def %s\(" % re.escape(name), env.read(p0) or ""):
        return _r("%s already has a function called %s; say what to change in it instead." % (env.rel(p0), name), "missing",
                  "newfn:exists", started=False)
    given = [x.strip() for x in fsig[len(name):].strip("()").split(",") if x.strip()] if "(" in fsig else None
    rc, comp_gap = compose_function(turn, name, given, p0, t)    # CODE_SPEC C1/C2: the composer, from examples and tests
    if rc:
        return rc
    import ast as _ast
    import make as _make
    import tools as _tools
    _make.KNOWN.clear()
    src, P = _make.compose("function %s: %s" % (fsig, steps), _tools._find_recs, _tools._read_rec)
    if P.gaps:                                       # "that keeps ..., then sums them": the builder reads commands; the
        def _imp(m):                                 # description says what the function does - each clause's verb as a command
            w = m.group(2)
            v = w[:-3] + "y" if w.endswith("ies") else w[:-2] if re.search(r"(?:ch|sh|x|ss|z)es$", w) else w[:-1]
            return m.group(1) + v
        alt = re.sub(r"(?i)(^|,\s*(?:and\s+|then\s+)?|\bthen\s+|;\s*|\band\s+)([a-z]{3,}s)\b(?!\s*(?:of|is|are)\b)", _imp, steps.strip())
        if alt != steps.strip():
            src2, P2 = _make.compose("function %s: %s" % (fsig, alt), _tools._find_recs, _tools._read_rec)
            if len(P2.gaps) < len(P.gaps):
                src, P, steps = src2, P2, alt
    if P.gaps:
        return _r("I could not compose every step of %s, so nothing was written:%s%s%s" % (
            name, NL, NL.join("  - " + g for g in P.gaps),
            (NL + "From its examples and tests: " + comp_gap) if comp_gap else
            (NL + "Give an example (%s(...) == ...) or a test, and it is composed from that." % name)),
                  "missing", "newfn:gap", started=False, gaps=P.gaps)
    tree = _ast.parse(src)
    keep, imports = [], []
    for node in tree.body:
        seg = _ast.get_source_segment(src, node) or ""
        if isinstance(node, (_ast.Import, _ast.ImportFrom)):
            imports.append(seg)
        elif isinstance(node, _ast.FunctionDef) and node.name not in ("run", "main", "_show"):
            keep.append(seg)
    if not any(re.match(r"def %s\(" % re.escape(name), k) for k in keep):
        return _r("The builder made no function called %s from those steps." % name, "missing", "newfn:gap", started=False)
    keep = [NL.join(ln for ln in k.splitlines() if not re.match(r"^\s*_show\(", ln)) for k in keep]
    hits = env.resolve(f)
    p = hits[0] if len(hits) == 1 else env.path(f)
    old = env.read(p) if env.exists(p) else ""
    if old is None:
        return _r("%s is not a text file I edit." % f, "refused", "newfn:file", started=False)
    if re.search(r"(?m)^def %s\(" % re.escape(name), old or ""):
        return _r("%s already has a function called %s; say what to change in it instead." % (env.rel(p), name), "missing",
                  "newfn:exists", started=False)
    have = set(re.findall(r"(?m)^(?:import|from) .+$", old or ""))
    add_imp = [i for i in imports if i not in have]
    new = old or ""
    if add_imp:
        lines = new.splitlines()
        at = 0
        for i, ln in enumerate(lines):
            if re.match(r"^(?:import|from) ", ln):
                at = i + 1
        lines[at:at] = add_imp
        new = NL.join(lines) + (NL if lines else "")
    new = new.rstrip(NL) + (NL + NL + NL if new.strip() else "") + (NL + NL + NL).join(keep) + NL
    bad = _compiles(p, new)
    if bad:
        return _r("Not written: the composed function would not compile: %s" % bad, "failed", "newfn:compile", started=False)
    import repair as R
    names = _load(_e(env, "names.json"), {})
    chk = _check_name(env)
    cmd = names[chk]["cmd"] if chk else R.test_command(env.root)
    before = R.run_check(cmd, env.root)[0] if cmd else None
    eid = _apply(turn, p, old or None, new, "new function " + name)
    steps_done = NL.join("  " + x for x in P.trace)
    head = "Composed %s from your steps (%d move%s) and put it in %s:%s%s" % (name, len(P.trace), "" if len(P.trace) == 1 else "s",
                                                                          env.rel(p), NL, steps_done)
    sig = (" Its inputs: %s." % fsig[len(name):]) if "(" in fsig else " It takes one value and returns the result."
    turn.last(kind="newfn", edit=eid, file=p, function=name)
    if cmd:
        ok, out, code = R.run_check(cmd, env.root)
        if not ok:
            return _r(head + NL + _diff(env, p, old or "", new) + NL + "The check `%s` FAILED after it (edit %d; \"undo\" takes it "
                      "back):%s```%s%s%s```" % (cmd, eid, NL, NL, out[-1200:], NL) + sig, "failed", "newfn", files=[env.rel(p)], edit=eid,
                      function=name, what="new function", exit=code)
        if not before:
            return _r(head + NL + _diff(env, p, old or "", new) + NL + "The check `%s` failed before and passes now. Edit %d." % (cmd, eid) + sig,
                      "changed-checked", "newfn", files=[env.rel(p)], edit=eid, function=name, what="new function", check="passed",
                      tried=1, exit=0)
    return _r(head + NL + _diff(env, p, old or "", new) + NL + "Edit %d. %s, so this is changed, not yet checked for what it does." % (
        eid, ("The check `%s` passed before and after it: it does not test %s" % (cmd, name)) if cmd else "There is no check here") + sig +
        " Try it:  run `python3 -c \"from %s import %s; print(%s(...))\"`" % (os.path.splitext(os.path.basename(p))[0], name, name),
        "changed-untested", "newfn", files=[env.rel(p)], edit=eid, function=name, what="new function", tried=1)


def value_reply(turn, text):
    o = next((x for x in turn.s.get("offers", []) if x["kind"] == "repair_value"), None)
    if not o:
        return None
    t = text.strip().rstrip(".")
    m = re.match(r"(?i)^(?:it should\s+|make it\s+|just\s+)?(?:return|give)?\s*(none|0|0\.0|\[\]|''|\"\"|false|true|-?\d+(?:\.\d+)?)$", t) or \
        re.match(r"(?i)^(?:return|give)\s+(none|0|0\.0|\[\]|''|\"\"|false|true|-?\d+(?:\.\d+)?)\b", t)
    if m:
        v = m.group(1)
        v = {"none": "None", "false": "False", "true": "True"}.get(v.lower(), v)
    else:
        m = re.match(r"(?i)^(?:it should\s+)?raise\s+(?:an?\s+)?(\w*Error)\b", t)
        if not m:
            return None
        v = "raise " + m.group(1)
    turn.s["offers"] = [x for x in turn.s["offers"] if x["kind"] != "repair_value"]
    turn.save()
    return repair_turn(turn, o["text"], value=v)


# ---------------------------------------------------------------- server findings
def audit(turn, text):
    import findings as F
    env = turn.env
    rules = F.rules_for(text)
    found, looked, unread = [], [], []
    eff, eff_rules = None, [r for r in rules if r.get("service") == "ssh" and "file" in r and r.get("fix")]
    if eff_rules and env.kind == "folder" and os.path.isfile(env.path("etc/ssh/sshd_config")):
        import effective as _eff                     # 12.5 12d(ii) (design 5.A): the service's own resolved reading
        eff = _eff.sshd(env.root)
        if eff.get("hole"):
            unread.append("the service's own reading (sshd -T): " + eff["hole"])
            eff = None
        else:
            looked += [env.rel(env.path("etc/ssh/sshd_config")),
                       "sshd -T (%s, sha %s)" % (eff["receipt"]["says"], eff["receipt"]["sha"][:12])]
    ng, ng_rules = None, [r for r in rules if r.get("service") == "nginx" and "file" in r]
    if ng_rules and env.kind == "folder" and os.path.isfile(env.path("etc/nginx/nginx.conf")):
        import effective as _eff                     # 12.5 12d(iii): nginx's own reading (nginx -T), resolved by block
        ng = _eff.nginx(env.root)
        if ng.get("hole"):
            unread.append("the service's own reading (nginx -T): " + ng["hole"])
            ng = None
        else:
            looked += [env.rel(env.path(x.lstrip("/"))) for x in ng["receipt"]["files"]] + [
                "nginx -T (%s, sha %s)" % (ng["receipt"]["says"], ng["receipt"]["sha"][:12])]
    for r in rules:
        if eff is not None and r in eff_rules:      # judged on the value the service resolves, not on a file's text
            found += _effective_finding(env, r, eff)
            continue
        if ng is not None and r in ng_rules:
            found += _effective_nginx_finding(env, r, ng)
            continue
        if "file" in r:
            pat = r["file"]
            base = env.path(pat.lstrip("/")) if env.kind == "folder" else pat
            paths = [base]
            if any(c in pat for c in "*?"):
                d = os.path.dirname(base)
                if env.kind == "folder":
                    paths = [os.path.join(d, f) for f in sorted(os.listdir(d))] if os.path.isdir(d) else []
                else:
                    paths = env.sh("ls -1d %s 2>/dev/null" % base, 20)[1].split()
            for p in paths:
                s = env.read(p)
                if s is None:
                    continue
                looked.append(env.rel(p))
                for inc in _INCLUDE.findall(s):      # 12.5 12d(i): what the service also loads, by its own directive
                    unread.append("%s (included by %s; the service reads it, this check did not)" % (inc.strip(), env.rel(p)))
                for f in F.check_text(r, p, s):
                    found.append(dict(f, file=p, test=r.get("test"), reload=r.get("reload")))
        elif "log" in r:
            p = env.path(r["log"].lstrip("/")) if env.kind == "folder" else r["log"]
            s = env.read(p, 50_000_000)
            if s is not None:
                looked.append(env.rel(p))
                found += F.check_text(r, p, s)
                d, b = os.path.split(p)
                if env.kind == "folder" and os.path.isdir(d):
                    unread += ["%s (a rotated log)" % env.rel(os.path.join(d, x)) for x in sorted(os.listdir(d))
                               if x.startswith(b + ".")]
            else:
                unread.append("%s (not present here)" % r["log"])
        elif "cmd" in r:
            if env.kind == "host" or os.environ.get("ORACLE7_BENCH_LOCALCMD") == "1":
                code, out = env.sh(r["cmd"], 30)
                looked.append(r["cmd"])
                found += F.check_cmd_output(r, out)
            else:
                unread.append("`%s` (a command check; not run on a folder)" % r["cmd"])
    if ng is not None and any(f.get("effective_service") == "nginx" for f in found):
        obs = _eff.observe_nginx(env.root, ng)       # 12.5 12d(vii) (design 5.C): what the folder's own nginx serves
        for f in found:
            if f.get("effective_service") == "nginx":
                f["observed"] = _observed_lines(f, obs)
    looked = list(dict.fromkeys(looked))
    unread = list(dict.fromkeys(unread))
    found.sort(key=lambda f: f.get("low", False))
    turn.s["findings"] = found
    turn.s["goal"] = turn.s.get("goal") or " ".join(text.split())[:200]
    turn.save()
    turn.last(kind="audit", n=len(found))
    if not looked:
        return _r("I found none of the files these checks read on %s (looked for: %s)." % (env.label(), ", ".join(
            sorted({r.get("file") or r.get("log") or r.get("cmd") for r in rules}))), "missing", "audit")
    if not found:
        # 12.5 12d(i) (round-2 design 5.D): an all-clear says what it read and what it did not; with anything unread it is
        # not an all-clear for the service as it runs, and is offered, never answered
        r = _r("Read %s on %s: no finding from the %d checks that apply, in what was read.%s" % (
            ", ".join(looked), env.label(), len(rules),
            (NL + "Not read, so this is not an all-clear for the service as it runs:" + NL + NL.join("- " + u for u in unread))
            if unread else ""), "read", "audit", coverage={"read": looked, "not_read": unread})
        if unread:
            r["status"] = "offered"
        return r
    out = ["Read %s on %s. Findings:" % (", ".join(looked), env.label())]
    for i, f in enumerate(found, 1):
        out.append("")
        out.append("%d. %s%s: %s" % (i, f["rule"], " (minor)" if f.get("low") else "", f["why"]))
        if f.get("effective"):
            ng_ = f.get("effective_service") == "nginx"
            out.append("   the installed %s reports: %s (%s, sha %s)" % ("nginx" if ng_ else "sshd", f["effective"],
                                                                   "nginx -T" if ng_ else "sshd -T", str(f.get("receipt"))[:12]))
        for ln, txt in f["evidence"][:6]:
            out.append("   %s:%s  %s" % (env.rel(f["where"]), ln, str(txt).strip()[:180]))
        for o_ in f.get("observed") or []:
            out.append("   " + o_)
        if f.get("manual"):
            m_ = f["manual"]
            out.append("   the installed manual, %s, says: %s [man:%s %s]" % (
                m_["name"], " ".join(m_["said"])[:500], m_["name"], m_["sha"][:12]))
            if f.get("fix") is None and m_.get("default") and m_["default"] not in " ".join(m_["said"]):
                out.append("   and of the default: %s [man:%s %s]" % (m_["default"], m_["name"], m_["sha"][:12]))
        elif f.get("manual_hole"):
            out.append("   (no stated effect cited: %s)" % f["manual_hole"])
        if f.get("fix"):
            out.append("   correction prepared: \"%s\" -> \"%s\"; say  fix %d" % (f["fix"][0], f["fix"][1], i))
        if f.get("advice"):
            out.append("   " + f["advice"])
        if f.get("caution"):
            out.append("   Caution: " + f["caution"])
    if unread:
        out += ["", "Not read (findings may also be there):"] + ["- " + u for u in unread]
    return _r(NL.join(out), "read", "audit", findings=len(found), coverage={"read": looked, "not_read": unread})


def _effective_finding(env, rule, eff):
    """one ssh rule judged on the resolved value: the rule's own correction names the keyword and the value it corrects;
    the origin pointer (the first line sshd obtained it from) is where the correction goes; an unset keyword's default is
    a finding with no line to edit, said as such"""
    key, bad = (x.lower() for x in rule["fix"][0].split(None, 1))
    val = eff["values"].get(key)
    if val is None or val.lower() != bad:
        return []
    base = {"rule": rule["id"], "why": rule["why"], "caution": rule.get("caution"), "low": rule.get("low", False),
            "test": rule.get("test"), "reload": rule.get("reload"), "effective": "%s %s" % (key, val),
            "effective_key": key, "effective_bad": bad, "receipt": eff["receipt"]["sha"]}
    import effective as _eff                         # 12.5 12d(iv) (design 5.B): the consequence from the sealed manual
    man = _eff.manual("ssh", key)
    if isinstance(man, dict) and not man.get("hole"):
        said = [man["paragraphs"][0]] if man["paragraphs"] else []
        said += [x for x in man["paragraphs"][1:] if re.search(r"\bset to\s+%s\b" % re.escape(bad), x, re.I)][:1]
        base["manual"] = {"name": man["name"], "said": said, "default": man["default"], "sha": man["sha"]}
    else:
        base["manual_hole"] = (man or {}).get("hole") or "the sealed manual holds no entry for %s" % key
    o = eff["origin"].get(key)
    if o:
        p, ln, txt = o
        return [dict(base, where=p, file=p, evidence=[(ln, txt)], fix=(txt.strip(), rule["fix"][1]))]
    conf = env.path("etc/ssh/sshd_config")
    return [dict(base, where=conf, file=conf, evidence=[], fix=None,
                 advice="No file read sets it, so sshd uses its default. To set it, add the line `%s` to %s." % (
                     rule["fix"][1], env.rel(conf)))]


def _observed_effect(rule_id, obs):
    """the served rows that show a rule's effect: a version in the Server header, or a listing"""
    rows = obs.get("served") or []
    if rule_id == "nginx-tokens":
        return [r for r in rows if r.get("server") and "/" in r["server"]]
    if rule_id == "nginx-autoindex":
        return [r for r in rows if r.get("listed")]
    return []


def _observed_lines(f, obs):
    if obs.get("hole"):
        return ["(" + obs["hole"] + ")"]
    seen = _observed_effect(f["rule"], obs)
    out = ["observed in the folder's own nginx: %s answers `Server: %s`" % (r["url"], r["server"]) if f["rule"] == "nginx-tokens"
           else "observed in the folder's own nginx: GET %s returns a listing" % r["url"] for r in seen[:4]]
    if not seen:
        out.append("(not observed: the folder's own nginx did not show it at the addresses read)")
    return out + ["(%s)" % h for h in obs.get("holes") or []]


def _effective_nginx_finding(env, rule, ng):
    """one nginx rule judged where requests are served: the rule's own correction names the directive and the value it
    corrects; one finding per file that sets it (the correction goes to that directive), or one for a default"""
    bad_line, good_line = rule.get("fix") or rule["fix_by"][-1]
    key, bad = bad_line.rstrip(";").split(None, 1)
    hits = [o for o in ng["values"].get(key, []) if str(o["value"]).lower() == bad.lower()]
    if not hits:
        return []
    base = {"rule": rule["id"], "why": rule["why"], "caution": rule.get("caution"), "low": rule.get("low", False),
            "test": rule.get("test"), "reload": rule.get("reload"), "effective_service": "nginx", "effective_key": key,
            "effective_bad": bad.lower(), "receipt": ng["receipt"]["sha"]}
    out, by = [], {}
    for o in hits:
        by.setdefault(o["origin"]["file"] if o["origin"] else None, []).append(o)
    for f, os_ in by.items():
        where = ", ".join(sorted({o["scope"] for o in os_}))[:300]
        if f is None:
            conf = env.path("etc/nginx/nginx.conf")
            out.append(dict(base, where=conf, file=conf, evidence=[], fix=None,
                            effective="%s %s (its default) at %s" % (key, bad, where),
                            advice="No file nginx loads sets it, so nginx uses its default. To set it, add `%s` to the http "
                                   "block of %s." % (good_line, env.rel(conf))))
            continue
        ev = sorted({(o["origin"]["line"], o["origin"]["text"]) for o in os_})
        src = next((o["origin"]["src"] for o in os_ if o["origin"].get("src")), None)
        out.append(dict(base, where=f, file=f, evidence=ev, fix=(src, good_line) if src else None,
                        effective="%s %s at %s" % (key, bad, where)))
    return out


_INCLUDE = re.compile(r"(?im)^[ \t]*include[ \t]+([^;#\r\n]+?)[ \t]*;?[ \t]*\r?$")   # sshd "Include x", nginx "include x;" (CRLF lines too)


def fix_finding(turn, n):
    import findings as F
    env = turn.env
    fs = turn.s.get("findings") or []
    if not (1 <= n <= len(fs)):
        return _r("There is no finding %d in this conversation; \"audit\" lists them." % n, "missing", "fix")
    f = fs[n - 1]
    if not f.get("fix"):
        return _r("Finding %d (%s) has no line correction; %s" % (n, f["rule"], f.get("advice") or "it needs a decision."),
                  "missing", "fix")
    p = f["file"]
    s = env.read(p)
    a, b = f["fix"]
    lines = s.splitlines(keepends=True)
    ev = {ln for ln, _ in f["evidence"]}
    new = "".join((ln.replace(a, b, 1) if i in ev else ln) for i, ln in enumerate(lines, 1))
    diff = _diff(env, p, s, new)
    if not _may_change(turn):
        turn.offer({"kind": "fix", "n": n, "rule": f["rule"], "file": p})
        return _r(diff + NL + "Prepared, not applied: this conversation may only read %s. Say \"allow changes\", then go." % env.label(),
                  "waiting", "fix:authority", started=False)
    eid = _apply(turn, p, s, new, "fix " + f["rule"])
    rule = next(r for r in F.RULES if r["id"] == f["rule"])
    out = [diff, "Edit %d applied to %s (backup kept; \"undo\" takes it back)." % (eid, env.rel(p))]
    if f.get("effective_key") and f.get("effective_service") == "nginx":
        import effective as _eff                     # 12.5 12d(iii): checked again by nginx's own reading
        e2 = _eff.nginx(env.root) if env.kind == "folder" else {"hole": "not a folder"}
        vals = (e2.get("values") or {}).get(f["effective_key"])
        still = [o for o in (vals or []) if str(o["value"]).lower() == f["effective_bad"]]
        ok = vals is not None and not still
        out.append("Checked again by the service's own reading: %s." % (
            "the installed nginx no longer serves %s %s anywhere" % (f["effective_key"], f["effective_bad"]) if ok else
            "the installed nginx STILL serves %s %s at %s" % (f["effective_key"], f["effective_bad"],
                                                              ", ".join(o["scope"] for o in still)[:200]) if vals is not None
            else "could not read it again (%s)" % e2.get("hole", "no value")))
    elif f.get("effective_key"):                     # 12.5 12d(ii): checked again by the service's own reading
        import effective as _eff
        e2 = _eff.sshd(env.root) if env.kind == "folder" else {"hole": "not a folder"}
        now = (e2.get("values") or {}).get(f["effective_key"])
        ok = now is not None and now.lower() != f["effective_bad"]
        out.append("Checked again by the service's own reading: %s." % (
            "the installed sshd now reports %s %s" % (f["effective_key"], now) if ok else
            "the installed sshd STILL reports %s %s" % (f["effective_key"], now) if now is not None else
            "could not read it again (%s)" % e2.get("hole", "no value")))
    else:
        again = F.check_text(rule, p, env.read(p) or "")
        ok = not again
        out.append("Checked again: %s." % ("the finding is gone" if ok else "the finding is STILL there"))
    test_state = None
    if f.get("effective_key") and env.kind == "folder":
        # 12.5 12d(ii)/(iii): in a folder the service's own config test is its own reading of the whole configuration in
        # the folder (the rule's command would test a fragment, or this machine's own /etc); it loaded or it did not
        test_state = "failed" if e2.get("hole") else "passed"
        out.append("The service's own config test (%s of the whole configuration in this folder): %s" % (
            "nginx -T" if f.get("effective_service") == "nginx" else "sshd -T",
            "passed" if test_state == "passed" else "FAILED: " + e2["hole"][:300]))
        ok = ok and test_state == "passed"
    elif f.get("test"):
        t = f["test"].format(file=p)
        code, o = env.sh(t, 30)
        test_state = "unrun" if (code is None or "not found" in o) else ("passed" if code == 0 else "failed")
        if code is None or "not found" in o:
            out.append("The service's own config test (%s) could not run here: %s" % (t, o.strip()[:160]))
        else:
            out.append("The service's own config test `%s`: %s%s" % (t, "passed" if code == 0 else "FAILED (exit %s)" % code,
                                                                   ("" if code == 0 else NL + o.strip()[:400])))
            ok = ok and code == 0
    folder_nginx = f.get("effective_service") == "nginx" and env.kind == "folder"
    if folder_nginx and ok:                          # 12.5 12d(vii) (design 5.C): done means the observed effect changed
        obs2 = _eff.observe_nginx(env.root, e2)
        if obs2.get("hole"):
            out.append("Not observed after the change (%s)." % obs2["hole"])
        else:
            still_seen = _observed_effect(f["rule"], obs2)
            ok = not still_seen
            out.append("Observed in the folder's own nginx after the change: %s." % (
                "the effect is gone at every address read" if ok else "STILL there at " + ", ".join(r["url"] for r in still_seen)))
        out.append("This folder's nginx is not this machine's running service, so nothing here is reloaded.")
    if f.get("reload") and ok and test_state in (None, "passed") and not folder_nginx:   # 12.5 step 7: only after its test passed
        turn.offer({"kind": "cmd", "cmd": f["reload"], "name": None, "file": p, "verdict": test_state or "passed"})
        out.append("The running service reads it after a reload: `%s`. Say go to reload." % f["reload"])
    elif f.get("reload") and not folder_nginx:
        out.append("No reload is offered: %s." % ("the service's own config test did not pass" if test_state == "failed"
                                                  else "the service's own config test could not run here" if test_state == "unrun"
                                                  else "the finding is still there"))
    f["fixed"] = ok
    turn.save()
    turn.last(kind="fix", edit=eid, file=p, rule=f["rule"])
    return _r(NL.join(out), "changed-checked" if ok else "failed", "fix", files=[env.rel(p)], edit=eid, check="passed" if ok else "failed")


# ---------------------------------------------------------------- tasks
def task_add(turn, text):
    env = turn.env
    ts = _load(_e(env, "tasks.json"), [])
    t = {"id": 1 + max([x["id"] for x in ts] or [0]), "text": " ".join(text.split())[:300], "t": time.time()}
    ts.append(t)
    _save(_e(env, "tasks.json"), ts)
    return _r("Task %d: %s" % (t["id"], t["text"]), "done", "task")


def tasks(turn, close=None):
    env = turn.env
    ts = _load(_e(env, "tasks.json"), [])
    if close is not None:
        for t in ts:
            if t["id"] == close:
                t["done"] = time.time()
                _save(_e(env, "tasks.json"), ts)
                return _r("Task %d closed: %s" % (close, t["text"]), "done", "task:done")
        return _r("There is no task %d." % close, "missing", "task:done")
    op = [t for t in ts if not t.get("done")]
    return _r(NL.join("%d. %s  (%s ago)" % (t["id"], t["text"], _ago(t["t"])) for t in op) if op else "No open tasks.", "read", "tasks")


# ---------------------------------------------------------------- go
def _delivered_seq(sid):
    """how many turns of this conversation have left by the one exit (reflect's record); 0 where none is kept"""
    try:
        import reflect as _rf
        return int(_rf.load(sid).get("seq") or 0)
    except Exception:  # noqa: BLE001
        return 0


def _same_offer(o):
    """what a row offers, apart from when and to whom: two rows with the same key are one offer made again"""
    return json.dumps([o.get(k) for k in ("kind", "cmd", "name", "n", "rule", "file", "function", "param", "sent", "dir")],
                      default=str)


def _lapsed(o, offers):
    """12.5 step 7, revised after q45 (held register, first row kind): an offer lapses once a later turn has offered
    something else; reads, status and permission turns between the offer and the go leave it standing (frozen G4/T7/I2)"""
    borns = [int(x["born"]) for x in offers if x.get("born") is not None]
    return o.get("born") is not None and bool(borns) and int(o["born"]) < max(borns)


def go(turn, which):
    offers = [o for o in turn.s.get("offers", []) if o.get("env") == turn.s.get("env")]
    if not offers:
        return None
    held = []
    if which is None:                                # a bare go binds only what the latest offering turn offered
        live = [o for o in offers if not _lapsed(o, offers)]
        held = [o for o in offers if _lapsed(o, offers)]
        offers = live or offers
    if which is None and len(offers) > 1:
        return _r("More than one thing is waiting:" + NL + NL.join("- go %d: %s" % (i + 1, _offer_text(o)) for i, o in enumerate(offers)),
                  "waiting", "go:which")
    i = (which or 1) - 1
    if not (0 <= i < len(offers)):
        return _r("There is no go %d." % (i + 1), "missing", "go")
    o = offers[i]
    if o.get("file") and o.get("file_sha"):          # 12.5 step 8 (held register): a go binds only what is as it was offered
        try:
            now_sha = hashlib.sha256((turn.env.read(o["file"]) or "").encode("utf-8", "replace")).hexdigest()
        except Exception:  # noqa: BLE001
            now_sha = None
        if now_sha != o["file_sha"]:
            turn.s["offers"] = [x for x in turn.s["offers"] if x is not o and x != o]
            turn.save()
            return _r("Not done: %s changed after I offered this (%s), so what was offered no longer applies. Ask again and I "
                      "prepare it on the file as it is now." % (turn.env.rel(o["file"]), _offer_text(o)), "refused",
                      "go:stale", started=False)
    if o.get("verdict") not in (None, "passed"):     # 12.5 step 8: a change offer stands only on a passing test
        turn.s["offers"] = [x for x in turn.s["offers"] if x is not o and x != o]
        turn.save()
        return _r("Not done: %s rests on a check that did not pass (%s)." % (_offer_text(o), o["verdict"]), "refused",
                  "go:verdict", started=False)
    turn.s["offers"] = [x for x in turn.s["offers"] if x is not o and x != o]
    turn.save()
    r = _go_one(turn, o)
    if held and isinstance(r, dict):                 # an older offer the bare go did not carry out is named, kept, not run
        alln = [x for x in turn.s.get("offers", []) if x.get("env") == turn.s.get("env")]
        r["response"] = str(r.get("response", "")) + NL + NL + "Not carried out (offered before your last offer, still waiting):" + NL +             NL.join("- go %d: %s" % (alln.index(x) + 1, _offer_text(x)) for x in held if x in alln)
    return r


def _go_one(turn, o):
    k = o["kind"]
    if k == "run":
        n = _load(_e(turn.env, "names.json"), {}).get(o["name"])
        return run_cmd(turn, n["cmd"], o["name"]) if n else None
    if k == "cmd":
        return run_cmd(turn, o["cmd"], o.get("name"), confirmed=True)
    if k == "fix":
        return fix_finding(turn, o["n"])
    if k == "repair_value":
        turn.offer(o)
        return _r("Say what %s() should give for an empty %s (for example: return 0, return None, raise ValueError)." % (
            o["function"], o["param"]), "waiting", "go:value")
    if k == "resolved":                              # the reading the operator accepted, carried out as its own sentence
        r = handle(o["sent"], turn.sid)
        if r:
            r["path"] = str(r.get("path", "")) + ">resolved:" + o.get("op", "")
            ex_ = r.get("execution") if isinstance(r.get("execution"), dict) else {}
            carried = (r.get("status") not in ("hole", "declined", "error") and ex_.get("started", True) is not False
                       and ex_.get("state") not in ("failed", "refused", "blocked", "missing", "interrupted"))
            if o.get("text") and carried:            # C29 (receive): the confirmed wording is kept; next time it is sure
                                                     # 12.5 step 8: never from a go that was refused or not carried out
                try:
                    import resolve as _rv
                    if _rv.learn(o["text"], o.get("op"), turn.env):
                        r["response"] = str(r.get("response", "")) + "%s(I keep that `%s` means %s; next time I do it at once%s.)" % (
                            NL + NL, o["text"][:80], o.get("op"), "" if o.get("op") in ("read", "ls", "grep", "diff", "log", "status", "tasks", "audit")
                            else ", after you say go")
                except Exception:  # noqa: BLE001
                    pass
            return r
        return _r("`%s` did not carry out here." % o["sent"], "missing", "resolved:go", started=False)
    if k == "selfdev_build":
        import selfdev
        return selfdev.build(turn, o)
    if k == "selfdev_adopt":
        import selfdev
        return selfdev.adopt(turn, o.get("dir"))
    return None


# ---------------------------------------------------------------- the door
_POL = r"^\s*(?:ok(?:ay)?[\s,]*|now\s+|please\s+|can you\s+|could you\s+|lets\s+|let's\s+)*"
_GO = re.compile(r"(?i)^\s*(?:ok(?:ay)?[\s,]*)?(?:yes|yep|yeah|go|go ahead|do it|run it|sure|proceed|lets do (?:it|that)|let's do (?:it|that))(?:\s+(\d))?\s*[.!]*\s*$")
_CANCEL = re.compile(r"(?i)^\s*(?:cancel|no|don't|do not|never ?mind|stop that)\b[\s.!]*(?:that|it)?\s*[.!]*$")
_OPEN = re.compile(r"(?i)" + _POL + r"(?:open|work (?:on|in)|switch to|cd|go to|project)\s+(?:the\s+)?(?:project\s+|folder\s+)?(\S.*?)(\s*,?\s*read[- ]only)?\s*$")
_HOST = re.compile(r"(?i)" + _POL + r"(?:connect to|ssh (?:to|into)|log ?in to|work on (?:the )?host|open (?:the )?host)\s+([\w.-]+(?::/\S*)?)(\s*,?\s*read[- ]only)?\s*$")
_ALLOW = re.compile(r"(?i)^\s*(?:(?:you may|you can|allow(?: you to)?)\s+(?:make )?changes?(?: here| on it| there)?|allow changes|"
                    r"you may change (?:it|this|files)|changes? (?:are )?allowed)\s*[.!]*$")
_RO = re.compile(r"(?i)^\s*(?:read[- ]only|only read|no changes|don't change anything)\s*[.!]*$")
_LS = re.compile(r"(?i)" + _POL + r"(?:ls|list(?: the)?(?: files)?(?: in)?|what(?:'s| is) in)\s*([\w./~-]*)\s*\??\s*$")
_FILES = re.compile(r"(?i)" + _POL + r"(?:find )?files? (?:named|called|like)\s+(.+?)\s*\??$")
_READ = re.compile(r"(?i)" + _POL + r"(?:read|show(?: me)?|open|cat|view|print)\s+(?:the\s+)?(?:file\s+)?([\w./~-]+\.\w{1,8}(?:\s+(?:lines?|from line)\s+\d+\s*(?:-|to|\.\.)?\s*\d*)?)\s*\??$")
_GREP = re.compile(r"(?is)" + _POL + r"(?:grep|search(?: the (?:code|project))? for|where(?: in the (?:code|project))? (?:is|are|do we use))\s+(.+?)(?:\s+in\s+([\w./~-]+))?\s*\??$")
_RUNQ = re.compile(r"(?is)" + _POL + r"(?:run|execute|start|launch)\s*:?\s*(?:```\w*\n(.+?)\n?```|`([^`]+)`)\s*\.?$")
_STOPAPP = re.compile(r"(?i)" + _POL + r"(?:stop|cancel)\s+(?:(?:the\s+)?(?:app|application|program)(?:\s+here)?|job\s+(\d+))\s*[.!?]*$")
_RUNN = re.compile(r"(?i)" + _POL + r"(?:run|rerun|start|launch|kick off|do)\s+(?:the\s+)?([\w -]{2,40}?)\s*(?:again|now)?\s*[.!]?$")
_AGAIN = re.compile(r"(?i)" + _POL + r"(?:run (?:it|that) again|rerun(?: it| that)?|try (?:it|that) again|again)\s*[.!]?$")
_CALL = re.compile(r"(?is)" + _POL + r"(?:call|name|save)\s+`([^`]+)`\s+(?:as\s+)?(?:the\s+)?([\w -]{2,30}?)(\s*,?\s*alone|\s*,?\s*one at a time)?\s*\.?$")
_RULE = re.compile(r"(?i)^\s*(?:the\s+)?([\w -]{2,30}?)\s+passes\s+(?:when|if)\s+(?:it|the output)\s+says\s+[\"'`](.+?)[\"'`]\s*\.?$")
_STATUS = re.compile(r"(?i)^\s*(?:ok(?:ay)?[\s,]*|so\s+)*(?:where are we(?: at| now)?|status|project|what(?:'s| is) running|"
                     r"is it (?:done|finished|ready)|did it (?:finish)|how(?:'s| is) (?:it|the \w+) going|"
                     r"is the \w+ (?:done|finished)|what(?:'s| is) the status)\s*[?.!]*\s*$")
_SOLVED = re.compile(r"(?i)^\s*(?:did (?:that|it|this) (?:solve|fix|work)(?: it)?|did it pass|is it fixed|does it work now)\s*\??\s*$")
_LOG = re.compile(r"(?i)\b(?:what failed|why did it fail|what went wrong|show (?:me )?the (?:log|output|failures?|results?)|"
                  r"log of|output of)\b")
_DIFF = re.compile(r"(?i)^\s*(?:diff|show (?:me )?the diff|what did (?:we|you|i) change|what(?:'s| has| have we)? changed)\s*\??\s*$")
_TASKS = re.compile(r"(?i)^\s*(?:tasks|todo|to do|task list|todo list|what(?:'s| is) left(?: to do)?|open tasks)\s*\??\s*$")
_DONE = re.compile(r"(?i)^\s*(?:done|close task|finished task|task)\s+#?(\d+)(?:\s+(?:is\s+)?done)?\s*\.?$")
_TODO = re.compile(r"(?i)^\s*(?:todo|to do|add a task|note a task)\s*:?\s+(\S.*)$")
_AUDIT = re.compile(r"(?i)\b(?:audit|harden|security|secure|vulnerab\w*|check|inspect|investigate|look at|review)\b.*\b(?:ssh|sshd|nginx|"
                    r"ports?|logs?|server|host|config(?:uration)?|security|login)\b")
_FIX = re.compile(r"(?i)^\s*(?:fix|apply|correct)\s+(?:finding\s+)?#?(\d+)\s*\.?$")
_CHANGE = re.compile(r"(?i)\b(?:fix|correct|repair|should|instead|handle|wrong|broken|bug|doesn't|does not|isn't|is not|"
                     r"subtracts|adds|multiplies|divides|crash(?:es)?|fails?)\b")
# a request to make or change something: never answered early as a reading of the folder
_MAKING = re.compile(r"(?i)\b(?:write|make|add|build|create|implement|compose|generate|fix|repair|correct|change|replace|"
                     r"rename|remove|delete|so that|passes)\b")


_OURS = re.compile(r"(?i)\b(?:we|us|our|ours)\b|\b(?:the|this|our)\s+(?:project|work|build|job|task)\b")
_ASKS = re.compile(r"(?i)\?\s*$|^\s*(?:(?:so|and|ok(?:ay)?|hey|well)[\s,]+)*(?:how|where|what|are|is|have|has|did|do|when)\b")


def ours_question(turn, t):
    """12.0 C29 (Ben: hold the meanings of current projects): is this a question about the work this conversation holds
    ("how far along are we?", "are we nearly there?", "how is our project coming along?")? Only a question that speaks of
    the shared work, while a project, work or job is held here; never one that names a file or a function, asks to make
    something, or has a sure reading of its own ("what files do we have?" stays ls)."""
    env = turn.env
    if env is None or not _ASKS.search(t) or not _OURS.search(t) or _MAKING.search(t):
        return False
    pj, wk = turn.s.get("project"), turn.s.get("work")
    held = (pj and pj.get("env") in (None, env.key)) or (wk and wk.get("env") == env.key) or bool(_jobs(env))
    if not held:
        return False
    try:                                               # the project's own record answer keeps the questions it words
        import language_bridge as _lb
        if pj and pj.get("env") in (None, env.key) and _lb.project_answer(t, pj):
            return False
    except Exception:  # noqa: BLE001
        pass
    try:
        import resolve as _rv
        b = _rv.bind(t, env)
        if b.get("file") or b.get("function"):
            return False
        sent, _name, _changes, sure = _rv.resolve(t, env, near_ok=False)
        if sent and sure:
            return False                               # its own sure reading wins (ls, diff, tasks, ...)
    except Exception:  # noqa: BLE001
        pass
    return True


def _about_our_work(turn, t):
    """the question about our work, answered from that work's own record (the status of what is held here)"""
    if not ours_question(turn, t):
        return None
    r = status(turn)
    if r:
        r["response"] = "(I read that as a question about the work we hold here; from its record:)%s%s" % (NL, r.get("response", ""))
        r["path"] = str(r.get("path", "")) + ">ours"
    return r


def _resolved(turn, sid, t, sure_only, read_only=False):
    try:
        import resolve as _rv
        if _rv.negated(t):                             # 12.5 C34: told not to; the operation it names is not done
            pos = re.sub(r"(?i)\b(?:please\s+)?(?:do\s+not|don'?t|dont|never|not|no\s+need\s+to)\s+", "", t, count=1)
            s0, n0, _c0, _s0 = _rv.resolve(pos, turn.env, near_ok=True) if pos != t else (None, None, None, None)
            if s0:
                return _r("Understood: I will not do that (`%s`). Nothing was run, read or changed." % s0, "done",
                          "resolved:declined:" + n0, started=False)
            return None
        sent, name, changes, sure = _rv.resolve(t, turn.env, near_ok=not sure_only)
    except Exception:  # noqa: BLE001
        return None
    if not sent or (sure_only and not sure) or sent.strip().lower() == t.strip().lower():
        return None
    if read_only and changes:
        return None
    if not changes and _MAKING.search(t):              # 12.0 C28b: a request to make something is never read as a reading
        return None
    if sure and not changes:
        r = handle(sent, sid)
        if r:
            r["response"] = "(I read that as: `%s`)%s%s" % (sent, NL, r.get("response", ""))
            r["path"] = str(r.get("path", "")) + ">resolved:" + name
            return r
        return None
    turn.offer({"kind": "resolved", "sent": sent, "op": name, "text": t})
    return _r("I read that as `%s`%s. Say go, or say it another way." % (
        sent, "" if sure else " (my nearest reading, not a sure one)"), "waiting", "resolved:offer:" + name, reading=sent)


def work_turn(turn, text, reading=None):
    """Compose general work in the same environment and authority as other bench parts."""
    import work_tasks as work
    import work_bindings as bindings
    import interactive_program as programs
    env = turn.env
    if env is None or env.kind != "folder":
        return None
    if _READ.match(text) or _LS.match(text) or _FILES.match(text) or _GREP.match(text):
        return None                                  # the bench's own explicit command, whole: read, ls, files, grep
    kept = turn.s.get("work")
    if kept and kept.get("env") != env.key:
        kept = None
    explicit_work = bool(re.fullmatch(r"(?i)\s*(?:continue|resume)\s+(?:the\s+)?work[.!]?\s*", text))
    if turn.s.get("focus") != "work" and not explicit_work:
        # The mirror of project_turn's rule: while the folder's table project
        # is the subject, its fills, additions, drops and revisions are its own
        # ("also save each loan with its fee ... to fees.csv: 1 -> 3, ...").
        import project as PJ
        import language_bridge as _language
        project = turn.s.get("project")
        if project and project.get("env") in (None, env.key) and not _language.asks_about(text) and PJ.is_project(text, project):
            return None
    if turn.s.get("focus") not in (None, "work") and not explicit_work:
        kept = None
    if kept is None and (explicit_work or turn.s.get("focus") in (None, "work") and
                         re.fullmatch(r"(?i)\s*(?:continue|resume)[.!]?\s*", text)):
        kept = work.load(env.root)
    if kept is None and work.repair_owns(text, reading):
        return None                              # a correction plus its check is repair's turn (repair runs the check)
    if re.search(r"(?i)\b(?:in)?to\s+(?:yourself|oracle7)\b|^\s*(?:please\s+)?(?:build|add|make|give)\s+(?:yourself|oracle7)\s*[:,-]", text):
        return None                              # a feature of Oracle7 itself: selfdev's project route (C10)
    program, program_error = None, None
    try:
        program = programs.request_contract(text, env.root, reading=reading)
    except programs.ProgramError as error:
        program_error = str(error)
    if not (program or program_error or work.accepts(text, env.root, kept=kept, reading=reading)
            or bindings.accepts(text, env.root, reading=reading)):
        return None
    read_status = work.is_status(text)
    if not _may_change(turn) and not read_status:
        return _r("This conversation may only read %s. Say \"allow changes\" to carry out the requested work." % env.label(),
                  "refused", "work:authority", started=False)
    received = text
    if program:
        received = json.dumps({"kind": "interactive_program", "args": program})
    elif program_error:
        received = json.dumps({"kind": "unbound", "args": {"error": program_error}})
    shape = work.receive(received, env.root, kept=kept, reading=reading)
    # one request, once its quoted examples are set aside: line breaks inside 'ab\ncd' join no clauses
    unquoted = re.sub(r"'[^']*'|\"[^\"]*\"|`[^`]*`", "''", text, flags=re.S)
    one_part = (len([s for s in shape.get("steps", []) if s.get("kind") != "check"]) == 1
                or not re.search(r"(?i)[;\n]|\bthen\b|\band\s+(?:run|check|test|fix|add|write|make)\b", unquoted))
    if (kept is None and not program and not program_error and not read_status and work._structured(text) is None
            and one_part):
        # One part's request (an edit, a file, a function from its examples or a
        # module from its tests) is that part's: it is tried first as itself, and
        # the work record takes over only when the part has nothing to give.
        for part in (edit, write, new_function, tests_goal):
            direct = part(turn, text)
            if direct is not None:
                return direct                        # done, or the part's own named hole with its reason
    if received != text:
        shape["turns"][-1]["text"] = text
        constraints = shape.setdefault("constraints", [])
        for constraint in (reading or {}).get("constraints", []):
            if not any(c.get("id") == constraint.get("id") and c.get("text") == constraint.get("text") for c in constraints):
                constraints.append(json.loads(json.dumps(constraint)))
        if not kept:
            shape["goal"] = text
        old_ids = {step["id"] for step in (kept or {}).get("steps", [])}
        for step in shape["steps"]:
            if step["id"] not in old_ids:
                step["request"] = text
        for requirement in shape["requirements"]:
            if requirement["id"] not in old_ids:
                requirement["text"] = text
    if not read_status:
        shape = bindings.bind(shape, env.root, reading=reading)
    shape["env"] = env.key
    if not shape.get("check"):
        shape["check"] = _check_cmd(env)

    def dispatch(step, goal):
        request = step.get("request") or step.get("text") or ""
        kind = step.get("kind")
        if step.get("binding_hole"):
            return {"state": "missing", "response": step["binding_hole"],
                    "hole": {"kind": "binding", "text": step["binding_hole"]}}
        if kind in bindings.REGISTRY:
            result = bindings.execute(kind, step.get("args") or {}, env.root, runenv=_guard_env(env))
            if result is not None:
                return result
        parts = {"edit": (edit,), "write": (write,), "compose": (new_function, tests_goal),
                 "repair": (repair_turn,), "project": (project_turn,), "interactive": (project_turn,),
                 "make": (new_function, tests_goal)}
        for part in parts.get(kind, ()):
            result = part(turn, request)
            if result is not None:
                return result
        return {"state": "missing", "response": "The %s part needs a concrete request it can receive." % kind,
                "hole": {"kind": "part", "text": "The %s part needs a concrete request it can receive." % kind},
                "holes": [{"kind": "part", "step": step.get("id"), "text": request}]}

    started_at = time.time()
    result = work.advance(shape, env.root, dispatch=dispatch, runenv=_guard_env(env), allowed_hosts=env.net_scope)
    # every change the work made goes into the conversation's one edit journal: "what changed" and "undo" see it
    try:
        for step in (result.get("shape") or {}).get("steps", []):
            for attempt in step.get("attempts") or []:
                if float(attempt.get("at") or 0) < started_at:
                    continue
                for change in ((attempt.get("result") or {}).get("changes") or []):
                    path = Path(env.root) / change["file"]
                    before = change.get("before")
                    if isinstance(before, (bytes, bytearray)):
                        before = before.decode("utf-8", "replace")
                    now = env.read(str(path)) if path.is_file() else None     # read as undo reads it (same line endings)
                    if before is not None and now is not None and "\r\n" in now and "\r\n" not in before:
                        before = before.replace("\n", "\r\n")                   # the work reads with \n; the file keeps \r\n
                    live = [e for e in _load(_e(env, "edits.json"), []) if e["file"] == str(path) and not e.get("undone")]
                    if now is not None and now != before and not (live and live[-1].get("after") == _sha(now)):
                        _record_edit(turn, str(path), before, now, "work %s" % step.get("id"))   # once per resulting state
    except Exception:  # noqa: BLE001 - the journal never blocks the work's own record
        pass
    holes = result.get("holes") or []
    if (kept is None and not program and not program_error and holes and not result.get("files")
            and all(h.get("kind") == "part" for h in holes)):
        return None                                  # no part receives it: not work; nothing is kept, later receivers read it
    shape = result.get("shape", shape)
    shape["env"] = env.key
    turn.s["work"] = shape
    turn.s["focus"] = "work"
    turn.save()
    if not read_status:
        work.save(env.root, shape)
    response = result.get("response") or "The work record is updated."
    if result.get("files"):
        response += NL + "Files: " + ", ".join("`%s`" % name for name in result["files"]) + "."
    for step in shape.get("steps", []):
        if (step.get("kind") == "interactive_program" or step.get('kind') == 'described_program' and
                shape.get('build_intent', {}).get('mode') == 'interactive') and step.get("state") == "done" and step.get("attempts"):
            built = step["attempts"][-1]["result"].get("value") or {}
            filename = built.get("file")
            if filename and filename in result.get("files", []):
                argument = ('"' + filename + '"') if os.name == "nt" else shlex.quote(filename)
                response += NL + "To open this app, say: run `python %s 8000`. Then open http://127.0.0.1:8000/. Say stop app when finished." % argument
    return _r(response, result.get("state", "missing"), "work",
              files=result.get("files", []), checks=result.get("checks", []), holes=result.get("holes", []),
              requirements=shape.get("requirements", []), work_id=shape.get("id"), steps=shape.get("steps", []))


def handle(text, sid="default", reading=None):
    t = (text or "").strip()
    if not t:
        return None
    turn = Turn(sid)
    turn.reading = reading
    try:
        try:                                         # C11: a capability I built into myself and adopted, by its own words
            import continuation as CT
            rc = CT.capability_turn(t, sid)
            if rc:
                return rc
        except Exception:  # noqa: BLE001
            pass
        m = _HOST.match(t)
        if m:
            return open_env(turn, m.group(1), host=True, readonly=bool(m.group(2)))
        m = _OPEN.match(t)
        if m and os.path.isdir(os.path.expanduser(m.group(1).strip().strip("`'\""))):
            return open_env(turn, m.group(1), readonly=bool(m.group(2)))
        if turn.env is None:
            return None                              # no environment open in this conversation: the chat is unchanged
        try:                                         # a question about its own work or the thread is reflection's
            import reflect as _rf
            if _rf.claims(t, sid):
                return None
        except Exception:  # noqa: BLE001
            pass
        m = _GO.match(t)
        if m:
            return go(turn, int(m.group(1)) if m.group(1) else None)
        if _CANCEL.match(t) and turn.s.get("offers"):
            n = len(turn.s["offers"])
            turn.s["offers"] = []
            turn.save()
            return _r("Cancelled %d waiting action%s." % (n, "" if n == 1 else "s"), "done", "cancel")
        m = _NET.match(t)
        if m:
            return net_scope(turn, m.group(1))
        if _NONET.match(t):
            return net_scope(turn, None)
        if _ALLOW.match(t):
            return authority(turn, True)
        if _RO.match(t):
            return authority(turn, False)
        r = value_reply(turn, t)
        if r:
            return r
        m = re.match(r"(?i)^\s*(?:please\s+)?roll\s*back\s+(?:the\s+)?(?:capability\s+)?([\w-]+)\s*\.?$", t)
        if m:
            import selfdev
            return selfdev.rollback(turn, m.group(1))
        if turn.s.get("focus") == "self":            # C11: a candidate of myself left with holes takes this turn's words
            import selfdev
            import project as PJ
            cd = selfdev.open_candidate(turn)
            if cd is not None and PJ.is_project(t, dict(PJ.load_project(cd) or {}, status="blocked")):
                return selfdev.self_project(turn, t, cont=cd)
        m = _RUNQ.match(t)
        if m:
            return run_cmd(turn, (m.group(1) or m.group(2)).strip())
        m = _STOPAPP.match(t)
        if m:
            return stop_job(turn, int(m.group(1)) if m.group(1) else None)
        kept_work = turn.s.get("work")
        ours = _about_our_work(turn, t)
        if ours:
            return ours
        if turn.s.get("focus") not in ("project", "self") and not _MAKING.search(t) and not (
                kept_work and kept_work.get("env") == getattr(turn.env, "key", None)
                and kept_work.get("state") not in ("done", "cancelled")):
            # A sure, read-only reading of this environment ("let me look at calc.py",
            # "what's in this folder") is that reading, done at once - not a work plan.
            rs = _resolved(turn, sid, t, sure_only=True, read_only=True)
            if rs:
                return rs
        try:
            r = work_turn(turn, t, reading=reading)
        except ImportError as e:
            if e.name != "work_tasks":
                raise
            r = None
        if r:
            return r
        for f in (project_turn, edit, write, new_function, tests_goal):
            r = f(turn, t)
            if r:
                return r
        if re.match(r"(?i)^\s*undo\b", t):
            return undo(turn)
        if _DIFF.match(t):
            return changed(turn)
        m = _DONE.match(t)
        if m:
            return tasks(turn, int(m.group(1)))
        if _TASKS.match(t):
            return tasks(turn)
        m = _TODO.match(t)
        if m:
            return task_add(turn, m.group(1))
        m = _CALL.match(t)
        if m:
            return name_cmd(turn, m.group(1).strip(), m.group(2).strip().lower(), bool(m.group(3)))
        m = _RULE.match(t)
        if m:
            return name_rule(turn, m.group(1).strip().lower(), m.group(2))
        m = _RUNQ.match(t)
        if m:
            return run_cmd(turn, (m.group(1) or m.group(2)).strip())
        if _AGAIN.match(t):
            last = turn.last()
            lj = next((j for j in _jobs(turn.env) if j["id"] == last.get("job")), None) if last.get("job") else None
            if lj and lj["state"] == "interrupted":
                return interrupted_check(turn, lj)
            if last.get("cmd"):
                return run_cmd(turn, last["cmd"], last.get("name"))
            chk = _check_name(turn.env)
            if chk:
                return run_cmd(turn, _load(_e(turn.env, "names.json"), {})[chk]["cmd"], chk)
        m = _RUNN.match(t)
        if m:
            names = _load(_e(turn.env, "names.json"), {})
            nm = m.group(1).strip().lower()
            if nm in names:
                return run_cmd(turn, names[nm]["cmd"], nm)
            if nm in ("tests", "test", "the tests"):
                import repair as R
                cmd = R.test_command(turn.env.root) if turn.env.kind == "folder" else None
                if cmd:
                    return run_cmd(turn, cmd, None)
        if _SOLVED.match(t):
            return solved(turn)
        if _LOG.search(t):
            return log_of(turn, t)
        if _STATUS.match(t):
            return status(turn)
        m = re.match(r"(?i)^\s*(?:please\s+)?(?:build|add|make|give)\s+(?:in)?to\s+(?:yourself|oracle7)\s*[:,-]?\s*(.+)$|"
                     r"^\s*(?:please\s+)?(?:build|add|make|give)\s+(?:yourself|oracle7)\s*[:,-]\s*(.+)$", t)
        if m:                                       # a feature of Oracle7 itself, as a project over its own records (C10)
            import selfdev
            return selfdev.self_project(turn, (m.group(1) or m.group(2)).strip())
        if re.match(r"(?i)^\s*(?:please\s+)?(?:propose|suggest|make)\s+(?:an?\s+)?(?:improvement|change|fix)\s+(?:to|for|of)\s+"
                    r"(?:yourself|your own code|you|oracle7)\b|^\s*(?:how could you|can you)\s+improve (?:yourself|your own code)\b|"
                    r"^\s*improve yourself\b", t):
            import selfdev
            import reflect as _rf2
            return selfdev.propose(turn, _rf2.load(sid)["ledger"])
        if re.match(r"(?i)^\s*(?:ok(?:ay)?[\s,]*)?adopt (?:it|the candidate|that|candidate)\b", t):
            import selfdev
            return selfdev.adopt(turn)
        m = _FIX.match(t)
        if m and turn.s.get("findings"):
            return fix_finding(turn, int(m.group(1)))
        m = _LS.match(t)
        if m:
            r = ls(turn, m.group(1))
            if r:
                return r
        m = _FILES.match(t)
        if m:
            return files_named(turn, m.group(1))
        m = _READ.match(t)
        if m:
            r = read(turn, m.group(1))
            if r:
                return r
        m = _GREP.match(t)
        if m:
            return grep(turn, m.group(1), m.group(2))
        if _AUDIT.search(t):
            if turn.env.kind == "host" or re.search(r"(?i)\b(ssh|sshd|nginx|ports?|auth\.log|server|security|harden)\b", t):
                return audit(turn, t)
        # Amendment 16: a request in another wording, read by Oracle7's own word meanings (resolve.py). Sure and only reading:
        # done, saying how it was read. Changing or running anything, or not sure: offered, done only on go.
        rs = _resolved(turn, sid, t, sure_only=True)
        if rs:
            return rs
        belief = False
        if reading and reading.get("available") and reading.get("intent") not in ("request", "commitment"):
            acting = any(c.get("kind") == "outcome" for c in reading.get("clauses", ()))
            code_reference = any(item.get("kind") in ("code", "file") for item in reading.get("literals", ()))
            code_reference = code_reference or bool(re.search(r"(?i)\b(?:function|method|module|codebase|repository|repo|traceback|exception|unit test)\b", t))
            belief = not acting and not code_reference   # a conversational belief is not a proposed repository repair
        if not belief and _CHANGE.search(t) and turn.env.kind == "folder" and not t.rstrip().endswith("?"):
            return repair_turn(turn, t)
        rs = _resolved(turn, sid, t, sure_only=False)
        if rs:
            return rs
    except Exception as e:  # noqa: BLE001
        return _r("That did not complete: %s" % repr(e)[:300], "failed", "error", started=False)
    return None