Skip to content
Merged
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/cli_commands/project_lifecycle_refresh_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,9 @@ def handle_refresh_state_command(
try:
ref = (exact_goal_ref(args.goal_id, args.goal_instance_id) if args.goal_instance_id
else capture_first_party_host_goal_ref(registry_path=registry_path, goal_id=args.goal_id))
# The launcher override only controls how subsequent commands are rendered.
requested_effects = vars(args).copy()
requested_effects.pop("control_cli_bin", None)
payload = commit_execution_loss_closeout(
registry_path=registry_path, runtime_root_override=args.runtime_root,
goal_id=args.goal_id, agent_id=args.agent_id or "", todo_id=args.todo_id or "",
Expand All @@ -468,7 +471,7 @@ def handle_refresh_state_command(
"expected_version": args.task_lease_expected_version},
progress_observation=inline_progress_observation(args),
delivery_outcome=args.delivery_outcome, delivery_boundary=args.delivery_boundary,
requested_effects=vars(args), dry_run=args.dry_run,
requested_effects=requested_effects, dry_run=args.dry_run,
)
except (OSError, RuntimeError, TypeError, ValueError) as exc:
code = getattr(exc, "code", None)
Expand Down
7 changes: 5 additions & 2 deletions loopx/control_plane/quota/execution_loss_closeout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,13 @@ export async function observeFencedExecution(root: string, identity: ReturnType<
|| todo.archive_state !== "active" || !rawLease) return null;
const lease = canonicalTaskLease(rawLease, identity.goal_id, identity.todo_id);
if (!fencesPreparedGeneration(prepared, lease)) return null;
const writerMatches = todo.claimed_by === identity.agent_id && lease.owner === identity.agent_id
&& todo.done !== true && leaseRepositoryRejection(todo, lease) === null
&& canonicalLeaseTodoFact(todo)?.excluded_agents.includes(identity.agent_id) === false;
const active = writerMatches && leaseIsActive(lease, new Date());
return {original_prepared_epoch: prepared.prepared_lease_epoch, current_lease_epoch: lease.lease_epoch,
current_lease_version: lease.version, current_owner: lease.owner,
current_control_writer_active: todo.claimed_by === identity.agent_id && lease.owner === identity.agent_id
&& leaseRepositoryRejection(todo, lease) === null && leaseIsActive(lease, new Date())};
current_control_writer_active: active, can_reclaim_control_writer: writerMatches && !active};
}

