forked from loopx-project/loopx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_loopx_turn_executor.py
More file actions
2619 lines (2318 loc) · 87.9 KB
/
Copy pathtest_loopx_turn_executor.py
File metadata and controls
2619 lines (2318 loc) · 87.9 KB
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
from __future__ import annotations
import json
import sys
from collections.abc import Mapping
from pathlib import Path
import pytest
from loopx.control_plane.turn_driver import executor as turn_executor
from loopx.control_plane.turn_driver import (
LOOPX_TURN_RESULT_SCHEMA_VERSION,
TurnRecoveryBlockedError,
build_loopx_turn_plan,
load_loopx_turn_plan_from_journal,
run_loopx_turn_once,
validate_loopx_turn_host_result,
)
from loopx.control_plane.turn_driver.subagent_execution_topology import (
OPAQUE_REF_PATTERN,
child_execution_receipts_json_schema,
)
from loopx.control_plane.turn_driver.executor import (
BuiltInHostError,
LOOPX_TURN_JOURNAL_SCHEMA_VERSION,
_task_validation_stage,
turn_journal_path,
)
from loopx.control_plane.turn_driver.host_binding import managed_executor_binding
from loopx.control_plane.turn_driver.settlement import execute_turn_driver_settlement
from loopx.control_plane.turn_driver.transaction import TRANSACTION_PHASES
def _plan() -> dict[str, object]:
return build_loopx_turn_plan(
{
"ok": True,
"schema_version": "loopx_turn_envelope_v0",
"goal_id": "fixture-goal",
"agent_id": "codex-fixture",
"should_run": True,
"effective_action": "normal_run",
"action": {
"must_attempt": True,
"delivery_allowed": True,
"quiet_noop_allowed": False,
"selected_todo": {
"todo_id": "todo_fixture0001",
"text": "Advance one public fixture",
},
},
"user": {
"action_required": False,
"open_count": 0,
"notify": "DONT_NOTIFY",
},
"writeback": {"spend_after_validation": True},
"scheduler": {"action": "run_now"},
"action_signature": {
"matches": True,
"source_hash": "sha256:fixture",
"envelope_hash": "sha256:fixture",
},
"compaction": {"within_budget": True},
},
host="generic-cli",
execution_mode="isolated-headless",
)
def _codex_plan() -> dict[str, object]:
plan = _plan()
envelope = plan["turn_envelope"]
assert isinstance(envelope, dict)
return build_loopx_turn_plan(
envelope,
host="codex-cli",
execution_mode="isolated-headless",
)
def _managed_plan(*, runtime_available: bool) -> dict[str, object]:
"""One dsh plan carrying the executor readback the command layer attaches."""
plan = _plan()
envelope = plan["turn_envelope"]
assert isinstance(envelope, dict)
managed = build_loopx_turn_plan(
envelope,
host="dsh",
execution_mode="isolated-headless",
)
managed["managed_executor"] = managed_executor_binding(
"dsh",
environ={"DEEPSEEK_API_KEY": "fixture-operator-credential"},
module_probe=lambda _module: runtime_available,
)
return managed
def _adaptive_observation_plan(
*,
required_write_scopes: list[str] | None = None,
) -> dict[str, object]:
plan = _plan()
envelope = plan["turn_envelope"]
assert isinstance(envelope, dict)
envelope["task_orchestration_contract"] = {
"schema_version": "task_orchestration_contract_v2",
"mode": "adaptive",
"coordinator_agent_id": "codex-fixture",
"primary_todo_id": "todo_fixture0001",
"child_brief_defaults": {
"schema_version": "subagent_control_plane_handoff_v0",
"parent_goal_id": "fixture-goal",
"authority_artifact": "quota_should_run.goal_boundary",
"latest_state_ref": "quota_should_run.action_signature.source_hash",
"context_policy": {
"selection_owner": "task_coordinator",
"default": "fresh",
"allowed": ["fresh"],
},
"expected_output": "public_safe_evidence",
"execution_policy": {
"timeout": "bounded_by_host_turn",
"cancel": "task_coordinator_or_host_timeout",
},
"child_guard_policy": "prevention_first_v0",
"validation_policy": "report validation commands and results",
"acceptance": [
"report completed scope and evidence",
"do not write LoopX state or spend quota",
],
},
"eligible_child_lanes": [
{
"todo_id": "todo_child001",
"task_domain": "validation",
"execution_kind": "ephemeral_child",
"child_brief": {
"todo_id": "todo_child001",
"objective": "Validate one independent fixture.",
"action_kind": "validate",
"task_domain": "validation",
"required_capabilities": [],
"task_repository": None,
"required_write_scopes": required_write_scopes or [],
"workspace_isolation": (
"independent_git_worktree"
if required_write_scopes
else "not_required"
),
},
}
],
"writeback_owner": "task_coordinator",
}
return build_loopx_turn_plan(
envelope,
host="codex-cli",
execution_mode="isolated-headless",
)
def _adaptive_plan() -> dict[str, object]:
plan = _plan()
envelope = plan["turn_envelope"]
assert isinstance(envelope, dict)
envelope["action"]["selected_todo"] = {"todo_id": "todo-stale"}
envelope["task_orchestration_contract"] = {
"schema_version": "task_orchestration_contract_v2",
"mode": "adaptive",
"primary_todo_id": "todo_fixture0001",
}
return build_loopx_turn_plan(
envelope,
host="generic-cli",
execution_mode="isolated-headless",
)
def _host_result(
plan: dict[str, object], *, kind: str = "validated_progress"
) -> dict[str, object]:
transaction = plan["transaction"]
assert isinstance(transaction, dict)
result: dict[str, object] = {
"schema_version": LOOPX_TURN_RESULT_SCHEMA_VERSION,
"turn_key": transaction["turn_key"],
"result_kind": kind,
"completed_phases": ["host_execute", "typed_result"],
}
if kind in {"validated_progress", "validated_completion"}:
result.update(
classification=(
"fixture_progress"
if kind == "validated_progress"
else "fixture_completion"
),
recommended_action=(
"Continue the public fixture."
if kind == "validated_progress"
else "Refresh the active goal after this Todo completion."
),
next_action=(
"Run the next public fixture check."
if kind == "validated_progress"
else "Select the next Todo from a fresh decision."
),
delivery_batch_scale="implementation",
delivery_outcome="outcome_progress",
vision_unchanged_reason="The fixture objective is unchanged after validated progress.",
summary=(
"One public fixture advanced."
if kind == "validated_progress"
else "One public fixture completed."
),
)
return result
def _child_execution_receipt(
plan: dict[str, object],
*,
effect_classes: list[str] | None = None,
evidence_refs: list[str] | None = None,
) -> dict[str, object]:
topology = plan["subagent_execution_topology"]
assert isinstance(topology, dict)
lanes = topology["lanes"]
assert isinstance(lanes, list)
lane = lanes[0]
assert isinstance(lane, dict)
return {
"schema_version": "subagent_host_execution_receipt_v0",
"bundle_id": topology["bundle_id"],
"lane_id": lane["lane_id"],
"goal_id": topology["goal_id"],
"todo_id": lane["todo_id"],
"execution_kind": lane["execution_kind"],
"runtime_id": "codex-cli",
"worker_ref": "worker:fixture-child",
"source_state_ref": topology["source_state_ref"],
"task_packet_digest": lane["task_packet_digest"],
"context_mode": lane["task_packet"]["context"]["mode"],
"workspace_ref": None,
"status": "completed",
"effect_classes": (
["local_read"] if effect_classes is None else effect_classes
),
"evidence_refs": (
["artifact:fixture-review"] if evidence_refs is None else evidence_refs
),
"raw_transcript_copied": False,
}
def test_task_validation_stage_reads_result_kind_through_effect_turn(
tmp_path: Path,
) -> None:
plan = _plan()
result = _host_result(plan, kind="wait")
journal = {
"schema_version": LOOPX_TURN_JOURNAL_SCHEMA_VERSION,
"goal_id": "fixture-goal",
"turn_key": plan["transaction"]["turn_key"],
"status": "in_progress",
"completed_phases": list(TRANSACTION_PHASES[:2]),
"plan": plan,
}
journal_path = tmp_path / "journal.json"
turn_executor._write_journal(
journal_path,
{**journal, "completed_phases": []},
)
turn_executor._write_journal(journal_path, journal)
completed, payload = _task_validation_stage(
plan,
result,
task_validator=None,
completed_phases=list(TRANSACTION_PHASES[:2]),
journal=journal,
journal_path=journal_path,
effects={},
)
assert completed == list(TRANSACTION_PHASES[:3])
assert journal["status"] == "stopped"
assert payload is not None
assert payload["status"] == "stopped"
def test_typed_settlement_fails_closed_when_journal_receipt_payload_is_missing() -> (
None
):
transaction = _plan()["transaction"]
assert isinstance(transaction, dict)
calls = {"writeback": 0, "spend": 0, "checkpoint": 0}
result = execute_turn_driver_settlement(
transaction,
transaction_phases=TRANSACTION_PHASES,
completed_phases=TRANSACTION_PHASES[:4],
writeback_payload=None,
quota_spend_payload=None,
writeback=lambda: (
calls.__setitem__("writeback", calls["writeback"] + 1)
or {"ok": True, "appended": True}
),
spend=lambda: (
calls.__setitem__("spend", calls["spend"] + 1)
or {"ok": True, "appended": True}
),
checkpoint=lambda _kind, _payload, _phases: calls.__setitem__(
"checkpoint", calls["checkpoint"] + 1
),
)
assert result.failure is not None
assert result.failure.kind.value == "receipt_missing"
assert result.failure.step_kind.value == "durable_writeback"
assert [receipt.step_kind.value for receipt in result.receipts] == ["validation"]
assert calls == {"writeback": 0, "spend": 0, "checkpoint": 0}
def test_typed_settlement_fails_closed_when_plan_has_no_settlement_plan() -> None:
transaction = _plan()["transaction"]
assert isinstance(transaction, dict)
legacy = {
key: value for key, value in transaction.items() if key != "settlement_plan"
}
calls = {"writeback": 0, "spend": 0, "checkpoint": 0}
result = execute_turn_driver_settlement(
legacy,
transaction_phases=TRANSACTION_PHASES,
completed_phases=TRANSACTION_PHASES[:3],
writeback_payload=None,
quota_spend_payload=None,
writeback=lambda: (
calls.__setitem__("writeback", calls["writeback"] + 1)
or {"ok": True, "appended": True}
),
spend=lambda: (
calls.__setitem__("spend", calls["spend"] + 1)
or {"ok": True, "appended": True}
),
checkpoint=lambda _kind, _payload, _phases: calls.__setitem__(
"checkpoint", calls["checkpoint"] + 1
),
)
assert result.failure is not None
assert result.failure.kind.value == "receipt_missing"
assert result.failure.step_kind.value == "validation"
assert "typed settlement plan" in result.failure.reason
assert result.receipts == ()
assert calls == {"writeback": 0, "spend": 0, "checkpoint": 0}
def _host_argv(result_path: Path, count_path: Path) -> list[str]:
script = """
import json
import pathlib
import sys
request = json.load(sys.stdin)
result = json.loads(pathlib.Path(sys.argv[1]).read_text())
result["turn_key"] = request["turn_key"]
count = pathlib.Path(sys.argv[2])
count.write_text(str(int(count.read_text()) + 1 if count.exists() else 1))
json.dump(result, sys.stdout)
"""
return [sys.executable, "-c", script, str(result_path), str(count_path)]
def _callbacks(calls: dict[str, int]):
def writeback(_result: dict[str, object]) -> dict[str, object]:
calls["writeback"] += 1
return {"ok": True, "appended": True, "classification": "fixture_progress"}
def spend() -> dict[str, object]:
calls["spend"] += 1
return {"ok": True, "appended": True, "slots": 1}
def scheduler(_spend: dict[str, object]) -> dict[str, object]:
calls["scheduler"] += 1
return {"completed": True, "acknowledged": False, "disposition": "not_required"}
return writeback, spend, scheduler
def _journal(runtime_root: Path) -> dict[str, object]:
journal_paths = [
path
for path in (runtime_root / "goals" / "fixture-goal" / "turns").glob("*.json")
if not path.name.endswith(".lock.holder.json")
]
assert len(journal_paths) == 1
return json.loads(journal_paths[0].read_text(encoding="utf-8"))
def _passing_validator(
_plan: dict[str, object],
_result: dict[str, object],
) -> dict[str, object]:
return {
"status": "passed",
"validator_kind": "fixture",
"summary": "independent fixture postconditions passed",
}
def test_host_result_requires_bounded_public_material_fields() -> None:
plan = _plan()
result = _host_result(plan)
result["raw_trajectory"] = "not allowed"
validation = validate_loopx_turn_host_result(plan, result)
assert validation["ok"] is False
assert "unsupported host result fields" in " ".join(validation["errors"])
def test_child_receipt_schema_excludes_registered_peer_authority() -> None:
schema = child_execution_receipts_json_schema()
item_schema = schema["items"]
properties = item_schema["properties"]
assert properties["execution_kind"]["enum"] == ["ephemeral_child"]
assert {"agent_id", "session_ref", "task_lease_ref"}.isdisjoint(properties)
assert {"agent_id", "session_ref", "task_lease_ref"}.isdisjoint(
item_schema["required"]
)
assert properties["worker_ref"]["pattern"] == OPAQUE_REF_PATTERN
assert (
properties["evidence_refs"]["items"]["pattern"]
== OPAQUE_REF_PATTERN
)
assert properties["evidence_refs"]["minItems"] == 1
def test_child_receipt_rejects_unknown_context_mode() -> None:
plan = _adaptive_observation_plan()
result = _host_result(plan)
result["child_execution_receipts"] = [
{
**_child_execution_receipt(plan),
"context_mode": "implicit_parent_history",
}
]
validation = validate_loopx_turn_host_result(plan, result)
assert validation["ok"] is False
assert "context_mode is unsupported" in " ".join(validation["errors"])
def test_host_result_reconciles_aligned_child_receipt() -> None:
plan = _adaptive_observation_plan()
result = _host_result(plan)
result["child_execution_receipts"] = [_child_execution_receipt(plan)]
validation = validate_loopx_turn_host_result(plan, result)
assert validation["ok"] is True
reconciliation = validation["result"]["subagent_reconciliation"]
assert reconciliation["status"] == "reconciled"
assert reconciliation["observation_only"] is True
assert reconciliation["settlement_enforced"] is False
assert reconciliation["child_guard"] == {
"schema_version": "child_execution_guard_v0",
"enforced_boundaries": ["pre_spawn_task_packet"],
"validated_observations": [
"receipt_task_packet_binding",
"context_mode_binding",
"workspace_boundary",
"effect_boundary",
],
"projected_dispositions": [
"stop_child",
"quarantine_evidence",
"continue_parent",
"fallback_actions",
],
"unsupported_boundaries": [
"evidence_acceptance_enforcement",
"live_host_tool_interception",
"automatic_host_child_termination",
],
"parent_acceptance_required": True,
}
assert reconciliation["parent_blocked"] is False
assert reconciliation["parent_continuation"] == "continue"
assert reconciliation["counts"] == {
"planned": 1,
"pre_spawn_rejected": 0,
"observed": 1,
"aligned": 1,
"incomplete": 0,
"rejected": 0,
"cancelled": 0,
"drifted": 0,
"orphaned": 0,
}
lane = reconciliation["lanes"][0]
assert lane["status"] == "aligned"
assert lane["evidence_disposition"] == "candidate_for_parent_acceptance"
assert lane["recommended_child_action"] == "return_to_parent"
assert lane["parent_blocked"] is False
assert lane["candidate_evidence_refs"] == ["artifact:fixture-review"]
assert "quarantined_evidence_refs" not in lane
def test_pre_spawn_rejection_remains_visible_without_blocking_parent() -> None:
plan = _adaptive_observation_plan()
topology = plan["subagent_execution_topology"]
topology["pre_spawn_rejections"] = [
{
"schema_version": "child_execution_rejection_v0",
"todo_id": "todo_child002",
"stage": "pre_spawn",
"reason_codes": ["child_task_packet_incomplete"],
"launch_allowed": False,
"recommended_child_action": "do_not_launch",
"parent_blocked": False,
"parent_continuation": "continue",
"fallback_actions": [
"retry_fresh",
"replace_child",
"serial_takeover",
"ignore_optional_result",
],
}
]
result = _host_result(plan)
result["child_execution_receipts"] = [_child_execution_receipt(plan)]
validation = validate_loopx_turn_host_result(plan, result)
assert validation["ok"] is True
reconciliation = validation["result"]["subagent_reconciliation"]
assert reconciliation["status"] == "guarded"
assert reconciliation["counts"]["pre_spawn_rejected"] == 1
assert reconciliation["parent_blocked"] is False
assert reconciliation["pre_spawn_rejections"] == topology[
"pre_spawn_rejections"
]
def test_host_result_observes_missing_and_drifted_child_receipts() -> None:
plan = _adaptive_observation_plan()
missing = validate_loopx_turn_host_result(plan, _host_result(plan))
assert missing["ok"] is True
assert missing["result"]["subagent_reconciliation"]["status"] == "incomplete"
assert missing["result"]["subagent_reconciliation"]["lanes"][0][
"reason_codes"
] == ["worker_receipt_missing"]
drifted_result = _host_result(plan)
drifted_result["child_execution_receipts"] = [
_child_execution_receipt(
plan,
effect_classes=["external_write"],
)
]
drifted = validate_loopx_turn_host_result(plan, drifted_result)
assert drifted["ok"] is True
reconciliation = drifted["result"]["subagent_reconciliation"]
assert reconciliation["status"] == "drifted"
assert reconciliation["lanes"][0]["reason_codes"] == [
"side_effect_boundary_exceeded"
]
assert reconciliation["lanes"][0]["evidence_disposition"] == "quarantined"
assert reconciliation["lanes"][0]["recommended_child_action"] == "stop_child"
assert reconciliation["lanes"][0]["parent_blocked"] is False
assert reconciliation["lanes"][0]["quarantined_evidence_refs"] == [
"artifact:fixture-review"
]
assert "candidate_evidence_refs" not in reconciliation["lanes"][0]
assert reconciliation["lanes"][0]["fallback_actions"] == [
"retry_fresh",
"replace_child",
"serial_takeover",
"ignore_optional_result",
]
packet_mismatch_result = _host_result(plan)
packet_mismatch_result["child_execution_receipts"] = [
{
**_child_execution_receipt(plan),
"task_packet_digest": "sha256:" + "0" * 64,
}
]
packet_mismatch = validate_loopx_turn_host_result(
plan, packet_mismatch_result
)
assert packet_mismatch["ok"] is True
assert packet_mismatch["result"]["subagent_reconciliation"]["lanes"][0][
"reason_codes"
] == ["task_packet_mismatch"]
context_mismatch_result = _host_result(plan)
context_mismatch_result["child_execution_receipts"] = [
{
**_child_execution_receipt(plan),
"context_mode": "forked_snapshot",
}
]
context_mismatch = validate_loopx_turn_host_result(
plan, context_mismatch_result
)
assert context_mismatch["ok"] is True
context_lane = context_mismatch["result"]["subagent_reconciliation"]["lanes"][0]
assert context_lane["reason_codes"] == ["context_mode_mismatch"]
assert context_lane["evidence_disposition"] == "quarantined"
no_evidence_result = _host_result(plan)
no_evidence_result["child_execution_receipts"] = [
_child_execution_receipt(plan, evidence_refs=[])
]
no_evidence = validate_loopx_turn_host_result(plan, no_evidence_result)
assert no_evidence["ok"] is True
assert no_evidence["result"]["subagent_reconciliation"]["lanes"][0][
"reason_codes"
] == ["aggregate_settlement_without_lane_evidence"]
@pytest.mark.parametrize(
("receipt_status", "lane_status"),
[
("failed", "rejected"),
("rejected", "rejected"),
("cancelled", "cancelled"),
],
)
def test_host_result_guards_terminal_unsuccessful_child_receipts(
receipt_status: str,
lane_status: str,
) -> None:
plan = _adaptive_observation_plan()
result = _host_result(plan)
result["child_execution_receipts"] = [
{
**_child_execution_receipt(plan),
"status": receipt_status,
}
]
validation = validate_loopx_turn_host_result(plan, result)
assert validation["ok"] is True
reconciliation = validation["result"]["subagent_reconciliation"]
assert reconciliation["status"] == "guarded"
assert reconciliation["parent_blocked"] is False
lane = reconciliation["lanes"][0]
assert lane["status"] == lane_status
assert lane["evidence_disposition"] == "quarantined"
assert lane["recommended_child_action"] == "stop_child"
def test_terminal_unsuccessful_child_takes_priority_over_incomplete_sibling() -> None:
plan = _adaptive_observation_plan()
topology = plan["subagent_execution_topology"]
lanes = topology["lanes"]
assert isinstance(lanes, list)
sibling = {
**lanes[0],
"lane_id": "lane_sibling",
"todo_id": "todo_sibling",
}
lanes.append(sibling)
result = _host_result(plan)
result["child_execution_receipts"] = [
{
**_child_execution_receipt(plan),
"status": "failed",
}
]
validation = validate_loopx_turn_host_result(plan, result)
assert validation["ok"] is True
reconciliation = validation["result"]["subagent_reconciliation"]
assert reconciliation["status"] == "guarded"
assert reconciliation["counts"]["rejected"] == 1
assert reconciliation["counts"]["incomplete"] == 1
def test_host_result_requires_planned_workspace_for_writing_child() -> None:
plan = _adaptive_observation_plan(required_write_scopes=["src/**"])
topology = plan["subagent_execution_topology"]
lane = topology["lanes"][0]
receipt = _child_execution_receipt(
plan,
effect_classes=["local_read", "held_workspace_write"],
)
result = _host_result(plan)
result["child_execution_receipts"] = [receipt]
missing_workspace = validate_loopx_turn_host_result(plan, result)
assert missing_workspace["ok"] is True
assert missing_workspace["result"]["subagent_reconciliation"]["lanes"][0][
"reason_codes"
] == ["workspace_mismatch"]
receipt["workspace_ref"] = lane["workspace_ref"]
aligned = validate_loopx_turn_host_result(plan, result)
assert aligned["ok"] is True
assert aligned["result"]["subagent_reconciliation"]["status"] == "reconciled"
def test_disabled_host_result_rejects_unadmitted_child_receipt() -> None:
plan = _plan()
receipt = {
"schema_version": "subagent_host_execution_receipt_v0",
"bundle_id": "bundle_unadmitted",
"lane_id": "lane_unadmitted",
"goal_id": "fixture-goal",
"todo_id": "todo_unadmitted",
"execution_kind": "ephemeral_child",
"runtime_id": "generic-cli",
"worker_ref": "worker:unadmitted",
"source_state_ref": "sha256:fixture",
"task_packet_digest": "sha256:" + "f" * 64,
"context_mode": "fresh",
"workspace_ref": None,
"status": "completed",
"effect_classes": ["local_read"],
"evidence_refs": ["artifact:unadmitted"],
"raw_transcript_copied": False,
}
result = _host_result(plan)
result["child_execution_receipts"] = [receipt]
rejected = validate_loopx_turn_host_result(plan, result)
assert rejected["ok"] is False
assert "unsupported host result fields: child_execution_receipts" in (
" ".join(rejected["errors"])
)
assert "subagent_reconciliation" not in rejected["result"]
def test_enabled_host_result_rejects_receipt_local_path() -> None:
plan = _adaptive_observation_plan()
result = _host_result(plan)
receipt = _child_execution_receipt(plan)
receipt["workspace_ref"] = "/Users/example/raw-worker-path"
result["child_execution_receipts"] = [receipt]
rejected = validate_loopx_turn_host_result(plan, result)
assert rejected["ok"] is False
assert "absolute local path" in " ".join(rejected["errors"])
@pytest.mark.parametrize(
("field", "value", "expected_error"),
[
# A drive-qualified path is now recognized as a local path, so the
# shared public-safety rule reports it before the opaque-shape check.
# Both rules reject the value; only the diagnostic differs.
(
"worker_ref",
"C:/workspace/private/worker.json",
"contains an absolute local path",
),
(
"evidence_refs",
["file:/tmp/private-result.json"],
"opaque 1-192 character public-safe reference",
),
],
)
def test_enabled_host_result_rejects_path_shaped_opaque_refs(
field: str,
value: object,
expected_error: str,
) -> None:
plan = _adaptive_observation_plan()
result = _host_result(plan)
receipt = _child_execution_receipt(plan)
receipt[field] = value
result["child_execution_receipts"] = [receipt]
rejected = validate_loopx_turn_host_result(plan, result)
assert rejected["ok"] is False
assert expected_error in " ".join(rejected["errors"])
assert "child_execution_receipts" not in rejected["result"]
rejected_value = value[0] if isinstance(value, list) else value
assert rejected_value not in json.dumps(
rejected["result"],
ensure_ascii=False,
)
reconciliation = rejected["result"]["subagent_reconciliation"]
assert reconciliation["counts"]["observed"] == 0
assert reconciliation["lanes"][0]["receipt_present"] is False
def test_observation_only_reconciliation_does_not_change_settlement(
tmp_path: Path,
) -> None:
plan = _adaptive_observation_plan()
calls = {"writeback": 0, "spend": 0, "scheduler": 0}
writeback, spend, scheduler = _callbacks(calls)
committed = run_loopx_turn_once(
plan,
host_runner=lambda _request: _host_result(plan),
project=tmp_path,
runtime_root=tmp_path / "runtime",
goal_id="fixture-goal",
timeout_seconds=5,
execute=True,
task_validator=_passing_validator,
writeback=writeback,
spend=spend,
scheduler=scheduler,
)
assert committed["ok"] is True
assert committed["status"] == "committed"
assert committed["subagent_reconciliation"]["status"] == "incomplete"
assert committed["subagent_reconciliation"]["settlement_enforced"] is False
assert committed["subagent_reconciliation"]["parent_blocked"] is False
assert _journal(tmp_path / "runtime")["host_result"][
"subagent_reconciliation"
] == committed["subagent_reconciliation"]
assert calls == {"writeback": 1, "spend": 1, "scheduler": 1}
def test_run_once_preview_has_no_host_or_journal_effects(tmp_path: Path) -> None:
plan = _plan()
payload = run_loopx_turn_once(
plan,
host_argv=[sys.executable, "-c", "raise SystemExit(9)"],
project=tmp_path,
runtime_root=tmp_path / "runtime",
goal_id="fixture-goal",
timeout_seconds=5,
execute=False,
)
assert payload["ok"] is True
assert payload["status"] == "preview"
assert payload["effects"] == {
"host_invoked": False,
"state_written": False,
"quota_spent": False,
"scheduler_acknowledged": False,
}
assert not (tmp_path / "runtime").exists()
def test_run_once_rejects_oversized_built_in_host_result(tmp_path: Path) -> None:
plan = _plan()
calls = {"writeback": 0, "spend": 0, "scheduler": 0}
writeback, spend, scheduler = _callbacks(calls)
oversized = _host_result(plan)
oversized["summary"] = "x" * 13_000
payload = run_loopx_turn_once(
plan,
host_runner=lambda _request: oversized,
project=tmp_path,
runtime_root=tmp_path / "runtime",
goal_id="fixture-goal",
timeout_seconds=5,
execute=True,
writeback=writeback,
spend=spend,
scheduler=scheduler,
)
assert payload["ok"] is False
assert payload["reason"] == "built-in host result exceeded the result budget"
assert calls == {"writeback": 0, "spend": 0, "scheduler": 0}
def test_run_once_explicitly_retries_failed_host_without_duplicate_effects(
tmp_path: Path,
) -> None:
plan = _plan()
calls = {"host": 0, "writeback": 0, "spend": 0, "scheduler": 0}
writeback, spend, scheduler = _callbacks(calls)
def host(_request: dict[str, object]) -> dict[str, object]:
calls["host"] += 1
if calls["host"] == 1:
raise BuiltInHostError("codex_cli_model_requires_newer_codex")
return _host_result(plan)
kwargs = {
"host_runner": host,
"project": tmp_path,
"runtime_root": tmp_path / "runtime",
"goal_id": "fixture-goal",
"timeout_seconds": 5,
"execute": True,
"task_validator": _passing_validator,
"writeback": writeback,
"spend": spend,
"scheduler": scheduler,
}
failed = run_loopx_turn_once(plan, **kwargs)
replayed = run_loopx_turn_once(plan, **kwargs)
recovered = run_loopx_turn_once(plan, retry_failed=True, **kwargs)
assert failed["reason"] == "codex_cli_model_requires_newer_codex"
assert failed["result_kind"] == "host_failure"
assert failed["receipt"]["result_kind"] == "host_failure"
assert failed["receipt"]["failed_phase"] == "host_execute"
assert replayed["replayed"] is True
assert recovered["status"] == "committed"
assert calls == {"host": 2, "writeback": 1, "spend": 1, "scheduler": 1}
def test_run_once_bounds_provider_capacity_retries_without_spending_quota(
tmp_path: Path,
) -> None:
plan = _plan()
calls = {"host": 0, "writeback": 0, "spend": 0, "scheduler": 0}
writeback, spend, scheduler = _callbacks(calls)
def host(_request: dict[str, object]) -> dict[str, object]:
calls["host"] += 1
raise BuiltInHostError(
"codex_cli_provider_capacity",
failure_kind="provider_capacity",
)
common = {
"host_runner": host,
"project": tmp_path,
"runtime_root": tmp_path / "runtime",
"goal_id": "fixture-goal",
"timeout_seconds": 5,
"execute": True,
"writeback": writeback,
"spend": spend,
"scheduler": scheduler,
}
first = run_loopx_turn_once(plan, **common)
second = run_loopx_turn_once(plan, retry_failed=True, **common)
third = run_loopx_turn_once(plan, retry_failed=True, **common)
assert first["host_failure"]["attempt"] == 1
assert first["host_failure"]["retry"]["backoff_seconds"] == 30
assert second["host_failure"]["attempt"] == 2
assert second["host_failure"]["retry"]["backoff_seconds"] == 60
assert third["host_failure"]["attempt"] == 3
assert third["host_failure"]["retry"]["max_attempts"] == 3
with pytest.raises(TurnRecoveryBlockedError) as exc_info:
run_loopx_turn_once(plan, retry_failed=True, **common)
assert exc_info.value.decision["reason"] == "host_retry_budget_exhausted"
assert calls == {"host": 3, "writeback": 0, "spend": 0, "scheduler": 0}
def test_run_once_resumes_session_observed_by_recoverable_failed_turn(
tmp_path: Path,
) -> None:
plan = _codex_plan()
calls = {"host": 0, "writeback": 0, "spend": 0, "scheduler": 0}
session_actions: list[str] = []
writeback, spend, scheduler = _callbacks(calls)
def host(request: dict[str, object]) -> dict[str, object]:
calls["host"] += 1
session = request["session"]
assert isinstance(session, dict)
session_actions.append(str(session["action"]))
if calls["host"] == 1:
raise BuiltInHostError(
"codex_cli_timeout",
recovery_kind="resume_session",
)
return _host_result(plan)
def session_binding(
_turn_envelope: Mapping[str, object],
) -> dict[str, object]:
return {
"schema_version": "loopx_turn_session_binding_v0",
"goal_id": "fixture-goal",
"agent_id": "codex-fixture",
"todo_id": "todo_fixture0001",
}
common = {
"host_runner": host,
"session_binding_resolver": session_binding,
"project": tmp_path,
"runtime_root": tmp_path / "runtime",
"goal_id": "fixture-goal",
"timeout_seconds": 5,
"execute": True,