File size: 70,472 Bytes
2a9dc4c
 
 
 
 
 
 
 
 
 
 
1ed2d7f
da61666
1ed2d7f
f628309
2a9dc4c
 
 
48f2b75
2a9dc4c
 
 
f4952b6
48f2b75
ba784dc
2a9dc4c
 
 
 
 
 
 
 
 
 
 
e1de134
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35ac38
e1de134
 
f4952b6
e1de134
ba784dc
f4952b6
48f2b75
e1de134
2a9dc4c
48f2b75
ba784dc
48f2b75
 
 
 
da61666
48f2b75
2a9dc4c
 
 
 
 
 
1ed2d7f
48f2b75
 
 
8947d88
 
 
 
 
 
 
ba784dc
 
 
 
 
da61666
 
 
 
 
 
 
 
 
ba784dc
 
 
 
 
da61666
ba784dc
da61666
f4952b6
 
 
 
 
 
 
da61666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba784dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f628309
 
 
 
 
 
 
ba784dc
 
 
f628309
 
 
 
 
 
ba784dc
f628309
 
1ed2d7f
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
8947d88
 
 
 
ba784dc
 
 
8947d88
 
2a9dc4c
 
 
 
8947d88
 
 
48f2b75
8947d88
 
 
2a9dc4c
 
 
 
48f2b75
8947d88
 
 
ba784dc
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f2b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
8947d88
2a9dc4c
48f2b75
2a9dc4c
8947d88
 
 
 
48f2b75
 
 
 
8947d88
 
48f2b75
 
2a9dc4c
 
 
 
48f2b75
2a9dc4c
 
48f2b75
 
 
 
 
 
 
 
 
8947d88
48f2b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8947d88
48f2b75
8947d88
48f2b75
 
 
 
 
8947d88
48f2b75
 
8947d88
48f2b75
2a9dc4c
48f2b75
2a9dc4c
48f2b75
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8947d88
48f2b75
c35ac38
f4952b6
2a9dc4c
 
 
 
 
 
 
 
 
 
 
c35ac38
 
 
 
f4952b6
c35ac38
f4952b6
8947d88
48f2b75
c35ac38
f4952b6
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35ac38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8947d88
f4952b6
 
8947d88
 
 
 
 
 
 
ba784dc
8947d88
 
 
 
2a9dc4c
48f2b75
ba784dc
48f2b75
 
 
ba784dc
 
48f2b75
 
 
 
 
 
 
 
 
 
 
ba784dc
 
48f2b75
ba784dc
 
48f2b75
 
c35ac38
 
 
 
 
 
 
 
 
 
 
ba784dc
 
 
 
 
 
 
c35ac38
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da61666
 
 
ba784dc
 
da61666
 
ba784dc
 
da61666
f4952b6
 
da61666
 
 
 
ba784dc
 
 
 
 
 
 
da61666
 
ba784dc
 
 
 
 
 
 
 
 
f4952b6
 
 
da61666
 
 
ba784dc
f4952b6
 
 
 
 
 
 
 
 
 
 
 
ba784dc
f4952b6
da61666
ba784dc
da61666
ba784dc
 
 
 
da61666
 
 
ba784dc
 
 
 
 
 
da61666
 
 
 
ba784dc
 
 
 
 
 
 
 
 
 
 
 
 
 
da61666
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
da61666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
48f2b75
 
 
ba784dc
 
 
 
 
 
 
48f2b75
2a9dc4c
 
 
 
 
 
 
 
 
 
1ed2d7f
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da61666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8947d88
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
f4952b6
c35ac38
 
 
1ed2d7f
 
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da61666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
e1de134
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
2a9dc4c
 
 
 
 
 
 
 
 
 
1ed2d7f
2a9dc4c
 
 
 
 
 
 
 
 
8947d88
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
f4952b6
c35ac38
1ed2d7f
 
 
c35ac38
 
 
1ed2d7f
 
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
da61666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
e1de134
 
 
da61666
2a9dc4c
e1de134
 
 
 
 
 
 
c390013
2a9dc4c
 
8947d88
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
2a9dc4c
 
f4952b6
c35ac38
 
 
1ed2d7f
 
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
da61666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
da61666
2a9dc4c
 
 
 
 
 
 
 
8947d88
 
 
 
2a9dc4c
 
 
 
 
 
e1de134
 
 
2a9dc4c
f4952b6
e1de134
 
2a9dc4c
 
 
 
 
 
 
 
 
 
e1de134
2a9dc4c
 
 
 
 
 
 
e1de134
 
2a9dc4c
 
f4952b6
c35ac38
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
e1de134
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
f628309
 
 
 
 
 
2a9dc4c
 
 
f628309
 
 
 
2a9dc4c
 
f628309
 
 
 
 
 
 
 
 
ba784dc
f628309
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
 
f4952b6
 
 
 
1ed2d7f
2a9dc4c
 
 
 
 
 
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
"""Transactional Python programming session built on the LingoLOGOS codex kernel.

A change is staged in an isolated copy of the workspace, evaluated by the
six-node codex pipeline (either in-process or as six isolated subprocesses
walking datasets/codex-python/topology.json), and committed atomically to the real
workspace via lingologos_codex.fsadapter only when the arbiter reaches the required
assurance threshold.
"""

from __future__ import annotations

import ast
import ctypes
import hashlib
import inspect
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import uuid
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple

from lingologos_python._codex_bridge import ensure_codex_on_path

ensure_codex_on_path()

from lingologos_codex import envelope as _envelope  # noqa: E402
from lingologos_codex.agents import ROLES, run_pipeline  # noqa: E402
from lingologos_codex.failures import detect_stall_from_hashes  # noqa: E402
from lingologos_codex.fsadapter import (  # noqa: E402
    FileSystemAdapterError,
    create_os_filesystem_adapter,
)
from lingologos_codex.fspolicy import (  # noqa: E402
    EOL_PRESERVE,
    FSPolicy,
    OP_DELETE,
    OP_WRITE,
    PathGuard,
    PathSecurityError,
    PlannedOp,
)
from lingologos_codex.patcher import (  # noqa: E402
    FuzzyPatchConfig,
    SearchReplaceBlock,
    apply_controlled_fuzzy_patch,
)

from lingologos_python.adapter import GATE_TIMEOUT_ENV  # noqa: E402
from lingologos_python.ast_graph import (  # noqa: E402
    IGNORED_DIRS,
    build_reverse_index,
    discover_python_files,
    hardlinked_file,
    importers_from_index,
    is_linked_path,
)
from lingologos_python.patterns import PatternPlan, plan_pattern  # noqa: E402
from lingologos_python.reasons import (  # noqa: E402
    HARDLINKED_PATH_IN_WORKSPACE,
    LINKED_PATH_IN_WORKSPACE,
    NODE_TIMEOUT,
    PATCH_NOT_APPLIED,
    PATH_POLICY,
    SESSION_LOCKED,
)

PYTHON_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_AGENT_SCRIPT = PYTHON_ROOT / "agents" / "python_agent.py"
DEFAULT_TOPOLOGY_PATH = PYTHON_ROOT / "topology.json"

DEFAULT_ALLOWED_PATTERNS: Tuple[str, ...] = ("*.py", "*.pyi")

# The clock the budgets read. A module attribute so a test can name a deadline
# without touching the clock of every other process on the machine.
_MONOTONIC = time.monotonic


class NodeTimeoutError(RuntimeError):
    """A node subprocess exhausted its time budget instead of answering."""


class WorkspaceLinkError(ValueError):
    """The workspace holds a link, or a name counted twice, whose copy cannot match the disk."""

    def __init__(self, message: str, reason: str = LINKED_PATH_IN_WORKSPACE) -> None:
        super().__init__(message)
        self.reason = reason


class SessionLockError(RuntimeError):
    """Another run holds the workspace lock, or its owner cannot be verified."""


