File size: 30,361 Bytes
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
"""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 json
import os
import shutil
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 create_os_filesystem_adapter  # noqa: E402
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 IGNORED_DIRS, discover_python_files  # noqa: E402
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")
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 _copy_workspace_for_staging(src_root: Path, dst_root: Path) -> None:
    """Copy a workspace cleanly without caches or virtual environments."""
    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(src_root.resolve())
        target_dir = dst_root / rel_dir
        target_dir.mkdir(parents=True, exist_ok=True)
        for name in filenames:
            src_file = Path(dirpath) / name
            if src_file.is_symlink():
                continue
            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: Path = DEFAULT_AGENT_SCRIPT,
    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."""
    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(agent_script), "--role", role, "--node-id", role]
        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,
        )
        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,
    ) -> 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)

    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]]:
        if self.use_subprocesses:
            return run_topology_subprocesses(case)
        return run_pipeline(case)

    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.
        lines = text.splitlines(keepends=True)
        if lines:
            first_line = lines[0]
            probe_search = first_line
            probe_replace = first_line.rstrip("\r\n") + "  # codex-verify-probe\n"
            original_for_patch = text
        else:
            probe_search = "# empty"
            probe_replace = "# empty verified"
            original_for_patch = "# empty\n"

        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()
            _copy_workspace_for_staging(self.workspace_root, staged_root)
            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))
        committed = False

        if commit and patch_res.applied and not plan.rejected and assurance >= self.min_assurance:
            real_fs = self._os_fs(self.workspace_root)
            tx = real_fs.begin_transaction()
            real_fs.stage_write_text(tx, rel_posix, patch_res.updated_text)
            real_fs.commit_transaction(tx)
            committed = True

        return SessionResult(
            case_id=case_id,
            verdict=verdict,
            assurance=assurance,
            reason=str(decision.get("reason", "")),
            detail=str(decision.get("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.

        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()
            _copy_workspace_for_staging(self.workspace_root, staged_root)
            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))
        committed = False

        if commit and assurance >= needed:
            real_fs = self._os_fs(self.workspace_root)
            tx = real_fs.begin_transaction()
            for edit in plan.edits:
                real_fs.stage_write_text(tx, edit.file, patched[edit.file])
            real_fs.commit_transaction(tx)
            committed = True

        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=str(decision.get("reason", "")),
            detail=str(decision.get("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("\\", "/")
        target = self.workspace_root / Path(*rel_posix.split("/"))
        if target.exists():
            raise FileExistsError(f"target already exists: '{rel_posix}'")

        guard = PathGuard(self.policy())
        try:
            plan = guard.plan_transaction([PlannedOp(op=OP_WRITE, rel_posix=rel_posix, content=content)])
        except PathSecurityError:
            return self.edit_file(rel_posix, "# NEW_FILE", content, case_id=case_id, note=note, commit=False)

        marker = "# __LGPYTHON_NEW_FILE__\n"
        with tempfile.TemporaryDirectory(prefix="lingologos_python_create_") as tmp_dir:
            staged_root = Path(tmp_dir).resolve()
            _copy_workspace_for_staging(self.workspace_root, staged_root)
            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))
        committed = False
        if commit and not plan.rejected and assurance >= self.min_assurance:
            real_fs = self._os_fs(self.workspace_root)
            tx = real_fs.begin_transaction()
            real_fs.stage_write_text(tx, rel_posix, content)
            real_fs.commit_transaction(tx)
            committed = True

        return SessionResult(
            case_id=case_id,
            verdict=verdict,
            assurance=assurance,
            reason=str(decision.get("reason", "")),
            detail=str(decision.get("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()
            _copy_workspace_for_staging(self.workspace_root, staged_root)
            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()

            # Evaluate syntax over remaining files by targeting a surviving file if available
            remaining = [p for p in discover_python_files(staged_root) if p != rel_posix]
            gate_target = remaining[0] if remaining else rel_posix
            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),
                **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))
        committed = False
        if commit and not plan.rejected and assurance >= self.min_assurance:
            guard.resolve_safe(rel_posix, for_write=True)
            current = self.workspace_root
            for part in Path(*rel_posix.split("/")).parts:
                current = current / part
                if current.is_symlink():
                    raise PathSecurityError(f"refusing to delete across symlink: '{rel_posix}'")
            if target.is_file():
                target.unlink()
            committed = True

        return SessionResult(
            case_id=case_id,
            verdict=verdict,
            assurance=assurance,
            reason=str(decision.get("reason", "")),
            detail=str(decision.get("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 sig:
                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