Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion loopx/control_plane/collaboration/request_amendment.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from typing import Any, Mapping

from .request_control_source import _execute, execute_request_control, request_amendment_snapshot
from ..effect_runtime import EffectRuntimeRejected, effect_runtime_result
from ..effect_runtime import EffectRuntimeRejected, effect_runtime_request_scope, effect_runtime_result
from ..goals.goal_amendment_runtime import _execute_goal_amendment
from ..projects.registry_codec import load_project_registry

Expand Down Expand Up @@ -91,6 +91,7 @@ def _finish(*, registry: Path, root: Path, ref: Mapping[str, str], receiver: str
return result


@effect_runtime_request_scope()
def execute_request_amendment(*, registry_path: Path, runtime_root: Path | None, goal_ref: Mapping[str, str],
receiver_agent_id: str, parameters: Mapping[str, Any], execute: bool) -> dict[str, Any]:
if set(parameters) != {"source_request", "operation_id", "proposal_id", "proposal_digest"}:
Expand Down Expand Up @@ -142,6 +143,7 @@ def execute_request_amendment(*, registry_path: Path, runtime_root: Path | None,
actor=receiver_agent_id, snapshot=snapshot, reservation=reservation, execute=True, attempt_observation=observation)


@effect_runtime_request_scope()
def recover_request_amendment(*, registry_path: Path, runtime_root: Path, goal_ref: Mapping[str, str],
receiver_agent_id: str, request_id: str, actor_agent_id: str | None,
execute: bool = False) -> dict[str, Any]:
Expand All @@ -165,6 +167,7 @@ def recover_request_amendment(*, registry_path: Path, runtime_root: Path, goal_r
actor=actor_agent_id, snapshot=snapshot, reservation=reservation, execute=execute, attempt_observation=observation)


@effect_runtime_request_scope()
def control_request(*, registry_path: Path, runtime_root: Path, goal_ref: Mapping[str, str],
receiver_agent_id: str, request_id: str, actor_agent_id: str | None,
operation: str, parameters: Mapping[str, Any] | None = None, execute: bool = False) -> dict[str, Any]:
Expand Down
2 changes: 2 additions & 0 deletions loopx/control_plane/work_items/lifecycle_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
from collections.abc import Callable, Iterable, Mapping
from typing import Any

from ..effect_runtime import effect_runtime_request_scope
from .replan_semantics_codec import project_replan_semantics


@effect_runtime_request_scope()
def receipt_bound_lifecycle_candidate(
*,
selected_obligation_id: str,
Expand Down
92 changes: 73 additions & 19 deletions tests/control_plane/test_canonical_claim_execution_proof.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,71 @@
"""The public claim command must never grant execution from historical proof."""
from contextlib import redirect_stderr, redirect_stdout
import io
import json
import os
import subprocess
import sys
from pathlib import Path
from typing import Any

import pytest
from canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime
from loopx.cli import main as loopx_cli_main
from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection
from loopx.control_plane.effect_runtime import close_stale_cleanup_sweeps, restart_effect_runtime
from loopx.control_plane.todos.markdown import render_todo_markdown

REPO = Path(__file__).resolve().parents[2]


def _invoke_loopx_cli(
arguments: list[str],
*,
expected_exit: int = 0,
via_subprocess: bool = False,
) -> dict[str, Any]:
if via_subprocess:
process = subprocess.run(
[sys.executable, "-m", "loopx.cli", *arguments],
cwd=REPO,
capture_output=True,
text=True,
timeout=90,
check=False,
)
assert process.returncode == expected_exit, process.stdout + process.stderr
return json.loads(process.stdout)

stdout, stderr = io.StringIO(), io.StringIO()
previous_cwd = Path.cwd()
os.chdir(REPO)
try:
with redirect_stdout(stdout), redirect_stderr(stderr):
try:
exit_code = int(loopx_cli_main(arguments))
except SystemExit as exc:
exit_code = (
exc.code
if isinstance(exc.code, int)
else (0 if exc.code is None else 1)
)
finally:
os.chdir(previous_cwd)
out, err = stdout.getvalue(), stderr.getvalue()
assert exit_code == expected_exit, out + err
return json.loads(out)


def _teardown_sqlite_runtime() -> None:
restart_effect_runtime(wait_for_exit=True)
close_stale_cleanup_sweeps()


@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("retirement", ["release", "transfer"])
def test_claim_replay_uses_current_execution(tmp_path, monkeypatch, provider, retirement):
isolate_sqlite_runtime(tmp_path, monkeypatch)
if provider == "sqlite":
isolate_sqlite_runtime(tmp_path, monkeypatch)
runtime, state, registry = tmp_path / "runtime", tmp_path / "state.md", tmp_path / "registry.json"
goal, target = "claim-execution", "todo_claim_execution"
state.write_text("# Claim execution\n\n## Agent Todo\n")
Expand All @@ -31,12 +81,12 @@ def test_claim_replay_uses_current_execution(tmp_path, monkeypatch, provider, re
initialize_canonical_authority(runtime, goal, projection, state_path=state, provider=provider)
state.unlink() # Recovery must not rebuild authority from missing Markdown.

def cli(command, *args, expected_exit=0):
process = subprocess.run([sys.executable, "-m", "loopx.cli", "--registry", str(registry), "--format", "json",
*command, "--goal-id", goal, "--todo-id", target, *args], cwd=REPO,
capture_output=True, text=True, timeout=90, check=False)
assert process.returncode == expected_exit, process.stdout + process.stderr
return json.loads(process.stdout)
def cli(command, *args, expected_exit=0, via_subprocess=False):
return _invoke_loopx_cli(
["--registry", str(registry), "--format", "json", *command, "--goal-id", goal, "--todo-id", target, *args],
expected_exit=expected_exit,
via_subprocess=via_subprocess,
)

request = ["--claimed-by", "agent-a", "--agent-id", "agent-a", "--claim-operation-id", "claim-original",
"--task-lease-idempotency-key", "execution-a", "--task-lease-expected-version", "0"]
Expand Down Expand Up @@ -71,19 +121,20 @@ def cli(command, *args, expected_exit=0):
assert not rejected.get("lease"), "a rejected old execution cannot return an active lease"
assert cli(["task-lease", "inspect"]) == before
assert not state.exists(), "rejected recovery cannot revive a legacy writer"
readback = cli(["todo", "list"])
readback = cli(["todo", "list"], via_subprocess=(provider == "file" and retirement == "release"))
assert first["source_authority"] == provider + "_v0"
assert readback["todo"]["claimed_by"] == ("agent-b" if retirement == "transfer" else "agent-a")
assert not (runtime / "goals" / goal / "task-leases" / f"{target}.json").exists()
finally:
subprocess.run([sys.executable, "-c", "from loopx.control_plane.effect_runtime import effect_runtime_result; effect_runtime_result('runtime.shutdown',{},retry_safe=False)"],
cwd=REPO, capture_output=True, text=True, timeout=30, check=True)
if provider == "sqlite":
_teardown_sqlite_runtime()


@pytest.fixture(params=["file", "sqlite"])
def expired_managed_claim(tmp_path, monkeypatch, request):
"""A real accepted receipt with a past synthetic clock, without waiting."""
isolate_sqlite_runtime(tmp_path, monkeypatch)
if request.param == "sqlite":
isolate_sqlite_runtime(tmp_path, monkeypatch)
runtime, state, registry = tmp_path / "runtime", tmp_path / "state.md", tmp_path / "registry.json"
goal, target = "expired-claim", "todo_expired_claim"
state.write_text("# Expired execution\n\n## Agent Todo\n")
Expand Down Expand Up @@ -132,19 +183,22 @@ def author(patch=None, *, todo_patch=None):
prefix = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json"]
selected = ["--goal-id", goal, "--todo-id", target]

def cli(arguments, expected_exit=0, *, use_fixture_route=True):
process = subprocess.run([sys.executable, "-m", "loopx.cli", *(prefix if use_fixture_route else []), *arguments], cwd=REPO,
capture_output=True, text=True, timeout=90, check=False)
assert process.returncode == expected_exit, process.stdout + process.stderr
return json.loads(process.stdout)
def cli(arguments, expected_exit=0, *, use_fixture_route=True, via_subprocess=False):
return _invoke_loopx_cli(
[*(prefix if use_fixture_route else []), *arguments],
expected_exit=expected_exit,
via_subprocess=via_subprocess,
)

def snapshot():
task = cli(["todo", "list", *selected])
return task["todo"], task["authority_read"]["provider_revision"], cli(["task-lease", "inspect", *selected])

yield cli, selected, snapshot, author, original
subprocess.run([sys.executable, "-c", "from loopx.control_plane.effect_runtime import effect_runtime_result; effect_runtime_result('runtime.shutdown',{},retry_safe=False)"],
cwd=REPO, capture_output=True, text=True, timeout=30, check=True)
try:
yield cli, selected, snapshot, author, original
finally:
if request.param == "sqlite":
_teardown_sqlite_runtime()


@pytest.mark.parametrize("command", ["update", "complete"])
Expand Down
69 changes: 69 additions & 0 deletions tests/control_plane/test_replan_semantics_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,72 @@ def derive(summary):
guard_recorded_at="2026-08-01T00:00:01.500Z", agent_id="fixture-agent",
items=[original, {**successor, "updated_at": "2026-08-01T00:00:00Z"}], derive=derive)
assert earlier is None


def test_receipt_bound_lifecycle_candidate_shares_one_effect_runtime_scope(
isolated_runtime: Path, monkeypatch: pytest.MonkeyPatch,
):
original = {
"todo_id": "todo_completed", "status": "done", "done": True,
"task_class": "advancement_task", "claimed_by": "fixture-agent",
"last_actor_agent_id": "fixture-agent", "completed_at": "2026-08-01T00:00:00Z",
"updated_at": "2026-08-01T00:00:00Z", "completion_turn_key": "original-completion",
}

def derive(summary):
return derive_goal_frontier_replan_obligation_from_summaries(
user_todo_summary=None, agent_todo_summary=summary, work_lane_contract=None,
agent_id="fixture-agent", existing_replan_obligation=None)

admitted = derive({"completed_without_successor_items": [original],
"completed_without_successor_count": 1})
successor = {
"todo_id": "todo_successor", "status": "open", "done": False,
"task_class": "advancement_task", "claimed_by": "fixture-agent",
"last_actor_agent_id": "fixture-agent", "updated_at": "2026-08-01T00:00:02Z",
"replan_obligation_id": admitted["obligation_id"], "action_kind": "validate",
"target_key": "snapshot-continuity", "resume_when": "todo_done:todo_completed",
}
condition = evaluate_todo_resume_conditions([successor], source_items=[original, successor])[
successor["todo_id"]]
successor = {**successor, "resume_condition": condition, "resume_ready": condition["satisfied"]}
assert effect_runtime.effect_runtime_result("runtime.ping", {})["ready"] is True

real_fp = effect_runtime._runtime_fingerprint
real_req_fp = effect_runtime._runtime_fingerprint_for_request
counts = {"fp": 0, "rpc": 0}

def spy_fp():
counts["fp"] += 1
return real_fp()

def spy_req_fp():
counts["rpc"] += 1
return real_req_fp()

monkeypatch.setattr(effect_runtime, "_runtime_fingerprint", spy_fp)
monkeypatch.setattr(effect_runtime, "_runtime_fingerprint_for_request", spy_req_fp)

candidate = receipt_bound_lifecycle_candidate(
selected_obligation_id=admitted["obligation_id"],
guard_recorded_at="2026-08-01T00:00:01.500Z", agent_id="fixture-agent",
items=[original, successor], derive=derive)
assert candidate is not None
assert counts["rpc"] >= 3
assert counts["fp"] == 1
assert effect_runtime._REQUEST_RUNTIME_REVISION.get() is None

counts["fp"] = 0
counts["rpc"] = 0

def failing_derive(_summary):
raise RuntimeError("injected derive failure")

with pytest.raises(RuntimeError, match="injected derive failure"):
receipt_bound_lifecycle_candidate(
selected_obligation_id=admitted["obligation_id"],
guard_recorded_at="2026-08-01T00:00:01.500Z", agent_id="fixture-agent",
items=[original, successor], derive=failing_derive)
assert counts["rpc"] >= 1
assert counts["fp"] == 1
assert effect_runtime._REQUEST_RUNTIME_REVISION.get() is None
89 changes: 89 additions & 0 deletions tests/control_plane/test_request_amendment_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,3 +664,92 @@ def agenda(agent):
_control(f, rid, "cancel", {"operation_id": "agenda-cancel", **_basis(revised), "reason": "Stop current request"})
assert agenda("agent-a")["items"] == []
assert agenda("agent-b")["items"] == []


def test_request_amendment_entrypoints_share_one_effect_runtime_scope(source_goal, monkeypatch):
from loopx.control_plane import effect_runtime

f = source_goal
rid = _request(f)["request_id"]
before = _control(f, rid, "inspect")["view"]
fail_rid = _request(f)["request_id"]
fail_before = _control(f, fail_rid, "inspect")["view"]

real_fp = effect_runtime._runtime_fingerprint
real_req_fp = effect_runtime._runtime_fingerprint_for_request
counts = {"fp": 0, "rpc": 0}
fail_on_rpc = None

def spy_fp():
counts["fp"] += 1
return real_fp()

def spy_req_fp():
counts["rpc"] += 1
if fail_on_rpc is not None and counts["rpc"] == fail_on_rpc:
raise RuntimeError("injected rpc failure")
return real_req_fp()

monkeypatch.setattr(effect_runtime, "_runtime_fingerprint", spy_fp)
monkeypatch.setattr(effect_runtime, "_runtime_fingerprint_for_request", spy_req_fp)

revised = control_request(
registry_path=f["registry"], runtime_root=f["runtime"], goal_ref=f["ref"],
receiver_agent_id="agent-a", request_id=rid, actor_agent_id="agent-b",
operation="revise",
parameters={
"operation_id": "scope-revise", **_basis(before),
"brief": {**BRIEF, "purpose": "Revised scope check"}, "reason": "Scoped check",
},
execute=True,
)
assert revised["ok"] is True
assert counts["rpc"] >= 2
assert counts["fp"] == 1
assert effect_runtime._REQUEST_RUNTIME_REVISION.get() is None

counts["fp"] = 0
counts["rpc"] = 0
cancelled = control_request(
registry_path=f["registry"], runtime_root=f["runtime"], goal_ref=f["ref"],
receiver_agent_id="agent-a", request_id=rid, actor_agent_id="agent-b",
operation="cancel",
parameters={
"operation_id": "scope-cancel", **_basis(revised["view"]),
"reason": "Scoped cancel check",
},
execute=True,
)
assert cancelled["ok"] is True
assert counts["rpc"] >= 3
assert counts["fp"] == 1
assert effect_runtime._REQUEST_RUNTIME_REVISION.get() is None

counts["fp"] = 0
counts["rpc"] = 0
recovered = recover_request_amendment(
registry_path=f["registry"], runtime_root=f["runtime"], goal_ref=f["ref"],
receiver_agent_id="agent-a", request_id=rid, actor_agent_id="agent-b", execute=False,
)
assert recovered["view"]["request_id"] == rid
assert counts["rpc"] >= 1
assert counts["fp"] == 1
assert effect_runtime._REQUEST_RUNTIME_REVISION.get() is None

counts["fp"] = 0
counts["rpc"] = 0
fail_on_rpc = 2
with pytest.raises(RuntimeError, match="injected rpc failure"):
control_request(
registry_path=f["registry"], runtime_root=f["runtime"], goal_ref=f["ref"],
receiver_agent_id="agent-a", request_id=fail_rid, actor_agent_id="agent-b",
operation="revise",
parameters={
"operation_id": "scope-fail-revise", **_basis(fail_before),
"brief": {**BRIEF, "purpose": "Injected failure check"}, "reason": "Scoped fail",
},
execute=True,
)
assert counts["rpc"] == 2
assert counts["fp"] == 1
assert effect_runtime._REQUEST_RUNTIME_REVISION.get() is None
Loading
Loading