File size: 142,659 Bytes
d9b105f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""project - a project received as a ledger of requirements, planned over shapes, written from parts, judged by what it

does, and continued from wherever it stopped (12.0 C9, C10; the review: "receive a request as explicit outputs,

constraints, dependencies and completion conditions"; the followup: "account for every requirement").



  receive   each turn's words join the project's clauses. A sentence is read into requirements: OUTCOMES someone can

            observe (a file written, rows kept in a database, a page served, lines printed), PROPERTIES of them (a timeout,

            an error counted as down, the time to answer, how many results are shown) and OPERATIONS on the rows (group,

            total, count, average, largest, smallest, keep only, sort, the first n, a value made from a column). Every

            word of a sentence must be owned: by a part's vocabulary, a column of the project's tables, a file, the

            project's own name or the words every sentence has. A word nobody owns is a HOLE (what does it mean?), never

            dropped: a requirement that is only kept as text is not a requirement.

  world     the tables the request names (csv, json), read afresh at every plan: their columns, which holds urls, which

            holds names. A file not there yet is a hole until it is.

  parts     declared contracts over shapes: table (file -> rows), probe (rows with urls -> results), compute (rows ->

            rows: the operations), keep (rows -> stored), latest (stored -> latest), export (rows -> a file), page

            (rows -> page), serve (page -> served), print (rows -> lines). A value made from a column is a part found in

            Oracle7's code store (the functions it composed and kept, lit on the Tree of Life spine by the words and the

            shape) or composed by the code composer from examples the next turn gives; either way it carries its sha.

  plan      for each entry (named in the request as `python3 m.py sub ARGS`, or proposed when the request names none):

            backward from its outcomes to a source (the table, the servers probed, or what another entry kept), the

            operations its words ask for in between. Every requirement is tied to the links that supply it.

  write     the parts' code in plan order, one module, entries dispatched by name.

  judge     every requirement against what happened: each entry run as named, rows read back from its database, files

            read back and compared with the rows an independent reading of the request gives, the page fetched from it

            running, the lines printed. A project is done only when every requirement has passed its judge.

  continue  a project that stops at a hole is kept as it is (in the conversation and in the project's .oracle7 folder):

            the next turn's example, file, explanation or "drop" fills the hole and the build goes on from there, after a

            restart too.

No language model."""
import csv
import hashlib
import json
import os
import re
import socket
import sqlite3
import subprocess
import sys
import time
from html import unescape as html_unescape
import urllib.request
from pathlib import Path
import project_sources as PS
import project_interactive as PI

ENTRY = re.compile(r"`\s*(?:python3?\s+)?([\w./-]+\.py)\s+([a-z][\w-]*)((?:\s+[A-Z_]+)*)\s*`")
URLV = re.compile(r"^https?://", re.I)
DATA = re.compile(r"\b([\w./-]+\.(?:csv|jsonl|json))\b")
BUILD = re.compile(r"(?i)\b(?:build|make|create|write|set up|put together|develop)\b")
SINK_FILE = re.compile(r"(?i)\b(?:save|saves|saved|saving|write|writes|written|export|exports|exported|output|outputs|put|puts|"
                       r"store|stores|dump|dumps)\b(?:(?!\.\s)[^;]){0,140}?\b(?:to|into|in|as)\s+(?:a\s+file\s+(?:called|named)\s+)?"
                       r"`?([\w./-]+\.(csv|json|txt|html))\b")
SINK_TO = re.compile(SINK_FILE.pattern.replace(r"(?:to|into|in|as)", r"(?:to|into|as)"))
SINK_IN = re.compile(SINK_FILE.pattern.replace("{0,140}?", "{0,140}"))   # greedy: the last 'in <file>' of the sentence
# 12.0 C28: the written file as the verb's own object ("write top.csv with the rows ...", "save a summary.json of ...")
SINK_OBJ = re.compile(r"(?i)\b(?:save|saves|write|writes|export|exports|output|outputs|produce|produces)\s+(?:a\s+|an\s+|the\s+)?"
                      r"(?:file\s+)?`?([\w./-]+\.(csv|json|txt|html))\b")


def sinks(s):
    """the files a sentence writes: 'to / into / as <file>' names where rows go; 'in <file>' does only when the sentence has

    no such target ('save the items in stock.csv ... to low.csv' reads stock.csv and writes low.csv); with neither, the file

    the verb writes as its own object ('write top.csv with ...')"""
    return list(SINK_TO.finditer(s)) or list(SINK_IN.finditer(s)) or list(SINK_OBJ.finditer(s))


STORED = re.compile(r"(?i)\b(?:database|sqlite|db)\b")
REVISE = re.compile(r"(?i)\b(?:change|changed|update|revise|instead|rather|make it|now)\b")
# the words just before an outcome that rule it out (up to three words between: "do not export the rows", "without a db")
NEGATED = re.compile(r"\b(?:do\s+not|does\s+not|don'?t|doesn'?t|never|without|no|not)\s+(?:[a-z]+\s+){0,3}$")
SERVED = re.compile(r"(?i)\b(?:browser|web ?page|webpage|website|serves?|served|on (?:a|the) page|(?:a|the) page)\b")
PRINTED = re.compile(r"(?i)\b(?:prints?|printed|terminal|console)\b")

# ---------------------------------------------------------------- the words every sentence has, and each part's own
GENERAL = set("""a an the and or but of to in on at by for from with without into onto as is are was were be been being it its

this that these those each every all any some my our your their his her them they we i me you he she one once two three

four five six seven eight nine ten both other others another than then so such not no do does did done has have had will

would should could can may might must shall also again just only very more most less much many same new old here there

when where which who whom whose what why how up out over under after before while until about per via if else whether

please want need like let able use using called named way ways get gets got go goes going thing things there's it's

want wants make makes made build builds built create creates created write writes written set put together project

program script tool app application run runs command commands file files folder data instead too still yet sure ok okay

now first next last later always never ever own change changes changed update updates updated revise revised rather

don't dont doesn't actually just really well oh hmm hey thanks thank""".split())
VOCAB = {
    "table": "table tables list lists listed listing row rows record records entry entries column columns sheet spreadsheet "
             "csv json inventory item items",
    "probe": "query queries queried check checks checked checking ping pings request requests fetch fetches fetched health "
             "url urls endpoint endpoints answer answers answered respond responds response reach reachable up down status "
             "statuses server servers service services site sites host hosts monitor monitors monitoring",
    "keep": "keep keeps kept store stores stored storing save saves saved record records recorded log logs logged database "
            "sqlite local timestamp timestamps timestamped time times losing lose lost result results history",
    "timeout": "within second seconds sec secs timeout slow silent",
    "error": "error errors fail fails failed failure failures",
    "ms": "millisecond milliseconds ms long took take takes latency",
    "latest": "current previous latest recent newest",
    "page": "page pages browser show shows shown showing display displays displayed view web html dashboard webpage website",
    "serve": "serve serves served port",
    "export": "export exports exported save write output outputs dump csv json file",
    "print": "print prints printed terminal console screen output",
    "ops": "group grouped groups grouping total totals sum sums summed add adds count counts counted number average averages "
           "averaged mean largest biggest highest most maximum max smallest lowest least minimum min sort sorted order "
           "ordered descending ascending top bottom where filter filtered over above under below greater than equal equals "
           "summary summaries summarize summarise report reports breakdown amount amounts across overall value values",
    "derive": "convert converted converts column columns",
    "design": "look looks feel feels style styled colour colours color colors font fonts typography palette theme dark light "
              "mode designed design editorial literary classic formal elegant luxurious quiet calm traditional scholarly warm "
              "friendly modern clean minimal technical precise scientific industrial neutral bold playful expressive dramatic "
              "accent accents",
}
PART_WORDS = {k: set(v.split()) for k, v in VOCAB.items()}
ALL_PART_WORDS = set().union(*PART_WORDS.values())


def stem(w):
    w = w.lower()
    if w.endswith("'s"):
        w = w[:-2]
    for suf in ("ies",):
        if len(w) > 4 and w.endswith(suf):
            return w[:-3] + "y"
    for suf in ("ing", "ed"):
        if len(w) > 4 and w.endswith(suf):
            return w[: -len(suf)]
    # C12b: "es" is a plural ending only after s, x, z, ch, sh ("boxes", "churches"); after another letter the e is the
    # word's own ("cubes" -> cube, "tubes" -> tube, not cub, tub)
    if len(w) > 4 and w.endswith("es") and re.search(r"(?:s|x|z|ch|sh)es$", w):
        return w[:-2]
    if len(w) > 3 and w.endswith("s") and not w.endswith(("ss", "us", "is")):
        return w[:-1]
    return w


def wmatch(a, b):
    a, b = stem(a), stem(b)
    return a == b or (len(a) >= 4 and len(b) >= 4 and (a.startswith(b) or b.startswith(a)))


def _owned(w, owners):
    return any(wmatch(w, o) for o in owners)


# ---------------------------------------------------------------- the world
def read_table(root, name):
    """a table of the project: its columns, the rows' values, which column holds urls and which the names"""
    p = Path(root) / name
    if not p.is_file():
        return {"file": name, "missing": True}
    try:
        if name.endswith(".jsonl"):
            rows = [json.loads(ln) for ln in p.read_text(encoding="utf-8").splitlines() if ln.strip()]
        elif name.endswith(".json"):
            rows = json.loads(p.read_text(encoding="utf-8"))
            if isinstance(rows, dict):
                rows = next((v for v in rows.values() if isinstance(v, list)), [rows])
        else:
            rows = list(csv.DictReader(p.read_text(encoding="utf-8").splitlines()))
    except (ValueError, OSError) as e:
        return {"file": name, "unreadable": str(e)[:120]}
    rows = [r for r in rows if isinstance(r, dict)]
    cols = list(rows[0].keys()) if rows else []
    url = next((c for c in cols if rows and all(URLV.match(str(r.get(c, ""))) for r in rows)), None)
    key = next((c for c in cols if c != url and rows and len({str(r[c]) for r in rows}) == len(rows)
                and not all(_isnum(r[c]) for r in rows)), None) or \
        next((c for c in cols if c != url and rows and len({str(r[c]) for r in rows}) == len(rows)), None)
    numeric = [c for c in cols if rows and all(_isnum(r.get(c)) for r in rows)]
    return {"file": name, "cols": cols, "url": url, "key": key, "n": len(rows), "numeric": numeric,
            "hosts": sorted({re.sub(r"^https?://([^/:]+).*$", r"\1", str(r[url])) for r in rows}) if url else [],
            "sample": {c: rows[0].get(c) for c in cols} if rows else {}}


def _isnum(v):
    if isinstance(v, bool):
        return False
    if isinstance(v, (int, float)):
        return True
    try:
        float(str(v).strip())
        return True
    except (TypeError, ValueError):
        return False


def num(v):
    if isinstance(v, (int, float)) and not isinstance(v, bool):
        return v
    s = str(v).strip()
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return v


def load_rows(root, name):
    p = Path(root) / name
    if name.endswith(".jsonl"):
        return [json.loads(ln) for ln in p.read_text(encoding="utf-8").splitlines() if ln.strip()]
    if name.endswith(".json"):
        rows = json.loads(p.read_text(encoding="utf-8"))
        if isinstance(rows, dict):
            rows = next((v for v in rows.values() if isinstance(v, list)), [rows])
        return [dict(r) for r in rows if isinstance(r, dict)]
    return list(csv.DictReader(p.read_text(encoding="utf-8").splitlines()))


# ---------------------------------------------------------------- receiving: the clauses, the fills
EXAMPLE = re.compile(r"(-?\d+(?:\.\d+)?|'[^']*'|\"[^\"]*\")\s*(?:->|=>|→|gives|becomes)\s*(-?\d+(?:\.\d+)?|'[^']*'|\"[^\"]*\")")
DROP = re.compile(r"(?i)^\s*(?:please\s+)?(?:drop|ignore|forget|leave out|skip)\s+(?:requirement\s+|r)?(\d+)\b")
DROP_WORD = re.compile(r"(?i)^\s*(?:please\s+)?(?:drop|ignore|forget|leave out|skip)\s+(?:the\s+(?:word\s+)?)?['\"`]?([a-z][\w-]*)['\"`]?\s*\.?$")
MEANS = re.compile(r"(?i)['\"`]?([a-z][\w-]*)['\"`]?\s+(?:means|is|meant)\s+(?:the\s+)?([\w\s-]{2,60}?)\s*\.?$")
CONTINUE = re.compile(r"(?i)^\s*(?:please\s+)?(?:continue|resume|go on|carry on|try again|retry|it'?s (?:there|in) now|"
                      r"(?:i\s+)?added (?:it|the file)|use it|keep going|finish (?:it|the project))\b")


def new_shape():
    return {"v": 2, "entries": {}, "module": None, "proposed": False, "clauses": [], "dropped": [], "meanings": {},
            "examples": {}, "derived": {}, "status": "new", "use": {}}


def receive(text, root, kept=None):
    """the project's shape after this turn's words. kept: the shape the conversation (or the project's folder) holds"""
    shape = json.loads(json.dumps(kept)) if kept else new_shape()
    if shape.get("v") != 2:                            # a shape kept by the first version: its clauses are read again
        old = shape
        shape = new_shape()
        shape["clauses"] = list(old.get("clauses") or [])
    t = " ".join(text.split())
    fill = False
    m = DROP.match(t)
    if m and kept:
        shape["dropped"].append("R%s" % m.group(1))
        fill = True
    m = DROP_WORD.match(t) if not fill else None
    if m and kept:
        shape["meanings"][m.group(1).lower()] = ""
        fill = True
    if not fill and kept:
        exs = EXAMPLE.findall(t)
        open_derive = [h for h in shape.get("holes_kept") or [] if h.get("kind") == "derive"]
        source_entries = {h.get("entry", "*") for h in shape.get("holes_kept") or [] if h.get("kind") == "source"}
        scope_holes = [h for h in shape.get("holes_kept") or [] if h.get("kind") == "scope"]
        named_entry = next((n for n in shape["entries"] if re.fullmatch(r"(?i)(?:the\s+)?`?" + re.escape(n) + r"`?(?:\s+command)?[.!]?", t)), None)
        entry_match = ENTRY.fullmatch(t)
        if entry_match and entry_match.group(1) == shape.get("module"):
            named_entry = entry_match.group(2)
        if len(scope_holes) == 1 and named_entry in scope_holes[0].get("entries", []):
            shape.setdefault("scope_fills", {})[str(scope_holes[0]["clause"])] = named_entry
            fill = True
        elif len(source_entries) == 1 and re.match(r"(?i)^\s*(?:match(?:ing|ed)?\s+(?:on|by)\s+|on\s+)[a-z_]", t):
            shape.setdefault("source_fills", {})[next(iter(source_entries))] = t
            fill = True
        elif exs and open_derive:
            h = open_derive[0]
            shape["examples"][h["fn"]] = shape["examples"].get(h["fn"], []) + [[_lit(a), _lit(b)] for a, b in exs]
            shape["example_words"] = (shape.get("example_words", "") + " " + EXAMPLE.sub(" ", t)).strip()
            fill = True
        elif re.search(r"(?i)\buse\s+(?:it|that|the kept one|[a-z_]+)\b", t) and \
                [h for h in shape.get("holes_kept") or [] if h.get("kind") == "derive" and h.get("offer")]:
            h = next(h for h in shape["holes_kept"] if h.get("kind") == "derive" and h.get("offer"))
            shape["use"][h["fn"]] = h["offer"]["sha256"]
            fill = True
        else:
            mm = MEANS.search(t)
            unread = {w for h in shape.get("holes_kept") or [] if h.get("kind") == "unread" for w in h.get("words", [])}
            if mm and mm.group(1).lower() in unread:
                shape["meanings"][mm.group(1).lower()] = mm.group(2).strip()
                fill = True
            elif CONTINUE.match(t):
                fill = True
    if not fill:
        shape["clauses"].append(t)
    hits = [(ci, m) for ci, c in enumerate(shape["clauses"]) for m in ENTRY.finditer(c)]
    for _ci, m in hits:
        shape["module"] = shape["module"] or m.group(1)
        shape["entries"].setdefault(m.group(2), {"args": m.group(3).split()})
    return shape


def _lit(s):
    s = s.strip()
    if s[:1] in "'\"":
        return s[1:-1]
    return num(s)


# ---------------------------------------------------------------- reading the requirements
def _sentences(clause):
    out, start = [], 0
    for m in re.finditer(r"(?<=[.;!?])\s+", clause):
        out.append((start, clause[start:m.start()]))
        start = m.end()
    out.append((start, clause[start:]))
    return [(o, s) for o, s in out if s.strip()]


def _segments(clause, hits):
    """the clause's sentences, each cut again where it names a command: every piece belongs to the command named at its

    start, or to the one named before it, or (before any command) to the whole project ("*"); None when the clause names none"""
    starts = [m.start() for m in hits]
    for off, s in _sentences(clause):
        cuts = [off] + [p for p in starts if off < p < off + len(s)] + [off + len(s)]
        for a, b in zip(cuts, cuts[1:]):
            piece = clause[a:b].strip(" ,;")
            if not piece:
                continue
            before = [m for m in hits if m.start() <= a]
            ent = before[-1].group(2) if before else ("*" if hits else None)
            yield a, piece, ent


def _words(s):
    s = DATA.sub(" ", ENTRY.sub(" ", s))
    s = re.sub(r"\b[\w./-]+\.(?:csv|jsonl|json|txt|html|py|db)\b", " ", s)
    return [w for w in re.findall(r"[a-z][a-z']*", s.lower().replace("-", " ")) if len(w) > 2]


def project_noun(shape):
    """the words the project calls itself: 'build a service-health dashboard ...' -> service, health, dashboard"""
    for c in shape["clauses"]:
        m = re.search(r"(?i)\b(?:build|make|create|write|set up|put together|develop)\s+(?:me\s+|us\s+)?(?:(?:a|an|the|my|our)\s+)?"
                      r"((?:[\w-]+\s+){0,3}?[\w-]+?)\s+(?:for|from|that|which|to|using|with|of|in|on|so|where|,|\.|`)", c + " .")
        if m:
            ws = [w for w in re.findall(r"[a-z]+", m.group(1).lower()) if w not in GENERAL]
            if ws:
                return ws[:4]
    return []


COLW = r"([a-z_]+)"


def _col(word, cols, derived=()):
    for c in list(cols) + list(derived):
        if wmatch(word, c) or wmatch(word, c.replace("_", " ").split()[-1]):
            return c
    return None


def read_ops(s, cols, numeric, derived_names, gcol_hint=None):
    """the operations a sentence asks of the rows. -> (ops, owned words, derive requests)"""
    low = " " + DATA.sub(" FILE ", s.lower()) + " "
    ops, own, derive = [], set(), []
    # A reference supplies a second value, not a unary example-driven function.
    calculations = []
    for m in re.finditer(r"\bmultiply\s+(?:each\s+|the\s+)?([a-z_]+)\s+by\s+(?:the\s+)?([a-z_]+)"
                         r"\s+(?:as|into)\s+([a-z_]+)", low):
        left, right = _col(m.group(1), cols), _col(m.group(2), cols)
        if left is not None and right is not None:
            calculations.append((left, right, m.group(3), m.group(0)))
    for m in re.finditer(r"\bconvert(?:s|ed|ing)?\s+(?:each\s+|every\s+|the\s+|all\s+)?([a-z_]+)"
                         r"(?:\s+from\s+FILE)?\s+(?:with|using)\s+(?:the\s+|its\s+|matching\s+)*([a-z_]+)", low):
        left, right = _col(m.group(1), cols), _col(m.group(2), cols)
        if left is not None and right is not None:
            calculations.append((left, right, "converted_" + left, m.group(0)))
    # C15: arithmetic between two columns in ordinary words ("cost as qty times price", "margin being price minus cost",
    # "total equal to a plus b", "share as part divided by whole"; "add/subtract/divide a to/from/by b as name")
    ARITH = {"times": "mul", "multiplied by": "mul", "x": "mul", "plus": "add", "added to": "add", "minus": "sub",
             "less": "sub", "take away": "sub", "divided by": "div", "over": "div", "per": "div"}
    arw = "|".join(sorted((re.escape(k) for k in ARITH), key=len, reverse=True))
    for m in re.finditer(r"\b([a-z_]+)\s+(?:as|is|=|being|equal to|which is|worked out as|computed as)\s+(?:the\s+)?([a-z_]+)\s+"
                         r"(%s)\s+(?:the\s+)?([a-z_]+)\b" % arw, low):
        left, right = _col(m.group(2), cols), _col(m.group(4), cols)
        if left is not None and right is not None and m.group(1) not in cols:     # a new name: exact, not near
            calculations.append((left, right, m.group(1), m.group(0), ARITH[m.group(3)]))
    for m in re.finditer(r"\b(add|subtract|divide)\s+(?:each\s+|the\s+)?([a-z_]+)\s+(to|from|by)\s+(?:the\s+)?([a-z_]+)"
                         r"\s+(?:as|into)\s+([a-z_]+)", low):
        a, b = _col(m.group(2), cols), _col(m.group(4), cols)
        if a is not None and b is not None:
            fn = {"add": "add", "subtract": "sub", "divide": "div"}[m.group(1)]
            left, right = (b, a) if fn == "sub" else (a, b)       # subtract a from b: b - a
            calculations.append((left, right, m.group(5), m.group(0), fn))
    calculations = [c if len(c) == 5 else c + ("mul",) for c in calculations]
    for left, right, name, phrase, fn in calculations:
        if not any(o.get("col") == name for o in ops):
            ops.append({"op": "calculate", "col": name, "left": left, "right": right, "fn": fn})
            own |= set(re.findall(r"[a-z_]+", phrase)) | {name}
    for _l, _r, _n, phrase, _f in calculations:      # C15: a phrase that defines a value is consumed by it - "both equal
        low = low.replace(phrase, " CALC ")          # to price plus cost" is not also a filter "both == price"
    calculated_names = [o["col"] for o in ops]
    for m in re.finditer(r"\b([a-z_]+?)s?\s+in\s+([a-z]+)\b(?!\s*\.\w)", low):
        c = _col(m.group(1), cols)
        tgt = m.group(2)
        if c and tgt not in GENERAL and not _col(tgt, cols) and tgt not in ALL_PART_WORDS and tgt != "file":
            derive.append({"col": c, "name": tgt, "phrase": m.group(0).strip()})
            own |= {m.group(1), tgt}
    for m in re.finditer(r"\bconvert(?:s|ed|ing)?\s+(?:each\s+|every\s+|the\s+|all\s+)?([a-z_]+?)s?\s+(?:to|into)\s+([a-z]+)\b", low):
        c = _col(m.group(1), cols)
        if c and not _col(m.group(2), cols):
            derive.append({"col": c, "name": m.group(2), "phrase": m.group(0).strip()})
            own |= {m.group(1), m.group(2)}
    for m in re.finditer(r"\b([a-z]+)\s+(?:made|computed|worked out|derived|calculated|figured)\s+(?:out\s+)?from\s+"
                         r"(?:the\s+|its\s+|their\s+|each\s+)?([a-z_]+?)s?\b", low):     # C11: "its weight made from units"
        c = _col(m.group(2), cols)
        if c and not _col(m.group(1), cols) and m.group(1) not in GENERAL and not any(d["name"] == m.group(1) for d in derive):
            derive.append({"col": c, "name": m.group(1), "phrase": m.group(0).strip()})
            own |= {m.group(1), m.group(2), "made", "computed", "worked", "out", "derived", "calculated", "figured", "from"}
    dmap = {d["col"]: d["name"] for d in derive}
    names = list(derived_names) + calculated_names + [d["name"] for d in derive]

    def col_of(w):
        c = _col(w, cols, names)
        return dmap.get(c, c)
    for m in re.finditer(r"\b(?:group(?:ed|s|ing)?\s+(?:[a-z_.]+\s+){0,3}?by|by|per|for each|for every)\s+(?:the\s+|their\s+|its\s+)?"
                         + COLW, low):
        c = _col(m.group(1), cols)
        if c and c not in numeric:
            if not any(o["op"] == "group" for o in ops):
                ops.append({"op": "group", "col": c})
            own.add(m.group(1))
            break
    aggs = [(r"\b(?:total|totals|sum|sums|add up|adds up)\s+(?:of\s+|up\s+)?(?:the\s+|all\s+|their\s+|its\s+|each\s+)?" + COLW, "sum"),
            (r"\b(?:average|averages|mean)\s+(?:of\s+)?(?:the\s+|all\s+|their\s+)?" + COLW, "mean"),
            (r"\b(?:largest|biggest|highest|maximum|max)\s+(?:of\s+)?(?:the\s+)?" + COLW, "max"),
            (r"\b(?:smallest|lowest|minimum|min)\s+(?:of\s+)?(?:the\s+)?" + COLW, "min")]
    for rx, fn in aggs:
        for m in re.finditer(rx, low):
            c = col_of(m.group(1))
            if c and (c in numeric or c in names):
                if not any(o["op"] == "agg" and o["fn"] == fn and o["col"] == c for o in ops):
                    ops.append({"op": "agg", "fn": fn, "col": c})
                own.add(m.group(1))
            elif fn == "sum" and len([x for x in numeric if x != gcol_hint]) == 1 and re.match(r"\s*(?:by|per|for)\b", low[m.end(1) - len(m.group(1)):][len(m.group(1)):]):
                pass
    # a word that is both an operation and a column of the table is the column where the sentence uses it as one
    # ("whose count is below 3", "sorted by the total"): such a use does not ask for the operation
    low_ops = re.sub(r"\b(?:whose|where|with|its|their|by|the)\s+([a-z_]+)\b(?!\s+of\b)",
                     lambda m: " COLUSE " if m.group(1) in ("count", "counts", "total", "totals", "sum", "number") and
                     _col(m.group(1), cols) else m.group(0), low)
    if re.search(r"\btotals?\b", low_ops) and not any(o["op"] == "agg" and o["fn"] == "sum" for o in ops):
        cand = [c for c in numeric if c != gcol_hint]
        if len(cand) == 1:
            ops.append({"op": "agg", "fn": "sum", "col": dmap.get(cand[0], cand[0])})
    if re.search(r"\b(?:count|counts|how many|number of)\b", low_ops):
        ops.append({"op": "agg", "fn": "count", "col": None})
    CMPW = r"(?:over|above|more|greater|at|under|below|less|fewer)\b"
    for m in re.finditer(r"\b(?:where|whose|with)\s+(?:the\s+|its\s+|their\s+)?" + COLW +
                         r"\s+(?:is|are|=|equals|equal to|of)\s+(?!" + CMPW + r")['\"`]?([\w.-]+)['\"`]?", low):
        c = col_of(m.group(1))
        if c:
            ops.append({"op": "filter", "col": c, "cmp": "==", "val": num(m.group(2))})
            own |= {m.group(1), m.group(2)}
    for m in re.finditer(COLW + r"\s+(?:is\s+|are\s+)?(over|above|more than|greater than|at least|under|below|less than|fewer than|at most)\s+(-?\d+(?:\.\d+)?)", low):
        c = col_of(m.group(1))
        if c:
            cmp = {"over": ">", "above": ">", "more than": ">", "greater than": ">", "at least": ">=", "under": "<",
                   "below": "<", "less than": "<", "fewer than": "<", "at most": "<="}[m.group(2)]
            ops.append({"op": "filter", "col": c, "cmp": cmp, "val": num(m.group(3))})
            own.add(m.group(1))
    m = re.search(r"\b(?:sort(?:ed|s)?|order(?:ed|s)?)\s+by\s+(?:the\s+|their\s+)?" + COLW + r"(\s+(?:descending|highest first|largest first|biggest first))?", low)
    if m and col_of(m.group(1)):
        ops.append({"op": "sort", "col": col_of(m.group(1)), "desc": bool(m.group(2))})
        own.add(m.group(1))
    elif re.search(r"\b(?:highest|largest|biggest|most)\s+first\b", low):
        ops.append({"op": "sort", "col": None, "desc": True})
    elif re.search(r"\b(?:lowest|smallest|least)\s+first\b", low):
        ops.append({"op": "sort", "col": None, "desc": False})
    m = re.search(r"\b(?:top|first)\s+(\d+)\b", low)
    if m:
        ops.append({"op": "top", "n": int(m.group(1))})
    return ops, own, derive


def _interaction_request(text):
    """Receive record actions and a separately named relationship source."""
    visible = DATA.sub(lambda m: " " * len(m.group()), text)
    edits = list(re.finditer(r"(?i)\beditable\b|\b(?:edit|modify|update|change)\s+(?:(?:the|these|my|each)\s+)?(?:records?|rows?|values|data)\b|\bread[- ]only\b", visible))
    edit = bool(edits and not NEGATED.search(visible[:edits[-1].start()].lower())
                and not re.fullmatch(r"(?i)read[- ]only", edits[-1].group()))
    relations = list(re.finditer(r"(?i)\b(?:relationships?|connections?|edges|links)\b", visible))
    relation = relations[-1] if relations and not NEGATED.search(visible[:relations[-1].start()].lower()) else None
    if not edits and not relations and not re.search(r"(?i)\binteractive\b", visible):
        return None
    edge, owned = None, set()
    owned.update("interactive selecting select selection click controls control".split())
    if edits:
        owned.update("editable edit modify update change edits changes editing modifying updating persist persists persistent save saving form fields field values read only".split())
    if relations:
        owned.update("relationship relationships connection connections edge edges link links linked connect connecting draw drawing drawn between endpoint endpoints source target create remove delete adding add".split())
    if relation:
        tail = text[relation.end():]
        named = re.match(r"(?i)\s+(?:from|in|using|stored in)\s+`?([\w./-]+\.(?:csv|jsonl|json))\b", tail)
        edge = {"file": named.group(1) if named else ".oracle7/relationships.csv", "create": not bool(named)}
        suffix = tail[named.end():] if named else tail
        cols = re.search(r"(?i)\b(?:using\s+|with\s+)?([a-z_]\w*)\s+(?:and|to|->)\s+([a-z_]\w*)\s+(?:as\s+)?(?:columns|endpoints)\b", suffix)
        if cols:
            edge.update({"from": cols.group(1), "to": cols.group(2)})
            owned.update(cols.groups())
    return {"edit": edit, "edges": edge, "owned": sorted(owned)}


def _source_contexts(shape, root):
    """Resolve sources in command scope; a named command never borrows another's columns."""
    output_files = {m.group(1) for c in shape["clauses"] for m in sinks(c)}
    groups = {"*": []}
    for ci, clause in enumerate(shape["clauses"]):
        for _off, sentence, entry in _segments(clause, list(ENTRY.finditer(clause))):
            if entry in (None, "*"):
                entry = shape.get("scope_fills", {}).get(str(ci), entry)
            groups.setdefault(entry or "*", []).append(sentence)
    texts = {name: " ".join(pieces) for name, pieces in groups.items()}
    source_fills = shape.get("source_fills", {})
    interactions = {name: _interaction_request(text) for name, text in texts.items()}
    auxiliary = {i["edges"]["file"] for i in interactions.values() if i and i.get("edges")}
    primary = lambda text: DATA.sub(lambda m: " " * len(m.group()) if m.group(1) in auxiliary else m.group(), text)
    default = PS.resolve(primary(texts["*"]), root, output_files=output_files, key_override=source_fills.get("*"))
    default["interaction"] = interactions.get("*")
    contexts = {}
    for name, text in texts.items():
        if name != "*":
            contexts[name] = PS.resolve(primary(text), root, fallback=default["source"], output_files=output_files,
                                        key_override=source_fills.get(name))
            contexts[name]["explicit"] = bool(PS.input_files(primary(text), output_files))
            contexts[name]["interaction"] = interactions.get(name) or interactions.get("*")
    distinct = {json.dumps(c["source"], sort_keys=True): c for c in contexts.values() if c.get("source")}
    if not default["source"] and not default["holes"] and len(distinct) == 1:
        inherited = next(iter(distinct.values()))
        default = dict(inherited, explicit=False, ops_text=texts["*"])
    default.setdefault("explicit", bool(PS.input_files(primary(texts["*"]), output_files)))
    contexts["*"] = default
    for name in shape["entries"]:
        if name not in contexts or (not contexts[name]["source"] and not contexts[name]["holes"]):
            named = [m for m in contexts if m not in (name, "*") and contexts[m].get("source") and
                     re.search(r"(?i)\b(?:from|of|what)\s+`?" + re.escape(m) + r"`?\b", texts.get(name, ""))]
            contexts[name] = dict(contexts[named[0]] if len(named) == 1 else default, explicit=False)
    shape["sources"] = {n: c.get("source") for n, c in contexts.items()}
    shape["auxiliary_inputs"] = sorted(auxiliary)
    return contexts, output_files


def _source_ops_text(text, source):
    """Matching keys select rows across tables; they are not a request to group the result."""
    if not source or source.get("op") not in ("join", "lookup"):
        return text
    columns = {c for pair in source.get("keys", []) for c in pair}
    token = r"(?:[a-z_][\w]*\.)?(?:" + "|".join(re.escape(c) for c in sorted(columns)) + r")\b"
    return re.sub(r"\b(?:matching\s+(?:(?:on|by)\s+)?|matched\s+(?:(?:on|by)\s+)?|on\s+)" + token +
                  r"(?:\s*(?:=|equals|to|with|,|and)\s*" + token + r")*", " ", text, flags=re.I)


def requirements(shape, root):
    """the ledger: every requirement the clauses make, each with its kind, its entry, the words it came from; and the

    holes reading leaves (words nobody owns, tables not there)"""
    contexts, out_files = _source_contexts(shape, root)
    shape["source_contexts"] = contexts
    tables = {f: read_table(root, f) for c in shape["clauses"] for f in PS.input_files(c, out_files) if f not in shape.get("auxiliary_inputs", [])}
    world = contexts["*"].get("world") or next((c["world"] for c in contexts.values() if c.get("world")), None) or \
        next(iter(tables.values()), None)
    if world:
        world = dict(world, hosts=sorted({h for w in tables.values() for h in w.get("hosts", [])}))
    cols = (world or {}).get("cols", [])
    numeric = (world or {}).get("numeric", [])
    stems = set()
    for f in list(tables):              # C11: a table read names its rows ("each city in weather.csv"); a file written
        b = Path(f).stem.lower()        # names nothing else in the sentence ("the lively products ... to lively.csv")
        stems |= {b} | set(re.findall(r"[a-z]+", b))
    noun = project_noun(shape)
    entries = list(shape["entries"])
    reqs, holes = [], []
    derived_names = list((shape.get("derived") or {}).keys())
    meanings = shape.get("meanings") or {}

    ids = shape.setdefault("ids", {})   # a requirement's id is kept by what it is: a drop or a fill never renumbers the rest

    def add(kind, text, ci, entry=None, **kw):
        key = (kind, kw.get("file"), kw.get("op_key"), entry if kind in ("served", "printed", "stored", "file", "op", "derive", "interaction") else None)
        for r in reqs:
            if r["key"] == list(key):
                if text not in r["from"]:
                    r["from"].append(text)
                old = {k: r.get(k) for k in kw if r.get(k) != kw[k]}
                if old:                                  # a later sentence's value replaces the earlier one ("5" -> "2")
                    r.setdefault("superseded", []).append(old)
                    r.update(kw)
                    r["clause"] = ci
                return r
        o = kw.get("op")
        if kind == "op" and o and REVISE.search(shape["clauses"][ci]):
            # a revision ("change it so ...", "instead", "now") names an operation the project already has on the same
            # column: the new one replaces it, the old kept as superseded
            same = [r for r in reqs if r["kind"] == "op" and r["entry"] == entry and r["clause"] < ci and r["op"]["op"] == o["op"] and
                    r["op"].get("col") == o.get("col") and r["op"].get("fn") == o.get("fn")]
            if same:
                r = same[-1]
                r.setdefault("superseded", []).append({k: v for k, v in r["op"].items() if o.get(k) != v})
                r.update(kw)
                r["key"], r["clause"] = list(key), ci
                r["from"].append(text)
                return r
        kid = json.dumps(list(key))
        old_key = json.dumps([kind, kw.get("file"), kw.get("op_key"), None])
        if kid not in ids and kind in ("op", "derive") and old_key in ids and not any(r["id"] == ids[old_key] for r in reqs):
            ids[kid] = ids[old_key]  # retain requirement identity when an older single-source project is continued
        if kid not in ids:
            ids[kid] = "R%d" % (max([int(v[1:]) for v in ids.values()] or [0]) + 1)
        r = {"id": ids[kid], "kind": kind, "entry": entry, "from": [text], "clause": ci, "key": list(key),
             "status": "open"}
        r.update(kw)
        reqs.append(r)
        return r

    for ci, clause in enumerate(shape["clauses"]):
        hits = list(ENTRY.finditer(clause))
        for off, s, ent in _segments(clause, hits):
            if ent in (None, "*"):
                ent = shape.get("scope_fills", {}).get(str(ci), ent)
            context = contexts.get(ent or "*", contexts["*"])
            # The original clauses remain the audit trail. An answered key hole
            # retires only its old binding phrase from this reading, so an old
            # misspelling cannot remain an unread requirement. Adjacent row
            # operations and outcomes are still read normally.
            for binding in context.get("retired_key_bindings", []):
                s = re.sub(r"(?<!\w)" + re.escape(binding) + r"(?!\w)", " ", s, flags=re.I)
            command_world = context.get("world") or {}
            cols, numeric = command_world.get("cols", []), command_world.get("numeric", [])
            revising = bool(REVISE.search(clause) or re.match(r"(?i)^\s*(?:(?:actually|wait|rather)\b|no\s*,)", clause))
            op_entry = ent
            previous_entries = {r["entry"] for r in reqs if r["kind"] == "op" and r["clause"] < ci}
            if revising and ent in (None, "*") and len(previous_entries) == 1:
                op_entry = next(iter(previous_entries))
            ambiguous_revision = revising and ent in (None, "*") and len(previous_entries) > 1
            # a word given a meaning ("flags means the rows whose amount is over 100") is read as its meaning; a meaning
            # that names nothing to do (no outcome, no operation, no value) leaves the word a hole that says so
            unbound = []
            for w, v in meanings.items():
                if v and re.search(r"(?i)(?<![\w./-])%s(?![\w/-]|\.\w)" % re.escape(w), s):
                    ops_v, _own_v, der_v = read_ops(v, cols, numeric, derived_names)
                    if sinks(v) or STORED.search(v) or SERVED.search(v) or PRINTED.search(v) or ops_v or der_v or v.strip().lower() in {c.lower() for c in cols}:
                        s = re.sub(r"(?i)(?<![\w./-])%s(?![\w/-]|\.\w)" % re.escape(w), lambda _m, v=v: v, s)
                    else:
                        unbound.append(w)
            # a revision that points at its value with a pronoun ("make it above 25 instead") means the column the
            # project's earlier comparison was on
            prior = [r for r in reqs if r["kind"] == "op" and r["entry"] in (op_entry, "*") and r["op"]["op"] == "filter" and r["clause"] < ci]
            pronoun = re.search(r"(?i)\b(?:it|that|them|this|the (?:limit|cutoff|threshold))\s+(?:is\s+|be\s+)?"
                                r"(?:over|above|more than|greater than|at least|under|below|less than|fewer than|at most)\s+-?\d", s)
            ambiguous_pronoun = bool(revising and pronoun and len({r["op"]["col"] for r in prior}) != 1)
            if prior and revising and not ambiguous_pronoun and not ambiguous_revision:
                s = re.sub(r"(?i)\b(?:it|that|them|this|the (?:limit|cutoff|threshold))(?=\s+(?:is\s+|be\s+)?"
                           r"(?:over|above|more than|greater than|at least|under|below|less than|fewer than|at most)\s+-?\d)",
                           prior[-1]["op"]["col"], s)
            # C15: a revision that gives only the new value ("no, I meant above 200", "over 30 instead") means the column
            # of the earlier comparison, when there is exactly one; a column it names itself is left as said
            if prior and revising and not ambiguous_revision and len({r["op"]["col"] for r in prior}) == 1:
                col0 = prior[-1]["op"]["col"]

                def _bare(m, col0=col0, s0=s):
                    before = re.findall(r"[A-Za-z_]+", s0[:m.start()])
                    if before and (_col(before[-1], cols) or before[-1].lower() in ("is", "are", "be", "whose", "where")):
                        return m.group(0)
                    return col0 + " " + m.group(0)
                s = re.sub(r"(?i)\b(?:over|above|more than|greater than|at least|under|below|less than|fewer than|at most)"
                           r"\s+-?\d+(?:\.\d+)?", _bare, s)
            low = s.lower()
            own = set(context.get("owned", []))
            interaction = context.get("interaction")
            if interaction:
                own.update(interaction["owned"])
            kinds, excluded = [], []
            # an outcome named without a file ("not write any file to disk", "save nothing"): ruled out, every file
            mg = re.search(r"\b(?:write|writes|save|saves|store|stores|export|exports|output|create|creates|make|makes)\s+"
                           r"(?:any|a|no|anything|nothing|files?)(?:\s+(?:files?|output))?(?:\s+to\s+(?:disk|the disk))?\b"
                           r"|\bto\s+(?:the\s+)?disk\b", low)
            if mg and (NEGATED.search(low[:mg.start()]) or re.search(r"\b(?:nothing|no)\b", mg.group(0))):
                excluded.append(("file", {"file": "*"}))
                own |= set(re.findall(r"[a-z]+", mg.group(0))) | {"disk", "any", "anything", "nothing"}

            def negated(pos):                            # "do not export ...", "without a database", "no page", "never print"
                return bool(NEGATED.search(low[:pos]))
            for m in sinks(s):
                kw = {"file": m.group(1), "fmt": m.group(2).lower(),
                      "every": bool(re.search(r"(?i)\b(?:every|all|history|each check)", s))}
                (excluded if negated(m.start()) else kinds).append(("file", dict(kw, _at=m.start())))
                # the outcome owns its verb, its preposition and its file token - not every word between them ("save the
                # suspicious items ... to x.csv": 'suspicious' is still to be read), nor its file's words said elsewhere
                own |= {re.match(r"[a-z]+", m.group(0).lower()).group(0), "to", "into", "in", "as", "file", "called", "named"}
            for kname, rx in (("stored", STORED), ("served", SERVED), ("printed", PRINTED)):
                m = rx.search(s)
                if m:
                    (excluded if negated(m.start()) else kinds).append((kname, {"_at": m.start()}))
            if interaction and not any(k == "served" for k, _kw in kinds + excluded) and _interaction_request(s):
                kinds.append(("served", {"_at": 0}))
            props = []
            mt = re.search(r"\bwithin\s+(\d+(?:\.\d+)?)\s*(?:s\b|sec|second)", low)
            if mt:
                props.append(("timeout", {"seconds": float(mt.group(1))}))
            if re.search(r"\berror|\bfail", low) and re.search(r"\bdown\b|\bfail|\berror", low) and world and world.get("url"):
                props.append(("error_down", {}))
            if re.search(r"\bmillisecond|\bms\b|how long|latency", low):
                props.append(("ms", {}))
            if re.search(r"\btime-?stamp", low):
                props.append(("timestamp", {}))
            mk = re.search(r"\blast\s+(\d+)\b", low)
            if mk or re.search(r"\bprevious\b", low):
                props.append(("keep_last", {"n": int(mk.group(1)) if mk else 2}))
            if any(k == "served" for k, _kw in kinds):
                lk = read_look(s)
                if lk:
                    props.append(("look", lk))
                    own |= set(lk.get("words", []))
            gh = None
            operation_text = _source_ops_text(s, context.get("source"))
            ops, oown, derive = read_ops(operation_text, cols, numeric, derived_names)
            own |= oown
            for o in ops:
                if o["op"] == "group":
                    gh = o["col"]
            if gh:
                ops2, _o2, _d2 = read_ops(operation_text, cols, numeric, derived_names, gcol_hint=gh)
                ops = ops2
            # who owns each word
            # the table's items, named by the request ("the books whose status is out", "each city in weather.csv")
            rownouns = set(re.findall(r"\b(?:the|each|every|all(?: the| my| our)?|any|my|our|your)\s+(?:kept\s+|stored\s+|listed\s+)?"
                                      r"([a-z]+?)(?:'s)?\s+(?:whose|that|which|who|"
                                      r"where|with|in|from|of|listed|kept|on)\b", DATA.sub(" in ", low)))
            rownouns |= set(re.findall(r"\b(?:each|every)\s+([a-z]+)'s\b", low))
            owners = set(GENERAL) | ALL_PART_WORDS | rownouns | set(cols) | {w for c in cols for w in re.findall(r"[a-z]+", c.lower())} | \
                stems | set(noun) | set(derived_names) | {d["name"] for d in derive} | own | \
                {w for w, v in meanings.items()} | {x for v in meanings.values() for x in re.findall(r"[a-z]+", v.lower())}
            for e in entries:
                owners |= set(re.findall(r"[a-z]+", e))
            unowned = []
            for w in _words(s):
                if w in GENERAL or _owned(w, owners) or w.isdigit():
                    continue
                if w not in unowned:
                    unowned.append(w)
            unowned = [w for w in unowned if meanings.get(w) is None] + [w for w in unbound if w not in unowned]
            if ambiguous_pronoun:
                unowned.append("it")
            if ambiguous_revision and (ops or pronoun):
                r = add("scope", s, ci, ent, op_key="scope %d %d" % (ci, off), entries=sorted(e for e in previous_entries if e))
                r["status"] = "hole"
            # C11: an operation asked inside a later outcome's own words ("... to f.csv and prints how many there are") is
            # that outcome's: the other outcomes keep the rows. Asked before the second outcome, it is the command's.
            scoped = {}
            at = sorted(kw.get("_at", 0) for _k, kw in kinds)
            if len(at) >= 2:
                head_ops = read_ops(s[:at[1]], cols, numeric, derived_names)[0]
                for i in range(1, len(at)):
                    piece_ops = read_ops(s[at[i]:at[i + 1] if i + 1 < len(at) else len(s)], cols, numeric, derived_names)[0]
                    for o in ops:
                        if o["op"] in ("agg", "group", "top") and o not in head_ops and o in piece_ops:
                            scoped.setdefault(json.dumps(o, sort_keys=True), at[i])
            excluded = [(k, {x: y for x, y in kw.items() if x != "_at"}) for k, kw in excluded]
            for k, kw in excluded:                       # an outcome the request rules out: judged as not done
                add("excluded", s, ci, ent, what=k, op_key="not " + k + (" " + kw["file"] if kw.get("file") else ""),
                    **({"file": kw["file"]} if kw.get("file") else {}))
            if not kinds and not props and not ops and not derive and not excluded:
                if ci == 0 and (BUILD.search(s) or DATA.search(s)) and not unowned:
                    add("context", s, ci, None)
                    continue
                if not unowned:
                    add("context", s, ci, None)
                    continue
            out_at = {}
            for k, kw in kinds:
                tgt_entry = ent
                out_at[kw.get("_at", 0)] = add(k, s, ci, tgt_entry, **{x: y for x, y in kw.items() if x != "_at"})["id"]
            for k, kw in props:
                add(k, s, ci, None, **kw)
            if interaction and _interaction_request(s):
                add("interaction", s, ci, ent, op_key="record actions", actions=interaction)
            for o in ops:
                ok_ = json.dumps(o, sort_keys=True)
                if ok_ in scoped:
                    add("op", s, ci, op_entry, op=o, op_key=ok_ + " @" + out_at[scoped[ok_]], out=out_at[scoped[ok_]])
                else:
                    add("op", s, ci, op_entry, op=o, op_key=ok_)
            for d in derive:
                fn = "%s_of_%s" % (re.sub(r"\W+", "_", d["name"]).strip("_"), d["col"])
                add("derive", s, ci, ent, col=d["col"], name=d["name"], fn=fn, op_key=fn)
            if unowned:
                # its identity is the sentence it sits in, not which of its words are still unread: a word dropped or
                # explained leaves the rest of the hole under the same id
                r = add("unread", s, ci, ent, words=unowned, op_key="unread %d %d" % (ci, off))
                r["status"] = "hole"
    for r in reqs:
        if r["id"] in shape.get("dropped", []):
            r["status"] = "dropped"
    reqs.sort(key=lambda r: int(r["id"][1:]))
    return reqs, world, tables


# ---------------------------------------------------------------- planning: entries, sources, links, holes
def _propose(shape, reqs):
    """entries for a request that names none: one that does the work (named by its verb) and one that serves the page"""
    outs = [r for r in reqs if r["kind"] in ("file", "stored", "printed", "served") and r["status"] != "dropped"]
    if not outs:
        return
    text = " ".join(shape["clauses"]).lower()
    if not shape.get("module"):
        noun = project_noun(shape)
        if not noun:                                  # no name of its own: its table and what it makes
            tbl = next((f for c in shape["clauses"] for f in DATA.findall(c)), "project")
            noun = [re.sub(r"\W+", "_", Path(tbl).stem).strip("_") or "project",
                    "page" if all(r["kind"] == "served" for r in outs) else "report"]
        shape["module"] = "_".join(noun[:3]) + ".py"
    batch = [r for r in outs if r["kind"] != "served"]
    served = [r for r in outs if r["kind"] == "served"]
    entries = {}
    if batch:
        verb = next((v for v in ("check", "report", "export", "update", "summarize", "collect", "refresh", "scan", "import",
                                 "sync", "build") if re.search(r"\b%s" % v, text)), "run")
        entries[verb] = {"args": [], "proposed": True}
    if served:
        entries["serve"] = {"args": ["PORT"], "proposed": True}
    shape["entries"] = entries
    shape["proposed"] = True
    bname = next((n for n in entries if n != "serve"), None)
    for r in outs:
        r["entry"] = "serve" if r["kind"] == "served" else bname


def _store_offer(fn, name, col, sample):
    """a kept function of Oracle7's store for a value made from a column: lit on the spine by the words and the shape,

    its name saying both the value and the column, its own evidence still holding"""
    try:
        sys.path.insert(0, str(Path(__file__).resolve().parent))
        import code_store as CS
        entries = CS.load()
    except Exception:  # noqa: BLE001
        return None, []
    if not entries:
        return None, []
    words = [stem(w) for w in re.findall(r"[a-z]+", name.lower())] + [stem(w) for w in re.findall(r"[a-z]+", col.lower())]
    shp = "'int'" if isinstance(sample, int) else "'float'" if isinstance(sample, float) else "'str'"
    try:
        lit = [e for _r, e in CS.CodeFlash(entries).light([shp], None, words)]
    except Exception:  # noqa: BLE001
        lit = entries
    by_sha = {e["sha256"]: e for e in entries}
    for e in lit:
        if len(e.get("params") or []) != 1:
            continue
        ew = [stem(w) for w in re.findall(r"[a-z]+", e["name"].lower())]
        if not all(any(wmatch(w, x) for x in ew) for w in words):
            continue
        if e.get("in_shapes") and e["in_shapes"][0] not in (shp, "'int'", "'float'") and shp != "'str'":
            continue
        why = CS.replay(e, by_sha)
        if why is None:
            deps = []
            seen = set()

            def addd(x):
                for _n, sha in (x.get("deps") or {}).items():
                    d = by_sha.get(sha)
                    if d is not None and sha not in seen:
                        seen.add(sha)
                        addd(d)
                        deps.append(d)
            addd(e)
            return e, deps
    return None, []


def plan(shape, root):
    """-> (pipes, holes, reqs, world). pipes: entry -> {source, ops, derive, sinks, links}; every open requirement tied

    to the links that supply it, or a hole saying what would fill it"""
    reqs, world, tables = requirements(shape, root)
    if not shape["entries"]:
        _propose(shape, reqs)
    gone = {r["id"] for r in reqs if r["status"] == "dropped"}
    for r in reqs:                                  # an operation of one outcome goes when that outcome is dropped
        if r.get("out") in gone and r["status"] != "dropped":
            r["status"], r["dropped_with"] = "dropped", r["out"]
    live = [r for r in reqs if r["status"] != "dropped"]
    holes = []
    contexts = shape.get("source_contexts", {})
    for name, context in contexts.items():
        for hole in context.get("holes", []):
            h = dict(hole, entry=name)
            if not any(x.get("text") == h.get("text") for x in holes):
                holes.append(h)
    for r in live:
        if r["kind"] == "scope":
            holes.append({"kind": "scope", "req": r["id"], "clause": r["clause"], "entries": r["entries"], "text": "%s: which command does this correction belong to? Say its name: %s. The correction is kept." % (r["id"], ", ".join("`%s`" % n for n in r["entries"]))})
        if r["kind"] == "unread":
            given = [(w, shape["meanings"][w]) for w in r["words"] if (shape.get("meanings") or {}).get(w)]
            if given:
                holes.append({"kind": "unread", "req": r["id"], "words": r["words"],
                              "text": "%s: you said %s, but I can't read that as something to do: no file, page, database, "
                                      "printing or operation on the rows. Say it as one (\"%s means the rows whose ... is "
                                      "over ...\"), or \"drop %s\"." % (r["id"], "; ".join("'%s' means '%s'" % g for g in given),
                                                                       given[0][0], r["id"][1:])})
                continue
            holes.append({"kind": "unread", "req": r["id"], "words": r["words"],
                          "text": "%s: I don't know what %s means here (\"%s\"). Say what it means (\"%s means ...\"), or "
                                  "\"drop %s\"." % (r["id"], ", ".join("'%s'" % w for w in r["words"]), r["from"][0][:140],
                                                     r["words"][0], r["id"][1:])})
    for f, w in (tables or {}).items():
        if w.get("missing"):
            holes.append({"kind": "world", "file": f, "text": "%s is not in the project yet. Add it and say \"continue\"." % f})
        elif w.get("unreadable"):
            holes.append({"kind": "world", "file": f, "text": "%s could not be read as a table (%s)." % (f, w["unreadable"])})
    if not world and any(r["kind"] in ("file", "stored", "served", "printed") for r in live):
        holes.append({"kind": "world", "text": "the request names no table of the project (a .csv or .json file) to work from."})
    for r in live:
        if r["kind"] == "file" and any(Path(root, r.get("file", "")).resolve() == Path(root, f).resolve() for f in tables):
            holes.append({"kind": "outcome", "req": r["id"],
                          "text": "%s: writing to %s would replace the table the project reads. Name another file to write "
                                  "(\"... to out.csv\"), or \"drop %s\"." % (r["id"], r["file"], r["id"][1:])})
    entries = shape["entries"]
    names = list(entries)
    if not names:
        holes.append({"kind": "outcome", "text": "nothing in the request is an outcome I can observe (a file written, rows kept "
                                                  "in a database, a page in the browser, lines printed)."})
        return {}, holes, reqs, world
    serve_name = next((n for n in names if "PORT" in entries[n]["args"]), None)
    if serve_name is None and any(r["kind"] == "served" for r in live):
        # a page asked of a project whose commands all run and stop: a command that serves it is proposed beside them
        entries["serve"] = {"args": ["PORT"], "proposed": True}
        names.append("serve")
        serve_name = "serve"
        for r in live:
            if r["kind"] == "served":
                r["entry"] = None
    batch_names = [n for n in names if n != serve_name] or names[:1]
    for r in live:                                  # an outcome named before any entry, or added later: its entry by kind
        if r["kind"] == "interaction" and (r["entry"] not in names or "PORT" not in entries[r["entry"]]["args"]):
            r["entry"] = serve_name or batch_names[0]
        if r["kind"] in ("file", "stored", "served", "printed") and (r["entry"] in (None, "*") or r["entry"] not in names):
            r["entry"] = serve_name if r["kind"] == "served" and serve_name else batch_names[0]
        if r["kind"] in ("op", "derive") and r["entry"] not in names:
            r["entry"] = "*"
    first = {}
    for r in live:                                  # the same outcome asked again (a change saying "on the page"): one record
        if r["kind"] in ("file", "stored", "served", "printed"):
            k = (r["kind"], r.get("file"), r["entry"])
            if k in first:
                first[k]["from"] += [x for x in r["from"] if x not in first[k]["from"]]
                r["status"] = "dropped"
                r["merged_into"] = first[k]["id"]
            else:
                first[k] = r
    live = [r for r in live if r["status"] != "dropped"]
    probe_words = PART_WORDS["probe"] - {"answer", "answers", "answered", "up", "down", "status", "server", "servers"}
    pipes = {}
    stores = {}
    for n in names:
        outs = [r for r in live if r["entry"] == n and r["kind"] in ("file", "stored", "served", "printed")]
        words = " ".join(x for r in live if r["entry"] in (n, "*") for x in r["from"]).lower()
        context = contexts.get(n, contexts.get("*", {}))
        pw = context.get("world") or {}
        probe = bool(pw.get("url") and any(re.search(r"\b%s\b" % w, words) for w in probe_words))
        has_store = any(r["kind"] == "stored" for r in outs)
        stores[n] = (probe, has_store)
        pipes[n] = {"outs": [r["id"] for r in outs], "probe": probe, "input": context.get("source"),
                    "world": pw, "explicit_source": context.get("explicit", False)}
    store_names = [n for n in names if stores[n][1]]
    for n in store_names:
        table_name = "results_" + re.sub(r"\W", "_", n)
        if sum(re.sub(r"\W", "_", m) == re.sub(r"\W", "_", n) for m in store_names) > 1:
            table_name += "_" + hashlib.sha256(n.encode()).hexdigest()[:8]
        pipes[n]["store_table"] = "results" if len(store_names) == 1 else table_name
    for n in names:
        p = pipes[n]
        pw = p["world"]
        outs = [r for r in live if r["id"] in p["outs"]]
        only_view = outs and all(r["kind"] in ("served", "printed") for r in outs)
        other_stores = [m for m in names if m != n and stores[m][1]]
        view_words = " ".join(x for r in outs for x in r["from"])
        named_stores = [m for m in other_stores if re.search(r"(?i)\b(?:from|of|what)\s+`?" + re.escape(m) + r"`?\b", view_words)]
        other_store = named_stores[0] if len(named_stores) == 1 else other_stores[0] if len(other_stores) == 1 else None
        if only_view and not p["explicit_source"] and len(other_stores) > 1 and other_store is None:
            holes.append({"kind": "source", "entry": n, "text": "`%s` could read several stored results; name the command it reads from: %s." % (n, ", ".join(other_stores))})
        if only_view and other_store and not p["explicit_source"]:
            src = "stored"                             # a view of what another command keeps reads it back
        elif p["probe"]:
            src = "probe"
        else:
            src = "table"
        p["source"] = src
        p["numeric"] = list(pw.get("numeric") or [])
        # a proposed view of a project that keeps nothing shows what the project's commands compute: their operations
        inherit = [m for m in names if m != n and pipes[m].get("input") == p.get("input")] if entries[n].get("proposed") and only_view and src == "table" else []
        p["ops"] = [r["op"] for r in live if r["kind"] == "op" and r["entry"] in [n, "*"] + inherit and not r.get("out")] \
            if src != "stored" else []
        p["out_ops"] = {}                            # C11: the operations one outcome asks for itself
        for r in live:
            if r["kind"] == "op" and r.get("out") in p["outs"]:
                p["out_ops"].setdefault(r["out"], []).append(r["op"])
        p["derive"] = [r for r in live if r["kind"] == "derive" and r["entry"] in [n, "*"] + inherit] if src == "table" else []
        for operation in p["ops"] + [o for operations in p["out_ops"].values() for o in operations]:
            if operation["op"] == "calculate" and pw.get("n", 0) and any(c not in p["numeric"] for c in (operation["left"], operation["right"])):
                holes.append({"kind": "source", "entry": n, "text": "`%s` needs numeric values in both %s and %s to calculate %s. Correct those input values and continue." % (n, operation["left"], operation["right"], operation["col"])})
        if src == "stored" and other_store:
            p["ops"] = [r["op"] for r in live if r["kind"] == "op" and r["entry"] == n and not r.get("out")]
            p["from"] = other_store
            p["store_probe"] = stores[other_store][0]
            p["store_table"] = pipes[other_store].get("store_table", "results")
            p["input"], p["world"] = pipes[other_store]["input"], pipes[other_store]["world"]
            pw = p["world"]
            p["numeric"] = list(pw.get("numeric") or [])
            if p["store_probe"] and (p["ops"] or p["out_ops"]):
                holes.append({"kind": "part", "entry": n, "text": "`%s` asks to transform stored probe results; say whether to use all history or only the latest result per server before that transformation." % n})
        if src != "stored" and not p.get("input") and p["outs"]:
            holes.append({"kind": "source", "entry": n, "text": "`%s` needs an input table or an explicitly named combination of tables." % n})
        links = []
        if src == "probe":
            links += [{"part": "table", "why": "the servers are listed in %s" % pw["file"]},
                      {"part": "probe", "why": "each row's url is asked once"}]
        elif src == "table":
            graph = p.get("input") or {}
            relationship = graph.get("op", "read")
            why = "%s: %s" % (relationship, ", ".join(PS.files(graph)) or "the table")
            if graph.get("keys"):
                why += " matching " + ", ".join("%s = %s" % tuple(k) for k in graph["keys"])
            links.append({"part": "table", "why": why})
        else:
            links += [{"part": "db", "why": "the rows `%s` keeps" % other_store}]
            if stores[other_store][0]:
                links.append({"part": "latest", "why": "each row's most recent results are read back"})
        for d in p["derive"]:
            links.append({"part": "derive", "why": "%s made from %s" % (d["name"], d["col"]), "req": d["id"]})
        if p["ops"]:
            links.append({"part": "compute", "why": "; ".join(_op_text(o) for o in p["ops"])})
        for r in outs:
            part = {"file": "export", "stored": "keep", "served": "page", "printed": "print"}[r["kind"]]
            if p["out_ops"].get(r["id"]):
                links.append({"part": "compute", "why": "for %s only: %s" % (r["id"], "; ".join(
                    _op_text(o) for o in p["out_ops"][r["id"]])), "req": r["id"]})
            links.append({"part": part, "why": {"file": "written to %s" % r.get("file"), "stored": "kept in the project's database",
                                                "served": "laid out as a page", "printed": "printed"}[r["kind"]], "req": r["id"]})
            if part == "page":
                links.append({"part": "serve", "why": "served to a browser on PORT", "req": r["id"]})
        p["links"] = links
        if src == "stored" and not stores[other_store][0]:
            p["record_fields"] = None
    if any(p["source"] == "probe" for p in pipes.values()):
        for n, p in pipes.items():
            if p["ops"] and p["source"] == "probe":
                holes.append({"kind": "part", "text": "`%s %s`: %s of probe results is not a part I have yet." % (
                    shape["module"], n, _op_text(p["ops"][0]))})
            pw = p.get("world", {})
            if p["source"] == "probe" and not (pw.get("url") and pw.get("key")):
                holes.append({"kind": "world", "text": "%s has no column of urls and one of names (columns: %s)" % (
                    pw.get("file"), ", ".join(pw.get("cols", [])))})
    # values made from a column: the store first, then the composer from examples
    derived = shape.setdefault("derived", {})
    for r in live:
        if r["kind"] != "derive":
            continue
        fn = r["fn"]
        if fn in derived:
            continue
        sample = num((pipes.get(r["entry"], {}).get("world") or world or {}).get("sample", {}).get(r["col"]))
        e, deps = _store_offer(fn, r["name"], r["col"], sample)
        if e is not None and (e["sha256"] == (shape.get("use") or {}).get(fn) or _names_equal(e["name"], fn)):
            derived[fn] = {"name": r["name"], "col": r["col"], "fn": e["name"], "source": e["source"], "sha256": e["sha256"],
                           "imports": e.get("imports") or [], "deps": [{"name": d["name"], "source": d["source"],
                                                                        "sha256": d["sha256"]} for d in deps],
                           "from": "store", "project": e.get("project"), "id": e["id"]}
            continue
        exs = (shape.get("examples") or {}).get(fn)
        if not exs:                                 # C11: examples given in the sentence that asked for the value
            got = [[_lit(a), _lit(b)] for t in r["from"] for a, b in EXAMPLE.findall(t)]
            if len(got) >= 3:
                exs = shape.setdefault("examples", {})[fn] = got
        if exs and len(exs) >= 3:
            holes.append({"kind": "compose", "req": r["id"], "fn": fn, "col": r["col"], "name": r["name"], "examples": exs,
                          "text": "%s: %s made from %s - composing it from the %d examples given." % (
                              r["id"], r["name"], r["col"], len(exs))})
            continue
        h = {"kind": "derive", "req": r["id"], "fn": fn, "col": r["col"], "name": r["name"],
             "text": "%s: no part I have makes %s from %s (\"%s\"). Give three examples of %s -> %s (like `%s -> ...`), "
                     "and I compose it and keep it." % (r["id"], r["name"], r["col"], r["from"][0][:120], r["col"], r["name"],
                                                         sample if sample is not None else "...")}
        if e is not None:
            h["offer"] = {"name": e["name"], "sha256": e["sha256"], "project": e.get("project")}
            h["text"] += " My store has %s (sha %s, kept from %s): say \"use it\" if that is what you mean." % (
                e["name"], e["sha256"][:12], e.get("project") or "earlier work")
        holes.append(h)
    if any(r["kind"] == "served" for r in live):
        shape["design"] = design_for([r for r in live if r["kind"] == "look"])
    for r in live:
        if r["kind"] != "interaction":
            continue
        p = pipes.get(r["entry"], {})
        if not p.get("input"):
            continue
        try:
            if p.get("source") != "table":
                raise PI.InteractionError("name the source records to edit; a stored history or probe result is not its source record")
            actions = (contexts.get(r["entry"]) or contexts.get("*") or {}).get("interaction") or r["actions"]
            edges = dict(actions["edges"]) if actions.get("edges") else None
            if edges and not all(edges.get(k) for k in ("from", "to")):
                if edges.get("create"):
                    edges.update({"from": "source", "to": "target", "label": "label"})
                else:
                    edge_columns, _edge_rows = PS.source_snapshot({"op": "read", "file": edges["file"]}, root)
                    pairs = [(a, b) for a, b in (("source", "target"), ("from", "to"), ("source_id", "target_id"),
                                                ("from_id", "to_id"), ("parent", "child")) if a in edge_columns and b in edge_columns]
                    if len(pairs) != 1:
                        raise PI.InteractionError("name the relationship endpoints: relationships from %s using COLUMN and COLUMN as endpoints" % edges["file"])
                    edges.update({"from": pairs[0][0], "to": pairs[0][1]})
                    if "label" in edge_columns:
                        edges["label"] = "label"
            if any(o["op"] in ("agg", "group") for o in p.get("ops", [])):
                raise PI.InteractionError("give the editor a view of individual source records; grouped totals have several owning records")
            shown = expected_rows(root, world, p, shape.get("derived") or {})
            identity = next(iter(shown[0]), None) if shown else next(iter(p["world"].get("cols", [])), None)
            p["interaction"] = PI.plan_interaction(root, p["input"], shown, identity=identity,
                                                     editable=None if actions["edit"] else [], edges=edges)
            r["binding"] = p["interaction"]
            p["links"].append({"part": "record actions", "why": "selection, source edits and relationships share the displayed record identities", "req": r["id"]})
        except (ValueError, OSError, KeyError, TypeError, AttributeError) as error:
            holes.append({"kind": "interaction", "req": r["id"], "text": "%s: %s" % (r["id"], error)})
    shape["status"] = "blocked" if holes else "planned"
    shape["holes_kept"] = holes
    return pipes, holes, reqs, world


def _names_equal(a, b):
    wa = sorted(stem(w) for w in re.findall(r"[a-z]+", a.lower()))
    wb = sorted(stem(w) for w in re.findall(r"[a-z]+", b.lower()))
    return wa == wb


def _op_text(o):
    if o["op"] == "calculate":
        return "%s made as %s %s %s" % (o["col"], o["left"], {"mul": "times", "add": "plus", "sub": "minus",
                                                              "div": "divided by"}.get(o.get("fn"), "?"), o["right"])
    if o["op"] == "group":
        return "grouped by %s" % o["col"]
    if o["op"] == "agg":
        return {"sum": "total", "mean": "average", "max": "largest", "min": "smallest", "count": "count"}[o["fn"]] + \
            ("" if o["col"] is None else " of %s" % o["col"])
    if o["op"] == "filter":
        return "only rows whose %s %s %s" % (o["col"], o["cmp"], o["val"])
    if o["op"] == "sort":
        return "sorted by %s%s" % (o["col"] or "the summary", ", highest first" if o["desc"] else "")
    if o["op"] == "top":
        return "the first %d" % o["n"]
    return str(o)


def sort_col(o, p, aggs):
    """what "highest first" sorts by when the request names no column: the summary it asks for, else the value it makes

    from a column, else the table's one column of numbers"""
    if o.get("col"):
        return o["col"]
    if aggs:
        return agg_name(aggs[0])
    if p.get("derive"):
        return p["derive"][-1]["name"]
    nums = p.get("numeric") or []
    return nums[0] if len(nums) == 1 else None


def agg_name(o):
    if o["fn"] == "count":
        return "count"
    return {"sum": "total", "mean": "average", "max": "largest", "min": "smallest"}[o["fn"]] + "_" + o["col"]


def settings(reqs):
    s = {"timeout": 10.0, "error_down": False, "ms": False, "timed": False, "keep_last": 1}
    for r in reqs:
        if r["status"] == "dropped":
            continue
        if r["kind"] == "timeout":
            s["timeout"] = r["seconds"]
        elif r["kind"] == "error_down":
            s["error_down"] = True
        elif r["kind"] == "ms":
            s["ms"] = True
        elif r["kind"] == "timestamp":
            s["timed"] = True
        elif r["kind"] == "keep_last":
            s["keep_last"] = max(s["keep_last"], r["n"])
    return s


# ---------------------------------------------------------------- writing: each part's code
def write(shape, pipes, reqs, world):
    st = settings(reqs)
    mod = shape["module"]
    db = Path(mod).stem + ".db"
    probe = any(p["source"] == "probe" or p.get("store_probe") for p in pipes.values())
    derived = shape.get("derived") or {}
    used_fns = [derived[d["fn"]] for p in pipes.values() for d in p.get("derive", []) if d["fn"] in derived]
    imports = sorted({"csv", "html", "http.server", "json", "sqlite3", "sys", "time"} |
                     ({"urllib.error", "urllib.request"} if probe else set()) |
                     {i for f in used_fns for i in f.get("imports") or []})
    parts_used = sorted({l["part"] for p in pipes.values() for l in p["links"]})
    L = ['"""%s - written by Oracle7 from the request (its parts: %s)."""' % (mod, ", ".join(parts_used))]
    L += ["import %s" % i for i in imports] + ["", ""]
    default_input = (world or {}).get("source") or {"op": "read", "file": world["file"]}
    L += PS.runtime_source().splitlines() + ["", ""]
    if any(p.get("interaction") for p in pipes.values()):
        L += PI.runtime_source().splitlines() + ["", ""]
    L += ["TABLE = %r" % world["file"], "DEFAULT_INPUT = %r" % default_input, "DB = %r" % db]
    if probe:
        fields = ["key", "url", "at", "status", "code", "error"] + (["ms"] if st["ms"] else [])
        probe_world = next((p.get("world") or world for p in pipes.values() if p["source"] == "probe"), world)
        L += ["KEY, URL = %r, %r" % (probe_world["key"], probe_world["url"]), "TIMEOUT = %r" % st["timeout"]]
    else:
        fields = None
    L += ["KEEP_LAST = %d" % st["keep_last"], "", ""]
    L += ["def table(source=None):", '    """the rows of a named source shape, read afresh"""',
          "    return read_source(DEFAULT_INPUT if source is None else source)", "", "",
          "def num(v):", '    """a number written as text, read as a number; other values as they are"""',
          "    if isinstance(v, (int, float)) and not isinstance(v, bool):", "        return v",
          "    s = str(v).strip()", "    try:", "        return int(s)", "    except ValueError:", "        pass",
          "    try:", "        return float(s)", "    except ValueError:", "        return v", "", ""]
    if probe:
        L += _emit_probe(st)
    for f in used_fns:
        for d in f.get("deps") or []:
            L += ["# kept function %s from Oracle7's store (sha %s)" % (d["name"], d["sha256"][:16])] + d["source"].splitlines() + ["", ""]
        L += ["# %s: %s made from %s - %s (sha %s)" % (
            f["fn"], f["name"], f["col"], "kept function from Oracle7's store, from %s" % (f.get("project") or "earlier work")
            if f.get("from") == "store" else "composed by Oracle7's code composer from the examples given", f["sha256"][:16])]
        L += f["source"].splitlines() + ["", ""]
    for n, p in pipes.items():
        if p["source"] in ("table", "stored"):
            provider = pipes.get(p.get("from"), p)
            stored_rows = "stored(%r)" % provider.get("store_table", p.get("store_table", "results")) if p["source"] == "stored" else None
            L += _emit_compute(n, p, derived, stored_rows)
            for rid in p.get("out_ops") or {}:
                L += _emit_compute(n, view(p, rid), derived, stored_rows, rid)
    rec_fields = {}
    store_tables = {}
    for n, p in pipes.items():
        if any(r["kind"] == "stored" for r in reqs if r["id"] in p["outs"]):
            sr = next(r["id"] for r in reqs if r["id"] in p["outs"] and r["kind"] == "stored")
            rec_fields[n] = list(dict.fromkeys(fields if p["source"] == "probe" else
                                              out_columns(view(p, sr), p.get("world") or world, derived) + ["at"]))
            store_tables[p.get("store_table", "results")] = rec_fields[n]
    if not store_tables:
        store_tables["results"] = fields if probe else ["at"]
    L += ["STORE_FIELDS = %r" % store_tables,
          "FIELDS = %r" % (fields if probe else next(iter(rec_fields.values()), ["at"])), "", "",
          "def _qid(value):", "    return chr(34) + str(value).replace(chr(34), chr(34) * 2) + chr(34)", "", "",
          "def connect(store='results'):", '    """one named result table per source command; previous rows stay"""',
          "    fs = STORE_FIELDS[store]",
          "    c = sqlite3.connect(DB)",
          "    c.execute('create table if not exists %s (%s)' % (_qid(store), ', '.join(_qid(f) for f in fs)))",
          "    have = [r[1] for r in c.execute('pragma table_info(%s)' % _qid(store))]",
          "    for f in fs:", "        if f not in have:", "            c.execute('alter table %s add column %s' % (_qid(store), _qid(f)))",
          "    return c", "", "",
          "def keep(rows, store='results'):", '    """every row kept in its command\'s table, with its time"""',
          "    c = connect(store)", "    fs = STORE_FIELDS[store]", "    at = time.strftime('%Y-%m-%d %H:%M:%S')",
          "    with c:", "        for r in rows:", "            r.setdefault('at', at)",
          "            c.execute('insert into %s (%s) values (%s)' % (_qid(store), ', '.join(_qid(f) for f in fs), ', '.join('?' * len(fs))),",
          "                      [r.get(f) for f in fs])", "    c.close()", "    return len(rows)", "", "",
          "def stored(store='results'):", '    """every row in this command\'s table, oldest first"""', "    c = connect(store)",
          "    fs = STORE_FIELDS[store]",
          "    rows = [dict(zip(fs, x)) for x in c.execute('select %s from %s order by rowid' % (', '.join(_qid(f) for f in fs), _qid(store)))]",
          "    c.close()", "    return rows", "", ""]
    head, why = design_head(shape.get("design"))
    L += ["DOC = %r" % '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" '
                       'content="width=device-width, initial-scale=1"><title>%s</title>',
          "# the look: Oracle7's design family (palette, type, layout, motion): " + why,
          "HEAD = %r" % head, "STAGE = %r" % (tuple((shape.get("design") or {}).get("stage") or ()) or None,), "", ""]
    if probe:
        L += _emit_latest_page(st)
    L += ["def scene_records(rows):",
          '    """the records a scene is bound to (12.0 C12): each row\'s id (its first column) and value (the first column after',
          '    it whose values are all numbers), in the page\'s order"""',
          "    cols = []", "    for r in rows:", "        for k in r:", "            if k not in cols:", "                cols.append(k)",
          "    if not cols:", "        return []",
          "    vc = next((c for c in cols[1:] if c != 'at' and rows and all(isinstance(num(r.get(c)), (int, float)) for r in rows)), None)",
          "    return [{'id': str(r.get(cols[0])), 'v': num(r.get(vc)) if vc else None} for r in rows]", "", ""]
    L += ["def page_rows(rows, title):", '    """the rows as a page: one line each, the columns side by side"""',
          "    cols = []", "    for r in rows:", "        for k in r:", "            if k not in cols:", "                cols.append(k)",
          "    head = ''.join('<th>%s</th>' % html.escape(str(c)) for c in cols)",
          "    body = ''.join('<tr data-id=\"%s\">%s</tr>' % (html.escape(str(r.get(cols[0]))), ''.join(",
          "                   '<td>%s</td>' % html.escape('' if r.get(c) is None else str(r.get(c))) for c in cols)) for r in rows)",
          "    stage = (STAGE[1] + STAGE[2].replace('__ROWS__', json.dumps(scene_records(rows)).replace('</', '<\\\\/'))) if STAGE else ''",
          "    record_json = json.dumps(rows, default=str).replace('<', '\\\\u003c')",
          "    return (DOC % html.escape(title) + HEAD + '<main><h1>%s</h1>' % html.escape(title) + stage +",
          "            '<table><tr>%s</tr>%s</table><script type=\"application/json\" id=\"oracle7-rows\">%s</script></main>' % (head, body, record_json))", "", "",
          "def serve(port, render):", '    """the page, served on loopback; made afresh on every visit"""',
          "    class H(http.server.BaseHTTPRequestHandler):", "        def do_GET(self):",
          "            b = render().encode()", "            self.send_response(200)",
          "            self.send_header('Content-Type', 'text/html; charset=utf-8')", "            self.end_headers()",
          "            self.wfile.write(b)", "", "        def log_message(self, *a):", "            pass", "",
          "    http.server.ThreadingHTTPServer(('127.0.0.1', port), H).serve_forever()", "", "",
          "def export(rows, path, columns=()):", '    """the rows written to a file; an empty CSV still declares its columns"""',
          "    cols = []", "    for r in rows:", "        for k in r:", "            if k not in cols:", "                cols.append(k)",
          "    if not cols:", "        cols = list(columns)",
          "    if path.endswith('.json'):", "        json.dump(rows, open(path, 'w'), indent=1, default=str)", "        return len(rows)",
          "    with open(path, 'w', newline='') as f:", "        w = csv.DictWriter(f, fieldnames=cols)", "        w.writeheader()",
          "        for r in rows:", "            w.writerow(r)", "    return len(rows)", "", ""]
    own_name = [w for w in project_noun(shape) if w not in ("page", "site", "website", "tool", "project", "app", "view")
                and w not in PART_WORDS["design"]]          # the look's words describe the page, they do not name it
    title = " ".join(w.capitalize() for w in (own_name or re.findall(r"[a-z]+", Path(world["file"]).stem.lower()) or
                                              [Path(mod).stem])).replace("_", " ")   # a generic noun names nothing: the table
    L += ["TITLE = %r" % title, "", "", "def main(argv):"]
    for n, p in pipes.items():
        outs = [r for r in reqs if r["id"] in p["outs"]]
        provider = pipes.get(p.get("from"), p)
        store_table = provider.get("store_table", "results") if p["source"] == "stored" else p.get("store_table", "results")
        input_shape = p.get("input") or default_input
        L.append("    if argv[:1] == [%r]:" % n)
        if p["source"] == "probe":
            pw = p.get("world") or world
            L.append("        rows = probe(table(%r), key=%r, url=%r)" % (input_shape, pw["key"], pw["url"]))
        elif p["source"] in ("table", "stored"):
            L.append("        rows = compute_%s()" % _compute_ident(n))
        else:
            L.append("        rows = stored(%r)" % store_table)
        for r in outs:
            if r["kind"] == "stored":
                L.append("        print('%%d rows kept in %%s' %% (keep(%s, %r), DB))" % (_rows_for(n, p, r["id"]), p.get("store_table", "results")))
        for r in outs:
            if r["kind"] == "file":
                src = "stored(%r)" % store_table if (r.get("every") and any(x["kind"] == "stored" for x in outs)) else _rows_for(n, p, r["id"])
                cols = (store_tables[store_table] if r.get("every") and any(x["kind"] == "stored" for x in outs) else
                        fields if p["source"] == "probe" or p.get("store_probe") else
                        out_columns(view(p, r["id"]), p.get("world") or world, derived))
                L.append("        print('%%d rows written to %%s' %% (export(%s, %r, %r), %r))" % (src, r["file"], cols, r["file"]))
        for r in outs:
            if r["kind"] == "printed":
                L.append("        for r in %s:" % _rows_for(n, p, r["id"]))
                L.append("            print('  '.join('%s %s' % (k, v) for k, v in r.items() if k != 'at'))")
        served = [r for r in outs if r["kind"] == "served"]
        if served:
            if p.get("interaction"):
                compute = "compute_%s" % _compute_ident(n, served[0]["id"] if (p.get("out_ops") or {}).get(served[0]["id"]) else None)
                L.append("        return serve_interactive(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_rows(%s(), TITLE), %r, %s)" % (compute, p["interaction"], compute))
            elif (p["source"] == "stored" and p.get("store_probe") and not p.get("ops") and
                    not p.get("derive") and not (p.get("out_ops") or {}).get(served[0]["id"])):
                pw = provider.get("world") or world
                L.append("        return serve(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_latest(%r, %r, %r))" % (
                    provider.get("input") or default_input, pw["key"], store_table))
            elif p["source"] in ("table", "stored"):
                L.append("        return serve(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_rows(compute_%s(), TITLE))"
                         % _compute_ident(n, served[0]["id"] if (p.get("out_ops") or {}).get(served[0]["id"]) else None))
            else:
                L.append("        return serve(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_rows(rows, TITLE))")
        L.append("        return 0")
    usage = " | ".join("%s %s%s" % (mod, n, "".join(" " + a for a in e["args"])) for n, e in shape["entries"].items())
    L += ["    print(%r)" % ("usage: " + usage), "    return 2", "", "",
          "if __name__ == '__main__':", "    sys.exit(main(sys.argv[1:]))", ""]
    return "\n".join(L)


def _ident(n):
    # Separate namespaces keep e.g. `report-a` distinct from `report_a`, even
    # when an ordinary command happens to contain an encoded-looking suffix.
    return "w_" + n if re.fullmatch(r"\w+", n) else "e_" + n.encode("utf-8").hex()


def _compute_ident(name, outcome=None):
    if outcome is None:
        return "entry_" + _ident(name)
    # Encoding each component makes a command named `report__r1` different
    # from the outcome r1 of report, with no separator ambiguity.
    return "outcome_" + name.encode("utf-8").hex() + "_" + outcome.encode("utf-8").hex()


def view(p, rid):
    """the pipe as one outcome sees it: the command's operations, then the ones that outcome asked for itself (C11)"""
    own = (p.get("out_ops") or {}).get(rid) if p else None
    return dict(p, ops=list(p["ops"]) + list(own)) if own else p


def _rows_for(n, p, rid):
    return "compute_%s()" % _compute_ident(n, rid) if (p.get("out_ops") or {}).get(rid) else "rows"


def out_columns(p, world, derived):
    ops = p.get("ops") or []
    g = next((o["col"] for o in ops if o["op"] == "group"), None)
    aggs = [o for o in ops if o["op"] == "agg"]
    if aggs:
        return ([g] if g else []) + [agg_name(o) for o in aggs]
    world = p.get("world") or world
    return list(dict.fromkeys(list((world or {}).get("cols", [])) +
                             [d["name"] for d in p.get("derive", []) if d["fn"] in derived] +
                             [o["col"] for o in ops if o["op"] == "calculate"]))


def _emit_compute(n, p, derived, rows_expr=None, outcome=None):
    """the operations, in the order a reader would do them: values made, rows kept, grouped and summed, sorted, cut"""
    if rows_expr is None:
        rows_expr = "table(%r)" % p["input"] if p.get("input") else "table()"
    L = ["def compute_%s():" % _compute_ident(n, outcome), '    """%s"""' % ("; ".join(_op_text(o) for o in p["ops"]) or "the rows as they are"),
         "    rows = " + rows_expr]
    for d in p.get("derive", []):
        f = derived.get(d["fn"])
        if f:
            L += ["    for r in rows:", "        r[%r] = %s(num(r[%r]))" % (d["name"], f["fn"], d["col"])]
    for o in p["ops"]:
        if o["op"] == "calculate":
            if o.get("fn") not in ("mul", "add", "sub", "div"):
                raise ValueError("calculation part %r is not represented" % o.get("fn"))
            L += ["    for r in rows:", "        factors = [num(r[%r]), num(r[%r])]" % (o["left"], o["right"]),
                  "        if any(isinstance(v, bool) or not isinstance(v, (int, float)) or (isinstance(v, float) and not _source_math.isfinite(v)) for v in factors):",
                  "            raise ValueError(%r)" % ("%s requires finite numeric values in %s and %s" % (o["col"], o["left"], o["right"])),
                  "        if %r == 'div' and factors[1] == 0:" % o.get("fn"),
                  "            raise ValueError(%r)" % ("%s divides by a zero %s" % (o["col"], o["right"])),
                  "        value = %s" % {"mul": "factors[0] * factors[1]", "add": "factors[0] + factors[1]",
                                         "sub": "factors[0] - factors[1]", "div": "factors[0] / factors[1]"}[o.get("fn", "mul")],
                  "        if isinstance(value, float) and not _source_math.isfinite(value):",
                  "            raise ValueError(%r)" % ("%s exceeds the finite numeric range" % o["col"]),
                  "        r[%r] = value" % o["col"]]
    for o in p["ops"]:
        if o["op"] == "filter":
            L.append("    rows = [r for r in rows if _cmp(num(r[%r]), %r, %r)]" % (o["col"], o["cmp"], o["val"]))
    g = next((o["col"] for o in p["ops"] if o["op"] == "group"), None)
    aggs = [o for o in p["ops"] if o["op"] == "agg"]
    if aggs:
        L += ["    groups = {}", "    for r in rows:",
              "        groups.setdefault(%s, []).append(r)" % ("r[%r]" % g if g else "None"), "    out = []",
              "    for k, rs in groups.items():", "        o = {%s}" % ("%r: k" % g if g else "")]
        for o in aggs:
            nm = agg_name(o)
            if o["fn"] == "count":
                L.append("        o[%r] = len(rs)" % nm)
            else:
                vals = "[num(r[%r]) for r in rs]" % o["col"]
                L.append("        o[%r] = %s" % (nm, {"sum": "round(sum(%s), 10)" % vals, "mean": "round(sum(%s) / len(rs), 10)" % vals,
                                                       "max": "max(%s)" % vals, "min": "min(%s)" % vals}[o["fn"]]))
        L += ["        out.append(o)", "    rows = out"]
    for o in p["ops"]:
        if o["op"] == "sort":
            col = sort_col(o, p, aggs)
            if col:
                L.append("    rows.sort(key=lambda r: num(r[%r]), reverse=%r)" % (col, o["desc"]))
    for o in p["ops"]:
        if o["op"] == "top":
            L.append("    rows = rows[:%d]" % o["n"])
    L += ["    return rows", "", "",
          "def _cmp(a, op, b):", "    if isinstance(a, str) or isinstance(b, str):", "        a, b = str(a).lower(), str(b).lower()",
          "    return {'==': a == b, '>': a > b, '<': a < b, '>=': a >= b, '<=': a <= b}[op]", "", ""]
    return L


def _emit_probe(st):
    L = ["def probe(rows, key=KEY, url=URL):",
         '    """each url asked once; no answer within TIMEOUT s%s is down, and the others go on"""' % (
             ", or an error status," if st["error_down"] else ""),
         "    out = []", "    for r in rows:",
         "        t0 = time.time()", "        res = {'key': r[key], 'url': r[url], 'at': time.strftime('%Y-%m-%d %H:%M:%S'),",
         "               'status': 'down', 'code': None, 'error': None}",
         "        try:", "            with urllib.request.urlopen(r[url], timeout=TIMEOUT) as a:",
         "                res['code'] = a.status", "                res['status'] = 'up'",
         "        except urllib.error.HTTPError as e:", "            res['code'] = e.code",
         "            res['error'] = 'HTTP %d' % e.code" if st["error_down"] else
         "            res['status'], res['error'] = 'up', 'HTTP %d' % e.code",
         "        except Exception as e:  # noqa: BLE001  (no answer in time, refused, unreachable)",
         "            res['error'] = type(e).__name__ + ': ' + str(e)[:120]"]
    if st["ms"]:
        L += ["        if res['status'] == 'up':", "            res['ms'] = round((time.time() - t0) * 1000)",
              "        else:", "            res['ms'] = None"]
    L += ["        out.append(res)", "    return out", "", ""]
    return L


def _emit_latest_page(st):
    shown = ["status", "at"] + (["ms"] if st["ms"] else []) + ["code", "error"]
    heads = ["current", "previous"] if st["keep_last"] == 2 else ["result %d" % (i + 1) for i in range(st["keep_last"])]
    return ["def latest(source=None, key=KEY, store='results'):", '    """each server\'s last KEEP_LAST results, newest first, in its source\'s order"""',
            "    c = connect(store)", "    fs = STORE_FIELDS[store]", "    out = []", "    for r in table(source):",
            "        rows = c.execute('select %s from %s where key = ? order by rowid desc limit ?' % (', '.join(_qid(f) for f in fs), _qid(store)),",
            "                         (r[key], KEEP_LAST)).fetchall()",
            "        out.append((r[key], [dict(zip(fs, x)) for x in rows]))", "    c.close()", "    return out", "", "",
            "SHOWN = %r" % shown, "HEADS = %r" % heads, "", "",
            "def page_latest(source=None, key=KEY, store='results'):", '    """the page: one row per server, its results side by side"""',
            "    def cell(x):", "        if x is None:", "            return '<td>-</td>'",
            "        return '<td class=\"%s\">' % html.escape(str(x['status'])) + '<br>'.join(",
            "            html.escape('%s: %s' % (f, '' if x.get(f) is None else x.get(f))) for f in SHOWN) + '</td>'",
            "    body = ''.join('<tr><th>%s</th>%s</tr>' % (html.escape(str(k)), ''.join(cell(rs[i] if i < len(rs) else None)",
            "                   for i in range(len(HEADS)))) for k, rs in latest(source, key, store))",
            "    return (DOC % 'Service health' + HEAD + '<main><h1>Service health</h1><table><tr><th>server</th>%s</tr>%s'",
            "            '</table></main>' % (''.join('<th>%s</th>' % h for h in HEADS), body))", "", ""]


# ---------------------------------------------------------------- the rows the request asks for, read independently
def expected_rows(root, world, p, derived, initial_rows=None):
    """what a reader of the request would compute from the table: the judge's own reading, not the written code's"""
    from judge.project_sources_judge import expected_source_rows
    if initial_rows is None:
        source = p.get("input") or {"op": "read", "file": (p.get("world") or world)["file"]}
        rows = expected_source_rows(root, source)
    else:
        rows = [dict(row) for row in initial_rows]
    for d in p.get("derive", []):
        f = derived.get(d["fn"])
        ns = {}
        for i in f.get("imports") or []:
            ns[i.split(".")[0]] = __import__(i)
        for dep in f.get("deps") or []:
            exec(compile(dep["source"], "judge:" + dep["name"], "exec"), ns)
        exec(compile(f["source"], "judge:" + f["fn"], "exec"), ns)
        for r in rows:
            r[d["name"]] = ns[f["fn"]](num(r[d["col"]]))
    for o in p["ops"]:
        if o["op"] == "calculate":
            if o.get("fn") not in ("mul", "add", "sub", "div"):
                raise ValueError("the judge does not know calculation %s" % o.get("fn"))
            for r in rows:                        # the judge's own arithmetic, read from the operation's name
                a, b = num(r[o["left"]]), num(r[o["right"]])
                if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
                    raise ValueError("%s requires numeric %s and %s" % (o["col"], o["left"], o["right"]))
                if o["fn"] == "div" and b == 0:
                    raise ValueError("%s divides by a zero %s" % (o["col"], o["right"]))
                r[o["col"]] = {"mul": lambda: a * b, "add": lambda: a + b, "sub": lambda: a - b, "div": lambda: a / b}[o["fn"]]()
    for o in p["ops"]:
        if o["op"] == "filter":
            def ok(r, o=o):
                a, b = num(r[o["col"]]), o["val"]
                if isinstance(a, str) or isinstance(b, str):
                    a, b = str(a).lower(), str(b).lower()
                return {"==": a == b, ">": a > b, "<": a < b, ">=": a >= b, "<=": a <= b}[o["cmp"]]
            rows = [r for r in rows if ok(r)]
    g = next((o["col"] for o in p["ops"] if o["op"] == "group"), None)
    aggs = [o for o in p["ops"] if o["op"] == "agg"]
    if aggs:
        keys = []
        for r in rows:
            k = r[g] if g else None
            if k not in keys:
                keys.append(k)
        out = []
        for k in keys:
            rs = [r for r in rows if (r[g] if g else None) == k]
            o = {g: k} if g else {}
            for a in aggs:
                vals = [num(r[a["col"]]) for r in rs] if a["col"] else []
                o[agg_name(a)] = {"count": len(rs), "sum": sum(vals) if vals else 0, "mean": (sum(vals) / len(vals)) if vals else 0,
                                  "max": max(vals) if vals else None, "min": min(vals) if vals else None}[a["fn"]]
            out.append(o)
        rows = out
    for o in p["ops"]:
        if o["op"] == "sort":
            col = sort_col(o, p, aggs)
            if col:
                rows = sorted(rows, key=lambda r: num(r[col]), reverse=o["desc"])
    for o in p["ops"]:
        if o["op"] == "top":
            rows = rows[:o["n"]]
    return rows


def _scene_records(rows):
    """the judge's own reading of which record each scene object should be (the contract the page's scene_records keeps)"""
    cols = []
    for r in rows:
        for k in r:
            if k not in cols:
                cols.append(k)
    if not cols:
        return []
    vc = next((c for c in cols[1:] if c != "at" and rows and all(isinstance(num(r.get(c)), (int, float)) for r in rows)), None)
    return [{"id": str(r.get(cols[0])), "v": num(r.get(vc)) if vc else None} for r in rows]


def _same(a, b):
    a, b = num(a), num(b)
    if isinstance(a, (int, float)) and isinstance(b, (int, float)):
        return abs(a - b) <= 1e-6 * max(1.0, abs(a), abs(b))
    return str(a) == str(b)


def rows_match(got, want):
    """the rows read back give the rows asked for: same number, and each asked row's values among the row read back"""
    if len(got) != len(want):
        return False, "%d rows, want %d" % (len(got), len(want))
    for i, (g, w) in enumerate(zip(got, want)):
        for k, v in w.items():
            if k not in g:
                return False, "row %d has no column %s" % (i + 1, k)
            # A source's textual identifiers retain their spelling: 001 is not 1.
            same = str(g[k]) == v if isinstance(v, str) else (g[k] in (None, "") if v is None else _same(g[k], v))
            if not same:
                return False, "row %d: %s is %s, want %s" % (i + 1, k, g[k], v)
    return True, "%d rows, every value as asked" % len(want)


def _page_rows_match(page, want):
    """Read visible table cells together; a city somewhere on a page cannot prove its order's city."""
    candidates = []
    for table in re.findall(r"<table\b[^>]*>(.*?)</table\s*>", page, re.I | re.S):
        columns, rows = [], []
        for line in re.findall(r"<tr\b[^>]*>(.*?)</tr\s*>", table, re.I | re.S):
            heads = re.findall(r"<th\b[^>]*>(.*?)</th\s*>", line, re.I | re.S)
            cells = re.findall(r"<td\b[^>]*>(.*?)</td\s*>", line, re.I | re.S)
            clean = lambda value: html_unescape(re.sub(r"<[^>]+>", "", value))
            if heads and not cells:
                columns = [clean(value) for value in heads]
            elif cells:
                if len(cells) != len(columns):
                    return False, "the page has a row with different columns from its header"
                rows.append(dict(zip(columns, [clean(value) for value in cells])))
        if not want or all(column in columns for column in want[0]):
            candidates.append(rows_match(rows, want))
    return next((result for result in candidates if result[0]),
                candidates[0] if candidates else (False, "the page has no table with the requested columns"))


# ---------------------------------------------------------------- judges: every requirement against what happened
def _free_port():
    s = socket.socket()
    s.bind(("127.0.0.1", 0))
    p = s.getsockname()[1]
    s.close()
    return p


def _db_rows(db, table="results"):
    if not db.exists():
        return []
    try:
        c = sqlite3.connect(str(db))
        try:
            quoted = '"' + table.replace('"', '""') + '"'
            cols = [r[1] for r in c.execute("pragma table_info(%s)" % quoted)]
            return [dict(zip(cols, x)) for x in c.execute("select * from %s order by rowid" % quoted)]
        finally:
            c.close()
    except sqlite3.Error:
        return []


def _db_has_table(db, table="results"):
    if not db.is_file():
        return False
    try:
        c = sqlite3.connect(str(db))
        try:
            return c.execute("select 1 from sqlite_master where type='table' and name=?", (table,)).fetchone() is not None
        finally:
            c.close()
    except sqlite3.Error:
        return False


def _read_file(path):
    if not path.is_file():
        return None
    try:
        if path.suffix == ".json":
            v = json.loads(path.read_text(encoding="utf-8"))
            return v if isinstance(v, list) else [v]
        if path.suffix == ".csv":
            return list(csv.DictReader(path.read_text(encoding="utf-8").splitlines()))
        return [{"text": ln} for ln in path.read_text(encoding="utf-8").splitlines()]
    except (ValueError, OSError):
        return None


def _judge_order(pipes, serve_names):
    """Run each command once, after the stored command it reads, with servers otherwise last."""
    ordered, visiting, done = [], [], set()

    def visit(name):
        if name in done:
            return
        if name in visiting:
            cycle = visiting[visiting.index(name):] + [name]
            raise ValueError("stored command dependency cycle: " + " -> ".join(cycle))
        if name not in pipes:
            raise ValueError("stored command dependency names an unknown provider: %s" % name)
        visiting.append(name)
        provider = pipes[name].get("from")
        if provider:
            visit(provider)
        visiting.pop()
        done.add(name)
        ordered.append(name)

    for name in [n for n in pipes if n not in serve_names] + list(serve_names):
        visit(name)
    return ordered


def judge(root, shape, pipes, reqs, world, runenv=None):
    """each entry run as the request names it (batch entries first), every outcome read back, every requirement given

    its verdict. -> (passed, lines, holes); reqs carry their status and evidence"""
    root = Path(root)
    if runenv is None:                              # round-3 R2: the project's entries run in the run jail
        import runjail
        runenv = runjail.env(root=root)
    mod = shape["module"]
    st = settings(reqs)
    derived = shape.get("derived") or {}
    db = root / (Path(mod).stem + ".db")
    live = {r["id"]: r for r in reqs if r["status"] != "dropped"}
    seen = {}
    lines = []
    names = list(pipes)
    excl_before = {r["file"]: ((root / r["file"]).stat().st_mtime if (root / r["file"]).is_file() else None)
                   for r in live.values() if r["kind"] == "excluded" and r.get("file") and r["file"] != "*"}
    files_at_start = {p.name: p.stat().st_mtime for p in root.iterdir() if p.is_file()}
    db_before = db.is_file()
    serve_names = [n for n in names if "PORT" in shape["entries"][n]["args"]]
    try:
        run_names = _judge_order(pipes, serve_names)
    except ValueError as exc:
        message = str(exc)
        for requirement in live.values():
            requirement["status"] = "failed"
            requirement["evidence"] = message
        return False, lines, [message]
    for n in run_names:
        p = pipes[n]
        pw = p.get("world") or world or {}
        if n in serve_names:
            port = _free_port()
            sp = subprocess.Popen([sys.executable, mod, n, str(port)], cwd=str(root), stdout=subprocess.DEVNULL,
                                  stderr=subprocess.PIPE, text=True, env=runenv)
            page = None
            last_error = ""
            for _ in range(40):
                try:
                    with urllib.request.urlopen("http://127.0.0.1:%d/" % port, timeout=5) as response:
                        page = response.read().decode("utf-8", "replace")
                    break
                except Exception as exc:  # noqa: BLE001
                    last_error = str(exc)
                    if sp.poll() is not None:
                        break
                    time.sleep(0.3)
            err = ""
            sp.terminate()
            try:
                _o, err = sp.communicate(timeout=5)
            except subprocess.TimeoutExpired:
                sp.kill()
                _o, err = sp.communicate(timeout=5)
            if page is None and not err:
                err = last_error
            seen[n] = {"page": page, "err": (err or "")[-300:]}
            lines.append("`python3 %s %s PORT` %s" % (mod, n, "served a page on loopback" if page is not None else
                                                     "served no page: " + (err or "")[-160:]))
            continue
        table = p.get("store_table") or pipes.get(p.get("from"), {}).get("store_table") or "results"
        before = _db_rows(db, table)
        files_before = {r["file"]: (root / r["file"]).stat().st_mtime if (root / r["file"]).is_file() else None
                        for r in live.values() if r["kind"] == "file" and r["entry"] == n}
        t0 = time.time()
        try:
            r = subprocess.run([sys.executable, mod, n], cwd=str(root), capture_output=True, text=True, env=runenv,
                               timeout=60 + st["timeout"] * max(1, pw.get("n", 1)))
            rc, out = r.returncode, (r.stdout + r.stderr)
        except subprocess.TimeoutExpired:
            rc, out = None, "ran past its time"
        took = time.time() - t0
        after = _db_rows(db, table)
        seen[n] = {"rc": rc, "out": out, "took": took, "before": before, "added": after[len(before):], "all": after,
                   "table": table, "table_exists": _db_has_table(db, table), "files_before": files_before}
        lines.append("`python3 %s %s` ran in %.1f s, exit %s" % (mod, n, took, rc))
    # each requirement
    for rid, r in live.items():
        k = r["kind"]
        ev, ok = "", None
        p = pipes.get(r["entry"]) if r.get("entry") in pipes else None
        pw = (p.get("world") if p else None) or world or {}
        want_rows = None
        if k in ("stored", "file", "served", "printed") and p:
            try:
                if p["source"] == "table":
                    want_rows = expected_rows(root, pw, view(p, rid), derived)
                elif p["source"] == "stored" and p.get("from") in pipes:
                    producer = pipes[p["from"]]
                    if producer["source"] == "table":
                        stored_rid = next((item["id"] for item in live.values()
                                           if item["entry"] == p["from"] and item["kind"] == "stored"), None)
                        stored_rows = list((seen.get(p["from"]) or {}).get("before", [])) + expected_rows(
                            root, producer.get("world") or world, view(producer, stored_rid), derived)
                        want_rows = expected_rows(root, pw, view(p, rid), derived, initial_rows=stored_rows)
                    elif view(p, rid).get("ops"):
                        want_rows = expected_rows(root, pw, view(p, rid), derived,
                                                  initial_rows=(seen.get(p["from"]) or {}).get("all", []))
            except (ValueError, KeyError, TypeError, OSError) as exc:
                r["status"], r["evidence"] = "failed", "the independent source judge could not resolve the input: %s" % exc
                continue
        if k == "context":
            ok, ev = True, "read"
        elif k in ("unread",):
            ok, ev = False, "not read"
        elif k == "excluded":                            # what the request rules out was not done
            w = r.get("what")
            if w == "file" and r["file"] == "*":       # no file at all: nothing new or rewritten beside the program
                made = sorted(p.name for p in root.iterdir() if p.is_file() and p.name != mod and
                              files_at_start.get(p.name) != p.stat().st_mtime)
                ok = not made
                ev = "no file written, as asked" if ok else "files written though the request ruled it out: %s" % \
                    ", ".join(made[:5])
            elif w == "file":
                f = root / r["file"]
                now = f.stat().st_mtime if f.is_file() else None
                ok = now == excl_before.get(r["file"])
                ev = "%s %s" % (r["file"], "not written, as asked" if ok else "was written, though the request ruled it out")
            elif w == "stored":
                ok = db_before or not db.is_file()
                ev = "no database made, as asked" if ok else "%s was made, though the request ruled out a database" % db.name
            elif w == "served":
                ok = not serve_names
                ev = "no page served, as asked" if ok else "a page is served, though the request ruled it out"
            else:
                outs = [x.get("out", "") for x in seen.values() if "out" in x]
                ok = not any((o or "").strip() for o in outs)
                ev = "nothing printed, as asked" if ok else "lines were printed, though the request ruled it out"
        elif k == "stored":
            s = seen.get(r["entry"]) or {}
            got = len(s.get("added", []))
            if want_rows is not None:
                match, details = rows_match(s.get("all", []), s.get("before", []) + want_rows)
                ok = s.get("rc") == 0 and s.get("table_exists", False) and match
                ev = "%s, table %s: %s; %d new rows" % (db.name, s.get("table", "results"), details, got)
            else:
                want = pw.get("n", 0) if p and p["source"] == "probe" else None
                ok = s.get("rc") == 0 and got > 0 and (want is None or got == want)
                ev = "%d rows kept in %s by one run (want %s)" % (got, db.name, want)
        elif k == "file":
            s = seen.get(r["entry"]) or {}
            path = root / r["file"]
            rows = _read_file(path)
            fresh = path.is_file() and path.stat().st_mtime != (s.get("files_before") or {}).get(r["file"])
            if rows is None or not fresh or s.get("rc") != 0:
                ok, ev = False, "%s was not written by `%s`" % (r["file"], r["entry"])
            elif want_rows is not None:
                expected = s.get("before", []) + want_rows if r.get("every") and any(
                    item["kind"] == "stored" and item["entry"] == r["entry"] for item in live.values()) else want_rows
                ok, ev = rows_match(rows, expected)
                ev = "%s: %s" % (r["file"], ev)
            elif r.get("every"):
                ok = len(rows) == len(s.get("all", [])) and len(rows) > 0
                ev = "%s holds %d rows; the database holds %d" % (r["file"], len(rows), len(s.get("all", [])))
            else:
                want = pw.get("n", 0)
                ok = len(rows) == want
                ev = "%s holds %d rows (want %d)" % (r["file"], len(rows), want)
        elif k == "served":
            s = seen.get(r["entry"]) or {}
            page = s.get("page")
            if page is None:
                ok, ev = False, "no page: %s" % s.get("err", "")
            elif not judge_look(page, {})[0]:
                ok, ev = False, "the page is not made from the design family's tokens: " + judge_look(page, {})[1]
            elif want_rows is not None:
                want = want_rows
                ok, ev = _page_rows_match(page, want)
                ev = "the page: " + ev
                mR = re.search(r"const R = (\[.*?\]), N = R\.length", page, re.S)
                if mR:                                   # C12: the scene's objects are the records asked, with their values
                    try:
                        got_r = json.loads(mR.group(1).replace("<\\/", "</"))
                    except ValueError:
                        got_r = None
                    want_r = _scene_records(want)
                    bad = "unreadable" if got_r is None else next((
                        "object %d is record %s, want %s" % (i + 1, g.get("id"), w["id"]) if str(g.get("id")) != w["id"] else
                        "record %s has value %s, want %s" % (w["id"], g.get("v"), w["v"])
                        for i, (g, w) in enumerate(zip(got_r, want_r))
                        if str(g.get("id")) != w["id"] or (w["v"] is not None and not _same(g.get("v"), w["v"]))), None)
                    if bad is None and len(got_r) != len(want_r):
                        bad = "%d objects for %d records" % (len(got_r), len(want_r))
                    ok = ok and bad is None
                    ev += "; the scene's objects: %s" % ("each bound to its record and value" if bad is None else bad)
            else:
                names = [str(x[pw["key"]]) for x in load_rows(root, pw["file"])] if pw.get("key") and pw.get("file") else []
                miss = [x for x in names if x not in page]
                ok = not miss and bool(names)
                ev = "the page names %d of the %d rows of %s" % (len(names) - len(miss), len(names), pw.get("file"))
        elif k == "printed":
            s = seen.get(r["entry"]) or {}
            want = want_rows if want_rows is not None else []
            miss = [str(v) for w in want for v in w.values() if not _on_page(v, s.get("out", ""))]
            ok = s.get("rc") == 0 and not miss
            ev = "printed %d lines; %s" % (len((s.get("out") or "").splitlines()), "every value as asked" if not miss else
                                          "missing: " + ", ".join(miss[:5]))
        elif k == "interaction":
            from judge.project_interactive_judge import check_interaction
            served = next((item["id"] for item in live.values()
                           if item["kind"] == "served" and item["entry"] == r["entry"]), None)
            if p is None or not p.get("interaction"):
                ok, ev = False, "the requested record actions have no source binding"
            else:
                ok, ev = check_interaction(root, shape, dict(view(p, served), entry=r["entry"]), runenv)
        elif k in ("op", "derive"):
            carriers = [x for x in live.values() if x["kind"] in ("file", "served", "printed", "stored") and
                        (r["entry"] in ("*", None) or x["entry"] == r["entry"]) and (not r.get("out") or x["id"] == r["out"])]
            r["_carriers"] = [x["id"] for x in carriers]
            ok, ev = None, "judged in " + ", ".join(x["id"] for x in carriers)
        elif k == "look":
            pages = [(n, x.get("page")) for n, x in seen.items() if x.get("page")]
            res = [judge_look(pg, r) for _n, pg in pages]
            ok = bool(res) and all(x[0] for x in res)
            ev = "; ".join(x[1] for x in res) or "no page to look at"
        elif k in ("timeout", "error_down", "ms", "timestamp", "keep_last"):
            ok, ev = _judge_prop(r, seen, pipes, world, st)
        r["status"] = "passed" if ok else ("failed" if ok is False else r["status"])
        r["evidence"] = ev
    for r in live.values():                            # an operation passes when every outcome carrying it passed
        if r["kind"] in ("op", "derive"):
            cs = [live[c] for c in r.get("_carriers", []) if c in live]
            r["status"] = "passed" if cs and all(c["status"] == "passed" for c in cs) else "failed"
            r["evidence"] = ("carried by %s" % ", ".join(c["id"] for c in cs)) if cs else "no outcome carries it"
            r.pop("_carriers", None)
    holes = ["%s (%s): %s" % (r["id"], r["kind"], r.get("evidence", "")) for r in live.values()
             if r["status"] not in ("passed",)]
    return not holes, lines, holes


def _on_page(v, page):
    s = str(v)
    if s in page:
        return True
    n = num(v)
    if isinstance(n, float):
        for f in ("%g" % n, "%.2f" % n, "%.1f" % n, str(round(n, 6))):
            if f in page:
                return True
    return False


def _judge_prop(r, seen, pipes, world, st):
    probes = [n for n, p in pipes.items() if p["source"] == "probe"]
    added = [x for n in probes for x in (seen.get(n) or {}).get("added", [])]
    pages = [s.get("page") for s in seen.values() if s.get("page")]
    k = r["kind"]
    if k == "timeout":
        took = max([(seen.get(n) or {}).get("took", 0) for n in probes] or [0])
        n = (world or {}).get("n", 1)
        ok = bool(probes) and bool(added) and took <= r["seconds"] * n + 30 and all(x.get("status") in ("up", "down") for x in added)
        return ok, "the check took %.1f s for %d servers (each given %g s); every row up or down" % (took, n, r["seconds"])
    if k == "error_down":
        bad = [x for x in added if (x.get("code") or 0) >= 400 and x.get("status") != "down"]
        return bool(added) and not bad, "%d rows; an error status recorded as down for every one (%d not)" % (len(added), len(bad))
    if k == "ms":
        nums = [x.get("ms") for x in added if x.get("status") == "up"]
        kept = bool(nums) and all(isinstance(v, (int, float)) for v in nums)
        shown = not pages or all(any(str(v) in pg for v in nums) for pg in pages)
        return kept and shown, "milliseconds kept for %d up rows: %s; shown on the page: %s" % (len(nums), kept, shown)
    if k == "timestamp":
        rows = added or [x for s in seen.values() for x in s.get("added", [])]
        return bool(rows) and all(x.get("at") for x in rows), "every kept row has its time: %s" % bool(rows)
    if k == "keep_last":
        ok = all(("previous" in pg or "result 2" in pg) for pg in pages) if pages else True
        return ok, "the page has a column for each of the last %d results: %s" % (r["n"], ok)
    return None, ""


# ---------------------------------------------------------------- the ledger, kept with the project
def ledger_lines(reqs):
    out = []
    for r in reqs:
        if r["kind"] == "context":
            continue
        if r.get("merged_into"):
            out.append("%s the same outcome as %s (\"%s\")" % (r["id"], r["merged_into"], r["from"][0][:80]))
            continue
        what = {"file": "writes %s" % r.get("file"), "stored": "keeps rows in a database", "served": "a page in the browser",
                "printed": "prints the rows", "op": _op_text(r["op"]) if r.get("op") else "", "derive": "%s made from %s" % (
                    r.get("name"), r.get("col")), "timeout": "no answer within %g s is down" % r.get("seconds", 0),
                "error_down": "an error status is down", "ms": "time to answer in milliseconds",
                "timestamp": "each row with its time", "keep_last": "the last %d results shown" % r.get("n", 1),
                "unread": "words not read: %s" % ", ".join(r.get("words", [])),
                "interaction": "record edits and relationships through the page",
                "look": "the look asked: %s" % ", ".join(r.get("words", [])),
                "excluded": "not done, as asked: %s" % {"file": ("no file written" if r.get("file") == "*" else "no %s written" % r.get("file")), "stored": "no database",
                                                         "served": "no page", "printed": "nothing printed"}.get(
                    r.get("what"), r.get("what"))}.get(r["kind"], r["kind"])
        if r.get("superseded"):
            what += " (was %s)" % ", ".join("%s %s" % (k, v) for old in r["superseded"] for k, v in old.items())
        if r.get("out"):
            what += " (for %s only)" % r["out"]
        if r.get("dropped_with"):
            what += " (went with %s)" % r["dropped_with"]
        out.append("%s %s%s - %s%s" % (r["id"], what, (" (`%s`)" % r["entry"]) if r.get("entry") not in (None, "*") else "",
                                       r["status"], (": " + r["evidence"]) if r.get("evidence") else ""))
    return out


# ---------------------------------------------------------------- the look: Oracle7's design family (workbench/design)
_DESIGN = {}


def _design():
    if not _DESIGN:
        import importlib.util
        d = Path(__file__).resolve().parent / "design"
        for n in ("palette", "type", "layout", "motion", "scene"):
            spec = importlib.util.spec_from_file_location("o7design_" + n, str(d / ("organ_%s.py" % n)))
            m = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(m)
            _DESIGN[n] = m
    return _DESIGN


def read_look(sentence):
    """the look a sentence asks of its page: a colour (a W3C colour name or a hex), tone words, dark. None when it asks none"""
    D = _design()
    low = sentence.lower()
    words = re.findall(r"[a-z]+", DATA.sub(" ", low))
    seed = next((w for w in words if w in D["palette"].NAMES and w not in ("white", "black")), None)
    m = re.search(r"#[0-9a-f]{6}\b", low)
    if m:
        seed = m.group(0)
    tones = [w for w in words if w in D["type"].TONES]
    dark = bool(re.search(r"\bdark\b", low))
    scene = None
    if re.search(r"\b3-?d\b|\bthree[- ]?d(?:imensional)?\b|\bthree\.?js\b|\bin three dimensions\b|\bscene\b", low):
        sw_ = getattr(D["scene"], "SHAPE_WORDS", {g: (g,) for g in D["scene"].GEOM})
        hit = next(((g, w) for w in words for g, names in sw_.items() if any(wmatch(w, n) for n in names)), None)
        shape, shape_word = hit if hit else ("box", None)
        scene = {"shape": shape, "camera": "static" if re.search(r"\bstill\b|\bstatic\b", low) else "orbit",
                 "light": next((w for w in words if w in D["scene"].RIGS), "daylight")}
    if not (seed or tones or dark or scene):
        return None
    sw = ([w for w in words if w in ("scene", "three", "dimensions", "dimensional", "camera", "orbit", "orbiting", "still", "static",
                                     scene["light"]) or wmatch(w, scene["shape"]) or (shape_word and wmatch(w, shape_word))] + (["3d"] if re.search(r"\b3-?d\b", low) else [])
          if scene else [])
    return {"seed": seed, "tone": tones, "dark": dark, "scene": scene,
            "words": [w for w in [seed] + tones + (["dark"] if dark else []) if w] + sw}


def design_for(looks):
    """the design family's answer for a project's pages: palette, type, layout and motion, each from its specialist"""
    D = _design()
    seed = next((l["seed"] for l in looks if l.get("seed")), None) or "slategray"
    tones = [t for l in looks for t in l.get("tone", [])] or ["clean"]
    dark = any(l.get("dark") for l in looks)
    pal = D["palette"].ask({"seed": seed, "modes": ["dark"] if dark else ["light", "dark"], "series": 0})
    typ = D["type"].ask({"tone": tones, "use": "site"})
    if typ.get("status") != "answered":
        typ = D["type"].ask({"tone": ["clean"], "use": "site"})
    lay = D["layout"].ask({"sections": ["table"], "widths": [375, 768, 1440], "body_size": typ.get("body_size", 18)})
    mot = D["motion"].ask({"changes": ["enter", "hover"], "tone": "calm" if "calm" in tones or "quiet" in tones else ""})
    cat = D["type"].catalogue()
    gen = lambda fam: "serif" if (cat.get(fam) or {}).get("category") in ("Serif", "Display") else "sans-serif"
    sc = next((l["scene"] for l in looks if l.get("scene")), None)
    stage = None
    if sc:                                          # the scene specialist: one object per row, on the palette's colours
        lp = D["palette"].ask({"seed": seed, "modes": ["light"], "series": 2})["modes"]["light"]
        stage = D["scene"].stage(sc["shape"], sc["light"], sc["camera"], lp)
    return {"seed": seed, "tone": tones, "dark_only": dark, "palette": pal, "type": typ, "layout": lay, "motion": mot,
            "generic": {"display": gen(typ.get("display")), "body": gen(typ.get("body"))}, "scene": sc,
            "stage": list(stage) if stage else None}


def design_head(dz):
    """the <link> and <style> a page carries: the design family's tokens as CSS custom properties"""
    if not dz or dz["palette"].get("status") != "answered":
        return "<style>body{font:16px/1.5 system-ui;margin:0 16px}</style>", "not asked"
    modes = dz["palette"]["modes"]
    t, lay, mot = dz["type"], dz["layout"], dz["motion"]

    def vars_(m):
        return ";".join("--%s:%s" % (k, m[k]) for k in ("background", "foreground", "muted", "border", "primary", "accent"))
    first = modes.get("light") or modes.get("dark")
    css = [":root{%s;--font-display:'%s',%s;--font-body:'%s',%s}" % (vars_(first), t["display"], dz["generic"]["display"],
                                                                     t["body"], dz["generic"]["body"])]
    if "light" in modes and "dark" in modes:
        css.append("@media (prefers-color-scheme: dark){:root{%s}}" % vars_(modes["dark"]))
    sz = t["sizes"]
    g = lay["grids"]
    wide = g[max(g, key=int)]
    css += ["*{box-sizing:border-box}",
            "body{margin:0;background:var(--background);color:var(--foreground);font:400 %dpx/%s var(--font-body)}" % (
                t["body_size"], t["line_height"]),
            "main{max-width:%dpx;margin:0 auto;padding:%dpx %dpx}" % (lay["max_width"], g["375"]["margin"] * 2,
                                                                      g["375"]["margin"]),
            "@media (min-width:600px){main{padding:%dpx %dpx}}" % (g["768"]["margin"] * 2, g["768"]["margin"]),
            "@media (min-width:1024px){main{padding:%dpx %dpx}}" % (wide["margin"] and 64, 32),
            "h1{font:%d %dpx/%s var(--font-display);margin:0 0 %dpx;color:var(--foreground)}" % (
                t["weights"]["display"][0], sz[min(4, len(sz) - 1)], t["display_line_height"], sz[1]),
            "table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}",
            "th{text-align:left;color:var(--muted);font-weight:%d;border-bottom:2px solid var(--border);padding:12px 16px}" % (
                t["weights"]["body"][-1]),
            "td{border-bottom:1px solid var(--border);padding:12px 16px;vertical-align:top}",
            "a{color:var(--primary)}",
            ".up{box-shadow:inset 4px 0 0 var(--primary)}.down{box-shadow:inset 4px 0 0 var(--accent)}",
            "td{transition:filter %dms %s}tr:hover td{filter:brightness(0.96)}" % (
                mot["kinds"]["hover"]["duration_ms"], mot["kinds"]["hover"]["easing"]),
            "main{animation:o7in %dms %s both}@keyframes o7in{from{opacity:0;transform:translateY(8px)}to{opacity:1;"
            "transform:none}}" % (mot["kinds"]["enter"]["duration_ms"], mot["kinds"]["enter"]["easing"]),
            mot["reduced_motion"]["css"]]
    fam = lambda f, ws: "family=%s:wght@%s" % (f.replace(" ", "+"), ";".join(str(w) for w in sorted(set(ws))))
    link = ('<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="stylesheet" href="https://fonts.googleapis.com/'
            'css2?%s&%s&display=swap">' % (fam(t["display"], t["weights"]["display"]), fam(t["body"], t["weights"]["body"])))
    why = "palette from %s (%s), type %s / %s at %d px on a %s scale, %d px content, motion %d/%d ms with reduced motion" % (
        dz["seed"], "dark" if dz["dark_only"] else "light and dark", t["display"], t["body"], t["body_size"], t["ratio"],
        lay["max_width"], mot["kinds"]["enter"]["duration_ms"], mot["kinds"]["hover"]["duration_ms"])
    if dz.get("stage"):
        css.append(dz["stage"][0])
        why += "; a three.js scene of one %s per row (%s light, %s camera)" % (dz["scene"]["shape"], dz["scene"]["light"],
                                                                             dz["scene"]["camera"])
    return link + "<style>" + "".join(css) + "</style>", why


def _lum(h):
    def lin(c):
        c = c / 255.0
        return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
    r, g, b = [lin(int(h[i:i + 2], 16)) for i in (1, 3, 5)]
    return 0.2126 * r + 0.7152 * g + 0.0722 * b


def judge_look(page, req):
    """the page's own tokens read back: text on its background at 7:1 or more in every mode it declares, its fonts named,

    a phone's margin, the reduced-motion rule; and what the request asked of the look (its colour's hue, dark)"""
    if not page:
        return False, "no page"
    blocks = re.findall(r"--background:(#[0-9a-f]{6});--foreground:(#[0-9a-f]{6})", page)
    if not blocks:
        return False, "no colour tokens"
    cs = [(max(_lum(f), _lum(b)) + 0.05) / (min(_lum(f), _lum(b)) + 0.05) for b, f in blocks]
    why = ["text contrast %s" % ", ".join("%.1f" % c for c in cs)]
    ok = all(c >= 7 for c in cs)
    fonts = re.findall(r"--font-(?:display|body):'([^']+)'", page)
    ok &= len(fonts) == 2
    why.append("fonts %s" % " / ".join(fonts))
    ok &= "prefers-reduced-motion" in page
    m = re.search(r"main\{max-width:\d+px;margin:0 auto;padding:\d+px (\d+)px\}", page)
    ok &= bool(m) and int(m.group(1)) >= 16
    why.append("phone margin %s px" % (m.group(1) if m else "?"))
    if req.get("seed"):
        D = _design()
        prim = re.search(r"--primary:(#[0-9a-f]{6})", page)
        seedhex = D["palette"].NAMES.get(req["seed"], req["seed"]) if not req["seed"].startswith("#") else req["seed"]
        _L, C, H = D["palette"].lch_of(seedhex)
        if prim and C > 0.02:
            ph = D["palette"].lch_of(prim.group(1))[2]
            d = min(abs(ph - H) % 360, 360 - abs(ph - H) % 360)
            ok &= d <= 20
            why.append("primary %s, %.0f degrees from %s" % (prim.group(1), d, req["seed"]))
    if req.get("scene"):
        # C12: the scene is bound to the page's records - the record payload's ids are the table rows' ids, in order
        mR = re.search(r"const R = (\[.*?\]), N = R\.length", page, re.S)
        try:
            recs = json.loads(mR.group(1).replace("<\\/", "</")) if mR else None
        except ValueError:
            recs = None
        tr_ids = [html_unescape(x) for x in re.findall(r'<tr data-id="([^"]*)">', page)]
        rows = len(tr_ids)
        n = re.match(r"(\d+)", str(len(recs))) if recs is not None else None
        three = re.search(r"three@\d+\.\d+\.\d+", page)
        bound = recs is not None and [str(x.get("id")) for x in recs] == tr_ids
        okc = bool(recs is not None and three and 'id="stage"' in page and len(recs) == rows and bound)
        # the shape asked is the geometry drawn (spheres asked: SphereGeometry in the stage), not only a stage
        want_geo = re.search(r"new THREE\.(\w+Geometry)", _design()["scene"].GEOM.get(req["scene"].get("shape"), "") or "")
        geo_ok = bool(want_geo) and ("new THREE.%s(" % want_geo.group(1)) in page
        okc &= geo_ok
        # the stage's script is run through a JavaScript engine where the box has one (node --check: it parses);
        # where none is installed the evidence says the script was not run - it is not counted as checked
        js = "\n".join(re.findall(r"<script type=\"module\">(.*?)</script>", page, re.S))
        ran = _js_parses(js) if js else None
        if ran is False:
            okc = False
        ok &= okc
        why.append("a three.js scene of %s objects for %d rows%s%s; %s drawn (%s asked)%s; script %s" % (
            n.group(1) if n else "no", rows, "" if three else ", three.js not pinned",
            ", each bound to its row's id" if bound else ", objects NOT bound to the table's rows",
            want_geo.group(1) if geo_ok else "not the shape", req["scene"].get("shape"), "",
            {True: "parses (node --check)", False: "does not parse (node --check)",
             None: "not run: no JavaScript engine on this box"}[ran]))
    if req.get("dark"):
        Lb = _design()["palette"].lch_of(blocks[0][0])[0]
        ok &= Lb < 0.3
        why.append("dark background L %.2f" % Lb)
    return bool(ok), "; ".join(why)


def _js_parses(js):
    """True / False when a JavaScript engine (node) is on this box and the module script parses or not; None without one"""
    import shutil
    import tempfile
    node = shutil.which("node") or shutil.which("nodejs")
    if not node:
        return None
    with tempfile.NamedTemporaryFile("w", suffix=".mjs", delete=False, encoding="utf-8") as f:
        f.write(js)
        path = f.name
    try:
        return subprocess.run([node, "--check", path], capture_output=True, timeout=30).returncode == 0
    except Exception:  # noqa: BLE001
        return None
    finally:
        os.unlink(path)


def save_project(root, shape):
    d = Path(root) / ".oracle7"
    d.mkdir(exist_ok=True)
    (d / "project.json").write_text(json.dumps(shape, indent=1, default=str), encoding="utf-8")


def load_project(root):
    p = Path(root) / ".oracle7" / "project.json"
    if p.is_file():
        try:
            return json.loads(p.read_text(encoding="utf-8"))
        except ValueError:
            return None
    return None


def derive_goal(h, shape):
    """a value made from a column, as a goal for the code composer: its examples from the turn that gave them"""
    exs = [((a,), b, None) for a, b in h["examples"]]
    return {"name": h["fn"], "params": [h["col"]], "module": Path(shape["module"] or "project.py").stem,
            "examples": exs, "module_text": ""}


def sha_of(name, src):
    return hashlib.sha256((name + "\n" + src).encode()).hexdigest()


def compose_holes(root, shape, holes, net_scope=()):
    """the values made from a column that now have examples: each composed by Oracle7's code composer (its search over

    typed moves, its read-back in a separate interpreter), the result going back into the plan under its sha. -> lines"""
    todo = [h for h in holes if h["kind"] == "compose"]
    if not todo:
        return []
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    import compose_code as CC
    out = []
    for h in todo:
        goal = derive_goal(h, shape)
        words = " ".join([shape.get("example_words", ""), h["name"], h["col"]] + [c for c in shape["clauses"]])
        res = CC.run_job(str(root), [goal], words=words, net_scope=list(net_scope))
        if res.get("stopped") and sys.modules.get("continuation") is not None:
            raise sys.modules["continuation"].Stopped("composing (%s)" % res["error"])   # C14: the examples stay kept
        r = (res.get("results") or [{}])[0] if "error" not in res else {"status": "error", "gap": res.get("error")}
        if r.get("status") == "composed":
            deps = []
            for s in r.get("support") or []:
                m = re.search(r"(?m)^def (\w+)\(", s)
                if m:
                    deps.append({"name": m.group(1), "source": s, "sha256": sha_of(m.group(1), s)})
            shape.setdefault("derived", {})[h["fn"]] = {
                "name": h["name"], "col": h["col"], "fn": h["fn"], "source": r["source"], "sha256": sha_of(h["fn"], r["source"]),
                "imports": sorted(set(r.get("imports") or []) | set(r.get("support_imports") or [])), "deps": deps,
                "from": "composed", "r": r, "goal": {"name": goal["name"], "params": goal["params"],
                                                     "examples": [[list(a), o] for a, o, _t in goal["examples"]]}}
            out.append("%s made from %s: composed from your %d examples - `%s` (read back by a separate interpreter: %s)" % (
                h["name"], h["col"], len(h["examples"]), r["source"].strip().splitlines()[-1].strip(), r.get("read_back")))
        else:
            shape["examples"].pop(h["fn"], None)     # the next examples start afresh
            out.append("%s made from %s: not composed - %s" % (h["name"], h["col"], (r.get("gap") or "")[:300]))
    return out


def keep_derived(root, shape):
    """the values composed for this project, kept in Oracle7's store once the project's judges passed with them (the law

    decides, not the composer): -> the kept records"""
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    import code_store as CS
    added = []
    for fn, d in (shape.get("derived") or {}).items():
        if d.get("from") != "composed" or d.get("kept"):
            continue
        g = dict(d["goal"])
        e = CS.entry_for(d["r"], g, "%s (%s)" % (shape.get("module"), Path(root).name), [])
        got = CS.keep([e]) if e else []
        if e:
            d["kept"] = e["id"]
            added += got or [e]
    return added


def is_project(text, kept, root=None):
    """a project request: a build verb, and an entry command, a table of the project or an outcome someone can see; not

    a request about tests or one function. Or a turn that continues or changes the project kept"""
    t = text.strip()
    other = re.search(r"(?i)\btests?\b|\bfunction\b|\bclass\b|\bdef\b|\bfix\b|\brepair\b|\bbug\b|\.py\b", t) and not ENTRY.search(t)
    if re.search(r"(?i)\b(?:in)?to\s+(?:yourself|oracle7)\b|^\s*(?:please\s+)?(?:build|add|make|give)\s+(?:yourself|oracle7)\s*[:,-]", t):
        return False                                   # a feature of Oracle7 itself: selfdev's project route (C10)
    if re.match(r"(?i)^\s*make\s+[\w-]+\s*:", t):
        return False                                   # the make command's own form: `make name: steps`
    if kept and not other:
        if _interaction_request(t):
            return True
        if re.match(r"(?i)^\s*(?:also|and also|now also|change it so|make it also|add|plus|then also)\b", t):
            return True
        if DROP.match(t) or DROP_WORD.match(t) or CONTINUE.match(t):
            return True
        if REVISE.search(t) or re.match(r"(?i)^\s*(?:(?:actually|wait|rather)\b|no\s*,)", t):
            return True                                # a revision of the project kept ("actually, make it above 25")
        if kept.get("status") == "blocked":
            if any(h.get("kind") == "scope" for h in kept.get("holes_kept", [])) and (
                    ENTRY.fullmatch(t) or any(re.fullmatch(r"(?i)(?:the\s+)?`?" + re.escape(n) + r"`?(?:\s+command)?[.!]?", t) for n in kept.get("entries", {}))):
                return True
            if EXAMPLE.search(t) or MEANS.search(t) or re.search(r"(?i)\buse\s+(?:it|that)\b", t):
                return True
            if any(h.get("kind") == "source" for h in kept.get("holes_kept", [])) and \
                    re.match(r"(?i)^\s*(?:match(?:ing|ed)?\s+(?:on|by)\s+|on\s+)[a-z_]", t):
                return True
    if other:
        return False
    if not BUILD.search(t):
        return False
    if ENTRY.search(t):
        return True
    has_table = bool(DATA.search(t))
    outcome = bool(_interaction_request(t) or SINK_FILE.search(t) or SINK_OBJ.search(t) or STORED.search(t) or re.search(r"(?i)\b(?:browser|web ?page|website|dashboard)\b", t)
                   or PRINTED.search(t))
    return has_table and outcome