function optionalAssignedReplan(receipt: JsonObject): boolean {
Expand Down
5 changes: 4 additions & 1 deletion loopx/control_plane/quota/execution_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,10 @@ def commit_execution_loss_closeout(

registry_path = registry_path.expanduser().resolve()
registry = load_project_registry(registry_path)
root = resolve_runtime_root(registry, runtime_root_override, registry_path=registry_path)
# Cross-runtime lock witnesses carry the physical target paths.
root = resolve_runtime_root(
registry, runtime_root_override, registry_path=registry_path,
).resolve()
identity = SettlementIdentity(goal_id=goal_id, agent_id=agent_id, todo_id=todo_id,
turn_instance_id=turn_instance_id).as_dict()
progress = (normalize_progress_observation(progress_observation, work_item_id=todo_id)
Expand Down
4 changes: 4 additions & 0 deletions loopx/control_plane/quota/unsettled_host_turn.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,10 @@ def _apply_recovery_projection(
payload.pop("selected_todo", None)
payload.pop("todo_id", None)
payload.pop("action_portfolio", None)
if recovery.get("repair") == "execution_loss_closeout":
# Ordinary preparation was built for potential current work. Its
# claim must never replace the prior Turn's administrative recovery.
payload.pop("execution_preparation", None)
payload.update(
{
"decision": "blocked_wait" if attention else "unsettled_host_turn_recovery",
Expand Down
17 changes: 13 additions & 4 deletions loopx/control_plane/work_items/unsettled_host_turn_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,21 @@ def recovery_cli_actions(
f" --progress-evidence-id {evidence} --task-lease-idempotency-key '<current-key>'"
" --task-lease-expected-version '<current-version>' --no-global-sync --suppress-external-sinks"
)
return [
f"{command_prefix} task-lease inspect {scope}",
"Use the current control-writer proof for the original Agent. When unavailable, recover ownership through the authorized Todo lifecycle before closing.",
inspect_lease = f"{command_prefix} task-lease inspect {scope}"
actions = [inspect_lease]
if proof.get("can_reclaim_control_writer") is True and lifecycle_actor_args:
writer = shlex.quote(str(proof["current_owner"]))
actions.extend([
"If the original Agent still owns this Todo and the lease is inactive, run the ordinary managed claim to obtain control-writer proof.",
f"{command_prefix} todo claim {scope}{lifecycle_actor_args} --claimed-by {writer} --thin",
inspect_lease,
])
actions.extend([
"Use the active control-writer proof for the original Agent. Hold if authorized ownership cannot be verified.",
f"{closeout} --dry-run",
"After the preview establishes a no-spend closeout, execute the same command without --dry-run and verify the original settlement. Resume fresh work only through its own guard.",
]
])
return actions
if recovery.get("repair") == "resume_prior_turn":
prior_turn_id = str(recovery["prior_turn_instance_id"])
return [
Expand Down
83 changes: 79 additions & 4 deletions tests/control_plane/test_execution_loss_closeout_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from datetime import datetime, timedelta, timezone
from hashlib import sha256
import json
import shlex
import sys

import pytest
Expand Down Expand Up @@ -297,6 +298,19 @@ def _closeout_args(context, *, lease=None, execution_loss=True):
*_proof(lease or context["current_lease"])]


def _projected_preview_args(cli_channel, lease):
[command] = [
action for action in cli_channel["next_cli_actions"]
if "--execution-loss-closeout" in action and "--dry-run" in action
]
tokens = shlex.split(command)
assert tokens[-1] == "--dry-run"
args = tokens[1:]
args[args.index("<current-key>")] = lease["idempotency_key"]
args[args.index("<current-version>")] = str(lease["version"])
return args


def _lease(context):
if context["source_profile"]:
inspected = effect_runtime_result("task_lease.inspect.native", {
Expand Down Expand Up @@ -403,11 +417,13 @@ def test_closeout_preserves_the_original_turn_and_releases_the_next_guard(
original = _readback(context)
_assert_original_prepared_generation(context, original)
assert not original.writeback.receipts and not original.spend.receipts
argv = _closeout_args(context)
if not source_profile:
# A fresh guard recognizes the generation change before attempting to
# re-enter the original guard. It offers only the administrative route.
route = str(tmp_path / "fixture launcher" / "loopx")
code, recovery = context["cli"](
"quota", "should-run", "--context-delivery", "off", "--codex-app",
"--cli-bin", route, "quota", "should-run", "--context-delivery", "off", "--codex-app",
"--goal-id", context["goal_id"], "--agent-id", OWNER, "--turn-instance-id", "needs-recovery",
)
assert code == 0, recovery
Expand All @@ -419,9 +435,8 @@ def test_closeout_preserves_the_original_turn_and_releases_the_next_guard(
assert recovery["execution_obligation"]["delivery_allowed"] is False
cli_channel = recovery["interaction_contract"]["cli_channel"]
assert cli_channel["spend_allowed_now"] is False
assert any("--execution-loss-closeout" in cmd and "--dry-run" in cmd
for cmd in cli_channel["next_cli_actions"])
argv = _closeout_args(context)
argv = _projected_preview_args(cli_channel, context["current_lease"])[:-1]
assert argv[:2] == ["--cli-bin", route]
before = _unchanged_state(context)
code, preview = context["cli"](*argv, "--dry-run")
assert code == 0 and preview["would_close_without_spend"] is True, preview
Expand Down Expand Up @@ -499,3 +514,63 @@ def recording_call(method, request, *, timeout=None):
code, closed = context["cli"](*_closeout_args(context))
assert code == 0, closed
assert seen_timeouts == [effect_runtime.CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS]


@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("owner", [OWNER, PEER])
@pytest.mark.parametrize("runtime_root_alias", [
pytest.param(False, id="direct-path"),
pytest.param(True, id="runtime-root-alias", marks=pytest.mark.skipif(
sys.platform == "win32", reason="requires directory symlink privileges",
)),
])
def test_recovery_guides_self_claim_only_for_the_retained_assignee(
tmp_path, monkeypatch, capsys, provider, owner, runtime_root_alias,
):
fixture_path = tmp_path
if runtime_root_alias:
fixture_path = tmp_path / "storage-alias"
fixture_path.symlink_to(tmp_path, target_is_directory=True)
context = _fixture(fixture_path, monkeypatch, capsys, provider, source_profile=False,
replacement_owner=owner)
lease = context["current_lease"]
code, released = context["cli"](
"task-lease", "release", "--goal-id", context["goal_id"], "--todo-id", context["todo"],
"--owner", owner, "--idempotency-key", lease["idempotency_key"],
"--expected-version", str(lease["version"]),
)
assert code == 0, released
code, recovery = context["cli"](
"quota", "should-run", "--context-delivery", "off", "--codex-app",
"--goal-id", context["goal_id"], "--agent-id", OWNER, "--turn-instance-id", "needs-control-writer",
)
assert code == 0, recovery
debt = recovery["unsettled_host_turn_recovery"]
assert debt["repair"] == "execution_loss_closeout"
assert debt["reason_code"] == "execution_loss_control_writer_required"
assert "execution_preparation" not in recovery
assert recovery["interaction_contract"]["agent_channel"]["must_attempt"] is False
assert recovery["execution_obligation"]["delivery_allowed"] is False
cli_channel = recovery["interaction_contract"]["cli_channel"]
assert cli_channel["spend_allowed_now"] is False
claim_commands = [command for command in cli_channel["next_cli_actions"] if "todo claim" in command]
if owner == PEER:
assert not claim_commands
_assert_no_completion_or_debit(context)
return

[claim_command] = claim_commands
tokens = shlex.split(claim_command)
code, claimed = context["cli"](*tokens[tokens.index("todo"):])
assert code == 0, claimed
current = _lease(context)
assert current["owner"] == OWNER and current["lease_epoch"] > lease["lease_epoch"]
argv = _projected_preview_args(cli_channel, current)
code, preview = context["cli"](*argv)
assert code == 0 and preview["would_close_without_spend"] is True, preview
code, closed = context["cli"](*argv[:-1])
assert code == 0 and closed["settlement_progress"]["no_spend"] is True, closed
assert closed["settlement_identity"] == _readback(context).identity.value.as_dict()
code, replay = context["cli"](*argv[:-1])
assert code == 0 and replay["idempotent_replay"] is True and replay["appended"] is False, replay
_assert_no_completion_or_debit(context)
Loading