# Two sessions committing to one workspace corrupt each other: each staged its
# own copy from a disk the other has already rewritten. The lock is taken with
# an exclusive create, so claiming it is never a polite ask, and released in a
# finally even when the run was refused. The lock file names the holder's pid,
# the creation time of that pid, and a token unique to the acquisition: the pid
# separates live from dead, the birth time separates the holder that was
# written down from a recycled pid wearing the same number, and the token keeps
# a run from unlinking a lock another run retook after it stalled.
SESSION_LOCK_NAME = ".lingologos-session.lock"
SESSION_LOCK_CLAIM_SUFFIX = ".stale"

# The gate budget reaches the kernel through the environment, and a process
# carries one such window at a time: every six-node call, together with the
# environment set and restore around it, is serialized by this lock. Documented
# limit: two CodeLinguistSessions in one process take their six-node turns in
# order rather than interleaving.
_KERNEL_CALL_LOCK = threading.Lock()


def _process_alive(pid: int) -> bool:
    """Best effort: is a process with this pid still running on this machine?"""
    if pid <= 0:
        return False
    if os.name == "nt":
        handle = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid)  # PROCESS_QUERY_LIMITED_INFORMATION
        if not handle:
            return False
        ctypes.windll.kernel32.CloseHandle(handle)
        return True
    try:
        os.kill(pid, 0)
    except ProcessLookupError:
        return False
    except PermissionError:
        return True
    return True


def _process_creation_time(pid: int) -> Optional[int]:
    """When the process behind this pid was born, or None when the host will not say.

    A pid alone says a number is answered; it does not say the answering
    process is the one that was written down. Birth times are the cheapest
    witness of a recycled pid.
    """
    if pid <= 0:
        return None
    if os.name == "nt":
        kernel32 = ctypes.windll.kernel32
        kernel32.OpenProcess.restype = ctypes.c_void_p
        kernel32.OpenProcess.argtypes = [ctypes.c_ulong, ctypes.c_bool, ctypes.c_ulong]
        handle = kernel32.OpenProcess(0x1000, False, pid)  # PROCESS_QUERY_LIMITED_INFORMATION
        if not handle:
            return None
        try:
            low = ctypes.c_ulong(0)
            high = ctypes.c_ulong(0)
            unused = ctypes.c_ulong(0)
            kernel32.GetProcessTimes.argtypes = [
                ctypes.c_void_p,
                ctypes.POINTER(ctypes.c_ulong),
                ctypes.POINTER(ctypes.c_ulong),
                ctypes.POINTER(ctypes.c_ulong),
                ctypes.POINTER(ctypes.c_ulong),
            ]
            if not kernel32.GetProcessTimes(
                handle, ctypes.byref(low), ctypes.byref(high), ctypes.byref(unused), ctypes.byref(unused)
            ):
                return None
            return (int(high.value) << 32) | int(low.value)
        finally:
            kernel32.CloseHandle(handle)
    try:
        # Field 22 of /proc/<pid>/stat is the start time in clock ticks; the
        # comm field before it may itself hold spaces, so count from the last.
        with open("/proc/%d/stat" % pid, encoding="ascii") as handle:
            after_name = handle.read().rsplit(")", 1)[-1].split()
        return int(after_name[19])
    except (OSError, ValueError, IndexError):
        return None


def _read_lock_record(lock: Path) -> Optional[Tuple[int, Optional[int], Optional[str]]]:
    """The (pid, birth, token) a lock file names, or None when it names nothing readable."""
    try:
        parts = lock.read_text(encoding="ascii").split()
    except (OSError, UnicodeDecodeError):
        return None
    if not parts:
        return None
    try:
        pid = int(parts[0])
    except ValueError:
        return None
    birth: Optional[int] = None
    if len(parts) > 1 and parts[1] != "-":
        try:
            birth = int(parts[1])
        except ValueError:
            return None
    token = parts[2] if len(parts) > 2 else None
    return (pid, birth, token)


def _lock_holder_is_alive(record: Tuple[int, Optional[int], Optional[str]]) -> bool:
    """A holder lives when its pid answers and is the same process it was when written.

    A pid recycled by a young process looks alive; the recorded birth time says
    the process now wearing the number is somebody else.
    """
    pid, birth, _token = record
    if not _process_alive(pid):
        return False
    if birth is not None:
        now = _process_creation_time(pid)
        if now is not None and now != birth:
            return False
    return True


def workspace_lock_status(workspace_root: str | Path) -> Dict[str, Any]:
    """What a reader may know about the workspace lock, reading and touching nothing.

    Three answers, no fourth: no lock at all; a lock whose holder lives; and a
    leftover whose holder no longer runs, which the next session takes over
    through the rename and which therefore reads as free. A lock file whose
    owner cannot even be read counts as held, because no run may grant itself
    the workspace without the takeover dance.
    """
    root = Path(workspace_root).resolve()
    lock = root / SESSION_LOCK_NAME
    status: Dict[str, Any] = {
        "workspace": str(root),
        "lock_file": SESSION_LOCK_NAME,
        "present": lock.is_file(),
        "held": False,
        "stale": False,
        "unreadable": False,
        "holder_pid": None,
        "holder_birth": None,
        "holder_alive": None,
    }
    if not status["present"]:
        return status
    record = _read_lock_record(lock)
    if record is None:
        status["held"] = True
        status["unreadable"] = True
        return status
    pid, birth, _token = record
    alive = _lock_holder_is_alive(record)
    status.update(
        holder_pid=pid,
        holder_birth=birth,
        holder_alive=alive,
        held=alive,
        stale=not alive,
    )
    return status


DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = (
    "*.env",
    ".env*",
    "*.pem",
    "*.key",
    ".git/*",
    "__pycache__/*",
)

ADAPTER_REF_DEFAULT = "lingologos_python.adapter:PythonLanguageAdapter"
ADAPTER_REF_STRICT = "lingologos_python.adapter:StrictPythonLanguageAdapter"
DEFAULT_GATES: Tuple[str, ...] = ("typecheck", "tests")


@dataclass(frozen=True)
class SessionResult:
    """Outcome of running the six-node codex pipeline over a Python workspace."""

    case_id: str
    verdict: str
    assurance: int
    reason: str
    detail: str
    committed: bool
    touched_files: Tuple[str, ...] = ()
    trace: Tuple[Dict[str, Any], ...] = field(default_factory=tuple)
    dossier: Dict[str, Any] = field(default_factory=dict)

    @property
    def accepted(self) -> bool:
        return self.verdict in ("VERIFIED", "SINGLE_PROVER")

    def to_dict(self) -> Dict[str, Any]:
        return {
            "case_id": self.case_id,
            "verdict": self.verdict,
            "assurance": self.assurance,
            "reason": self.reason,
            "detail": self.detail,
            "committed": self.committed,
            "touched_files": list(self.touched_files),
            "decision": dict(self.dossier.get("decision", {})),
            "gates": list(self.dossier.get("gates", [])),
            "checkers": list(self.dossier.get("checkers", [])),
        }


@dataclass(frozen=True)
class RetryContext:
    """What the attempts before this one leave to the proposer: results with trace and dossier.

    A loop that hands the proposer only the index and the last result teaches it
    nothing about why the nodes refused. A proposer that accepts a third
    argument receives all of it: every prior result with its verdict, reason,
    trace lines and the dossier the kernel returned, plus the patch signatures
    the loop detector compares, which read the fate of a patch and not its
    words. A two-argument proposer keeps working unchanged.
    """

    attempt: int
    rel_path: str
    attempts: Tuple[SessionResult, ...] = ()
    failure_reasons: Tuple[str, ...] = ()
    patch_signatures: Tuple[str, ...] = ()


def _disk_text(root: Path, rel_posix: str) -> str:
    """The current text of one workspace file, or an empty string when it is not there."""

    path = root / Path(*rel_posix.split("/"))
    return path.read_text(encoding="utf-8", newline="") if path.is_file() else ""


def _restore_originals(
    root: Path,
    originals: Dict[str, str],
    recreate: Sequence[str] = (),
) -> List[str]:
    """Put every named workspace path back to the text held in memory, listing failures."""

    problems: List[str] = []
    for rel_posix, text in originals.items():
        target = root / Path(*rel_posix.split("/"))
        try:
            if text == "" and rel_posix not in recreate:
                # The pre-image of a created file is an absent path, so undoing a
                # create means removing the file the transaction left behind.
                if target.is_file():
                    target.unlink()
            else:
                target.parent.mkdir(parents=True, exist_ok=True)
                target.write_text(text, encoding="utf-8", newline="")
        except OSError:
            problems.append(rel_posix)
    return problems


