File size: 44,624 Bytes
2a9dc4c
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
8947d88
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
 
 
 
 
2a9dc4c
 
 
 
 
 
 
1ed2d7f
 
 
 
8947d88
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8947d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
8947d88
 
 
 
 
 
 
2a9dc4c
 
 
 
8947d88
 
 
 
 
 
 
2a9dc4c
 
 
 
8947d88
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8947d88
2a9dc4c
 
8947d88
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
8947d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8947d88
2a9dc4c
 
 
 
 
 
 
 
 
 
 
8947d88
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8947d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8947d88
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
1ed2d7f
 
 
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
2a9dc4c
 
 
 
 
 
 
 
 
 
1ed2d7f
2a9dc4c
 
 
 
 
 
 
 
 
8947d88
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
1ed2d7f
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
 
 
2a9dc4c
 
e1de134
 
 
 
 
 
 
c390013
2a9dc4c
 
8947d88
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
2a9dc4c
 
1ed2d7f
 
 
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8947d88
 
 
 
2a9dc4c
 
 
 
 
 
e1de134
 
 
2a9dc4c
e1de134
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
e1de134
2a9dc4c
 
 
 
 
 
 
e1de134
 
2a9dc4c
 
e1de134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
e1de134
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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 hashlib
import json
import os
import shutil
import stat
import subprocess
import sys
import tempfile
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.ast_graph import (  # noqa: E402
    IGNORED_DIRS,
    discover_python_files,
    importers_of,
)
from lingologos_python.patterns import PatternPlan, plan_pattern  # noqa: E402

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")

# Named session refusals, alongside the reason codes the rule catalog answers with.
PATH_POLICY = "PATH_POLICY"
PATCH_NOT_APPLIED = "PATCH_NOT_APPLIED"
NODE_TIMEOUT = "NODE_TIMEOUT"
LINKED_PATH_IN_WORKSPACE = "LINKED_PATH_IN_WORKSPACE"


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


class WorkspaceLinkError(ValueError):
    """The workspace holds a symlink or a junction whose copy cannot match the disk."""
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", [])),
        }


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 _is_linked(path: Path) -> bool:
    """True when the path is a symlink or, on Windows, any reparse point such as a junction.

    Since Python 3.12 a Windows junction is no longer reported as a symlink, yet a
    directory walk still descends into it. The reparse attribute is the honest test.
    """
    if path.is_symlink():
        return True
    if os.name == "nt":
        try:
            attributes = path.lstat().st_file_attributes
        except OSError:
            return False
        return bool(attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT)
    return False


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.
    """
    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(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(src_file):
                raise WorkspaceLinkError(
                    "linked file in the workspace: '%s'" % (rel_dir / name).as_posix()
                )
            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 run_topology_subprocesses(
    case: Dict[str, Any],
    *,
    agent_script: Optional[Path] = None,
    timeout_sec: float = 120.0,
) -> 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.
    """
    script = Path(agent_script) if agent_script else DEFAULT_AGENT_SCRIPT
    seed = _envelope.make_envelope("arbiter", 0, 0, "task received", dict(case))
    trace: List[Dict[str, Any]] = [seed]
    current = seed
    env = _subprocess_env()

    for role in ROLES:
        cmd = [sys.executable, "-B", str(script), "--role", role, "--node-id", role]
        try:
            completed = subprocess.run(
                cmd,
                input=json.dumps(current),
                capture_output=True,
                text=True,
                encoding="utf-8",
                errors="replace",
                timeout=timeout_sec,
                cwd=str(PYTHON_ROOT),
                env=env,
            )
        except subprocess.TimeoutExpired as exc:
            raise NodeTimeoutError(
                "node '%s' exhausted its %s s budget without answering" % (role, timeout_sec)
            ) from exc
        if completed.returncode != 0:
            raise RuntimeError(
                f"node '{role}' exited with {completed.returncode}: {completed.stderr.strip()}"
            )
        current = json.loads(completed.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,
    ) -> 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)
        self.node_timeout_sec = float(node_timeout_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 _run_six_nodes(self, case: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
        try:
            if self.use_subprocesses:
                return run_topology_subprocesses(case, timeout_sec=self.node_timeout_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),
                }
            }

    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=LINKED_PATH_IN_WORKSPACE,
            detail=str(exc),
            committed=False,
            touched_files=(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:
        """Verify an existing file or the whole Python workspace without modifying disk."""
        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."""
        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:
            if _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 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:
            drifted = [
                edit.file for edit in plan.edits
                if _disk_text(self.workspace_root, edit.file) != originals[edit.file]
            ]
            if 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."""
        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_file(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:
            if 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."""
        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_file(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_of(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:
            if _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."""
        history: List[str] = []
        attempts: List[SessionResult] = []
        last: Optional[SessionResult] = None

        for idx in range(1, max_attempts + 1):
            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.
                sig = hashlib.sha1((search + "\x00" + replace).encode("utf-8")).hexdigest()
            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