File size: 34,173 Bytes
339ddd8
 
 
 
8947d88
f4952b6
 
ba784dc
c35ac38
339ddd8
1ed2d7f
339ddd8
8947d88
 
e1de134
 
8947d88
c35ac38
8947d88
ba784dc
8947d88
 
 
 
 
 
 
 
 
 
339ddd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
f628309
 
 
 
 
 
 
 
 
 
 
 
 
ba784dc
f628309
 
 
 
 
 
 
 
ba784dc
 
 
 
f628309
 
1ed2d7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8947d88
 
 
48f2b75
8947d88
 
 
 
 
 
48f2b75
8947d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f2b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35ac38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f2b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da61666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba784dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba784dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tests for PythonWorkspaceSession transactional editing, verification, and rollback."""

from __future__ import annotations

import os
import subprocess
import sys
import threading
import time
from pathlib import Path
from typing import Any, Dict, Tuple

import pytest

from lingologos_codex.fsadapter import FileSystemAdapterError

import lingologos_python.session as session_module
from lingologos_python.adapter import GATE_TIMEOUT_ENV
from lingologos_python.session import (
    HARDLINKED_PATH_IN_WORKSPACE,
    LINKED_PATH_IN_WORKSPACE,
    NODE_TIMEOUT,
    NodeTimeoutError,
    PythonWorkspaceSession,
    SessionResult,
    WorkspaceLinkError,
    _verify_probe,
)


def test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None:
    session = PythonWorkspaceSession(sample_pkg)
    res = session.verify("src/mathops.py")
    assert res.verdict == "VERIFIED"
    assert res.assurance == 3
    assert res.committed is False


def test_edit_file_commits_only_when_verified(sample_pkg: Path) -> None:
    session = PythonWorkspaceSession(sample_pkg)

    res = session.edit_file(
        "src/mathops.py",
        "return left + right",
        "return int(left) + int(right)",
        commit=True,
    )
    assert res.verdict == "VERIFIED"
    assert res.assurance == 3
    assert res.committed is True
    assert "return int(left) + int(right)" in (sample_pkg / "src" / "mathops.py").read_text(
        encoding="utf-8"
    )


def test_edit_file_does_not_touch_disk_when_tests_fail(sample_pkg: Path) -> None:
    session = PythonWorkspaceSession(sample_pkg)
    before = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8")

    res = session.edit_file(
        "src/mathops.py",
        "return left + right",
        "return left - right",
        commit=True,
    )
    after = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8")
    assert res.verdict == "UNKNOWN"
    assert res.reason == "GATE_REJECTED"
    assert res.committed is False
    assert before == after


def test_edit_file_refuses_protected_and_traversal_paths(sample_pkg: Path) -> None:
    (sample_pkg / ".env").write_text("KEY=1\n", encoding="utf-8")
    session = PythonWorkspaceSession(sample_pkg)

    env_res = session.edit_file(".env", "KEY=1", "KEY=2", commit=True)
    assert env_res.verdict == "UNKNOWN"
    assert env_res.reason == "PROTECTED_PATH"
    assert env_res.committed is False
    assert (sample_pkg / ".env").read_text(encoding="utf-8") == "KEY=1\n"

    esc_res = session.edit_file("../outside.py", "a = 1", "a = 2", commit=True)
    assert esc_res.verdict == "UNKNOWN"
    assert esc_res.reason in ("PROTECTED_PATH", "NOT_APPLIED")
    assert esc_res.committed is False


def test_create_and_delete_file_transactions(sample_pkg: Path) -> None:
    session = PythonWorkspaceSession(sample_pkg)

    created = session.create_file(
        "src/helper.py",
        '"""Extra module."""\n\n\ndef square(x: int) -> int:\n    return x * x\n',
        commit=True,
    )
    assert created.verdict == "VERIFIED"
    assert created.committed is True
    assert (sample_pkg / "src" / "helper.py").is_file()

    deleted = session.delete_file("src/helper.py", commit=True)
    assert deleted.verdict == "VERIFIED"
    assert deleted.committed is True
    assert not (sample_pkg / "src" / "helper.py").exists()


def test_retry_loop_stops_on_identical_failure_stall(sample_pkg: Path) -> None:
    session = PythonWorkspaceSession(sample_pkg)

    def repeated_bad_edit(attempt: int, last_result: object) -> tuple[str, str]:
        return ("return left + right", "return left - right")

    final, attempts = session.run_retry_loop("src/mathops.py", repeated_bad_edit, max_attempts=5)
    assert final.verdict == "UNKNOWN"
    assert len(attempts) == 2
    assert any(c.get("role") == "adversary_loop" for c in final.dossier.get("checkers", []))


def test_a_three_argument_proposer_is_handed_the_failure_it_should_learn_from(sample_pkg: Path) -> None:
    session = PythonWorkspaceSession(sample_pkg)
    seen: Dict[str, object] = {}

    def learning_proposer(attempt: int, last_result: object, context: object) -> tuple[str, str]:
        if attempt == 1:
            # An anchor that is not in the file: the patch is not applied, so the
            # second attempt is a move and not the loop the stall detector blocks.
            return ("return left * right", "return left / right")
        seen["reasons"] = tuple(context.failure_reasons)
        seen["trace"] = context.attempts[0].trace
        seen["attempt"] = context.attempt
        seen["path"] = context.rel_path
        seen["signatures"] = tuple(context.patch_signatures)
        return ("return left + right", "return left + right  # proposed again")

    final, _attempts = session.run_retry_loop("src/mathops.py", learning_proposer, max_attempts=3)
    assert final.committed is True
    assert seen["reasons"]
    assert len(seen["trace"]) >= 6
    assert seen["attempt"] == 2
    assert seen["path"] == "src/mathops.py"
    # The fate of the first patch, not its words: the signature the stall
    # detector read is handed to the proposer that should learn from it.
    assert len(seen["signatures"]) == 1
    assert seen["signatures"][0].startswith("sha256:") or len(seen["signatures"][0]) == 40


def test_verify_probe_annotates_a_line_that_keeps_the_file_parsable() -> None:
    text = '"""Module doc.\n\nSpread over several lines.\n"""\n\n\ndef go() -> int:\n    return 1\n'
    search, replace, original = _verify_probe(text)
    assert search == "def go() -> int:"
    assert replace == search + "  # codex-verify-probe\n"
    assert original is text
    compile(original.replace(search, replace, 1), "module.py", "exec")
    empty_search, _empty_replace, empty_text = _verify_probe("")
    assert empty_text == "# empty\n"
    assert empty_search in empty_text


def test_edit_file_refuses_when_the_file_moved_during_the_run(sample_pkg: Path, monkeypatch) -> None:
    session = PythonWorkspaceSession(sample_pkg)
    real_run = session._run_six_nodes

    def run_with_a_moving_workspace(case: Dict[str, Any]) -> Tuple[Any, ...]:
        path = sample_pkg / "src" / "mathops.py"
        path.write_text(
            path.read_text(encoding="utf-8", newline="").replace(
                "return left + right", "return left + right  # moved"
            ),
            encoding="utf-8",
            newline="",
        )
        return real_run(case)

    monkeypatch.setattr(session, "_run_six_nodes", run_with_a_moving_workspace)
    res = session.edit_file(
        "src/mathops.py",
        "return left + right",
        "return int(left) + int(right)",
        commit=True,
    )
    assert res.verdict == "REFUSED"
    assert res.reason == "PATCH_NOT_APPLIED"
    assert res.committed is False
    on_disk = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8")
    assert "# moved" in on_disk
    assert "int(left)" not in on_disk


def test_create_file_refuses_when_a_file_landed_at_its_path_during_the_run(
    sample_pkg: Path, monkeypatch
) -> None:
    session = PythonWorkspaceSession(sample_pkg)
    real_run = session._run_six_nodes

    def run_that_lands_a_file(case: Dict[str, Any]) -> Tuple[Any, ...]:
        (sample_pkg / "src" / "landed.py").write_text("VALUE = 1\n", encoding="utf-8", newline="\n")
        return real_run(case)

    monkeypatch.setattr(session, "_run_six_nodes", run_that_lands_a_file)
    res = session.create_file("src/landed.py", "VALUE = 2\n", commit=True)
    assert res.verdict == "REFUSED"
    assert res.reason == "PATCH_NOT_APPLIED"
    assert res.committed is False
    assert (sample_pkg / "src" / "landed.py").read_text(encoding="utf-8") == "VALUE = 1\n"


def test_retry_loop_spots_repetition_even_without_a_patch_signature(
    sample_pkg: Path, monkeypatch
) -> None:
    session = PythonWorkspaceSession(sample_pkg)

    def always_unknown(rel_path: str, search: str, replace: str, **kwargs: Any) -> SessionResult:
        return SessionResult(
            case_id=str(kwargs.get("case_id", "python-edit")),
            verdict="UNKNOWN",
            assurance=0,
            reason="GATE_REJECTED",
            detail="",
            committed=False,
        )

    monkeypatch.setattr(session, "edit_file", always_unknown)

    def same_proposal(attempt: int, last_result: object) -> tuple:
        return ("return left + right", "return left - right")

    final, attempts = session.run_retry_loop("src/mathops.py", same_proposal, max_attempts=5)
    assert final.verdict == "UNKNOWN"
    assert len(attempts) == 2


def test_create_file_refuses_an_escaping_path_before_touching_it(tmp_path: Path) -> None:
    """The path policy answers before the workspace code probes the named path.

    Joining the workspace root with an absolute path replaces the root on Windows,
    so an exists probe placed before the guard reaches files outside the workspace
    and can even name one back in an error.
    """
    ws = tmp_path / "ws"
    ws.mkdir()
    (ws / "value.py").write_text("VALUE = 1\n", encoding="utf-8")
    outside = tmp_path / "outside.py"
    outside.write_text("VALUE = 1\n", encoding="utf-8", newline="")

    session = PythonWorkspaceSession(ws)
    res = session.create_file(str(outside), "VALUE = 2\n", commit=True)
    assert res.committed is False
    assert res.verdict in ("UNKNOWN", "REFUSED")
    assert outside.read_text(encoding="utf-8", newline="") == "VALUE = 1\n"


def test_a_commit_refused_by_the_disk_restores_the_file_from_memory(
    sample_pkg: Path, monkeypatch
) -> None:
    """A commit that fails mid flight must not leave the run claiming a write it lost."""
    session = PythonWorkspaceSession(sample_pkg)
    real_os_fs = session._os_fs

    class CommitRefusingFs:
        def __init__(self, inner: Any) -> None:
            self._inner = inner

        def __getattr__(self, name: str) -> Any:
            return getattr(self._inner, name)

        def commit_transaction(self, tx: Any) -> None:
            raise FileSystemAdapterError("the disk refused the replace")

    def os_fs(root: Path, *, check_allowed: bool = True) -> Any:
        fs = real_os_fs(root, check_allowed=check_allowed)
        if Path(root).resolve() == sample_pkg.resolve():
            return CommitRefusingFs(fs)
        return fs

    monkeypatch.setattr(session, "_os_fs", os_fs)
    before = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="")
    res = session.edit_file(
        "src/mathops.py",
        "return left + right",
        "return int(left) + int(right)",
        commit=True,
    )
    after = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="")
    assert res.verdict == "REFUSED"
    assert res.reason == "PATCH_NOT_APPLIED"
    assert res.committed is False
    assert "refused the replace" in res.detail
    assert before == after


def test_a_delete_refused_by_the_disk_leaves_the_file_in_place(
    sample_pkg: Path, monkeypatch
) -> None:
    """A delete goes through the kernel transaction, and committed only says the file is gone."""
    session = PythonWorkspaceSession(sample_pkg)
    created = session.create_file(
        "src/helper.py", '"""Extra module."""\n\nVALUE = 1\n', commit=True
    )
    assert created.committed is True

    real_os_fs = session._os_fs

    class DeleteRefusingFs:
        def __init__(self, inner: Any) -> None:
            self._inner = inner

        def __getattr__(self, name: str) -> Any:
            return getattr(self._inner, name)

        def stage_delete(self, tx: Any, rel_path: str) -> None:
            raise FileSystemAdapterError("the disk refused the removal")

    def os_fs(root: Path, *, check_allowed: bool = True) -> Any:
        fs = real_os_fs(root, check_allowed=check_allowed)
        if Path(root).resolve() == sample_pkg.resolve():
            return DeleteRefusingFs(fs)
        return fs

    monkeypatch.setattr(session, "_os_fs", os_fs)
    res = session.delete_file("src/helper.py", commit=True)
    assert res.verdict == "REFUSED"
    assert res.reason == "PATCH_NOT_APPLIED"
    assert res.committed is False
    helper = sample_pkg / "src" / "helper.py"
    assert helper.is_file()
    assert helper.read_text(encoding="utf-8", newline="") == '"""Extra module."""\n\nVALUE = 1\n'


def test_a_linked_directory_in_the_workspace_refuses_any_staged_run(
    sample_pkg: Path, tmp_path: Path, dir_link
) -> None:
    """A junction or symlink makes the staging copy lie, so the session refuses by name."""
    outside = tmp_path / "outside"
    outside.mkdir()
    (outside / "elsewhere.py").write_text("SECRET = 1\n", encoding="ascii", newline="")
    link = sample_pkg / "vendor"
    if not dir_link(link, outside):
        pytest.skip("this host offers no way to create a directory link")

    session = PythonWorkspaceSession(sample_pkg)
    res = session.edit_file(
        "src/mathops.py",
        "return left + right",
        "return int(left) + int(right)",
        commit=False,
    )
    assert res.verdict == "REFUSED"
    assert res.reason == LINKED_PATH_IN_WORKSPACE
    assert "vendor" in res.detail
    assert res.committed is False
    created = session.create_file("src/newcomer.py", "VALUE = 1\n", commit=True)
    assert created.verdict == "REFUSED"
    assert created.reason == LINKED_PATH_IN_WORKSPACE
    assert created.committed is False
    assert not (sample_pkg / "src" / "newcomer.py").exists()
    assert (outside / "elsewhere.py").read_text(encoding="utf-8") == "SECRET = 1\n"


def test_the_staging_copy_refuses_a_linked_file_by_name(sample_pkg: Path, tmp_path: Path) -> None:
    """The refusal is not limited to directories: one linked file is enough."""
    target = tmp_path / "outside_helper.py"
    target.write_text("VALUE = 1\n", encoding="ascii", newline="")
    link = sample_pkg / "src" / "linked.py"
    try:
        os.symlink(str(target), str(link))
    except (OSError, NotImplementedError):
        pytest.skip("this host does not allow creating a file symlink")
    with pytest.raises(WorkspaceLinkError) as caught:
        session_module._copy_workspace_for_staging(sample_pkg, tmp_path / "staged")
    assert "src/linked.py" in str(caught.value)


def test_a_node_that_exhausts_its_budget_raises_a_named_error(tmp_path: Path) -> None:
    """The subprocess runner turns an exhausted per-node budget into NodeTimeoutError."""
    stub = tmp_path / "sleeping_agent.py"
    stub.write_text("import time\n\ntime.sleep(30)\n", encoding="ascii", newline="")
    with pytest.raises(NodeTimeoutError) as caught:
        session_module.run_topology_subprocesses(
            {"case_id": "budget"}, agent_script=stub, timeout_sec=1.0
        )
    assert "exhausted its" in str(caught.value)


def test_a_timed_out_node_answers_unknown_instead_of_a_traceback(
    sample_pkg: Path, tmp_path: Path, monkeypatch
) -> None:
    """The session reports the budget refusal with a reason, like any other abstain."""
    stub = tmp_path / "sleeping_agent.py"
    stub.write_text("import time\n\ntime.sleep(30)\n", encoding="ascii", newline="")
    monkeypatch.setattr(session_module, "DEFAULT_AGENT_SCRIPT", stub)
    session = PythonWorkspaceSession(sample_pkg, use_subprocesses=True, node_timeout_sec=1.0)
    res = session.verify("src/mathops.py")
    assert res.verdict == "UNKNOWN"
    assert res.reason == NODE_TIMEOUT
    assert res.assurance == 0
    assert res.committed is False


def test_a_total_budget_shrinks_the_wait_of_the_first_node(tmp_path: Path) -> None:
    """A node gets the smaller of its own budget and what the total still allows."""
    stub = tmp_path / "sleeping_agent.py"
    stub.write_text("import time\n\ntime.sleep(30)\n", encoding="ascii", newline="")
    with pytest.raises(NodeTimeoutError) as caught:
        session_module.run_topology_subprocesses(
            {"case_id": "total"}, agent_script=stub, timeout_sec=30.0, total_budget_sec=1.0
        )
    assert "exhausted its 1.0 s budget" in str(caught.value)


def test_a_spent_total_budget_refuses_a_node_before_starting_it(tmp_path: Path, monkeypatch) -> None:
    """Once the total is gone, the run says so instead of paying for one more node."""
    echo = tmp_path / "echo_agent.py"
    echo.write_text("import sys\n\nsys.stdout.write(sys.stdin.read())\n", encoding="ascii", newline="")
    clock = iter([1000.0, 1000.5, 2000.0])
    monkeypatch.setattr(session_module, "_MONOTONIC", lambda: next(clock))
    with pytest.raises(NodeTimeoutError) as caught:
        session_module.run_topology_subprocesses(
            {"case_id": "late"}, agent_script=echo, timeout_sec=10.0, total_budget_sec=5.0
        )
    assert "total budget" in str(caught.value)


def test_a_nonpositive_budget_is_refused_before_anything_runs(sample_pkg: Path) -> None:
    """A budget of zero seconds is a mistake, not a promise to abstain instantly."""
    with pytest.raises(ValueError):
        session_module.run_topology_subprocesses({"case_id": "bad"}, timeout_sec=0.0)
    with pytest.raises(ValueError):
        PythonWorkspaceSession(sample_pkg, total_budget_sec=-1.0)
    with pytest.raises(ValueError):
        PythonWorkspaceSession(sample_pkg, gate_timeout_sec=0.0)


def test_the_session_hands_its_gate_budget_to_the_environment(
    sample_pkg: Path, monkeypatch
) -> None:
    """The kernel builds the adapter from a ref string, so the environment carries the number."""
    monkeypatch.delenv(GATE_TIMEOUT_ENV, raising=False)
    session = PythonWorkspaceSession(sample_pkg, gate_timeout_sec=2.5)
    previous = session._enter_gate_timeout_env()
    try:
        assert os.environ[GATE_TIMEOUT_ENV] == "2.5"
    finally:
        session._exit_gate_timeout_env(previous)
    assert GATE_TIMEOUT_ENV not in os.environ


def test_a_test_runner_that_outruns_its_gate_budget_abstains(sample_pkg: Path) -> None:
    """A runner that hangs is answered with a named abstain, not an endless wait."""
    sleeper = sample_pkg / "tests" / "conftest.py"
    sleeper.write_text("import time\n\ntime.sleep(60)\n", encoding="ascii", newline="")
    session = PythonWorkspaceSession(sample_pkg, gate_timeout_sec=2.0)
    started = time.monotonic()
    res = session.verify("src/mathops.py")
    elapsed = time.monotonic() - started
    assert res.verdict == "UNKNOWN"
    assert res.reason == "GATE_ABSTAIN"
    assert res.committed is False
    # The runner sleeps for a minute; a run that comes back long before it was
    # waited out, and abstains instead of passing, was cut by the budget.
    assert elapsed < 30.0
    assert "abstained" in res.detail


def test_a_junction_created_while_the_gates_run_is_refused_at_commit(
    sample_pkg: Path, tmp_path: Path, dir_link
) -> None:
    """The commit re-asks the link question, so a link that appeared mid-run is refused too."""
    vendor = tmp_path / "vendor"
    vendor.mkdir()
    (vendor / "helper.py").write_text("VALUE = 1\n", encoding="ascii", newline="")
    if not dir_link(tmp_path / "probe_link", vendor):
        pytest.skip("this host offers no way to create a directory link")
    link = sample_pkg / "vendor_link"
    hook = sample_pkg / "tests" / "conftest.py"
    hook.write_text(
        "import subprocess\n"
        "import sys\n\n"
        "VENDOR = %r\n"
        "LINK = %r\n\n\n"
        "def pytest_configure(config):\n"
        "    try:\n"
        "        if sys.platform == 'win32':\n"
        "            subprocess.run(\n"
        "                ['cmd', '/c', 'mklink', '/J', LINK, VENDOR],\n"
        "                stdin=subprocess.DEVNULL,\n"
        "                stdout=subprocess.DEVNULL,\n"
        "                stderr=subprocess.DEVNULL,\n"
        "            )\n"
        "        else:\n"
        "            import os\n\n"
        "            os.symlink(VENDOR, LINK, target_is_directory=True)\n"
        "    except OSError:\n"
        "        pass\n" % (str(vendor), str(link)),
        encoding="ascii",
        newline="",
    )
    session = PythonWorkspaceSession(sample_pkg)
    res = session.edit_file(
        "src/mathops.py",
        "return left + right",
        "return int(left) + int(right)",
        commit=True,
    )
    assert res.verdict == "REFUSED"
    assert res.reason == LINKED_PATH_IN_WORKSPACE
    assert res.committed is False
    assert "before the commit" in res.detail
    text = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="")
    assert "return left + right" in text


def test_verify_refuses_a_workspace_held_together_by_a_link(
    sample_pkg: Path, tmp_path: Path, dir_link
) -> None:
    """verify has no staging copy to refuse for it, so it asks the link question itself."""
    outside = tmp_path / "outside"
    outside.mkdir()
    (outside / "elsewhere.py").write_text("VALUE = 1\n", encoding="ascii", newline="")
    link = sample_pkg / "vendor"
    if not dir_link(link, outside):
        pytest.skip("this host offers no way to create a directory link")
    session = PythonWorkspaceSession(sample_pkg)
    res = session.verify("src/mathops.py")
    assert res.verdict == "REFUSED"
    assert res.reason == LINKED_PATH_IN_WORKSPACE
    assert res.assurance == 0
    assert "vendor" in res.detail
    assert res.touched_files == ("vendor",)


def test_a_second_session_on_one_workspace_is_answered_session_locked(
    sample_pkg: Path,
) -> None:
    """The lock is an exclusive create, so claiming a held workspace is a refusal, not a queue."""
    session = PythonWorkspaceSession(sample_pkg)
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    assert not lock.exists()
    handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    try:
        os.write(handle, str(os.getpid()).encode("ascii"))
    finally:
        os.close(handle)
    res = session.verify("src/mathops.py")
    assert res.verdict == "REFUSED"
    assert res.reason == session_module.SESSION_LOCKED
    assert res.committed is False
    assert str(os.getpid()) in res.detail
    lock.unlink()
    again = session.verify("src/mathops.py")
    assert again.verdict == "VERIFIED"


def test_a_locked_edit_refuses_before_reading_anything(sample_pkg: Path) -> None:
    """The refusal precedes the edit machinery: no staging copy, no disk read of the pair."""
    session = PythonWorkspaceSession(sample_pkg)
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    try:
        os.write(handle, str(os.getpid()).encode("ascii"))
    finally:
        os.close(handle)
    res = session.edit_file(
        "src/mathops.py", "return left + right", "return left * right", commit=True
    )
    assert res.verdict == "REFUSED"
    assert res.reason == session_module.SESSION_LOCKED
    assert res.touched_files == ("src/mathops.py",)
    text = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="")
    assert "return left + right" in text
    lock.unlink()


def test_the_lock_lives_for_exactly_the_length_of_a_run(
    sample_pkg: Path, monkeypatch
) -> None:
    """Held while the six nodes judge, gone the moment the run ends, refusal included."""
    session = PythonWorkspaceSession(sample_pkg)
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    seen = {}
    real_pipeline = session_module.run_pipeline

    def spy_pipeline(case):
        seen["held_mid_run"] = lock.exists()
        return real_pipeline(case)

    monkeypatch.setattr(session_module, "run_pipeline", spy_pipeline)
    res = session.verify("src/mathops.py")
    assert res.verdict == "VERIFIED"
    assert seen.get("held_mid_run") is True
    assert not lock.exists()


def test_a_lock_left_by_a_dead_process_is_taken_over(sample_pkg: Path) -> None:
    """A leftover lock names a process that no longer runs; the takeover is honest, not rude."""
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    lock.write_text("99999999\n", encoding="ascii", newline="")
    session = PythonWorkspaceSession(sample_pkg)
    res = session.verify("src/mathops.py")
    assert res.verdict == "VERIFIED"
    assert not lock.exists()


def test_a_lock_whose_owner_cannot_be_read_is_never_stolen(sample_pkg: Path) -> None:
    """Unreadable owner means a live holder we cannot name: the refusal stands."""
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    lock.write_text("not a pid\n", encoding="ascii", newline="")
    session = PythonWorkspaceSession(sample_pkg)
    res = session.verify("src/mathops.py")
    assert res.verdict == "REFUSED"
    assert res.reason == session_module.SESSION_LOCKED
    assert "cannot be read" in res.detail
    lock.unlink()


def test_the_lock_file_names_pid_birth_and_a_token_this_run_can_prove(
    sample_pkg: Path, monkeypatch
) -> None:
    """The written record carries three fields, and the token belongs to this acquisition."""
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    seen: Dict[str, str] = {}
    real_pipeline = session_module.run_pipeline

    def spy_pipeline(case):
        seen["record"] = lock.read_text(encoding="ascii")
        return real_pipeline(case)

    monkeypatch.setattr(session_module, "run_pipeline", spy_pipeline)
    session = PythonWorkspaceSession(sample_pkg)
    res = session.verify("src/mathops.py")
    assert res.verdict == "VERIFIED"
    parts = seen["record"].split()
    assert parts[0] == str(os.getpid())
    assert parts[1] != "-" and int(parts[1]) > 0
    assert len(parts[2]) == 32
    assert not lock.exists()


def test_a_recycled_pid_with_a_different_birth_is_not_the_recorded_holder(
    sample_pkg: Path,
) -> None:
    """A live pid is not proof: the birth time written in the lock has to match."""
    birth = session_module._process_creation_time(os.getpid())
    if birth is None:
        pytest.skip("this host does not report process birth times")
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    lock.write_text("%d %d t0k0n\n" % (os.getpid(), birth + 10**9), encoding="ascii", newline="")
    session = PythonWorkspaceSession(sample_pkg)
    res = session.verify("src/mathops.py")
    # The number answers, the birth does not: the holder recorded is gone and
    # the takeover is honest.
    assert res.verdict == "VERIFIED"
    assert not lock.exists()


def test_two_runs_taking_over_one_leftover_lock_leave_a_single_holder(sample_pkg: Path) -> None:
    """The takeover renames the corpse first: the loser of the rename is refused."""
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    lock.write_text("99999999\n", encoding="ascii", newline="")
    sessions = [PythonWorkspaceSession(sample_pkg) for _ in range(2)]
    outcomes: Dict[int, str] = {}
    gate = threading.Barrier(2)

    def grab(index: int) -> None:
        try:
            gate.wait()
            sessions[index]._acquire_session_lock()
            outcomes[index] = "held"
        except session_module.SessionLockError:
            outcomes[index] = "refused"

    threads = [threading.Thread(target=grab, args=(i,)) for i in range(2)]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()
    assert sorted(outcomes.values()) == ["held", "refused"]
    record = session_module._read_lock_record(lock)
    assert record is not None and record[0] == os.getpid()
    winner = sessions[next(i for i, v in outcomes.items() if v == "held")]
    winner._release_session_lock()
    assert not lock.exists()
    stale = sample_pkg / (session_module.SESSION_LOCK_NAME + session_module.SESSION_LOCK_CLAIM_SUFFIX)
    assert not stale.exists()


def test_a_run_never_unlinks_a_lock_another_run_retook(
    sample_pkg: Path, monkeypatch
) -> None:
    """Release checks its own token: a lock rewritten while we run is not ours to delete."""
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    real_pipeline = session_module.run_pipeline

    def hijack_pipeline(case):
        # Mid-run, a different holder takes the workspace over under our name.
        lock.write_text("99999999 - someone-elses-token\n", encoding="ascii", newline="")
        return real_pipeline(case)

    monkeypatch.setattr(session_module, "run_pipeline", hijack_pipeline)
    session = PythonWorkspaceSession(sample_pkg)
    res = session.verify("src/mathops.py")
    assert res.verdict == "VERIFIED"
    # Our release read the token, found it was not ours, and left the lock alone.
    assert lock.exists()
    assert "someone-elses-token" in lock.read_text(encoding="ascii")
    lock.unlink()


def test_a_commit_refuses_when_the_lock_stops_naming_the_run(
    sample_pkg: Path, monkeypatch
) -> None:
    """The commit re-asks the lock question: a stolen lock stops the write."""
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    real_pipeline = session_module.run_pipeline

    def hijack_pipeline(case):
        lock.write_text("99999999 - someone-elses-token\n", encoding="ascii", newline="")
        return real_pipeline(case)

    monkeypatch.setattr(session_module, "run_pipeline", hijack_pipeline)
    session = PythonWorkspaceSession(sample_pkg)
    target = sample_pkg / "src" / "mathops.py"
    before = target.read_bytes()
    res = session.edit_file(
        "src/mathops.py", "return left + right", "return int(left) + int(right)", commit=True
    )
    assert res.verdict == "REFUSED"
    assert res.reason == session_module.SESSION_LOCKED
    assert res.committed is False
    assert target.read_bytes() == before
    assert "someone-elses-token" in lock.read_text(encoding="ascii")
    lock.unlink()


def test_a_commit_refuses_when_the_lock_disappears_mid_run(
    sample_pkg: Path, monkeypatch
) -> None:
    """A lock unlinked while the run works leaves the commit without a holder."""
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    real_pipeline = session_module.run_pipeline

    def vanish_pipeline(case):
        lock.unlink()
        return real_pipeline(case)

    monkeypatch.setattr(session_module, "run_pipeline", vanish_pipeline)
    session = PythonWorkspaceSession(sample_pkg)
    target = sample_pkg / "src" / "mathops.py"
    before = target.read_bytes()
    res = session.edit_file(
        "src/mathops.py", "return left + right", "return int(left) + int(right)", commit=True
    )
    assert res.verdict == "REFUSED"
    assert res.reason == session_module.SESSION_LOCKED
    assert target.read_bytes() == before


def test_a_hardlinked_pair_in_the_workspace_is_refused_by_name(sample_pkg: Path) -> None:
    """Two names, one file: the copy would split what the disk holds as one."""
    twin = sample_pkg / "src" / "mathops_twin.py"
    os.link(sample_pkg / "src" / "mathops.py", twin)
    session = PythonWorkspaceSession(sample_pkg)
    res = session.verify("src/mathops.py")
    assert res.verdict == "REFUSED"
    assert res.reason == HARDLINKED_PATH_IN_WORKSPACE
    assert "src/mathops" in res.detail
    twin.unlink()


def test_an_edit_does_not_commit_through_a_hardlinked_name(sample_pkg: Path) -> None:
    """The staging copy refuses the hardlink and the real file keeps its bytes."""
    twin = sample_pkg / "src" / "mathops_twin.py"
    os.link(sample_pkg / "src" / "mathops.py", twin)
    session = PythonWorkspaceSession(sample_pkg)
    res = session.edit_file(
        "src/mathops.py", "return left + right", "return left * right", commit=True
    )
    assert res.verdict == "REFUSED"
    assert res.reason == HARDLINKED_PATH_IN_WORKSPACE
    assert res.committed is False
    text = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="")
    assert "return left + right" in text
    twin.unlink()


def test_a_killed_session_freezes_no_tree_and_blocks_no_next_run(
    sample_pkg: Path, tmp_path: Path
) -> None:
    """The crash drill: kill a live session mid run and check what the disk keeps.

    A helper process takes the workspace lock and starts an edit; the test
    kills it as soon as the lock appears, while the six nodes are still
    talking and no commit has been attempted. The tree must hold exactly the
    bytes it held before, the lock must stay behind naming a process that no
    longer runs, and the next session must take that leftover over and finish
    the very edit the killed run left undone.
    """
    helper_path = sample_pkg / "src" / "crashme.py"
    helper_path.write_text('"""Crash subject."""\n\nVALUE = 1\n', encoding="utf-8", newline="")
    script = tmp_path / "crash_helper.py"
    script.write_text(
        "import sys\n"
        "from lingologos_python.session import PythonWorkspaceSession\n"
        "session = PythonWorkspaceSession(sys.argv[1])\n"
        "res = session.edit_file('src/crashme.py', 'VALUE = 1', 'VALUE = 2')\n"
        "print(res.verdict)\n",
        encoding="utf-8",
        newline="",
    )
    root = Path(__file__).resolve().parents[1]
    proc = subprocess.Popen(
        [sys.executable, "-B", str(script), str(sample_pkg)],
        cwd=str(root),
        env=dict(os.environ, PYTHONPATH=str(root)),
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    lock = sample_pkg / session_module.SESSION_LOCK_NAME
    deadline = time.monotonic() + 20.0
    while not lock.is_file() and time.monotonic() < deadline:
        if proc.poll() is not None:
            pytest.fail("the helper session ended before it took the workspace lock")
        time.sleep(0.05)
    assert lock.is_file(), "the helper session never took the workspace lock"
    proc.kill()
    proc.wait(timeout=10)

    assert helper_path.read_text(encoding="utf-8") == '"""Crash subject."""\n\nVALUE = 1\n'
    status = session_module.workspace_lock_status(sample_pkg)
    assert status["present"] is True
    assert status["held"] is False
    assert status["stale"] is True

    session = PythonWorkspaceSession(sample_pkg)
    res = session.edit_file("src/crashme.py", "VALUE = 1", "VALUE = 2", commit=True)
    assert res.verdict == "VERIFIED"
    assert res.assurance == 3
    assert res.committed is True
    assert "VALUE = 2" in helper_path.read_text(encoding="utf-8")
    assert session_module.workspace_lock_status(sample_pkg)["present"] is False