def _commit_or_restore(
    fs: Any,
    root: Path,
    writes: Dict[str, str],
    originals: Dict[str, str],
    recreate: Sequence[str] = (),
) -> Tuple[bool, str]:
    """Commit the verified writes, and restore the in-memory pre-images when the commit fails.

    The kernel transaction replaces one file at a time and attempts a best-effort
    rollback of its own when a replace fails part way, swallowing the errors of that
    rollback. The session does not trust it: it keeps every pre-image in memory,
    writes them back itself after any failure, and re-reads each written file once
    the commit reports success, so committed is only ever true when the verified
    text is the text on disk.
    """

    tx = fs.begin_transaction()
    try:
        for rel_posix, text in writes.items():
            fs.stage_write_text(tx, rel_posix, text)
        fs.commit_transaction(tx)
    except FileSystemAdapterError as exc:
        problems = _restore_originals(root, originals, recreate)
        if problems:
            return False, (
                "the commit failed and these paths could not be restored from memory: "
                + ", ".join(problems) + " (" + str(exc) + ")"
            )
        return False, "the commit failed, the workspace was restored from the in-memory originals: " + str(exc)
    drifted: List[str] = []
    for rel_posix, text in writes.items():
        on_disk = _disk_text(root, rel_posix)
        if on_disk != text and on_disk.replace("\r\n", "\n") != text.replace("\r\n", "\n"):
            drifted.append(rel_posix)
    if drifted:
        problems = _restore_originals(root, originals, recreate)
        if problems:
            return False, (
                "the commit landed the wrong text and these paths could not be restored: "
                + ", ".join(problems) + " (drifted: " + ", ".join(drifted) + ")"
            )
        return False, "the text on disk after the commit is not the verified text: " + ", ".join(drifted)
    return True, ""


def _delete_or_restore(
    fs: Any,
    root: Path,
    rel_posix: str,
    original_text: str,
) -> Tuple[bool, str, str]:
    """Delete one workspace file through the kernel transaction, honestly reporting the outcome.

    Returns committed, the refusal reason code when it did not land, and the detail.
    A path the policy refuses is a named refusal, not a crash, and a transaction the
    disk refuses puts the file back from the in-memory original.
    """

    tx = fs.begin_transaction()
    try:
        fs.stage_delete(tx, rel_posix)
        fs.commit_transaction(tx)
    except PathSecurityError as exc:
        return False, PATH_POLICY, "the path policy refused the delete: " + str(exc)
    except FileSystemAdapterError as exc:
        problems = _restore_originals(root, {rel_posix: original_text}, recreate=(rel_posix,))
        if problems:
            return False, PATCH_NOT_APPLIED, (
                "the delete failed and the file could not be restored from memory: " + str(exc)
            )
        return False, PATCH_NOT_APPLIED, "the delete failed, the file was restored from the in-memory original: " + str(exc)
    target = root / Path(*rel_posix.split("/"))
    if target.exists():
        return False, PATCH_NOT_APPLIED, "the file is still on disk after the delete commit: '%s'" % rel_posix
    return True, "", ""


def _verify_probe(text: str) -> Tuple[str, str, str]:
    """A search, replace, text triple that annotates one line without breaking the file.

    The anchor is the first top level statement whose own line still parses once a
    comment is appended to it, so the probe cannot turn a valid workspace file into a
    syntax error. When nothing safer is found the first line is used as it has always
    been, and an empty file gets a probe text of its own.
    """

    lines = text.splitlines(keepends=True)
    if not lines:
        return "# empty", "# empty verified", "# empty\n"
    probe_note = "  # codex-verify-probe\n"
    try:
        tree = ast.parse(text)
    except SyntaxError:
        tree = None
    if tree is not None:
        for node in tree.body:
            if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
                continue
            line = lines[node.lineno - 1].rstrip("\r\n")
            if not line:
                continue
            candidate = line + probe_note
            try:
                ast.parse(text.replace(line, candidate, 1))
            except SyntaxError:
                continue
            return line, candidate, text
    first = lines[0].rstrip("\r\n")
    return first, first + probe_note, text


def _copy_workspace_for_staging(src_root: Path, dst_root: Path) -> None:
    """Copy a workspace cleanly without caches or virtual environments.

    A symlink or a junction anywhere under the root is refused by name: a copy
    that quietly omits a link is not the workspace the six nodes were asked to
    judge, and a copy that follows one reaches files outside the workspace. A
    file standing under two names is refused too: the copy would split one
    file into two, and a later commit could not tell the names apart.
    """
    root = src_root.resolve()
    for dirpath, dirnames, filenames in os.walk(src_root):
        dirnames[:] = [
            d for d in dirnames if d not in IGNORED_DIRS and not d.endswith(".egg-info")
        ]
        rel_dir = Path(dirpath).resolve().relative_to(root)
        for name in dirnames:
            entry = Path(dirpath) / name
            if is_linked_path(entry):
                raise WorkspaceLinkError(
                    "linked directory in the workspace: '%s'" % (rel_dir / name).as_posix()
                )
        target_dir = dst_root / rel_dir
        target_dir.mkdir(parents=True, exist_ok=True)
        for name in filenames:
            src_file = Path(dirpath) / name
            if is_linked_path(src_file):
                raise WorkspaceLinkError(
                    "linked file in the workspace: '%s'" % (rel_dir / name).as_posix()
                )
            if hardlinked_file(src_file):
                raise WorkspaceLinkError(
                    "hardlinked file in the workspace: '%s'" % (rel_dir / name).as_posix(),
                    HARDLINKED_PATH_IN_WORKSPACE,
                )
            shutil.copy2(src_file, target_dir / name)


def _subprocess_env() -> Dict[str, str]:
    env = dict(os.environ)
    env["PYTHONDONTWRITEBYTECODE"] = "1"
    python_pkg_root = str(PYTHON_ROOT)
    codex_root = str(ensure_codex_on_path())
    existing = env.get("PYTHONPATH", "")
    parts = [python_pkg_root, codex_root]
    if existing:
        parts.append(existing)
    env["PYTHONPATH"] = os.pathsep.join(parts)
    return env


def _kill_process_tree(proc: subprocess.Popen) -> None:
    """Kill a node and everything it started: a budget that leaks grandchildren is not a budget.

    A node runs its own gates as children (pytest, a static checker), so killing
    only the direct child would leave those processes running past the budget.
    Windows gets the process tree through taskkill; elsewhere the node leads its
    own process group and the whole group is signalled.
    """
    if os.name == "nt":
        done = subprocess.run(
            ["taskkill", "/T", "/F", "/PID", str(proc.pid)],
            stdin=subprocess.DEVNULL,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        if done.returncode == 0:
            return
    else:
        try:
            os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
        except OSError:
            pass
    try:
        proc.kill()
    except OSError:
        pass


def run_topology_subprocesses(
    case: Dict[str, Any],
    *,
    agent_script: Optional[Path] = None,
    timeout_sec: float = 120.0,
    total_budget_sec: Optional[float] = None,
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
    """Execute the six roles via isolated node subprocesses communicating over JSON stdio.

    The agent script is read from the module at call time, so a caller that names
    a different six-node executable gets it, and the per-node budget is the one
    asked for rather than one frozen at import. A budget is honest only if it
    reaches the whole tree: an exhausted node is killed together with the gates
    it had started. ``total_budget_sec`` caps the sum of the six waits, and each
    node then gets the smaller of its own budget and the time the total still allows.
    """
    script = Path(agent_script) if agent_script else DEFAULT_AGENT_SCRIPT
    if timeout_sec <= 0 or (total_budget_sec is not None and total_budget_sec <= 0):
        raise ValueError("budgets must be positive numbers of seconds")
    seed = _envelope.make_envelope("arbiter", 0, 0, "task received", dict(case))
    trace: List[Dict[str, Any]] = [seed]
    current = seed
    env = _subprocess_env()
    deadline = _MONOTONIC() + total_budget_sec if total_budget_sec else None

    for role in ROLES:
        node_timeout = timeout_sec
        if deadline is not None:
            remaining = deadline - _MONOTONIC()
            if remaining <= 0:
                raise NodeTimeoutError(
                    "the run exhausted its %s s total budget before node '%s' started"
                    % (total_budget_sec, role)
                )
            node_timeout = min(timeout_sec, remaining)
        cmd = [sys.executable, "-B", str(script), "--role", role, "--node-id", role]
        popen_kwargs: Dict[str, Any] = dict(
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            encoding="utf-8",
            errors="replace",
            cwd=str(PYTHON_ROOT),
            env=env,
        )
        if os.name == "nt":
            popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
        else:
            popen_kwargs["start_new_session"] = True
        proc = subprocess.Popen(cmd, **popen_kwargs)
        try:
            stdout, stderr = proc.communicate(input=json.dumps(current), timeout=node_timeout)
        except subprocess.TimeoutExpired as exc:
            _kill_process_tree(proc)
            try:
                proc.communicate(timeout=5)
            except (subprocess.TimeoutExpired, ValueError, OSError):
                pass
            raise NodeTimeoutError(
                "node '%s' exhausted its %s s budget without answering"
                % (role, round(node_timeout, 3))
            ) from exc
        if proc.returncode != 0:
            raise RuntimeError(
                f"node '{role}' exited with {proc.returncode}: {(stderr or '').strip()}"
            )
        current = json.loads(stdout)
        trace.append(current)
    return trace, _envelope.read_dossier(current)


class PythonWorkspaceSession:
    """High-level interface to inspect, edit, verify, and commit Python code via codex."""

    def __init__(
        self,
        workspace_root: str | Path,
        *,
        allowed_patterns: Sequence[str] = DEFAULT_ALLOWED_PATTERNS,
        protected_patterns: Sequence[str] = DEFAULT_PROTECTED_PATTERNS,
        required_gates: Sequence[str] = DEFAULT_GATES,
        strict_tools: bool = False,
        spec_path: Optional[str | Path] = None,
        use_subprocesses: bool = False,
        min_assurance: int = 3,
        node_timeout_sec: float = 120.0,
        total_budget_sec: Optional[float] = None,
        gate_timeout_sec: Optional[float] = None,
        lock_wait_sec: float = 0.0,
    ) -> None:
        self.workspace_root = Path(workspace_root).resolve()
        if not self.workspace_root.is_dir():
            raise FileNotFoundError(f"workspace does not exist: '{self.workspace_root}'")
        self.allowed_patterns = tuple(allowed_patterns)
        self.protected_patterns = tuple(protected_patterns)
        self.required_gates = tuple(required_gates)
        self.strict_tools = bool(strict_tools)
        self.spec_path = str(Path(spec_path).resolve()) if spec_path else None
        self.use_subprocesses = bool(use_subprocesses)
        self.min_assurance = int(min_assurance)
        if (
            node_timeout_sec <= 0
            or (total_budget_sec is not None and total_budget_sec <= 0)
            or (gate_timeout_sec is not None and gate_timeout_sec <= 0)
            or lock_wait_sec < 0
        ):
            raise ValueError("budgets must be positive numbers of seconds, and the lock wait may not go negative")
        self.node_timeout_sec = float(node_timeout_sec)
        self.total_budget_sec = float(total_budget_sec) if total_budget_sec else None
        self.gate_timeout_sec = float(gate_timeout_sec) if gate_timeout_sec else None
        self.lock_wait_sec = float(lock_wait_sec)

    def policy_dict(self, root: Optional[Path] = None) -> Dict[str, Any]:
        return {
            "repo_root": str((root or self.workspace_root).resolve()),
            "allowed_patterns": list(self.allowed_patterns),
            "protected_patterns": list(self.protected_patterns),
            "default_eol": EOL_PRESERVE,
        }

    def policy(self, root: Optional[Path] = None) -> FSPolicy:
        return FSPolicy(
            repo_root=str((root or self.workspace_root).resolve()),
            allowed_patterns=self.allowed_patterns,
            protected_patterns=self.protected_patterns,
            case_insensitive=(os.name == "nt"),
            default_eol=EOL_PRESERVE,
        )

    def _os_fs(self, root: Path, *, check_allowed: bool = True):
        policy = FSPolicy(
            repo_root=str(root.resolve()),
            allowed_patterns=self.allowed_patterns if check_allowed else (),
            protected_patterns=self.protected_patterns,
            case_insensitive=(os.name == "nt"),
            default_eol=EOL_PRESERVE,
        )
        fs = create_os_filesystem_adapter(
            root,
            protected_patterns=self.protected_patterns,
            allowed_patterns=self.allowed_patterns if check_allowed else (),
        )
        fs.policy = policy
        fs.guard = PathGuard(policy)
        return fs

    def _adapter_fields(self) -> Dict[str, Any]:
        if self.spec_path:
            return {"spec": self.spec_path}
        return {"adapter": ADAPTER_REF_STRICT if self.strict_tools else ADAPTER_REF_DEFAULT}

    def _enter_gate_timeout_env(self) -> Optional[str]:
        """Hand the gate budget down to the adapter, which reads its own environment.

        The kernel instantiates the adapter from a reference string, so the
        session cannot pass it a constructor argument. The environment is the
        channel both the in-process pipeline and the node subprocesses read.
        """
        if self.gate_timeout_sec is None:
            return None
        previous = os.environ.get(GATE_TIMEOUT_ENV)
        os.environ[GATE_TIMEOUT_ENV] = repr(self.gate_timeout_sec)
        return previous

    @staticmethod
    def _exit_gate_timeout_env(previous: Optional[str]) -> None:
        if previous is None:
            os.environ.pop(GATE_TIMEOUT_ENV, None)
        else:
            os.environ[GATE_TIMEOUT_ENV] = previous

    def _run_six_nodes(self, case: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
        with _KERNEL_CALL_LOCK:
            # The budget travels through the environment, which one process
            # shares; holding the module lock across the whole call is what
            # keeps one session's window from bleeding into another's.
            previous_env = self._enter_gate_timeout_env()
            try:
                if self.use_subprocesses:
                    return run_topology_subprocesses(
                        case,
                        timeout_sec=self.node_timeout_sec,
                        total_budget_sec=self.total_budget_sec,
                    )
                return run_pipeline(case)
            except NodeTimeoutError as exc:
                # A node that exhausts its budget abstains: the session answers
                # UNKNOWN with the named reason instead of a traceback or a verdict.
                return [], {
                    "decision": {
                        "verdict": "UNKNOWN",
                        "assurance": 0,
                        "reason": NODE_TIMEOUT,
                        "detail": str(exc),
                    }
                }
            finally:
                self._exit_gate_timeout_env(previous_env)

    def _link_refusal(self, case_id: str, rel_posix: str, exc: WorkspaceLinkError) -> SessionResult:
        """A workspace held together by links cannot be copied to staging faithfully."""
        return SessionResult(
            case_id=case_id,
            verdict="REFUSED",
            assurance=0,
            reason=getattr(exc, "reason", LINKED_PATH_IN_WORKSPACE),
            detail=str(exc),
            committed=False,
            touched_files=(rel_posix,),
        )

    def _linked_path_in_workspace(self) -> Optional[Tuple[str, str]]:
        """Return ('directory'|'file'|'hardlink', rel_posix) for the first anomaly under the root.

        Verify judges the workspace where it stands, with no staging copy to
        refuse for it, so it asks the same question the copy asks: is any part
        of this tree somewhere else, or does any single file answer under two
        names.
        """
        root = Path(self.workspace_root).resolve()
        for dirpath, dirnames, filenames in os.walk(root):
            dirnames[:] = [
                d for d in dirnames if d not in IGNORED_DIRS and not d.endswith(".egg-info")
            ]
            rel_dir = Path(dirpath).resolve().relative_to(root)
            for name in dirnames:
                if is_linked_path(Path(dirpath) / name):
                    return ("directory", (rel_dir / name).as_posix())
            for name in filenames:
                entry = Path(dirpath) / name
                if is_linked_path(entry):
                    return ("file", (rel_dir / name).as_posix())
                if hardlinked_file(entry):
                    return ("hardlink", (rel_dir / name).as_posix())
        return None

    def _late_link_at_commit(self) -> Optional[Tuple[str, int, str, str]]:
        """The link question, asked again at the moment of writing.

        A link can appear after the run judged the tree. The commit already
        re-reads the bytes to catch a workspace that moved; it re-asks the same
        question those bytes still belong to the tree the six nodes verified.
        """
        linked = self._linked_path_in_workspace()
        if linked is None:
            return None
        kind, rel = linked
        if kind == "hardlink":
            return (
                "REFUSED",
                0,
                HARDLINKED_PATH_IN_WORKSPACE,
                "a hardlinked file appeared in the workspace before the commit: '%s'" % rel,
            )
        return (
            "REFUSED",
            0,
            LINKED_PATH_IN_WORKSPACE,
            "a linked %s appeared in the workspace before the commit: '%s'" % (kind, rel),
        )

    def _lock_lost_at_commit(self) -> Optional[Tuple[str, int, str, str]]:
        """The lock question, asked again at the moment of writing.

        The workspace lock is taken at the start of a run, and another run can
        take over a leftover claim while this run is busy. A commit whose lock
        no longer names this run is a named refusal: the bytes are still the
        tree the six nodes verified, but they would be written without a holder.
        """
        token = getattr(self, "_lock_token", None)
        if token is None:
            return None
        record = _read_lock_record(self._lock_path())
        if record is not None and record[2] == token:
            return None
        return (
            "REFUSED",
            0,
            SESSION_LOCKED,
            "the workspace lock no longer names this run before the commit: '%s'" % self._lock_path(),
        )

    def _lock_path(self) -> Path:
        return Path(self.workspace_root) / SESSION_LOCK_NAME

    def _lock_owner(self) -> Optional[Tuple[int, Optional[int], Optional[str]]]:
        return _read_lock_record(self._lock_path())

    @staticmethod
    def _lock_detail(lock: Path, record: Optional[Tuple[int, Optional[int], Optional[str]]]) -> str:
        if record is None:
            return "a lock file sits at '%s' and its owner cannot be read" % lock
        note = "" if record[1] is not None else ", whose birth time this system cannot read"
        return "another session run holds the workspace: '%s' names process %d%s" % (lock, record[0], note)

    def _acquire_session_lock(self) -> None:
        """Take the workspace lock with an exclusive create, never a polite ask.

        The lock names the holder's pid, its birth time, and a token unique to
        this acquisition. A lock left behind by a process that no longer runs is
        taken over through a rename: two runs that find the same leftover race
        for the rename, only one proceeds, and the loser is refused rather than
        handed a second silent holder. A lock whose owner is alive, or that has
        recycled only its pid number, or whose owner cannot even be read, is a
        refusal the caller can read.
        """
        lock = self._lock_path()
        claim = Path(str(lock) + SESSION_LOCK_CLAIM_SUFFIX)
        if claim.exists():
            try:
                # Bookkeeping of a takeover that finished or died mid-step; the
                # exclusive create below is what actually grants the workspace.
                claim.unlink()
            except OSError:
                pass
        token = uuid.uuid4().hex
        deadline = time.monotonic() + max(0.0, self.lock_wait_sec)
        takeovers = 0
        while True:
            try:
                handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
            except FileExistsError:
                record = self._lock_owner()
                if record is not None and not _lock_holder_is_alive(record) and takeovers < 2:
                    takeovers += 1
                    try:
                        os.rename(str(lock), str(claim))
                    except OSError:
                        raise SessionLockError(
                            "the leftover lock at '%s' is being taken over by another run" % lock
                        )
                    continue
                # A live holder keeps the workspace until it releases or the
                # caller's patience runs out; waiting was asked, waiting is what happens.
                if time.monotonic() >= deadline:
                    raise SessionLockError(self._lock_detail(lock, record))
                time.sleep(min(0.05, max(0.0, deadline - time.monotonic())))
                continue
            birth = _process_creation_time(os.getpid())
            try:
                os.write(
                    handle,
                    ("%d %s %s" % (os.getpid(), "-" if birth is None else birth, token)).encode("ascii"),
                )
            finally:
                os.close(handle)
            self._held_lock = lock
            self._lock_token = token
            if claim.exists():
                try:
                    claim.unlink()
                except OSError:
                    pass
            return

    def _release_session_lock(self) -> None:
        lock = getattr(self, "_held_lock", None)
        if lock is None:
            return
        self._held_lock = None
        token = getattr(self, "_lock_token", None)
        self._lock_token = None
        record = _read_lock_record(lock)
        if token is None or record is None or record[2] != token:
            # The lock under this name is no longer ours: a takeover happened
            # while this run stalled, and unlinking it would steal that holder.
            return
        try:
            lock.unlink()
        except OSError:
            pass

    def _lock_refusal(
        self, case_id: str, rel_posix: Optional[str], exc: SessionLockError
    ) -> SessionResult:
        return SessionResult(
            case_id=case_id,
            verdict="REFUSED",
            assurance=0,
            reason=SESSION_LOCKED,
            detail=str(exc),
            committed=False,
            touched_files=() if rel_posix is None else (rel_posix,),
        )

    def list_files(self) -> List[str]:
        """Return all Python source files in the workspace."""
        return discover_python_files(self.workspace_root)

    def verify(
        self,
        target_file: Optional[str] = None,
        *,
        case_id: str = "python-verify",
        note: str = "verify Python workspace against codex gates",
    ) -> SessionResult:
        """Judge the workspace, holding the session lock for the whole run.

        Two sessions committing to one tree each staged its copy from a disk
        the other had already rewritten, so the lock is taken before anything
        is read and released in a finally even when the run was refused.
        """
        try:
            self._acquire_session_lock()
        except SessionLockError as exc:
            return self._lock_refusal(case_id, target_file, exc)
        try:
            return self._verify_run(target_file, case_id=case_id, note=note)
        finally:
            self._release_session_lock()

    def _verify_run(
        self,
        target_file: Optional[str] = None,
        *,
        case_id: str = "python-verify",
        note: str = "verify Python workspace against codex gates",
    ) -> SessionResult:
        """Verify an existing file or the whole Python workspace without modifying disk."""
        linked = self._linked_path_in_workspace()
        if linked is not None:
            kind, rel = linked
            if kind == "hardlink":
                exc = WorkspaceLinkError(
                    "hardlinked file in the workspace: '%s'" % rel,
                    HARDLINKED_PATH_IN_WORKSPACE,
                )
            else:
                exc = WorkspaceLinkError("linked %s in the workspace: '%s'" % (kind, rel))
            return self._link_refusal(case_id, rel, exc)
        py_files = self.list_files()
        chosen = (target_file or (py_files[0] if py_files else "src/__init__.py")).replace("\\", "/")
        target_path = self.workspace_root / Path(*chosen.split("/"))
        if target_path.is_file():
            text = target_path.read_text(encoding="utf-8", newline="")
        else:
            text = ""

        # Verify without changing file content by probing a non-mutating exact check
        # over a temporary staging copy so real workspace files remain untouched.
        probe_search, probe_replace, original_for_patch = _verify_probe(text)

        case: Dict[str, Any] = {
            "case_id": case_id,
            "workspace": str(self.workspace_root),
            "file": chosen,
            "text": original_for_patch,
            "search": probe_search,
            "replace": probe_replace,
            "note": note,
            "required_gates": list(self.required_gates),
            "policy": self.policy_dict(),
            **self._adapter_fields(),
        }
        trace, dossier = self._run_six_nodes(case)
        decision = dict(dossier.get("decision", {}))
        return SessionResult(
            case_id=case_id,
            verdict=str(decision.get("verdict", "UNKNOWN")),
            assurance=int(decision.get("assurance", 0)),
            reason=str(decision.get("reason", "")),
            detail=str(decision.get("detail", "")),
            committed=False,
            touched_files=(chosen,),
            trace=tuple(trace),
            dossier=dossier,
        )

    def edit_file(
        self,
        rel_path: str,
        search: str,
        replace: str,
        *,
        case_id: str = "python-edit",
        note: str = "apply controlled search-and-replace edit",
        commit: bool = True,
        attempt_signatures: Sequence[str] = (),
        patch_config: FuzzyPatchConfig = FuzzyPatchConfig(),
    ) -> SessionResult:
        """Stage a search-and-replace edit, verify via codex, and commit atomically on pass."""
        try:
            self._acquire_session_lock()
        except SessionLockError as exc:
            return self._lock_refusal(case_id, rel_path.replace("\\", "/"), exc)
        try:
            return self._edit_run(
                rel_path,
                search,
                replace,
                case_id=case_id,
                note=note,
                commit=commit,
                attempt_signatures=attempt_signatures,
                patch_config=patch_config,
            )
        finally:
            self._release_session_lock()

    def _edit_run(
        self,
        rel_path: str,
        search: str,
        replace: str,
        *,
        case_id: str = "python-edit",
        note: str = "apply controlled search-and-replace edit",
        commit: bool = True,
        attempt_signatures: Sequence[str] = (),
        patch_config: FuzzyPatchConfig = FuzzyPatchConfig(),
    ) -> SessionResult:
        """Stage a search-and-replace edit, verify via codex, and commit atomically on pass."""
        rel_posix = rel_path.replace("\\", "/")
        guard = PathGuard(self.policy())

        # Check path policy before touching or staging anything
        try:
            plan = guard.plan_transaction([PlannedOp(op=OP_WRITE, rel_posix=rel_posix, content="")])
        except PathSecurityError:
            case = {
                "case_id": case_id,
                "workspace": str(self.workspace_root),
                "file": rel_posix,
                "text": "",
                "search": search,
                "replace": replace,
                "note": note,
                "required_gates": list(self.required_gates),
                "policy": self.policy_dict(),
                "attemptSignatures": list(attempt_signatures),
                **self._adapter_fields(),
            }
            trace, dossier = self._run_six_nodes(case)
            decision = dict(dossier.get("decision", {}))
            return SessionResult(
                case_id=case_id,
                verdict=str(decision.get("verdict", "UNKNOWN")),
                assurance=int(decision.get("assurance", 0)),
                reason=str(decision.get("reason", "")),
                detail=str(decision.get("detail", "")),
                committed=False,
                touched_files=(rel_posix,),
                trace=tuple(trace),
                dossier=dossier,
            )

        target = self.workspace_root / Path(*rel_posix.split("/"))
        original_text = target.read_text(encoding="utf-8", newline="") if target.is_file() else ""
        patch_res = apply_controlled_fuzzy_patch(
            original_text, SearchReplaceBlock(search, replace), patch_config
        )

        with tempfile.TemporaryDirectory(prefix="lingologos_python_stage_") as tmp_dir:
            staged_root = Path(tmp_dir).resolve()
            try:
                _copy_workspace_for_staging(self.workspace_root, staged_root)
            except WorkspaceLinkError as exc:
                return self._link_refusal(case_id, rel_posix, exc)
            if patch_res.applied and not plan.rejected:
                staged_fs = self._os_fs(staged_root)
                tx = staged_fs.begin_transaction()
                staged_fs.stage_write_text(tx, rel_posix, patch_res.updated_text)
                staged_fs.commit_transaction(tx)

            case = {
                "case_id": case_id,
                "workspace": str(staged_root),
                "file": rel_posix,
                "text": original_text,
                "search": search,
                "replace": replace,
                "note": note,
                "required_gates": list(self.required_gates),
                "policy": self.policy_dict(staged_root),
                "options": {
                    "min_similarity": patch_config.min_similarity,
                    "ambiguity_margin": patch_config.ambiguity_margin,
                },
                "attemptSignatures": list(attempt_signatures),
                **self._adapter_fields(),
            }
            trace, dossier = self._run_six_nodes(case)

        decision = dict(dossier.get("decision", {}))
        verdict = str(decision.get("verdict", "UNKNOWN"))
        assurance = int(decision.get("assurance", 0))
        reason = str(decision.get("reason", ""))
        detail = str(decision.get("detail", ""))
        committed = False

        if commit and patch_res.applied and not plan.rejected and assurance >= self.min_assurance:
            late_link = self._late_link_at_commit() or self._lock_lost_at_commit()
            if late_link is not None:
                verdict, assurance, reason, detail = late_link
            elif _disk_text(self.workspace_root, rel_posix) != original_text:
                # The workspace moved while the six nodes were running: the patch that
                # was verified is no longer the patch for the file on disk, so nothing
                # is written and the run reports the named refusal instead.
                verdict = "REFUSED"
                assurance = 0
                reason = PATCH_NOT_APPLIED
                detail = "the file changed on disk after the run verified the patch: '%s'" % rel_posix
            else:
                committed, failure = _commit_or_restore(
                    self._os_fs(self.workspace_root),
                    self.workspace_root,
                    {rel_posix: patch_res.updated_text},
                    {rel_posix: original_text},
                )
                if not committed:
                    verdict = "REFUSED"
                    assurance = 0
                    reason = PATCH_NOT_APPLIED
                    detail = failure

        return SessionResult(
            case_id=case_id,
            verdict=verdict,
            assurance=assurance,
            reason=reason,
            detail=detail,
            committed=committed,
            touched_files=(rel_posix,),
            trace=tuple(trace),
            dossier=dossier,
        )

    def apply_pattern(
        self,
        pattern_id: str,
        *,
        target: Optional[str] = None,
        case_id: Optional[str] = None,
        note: Optional[str] = None,
        commit: bool = True,
        patch_config: FuzzyPatchConfig = FuzzyPatchConfig(),
    ) -> SessionResult:
        """Apply one catalog card under the session lock, pair of files and all."""
        try:
            self._acquire_session_lock()
        except SessionLockError as exc:
            return self._lock_refusal(
                case_id or "python-pattern-%s" % pattern_id, target, exc
            )
        try:
            return self._apply_pattern_run(
                pattern_id,
                target=target,
                case_id=case_id,
                note=note,
                commit=commit,
                patch_config=patch_config,
            )
        finally:
            self._release_session_lock()

    def _apply_pattern_run(
        self,
        pattern_id: str,
        *,
        target: Optional[str] = None,
        case_id: Optional[str] = None,
        note: Optional[str] = None,
        commit: bool = True,
        patch_config: FuzzyPatchConfig = FuzzyPatchConfig(),
    ) -> SessionResult:
        """Apply one catalog card to one target, primary edit and lock test together.

        Both files of the pair land in the same staged copy, so the test gate runs against
        the rewritten source and the lock test that can only pass once the rewrite landed.
        The kernel claim stays the primary edit, because that is the edit the six nodes are
        asked to judge, and the companion paths are announced on the same case. The commit
        is one transaction: the source replaced and the test file replaced, or neither.
        If the disk refuses that transaction part way, the session restores both files
        from the in-memory originals and reports the named refusal instead.

        A card that refuses is not a failed run. It reports the reason code the rule named
        and never reaches the six nodes, because there is nothing there to verify. A card
        that applies but whose anchors do not apply writes nothing either: a pattern that
        would have to edit one file of its pair and skip the other is a pattern this
        session does not run.
        """
        chosen_case_id = case_id or "pattern-%s" % pattern_id
        plan = plan_pattern(self.workspace_root, pattern_id, target)
        if plan.refused:
            return SessionResult(
                case_id=chosen_case_id,
                verdict="REFUSED",
                assurance=0,
                reason=plan.reason_code,
                detail=plan.detail,
                committed=False,
                touched_files=(),
                dossier={
                    "pattern": pattern_id,
                    "target": plan.target,
                    "refusal": plan.reason_code,
                    "decision": {
                        "verdict": "REFUSED",
                        "assurance": 0,
                        "reason": plan.reason_code,
                        "detail": plan.detail,
                    },
                    "gates": [],
                    "checkers": [],
                },
            )

        primary = plan.primary()
        guard = PathGuard(self.policy())
        try:
            planned = guard.plan_transaction(
                [PlannedOp(op=OP_WRITE, rel_posix=edit.file, content="") for edit in plan.edits]
            )
        except PathSecurityError:
            case = {
                "case_id": chosen_case_id,
                "workspace": str(self.workspace_root),
                "file": primary.file,
                "text": "",
                "search": primary.search,
                "replace": primary.replace,
                "note": note or plan.summary(),
                "required_gates": list(self.required_gates),
                "policy": self.policy_dict(),
                "pattern": pattern_id,
                "companionFiles": [edit.file for edit in plan.companions()],
                **self._adapter_fields(),
            }
            trace, dossier = self._run_six_nodes(case)
            decision = dict(dossier.get("decision", {}))
            return SessionResult(
                case_id=chosen_case_id,
                verdict=str(decision.get("verdict", "UNKNOWN")),
                assurance=int(decision.get("assurance", 0)),
                reason=str(decision.get("reason", "")),
                detail=str(decision.get("detail", "")),
                committed=False,
                touched_files=plan.files,
                trace=tuple(trace),
                dossier=dossier,
            )

        originals: Dict[str, str] = {}
        patched: Dict[str, str] = {}
        unapplied: List[str] = []
        for edit in plan.edits:
            source = self.workspace_root / Path(*edit.file.split("/"))
            original = source.read_text(encoding="utf-8", newline="") if source.is_file() else ""
            originals[edit.file] = original
            outcome = apply_controlled_fuzzy_patch(
                original, SearchReplaceBlock(edit.search, edit.replace), patch_config
            )
            if not outcome.applied:
                unapplied.append(edit.file)
            patched[edit.file] = outcome.updated_text
        if planned.rejected or unapplied:
            # Nothing of the pair is written: a half pair is exactly the state the lock
            # test exists to prevent, and staging it would judge a change nobody proposed.
            return SessionResult(
                case_id=chosen_case_id,
                verdict="REFUSED",
                assurance=0,
                reason=PATH_POLICY if planned.rejected else PATCH_NOT_APPLIED,
                detail=(
                    "the path policy rejected the pair: " + ", ".join(plan.files)
                    if planned.rejected
                    else "the anchor of this card did not apply in: " + ", ".join(unapplied)
                ),
                committed=False,
                touched_files=plan.files,
                dossier={
                    "pattern": pattern_id,
                    "target": plan.target,
                    "refusal": PATH_POLICY if planned.rejected else PATCH_NOT_APPLIED,
                    "decision": {"verdict": "REFUSED", "assurance": 0},
                    "gates": [],
                    "checkers": [],
                },
            )

        needed = max(self.min_assurance, plan.min_assurance)
        with tempfile.TemporaryDirectory(prefix="lingologos_python_pattern_stage_") as tmp_dir:
            staged_root = Path(tmp_dir).resolve()
            try:
                _copy_workspace_for_staging(self.workspace_root, staged_root)
            except WorkspaceLinkError as exc:
                return self._link_refusal(chosen_case_id, primary.file, exc)
            staged_fs = self._os_fs(staged_root)
            tx = staged_fs.begin_transaction()
            for edit in plan.edits:
                staged_fs.stage_write_text(tx, edit.file, patched[edit.file])
            staged_fs.commit_transaction(tx)

            case = {
                "case_id": chosen_case_id,
                "workspace": str(staged_root),
                "file": primary.file,
                "text": originals[primary.file],
                "search": primary.search,
                "replace": primary.replace,
                "note": note or plan.summary(),
                "required_gates": list(self.required_gates),
                "policy": self.policy_dict(staged_root),
                "options": {
                    "min_similarity": patch_config.min_similarity,
                    "ambiguity_margin": patch_config.ambiguity_margin,
                },
                "attemptSignatures": [],
                "pattern": pattern_id,
                "companionFiles": [edit.file for edit in plan.companions()],
                **self._adapter_fields(),
            }
            trace, dossier = self._run_six_nodes(case)

        decision = dict(dossier.get("decision", {}))
        verdict = str(decision.get("verdict", "UNKNOWN"))
        assurance = int(decision.get("assurance", 0))
        reason = str(decision.get("reason", ""))
        detail = str(decision.get("detail", ""))
        committed = False

        if commit and assurance >= needed:
            late_link = self._late_link_at_commit() or self._lock_lost_at_commit()
            drifted = [] if late_link is not None else [
                edit.file for edit in plan.edits
                if _disk_text(self.workspace_root, edit.file) != originals[edit.file]
            ]
            if late_link is not None:
                verdict, assurance, reason, detail = late_link
            elif drifted:
                # The pair was verified against the workspace as it was at staging time.
                # If a file of the pair moved since, the anchors proven in staging are
                # not the anchors of what is on disk, so the pair is not written.
                verdict = "REFUSED"
                assurance = 0
                reason = PATCH_NOT_APPLIED
                detail = "these files changed on disk after the pair was verified: " + ", ".join(drifted)
            else:
                committed, failure = _commit_or_restore(
                    self._os_fs(self.workspace_root),
                    self.workspace_root,
                    {edit.file: patched[edit.file] for edit in plan.edits},
                    {edit.file: originals[edit.file] for edit in plan.edits},
                )
                if not committed:
                    verdict = "REFUSED"
                    assurance = 0
                    reason = PATCH_NOT_APPLIED
                    detail = failure

        dossier["pattern"] = pattern_id
        dossier["target"] = plan.target
        dossier["companionFiles"] = [edit.file for edit in plan.companions()]
        dossier["requiredAssurance"] = needed
        return SessionResult(
            case_id=chosen_case_id,
            verdict=verdict,
            assurance=assurance,
            reason=reason,
            detail=detail,
            committed=committed,
            touched_files=plan.files,
            trace=tuple(trace),
            dossier=dossier,
        )

    def create_file(
        self,
        rel_path: str,
        content: str,
        *,
        case_id: str = "python-create",
        note: str = "create verified Python module",
        commit: bool = True,
    ) -> SessionResult:
        """Create a new Python file, verifying it in isolation before committing."""
        try:
            self._acquire_session_lock()
        except SessionLockError as exc:
            return self._lock_refusal(case_id, rel_path.replace("\\", "/"), exc)
        try:
            return self._create_run(
                rel_path, content, case_id=case_id, note=note, commit=commit
            )
        finally:
            self._release_session_lock()

    def _create_run(
        self,
        rel_path: str,
        content: str,
        *,
        case_id: str = "python-create",
        note: str = "create verified Python module",
        commit: bool = True,
    ) -> SessionResult:
        """Create a new Python file, verifying it in isolation before committing."""
        rel_posix = rel_path.replace("\\", "/")
        guard = PathGuard(self.policy())
        try:
            plan = guard.plan_transaction([PlannedOp(op=OP_WRITE, rel_posix=rel_posix, content=content)])
        except PathSecurityError:
            # The policy answers first. Probing the named path before the guard would let
            # an absolute path replace the workspace root on Windows and touch a file
            # outside the workspace, naming it back in the error.
            return self._edit_run(rel_posix, "# NEW_FILE", content, case_id=case_id, note=note, commit=False)

        # The guard has resolved the path inside the workspace by now; build the target
        # from the resolved rel path, never from the raw input.
        safe_rel = plan.touched_files[0] if plan.touched_files else rel_posix
        target = self.workspace_root / Path(*safe_rel.split("/"))
        if target.exists():
            raise FileExistsError(f"target already exists: '{rel_posix}'")

        marker = "# __LINGOLOGOS_PYTHON_NEW_FILE__\n"
        with tempfile.TemporaryDirectory(prefix="lingologos_python_create_") as tmp_dir:
            staged_root = Path(tmp_dir).resolve()
            try:
                _copy_workspace_for_staging(self.workspace_root, staged_root)
            except WorkspaceLinkError as exc:
                return self._link_refusal(case_id, rel_posix, exc)
            if not plan.rejected:
                staged_fs = self._os_fs(staged_root)
                tx = staged_fs.begin_transaction()
                staged_fs.stage_write_text(tx, rel_posix, content)
                staged_fs.commit_transaction(tx)

            case = {
                "case_id": case_id,
                "workspace": str(staged_root),
                "file": rel_posix,
                "text": marker,
                "search": marker,
                "replace": content,
                "note": note,
                "required_gates": list(self.required_gates),
                "policy": self.policy_dict(staged_root),
                **self._adapter_fields(),
            }
            trace, dossier = self._run_six_nodes(case)

        decision = dict(dossier.get("decision", {}))
        verdict = str(decision.get("verdict", "UNKNOWN"))
        assurance = int(decision.get("assurance", 0))
        reason = str(decision.get("reason", ""))
        detail = str(decision.get("detail", ""))
        committed = False
        if commit and not plan.rejected and assurance >= self.min_assurance:
            late_link = self._late_link_at_commit() or self._lock_lost_at_commit()
            if late_link is not None:
                verdict, assurance, reason, detail = late_link
            elif target.is_file():
                # The verified text was staged as a new file. If a file landed at that
                # path while the run was going, writing would replace something the
                # six nodes never saw, so the create is not committed.
                verdict = "REFUSED"
                assurance = 0
                reason = PATCH_NOT_APPLIED
                detail = "a file appeared at '%s' while the create was being verified" % rel_posix
            else:
                committed, failure = _commit_or_restore(
                    self._os_fs(self.workspace_root),
                    self.workspace_root,
                    {rel_posix: content},
                    {rel_posix: ""},
                )
                if not committed:
                    verdict = "REFUSED"
                    assurance = 0
                    reason = PATCH_NOT_APPLIED
                    detail = failure

        return SessionResult(
            case_id=case_id,
            verdict=verdict,
            assurance=assurance,
            reason=reason,
            detail=detail,
            committed=committed,
            touched_files=(rel_posix,),
            trace=tuple(trace),
            dossier=dossier,
        )

    def delete_file(
        self,
        rel_path: str,
        *,
        case_id: str = "python-delete",
        note: str = "delete Python module with full regression check",
        commit: bool = True,
    ) -> SessionResult:
        """Delete a Python file only if the full regression passes after removal."""
        try:
            self._acquire_session_lock()
        except SessionLockError as exc:
            return self._lock_refusal(case_id, rel_path.replace("\\", "/"), exc)
        try:
            return self._delete_run(rel_path, case_id=case_id, note=note, commit=commit)
        finally:
            self._release_session_lock()

    def _delete_run(
        self,
        rel_path: str,
        *,
        case_id: str = "python-delete",
        note: str = "delete Python module with full regression check",
        commit: bool = True,
    ) -> SessionResult:
        """Delete a Python file only if the full regression passes after removal."""
        rel_posix = rel_path.replace("\\", "/")
        guard = PathGuard(self.policy())
        try:
            plan = guard.plan_transaction([PlannedOp(op=OP_DELETE, rel_posix=rel_posix)])
        except PathSecurityError:
            return self._edit_run(rel_posix, "# DELETE", "", case_id=case_id, note=note, commit=False)

        target = self.workspace_root / Path(*rel_posix.split("/"))
        if not target.is_file():
            raise FileNotFoundError(f"target file does not exist: '{rel_posix}'")
        original_text = target.read_text(encoding="utf-8", newline="")

        with tempfile.TemporaryDirectory(prefix="lingologos_python_delete_") as tmp_dir:
            staged_root = Path(tmp_dir).resolve()
            try:
                _copy_workspace_for_staging(self.workspace_root, staged_root)
            except WorkspaceLinkError as exc:
                return self._link_refusal(case_id, rel_posix, exc)
            if not plan.rejected:
                # Unlink only the target file; lingologos_codex.fsadapter.stage_delete walks parent dirs.
                staged_target = staged_root / Path(*rel_posix.split("/"))
                if staged_target.is_file() and not staged_target.is_symlink():
                    staged_target.unlink()

            # A delete is judged where it can actually hurt: the surviving files that
            # import the module being removed are the gate target and its companions,
            # not the alphabetically first file of the copy.
            remaining = [p for p in discover_python_files(staged_root) if p != rel_posix]
            importers = importers_from_index(build_reverse_index(staged_root, remaining), rel_posix)
            gate_target = importers[0] if importers else (remaining[0] if remaining else rel_posix)
            companion_files = [p for p in importers if p != gate_target]
            case = {
                "case_id": case_id,
                "workspace": str(staged_root),
                "file": gate_target,
                "text": original_text,
                "search": original_text if original_text.strip() else "# empty",
                "replace": "# deleted\n",
                "note": note,
                "required_gates": list(self.required_gates),
                "policy": self.policy_dict(staged_root),
                "companionFiles": companion_files,
                **self._adapter_fields(),
            }
            trace, dossier = self._run_six_nodes(case)

        decision = dict(dossier.get("decision", {}))
        verdict = str(decision.get("verdict", "UNKNOWN"))
        assurance = int(decision.get("assurance", 0))
        reason = str(decision.get("reason", ""))
        detail = str(decision.get("detail", ""))
        committed = False
        if commit and not plan.rejected and assurance >= self.min_assurance:
            late_link = self._late_link_at_commit() or self._lock_lost_at_commit()
            if late_link is not None:
                verdict, assurance, reason, detail = late_link
            elif _disk_text(self.workspace_root, rel_posix) != original_text:
                # The file moved while the six nodes were running: the removal that was
                # verified is no longer the removal of what is on disk.
                verdict = "REFUSED"
                assurance = 0
                reason = PATCH_NOT_APPLIED
                detail = "the file changed on disk after the run verified the delete: '%s'" % rel_posix
            else:
                committed, refusal_reason, failure = _delete_or_restore(
                    # The guard above has already decided the policy for this delete;
                    # the kernel stage_delete re-walks the parent directories against
                    # the allowed set and refuses legitimate paths, so the adapter
                    # only enforces the protected patterns here.
                    self._os_fs(self.workspace_root, check_allowed=False),
                    self.workspace_root,
                    rel_posix,
                    original_text,
                )
                if not committed:
                    verdict = "REFUSED"
                    assurance = 0
                    reason = refusal_reason
                    detail = failure

        dossier["companionFiles"] = companion_files
        return SessionResult(
            case_id=case_id,
            verdict=verdict,
            assurance=assurance,
            reason=reason,
            detail=detail,
            committed=committed,
            touched_files=(rel_posix,),
            trace=tuple(trace),
            dossier=dossier,
        )

    def run_retry_loop(
        self,
        rel_path: str,
        proposer: Callable[[int, Optional[SessionResult]], Tuple[str, str]],
        *,
        max_attempts: int = 4,
        commit: bool = True,
    ) -> Tuple[SessionResult, List[SessionResult]]:
        """Run bounded edit attempts using codex stall detection to stop identical or cyclic failures.

        The proposer takes the attempt index and the last result. A proposer that
        accepts a third argument also receives a RetryContext with every prior
        attempt, its trace and its dossier.
        """
        history: List[str] = []
        attempts: List[SessionResult] = []
        last: Optional[SessionResult] = None
        try:
            accepts_context = len(inspect.signature(proposer).parameters) >= 3
        except (TypeError, ValueError):
            accepts_context = False

        for idx in range(1, max_attempts + 1):
            if accepts_context:
                search, replace = proposer(
                    idx,
                    last,
                    RetryContext(
                        attempt=idx,
                        rel_path=rel_path,
                        attempts=tuple(attempts),
                        failure_reasons=tuple(r.reason for r in attempts),
                        patch_signatures=tuple(history),
                    ),
                )
            else:
                search, replace = proposer(idx, last)
            result = self.edit_file(
                rel_path,
                search,
                replace,
                case_id=f"retry-{idx}",
                commit=commit,
                attempt_signatures=history,
            )
            attempts.append(result)
            last = result
            sig = str(result.dossier.get("patchSignature", ""))
            if not sig:
                # Two attempts that propose the same anchor and the same text have to
                # share one hash even when the kernel recorded no patch signature, or
                # the stall detector never sees the repetition. The hash keeps the
                # shape of a kernel signature, "sha256:" and sixteen hex digits, so a
                # history of attempts never mixes two notations for one fact.
                sig = "sha256:" + hashlib.sha256((search + "\x00" + replace).encode("utf-8")).hexdigest()[:16]
            history.append(sig)
            if result.assurance >= self.min_assurance:
                return result, attempts
            if detect_stall_from_hashes(history) is not None:
                return result, attempts
        assert last is not None
        return last, attempts