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
3 changes: 3 additions & 0 deletions loopx/chat_codex_goal.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ def _response(self, goal: dict[str, Any] | None, text: str = "", *, messages: li
def run(
self, command: NativeGoalCommand, emit: Callable[[str, dict[str, Any]], None],
*, execution_context: str | None = None,
on_resume_activated: Callable[[], None] | None = None,
) -> dict[str, Any]:
if command.operation == "help":
return parse_agent_response(USAGE, protected_paths=[self.session.work_dir])
Expand Down Expand Up @@ -240,6 +241,8 @@ def run(
**({"objective": objective} if objective is not None else {}),
},
)
if command.operation == "resume" and on_resume_activated is not None:
on_resume_activated()
except Exception:
# A lost response does not prove that activation failed.
self._stop_owned_transport_on_failure()
Expand Down
55 changes: 54 additions & 1 deletion loopx/chat_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1913,7 +1913,60 @@ def event_sink(kind: str, payload: dict[str, Any]) -> None:
execution_context = execution_guidance(self.store.load_turn(session_id, turn_id)) + "\nFresh scoped evidence:\n" + json.dumps(context, ensure_ascii=False)
if execution_ended():
return
response = adapter.goal_driver.run(native_command, event_sink, execution_context=execution_context)
on_resume_activated = None
loopx_request = current_turn.get("loopx_request")
delegation_wake = (
isinstance(loopx_request, Mapping)
and loopx_request.get("operation") == "wake"
)
registry_path = self.registry_path
if (
native_command.operation == "resume"
and not delegation_wake
and registry_path is not None
):
from .agent_registry import load_goal_from_registry
from .control_plane.goals.activation_service import (
GoalActivationState,
goal_activation_state,
set_goal_activation_state,
)

registered_goal = load_goal_from_registry(
registry_path, session["goal_id"]
)
if (
registered_goal is not None
and goal_activation_state(registered_goal)
is GoalActivationState.ACTIVE
):
def record_owner_resume() -> None:
activation = set_goal_activation_state(
registry_path=registry_path,
goal_id=session["goal_id"],
state="active",
reason="Explicit Codex Goal resume",
actor_kind="owner",
owner_resume_action=True,
execute=True,
)
if not activation.get("ok"):
raise CodexChatAgentError(
str(
activation.get("error")
or "LoopX owner resume epoch could not be recorded"
),
error_code="goal_owner_resume_write_failed",
gate=None,
)

on_resume_activated = record_owner_resume
response = adapter.goal_driver.run(
native_command,
event_sink,
execution_context=execution_context,
on_resume_activated=on_resume_activated,
)
finally:
if execution_lock is not None:
execution_lock.__exit__(None, None, None)
Expand Down
122 changes: 87 additions & 35 deletions loopx/cli_commands/todo.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@
local_authority_is_promoted,
)
from ..control_plane.effect_runtime import effect_runtime_result
from ..control_plane.quota.effect_program import SettlementBindingKind
from ..control_plane.quota.settlement import (
SettlementFailureKind,
SettlementIdentity,
read_heartbeat_settlement,
settlement_result_payload,
)
from ..control_plane.quota.heartbeat_receipt import (
bind_replan_successor_heartbeat_receipt,
)
from ..control_plane.goals.first_party_host_admission import (
FirstPartyHostGoalAdmission,
capture_first_party_host_goal_ref,
Expand All @@ -24,11 +34,6 @@
build_task_planning_packet,
render_task_planning_packet,
)
from ..control_plane.quota.settlement import (
SettlementIdentity,
read_heartbeat_settlement,
settlement_result_payload,
)
from ..control_plane.todos.completion_result import read_completion_result
from ..control_plane.todos.list_readback import list_goal_todos
from ..control_plane.todos.markdown import render_todo_markdown
Expand Down Expand Up @@ -274,35 +279,8 @@ def handle_todo_command(
registry_path=registry_path,
runtime_root_arg=runtime_root_arg,
)
successor_settlement = None
if replan_obligation_id and args.turn_instance_id:
runtime_root = resolve_runtime_root(
load_registry(registry_path), runtime_root_arg
)
successor_settlement = read_heartbeat_settlement(
runtime_root,
goal_id=args.goal_id,
agent_id=args.claimed_by,
todo_id=None,
turn_instance_id=args.turn_instance_id,
resolve_original_binding=True,
registry_path=registry_path,
goal_ref=goal_ref,
)
if successor_settlement is None or successor_settlement.identity.value is None:
raise ValueError(
"replan successor requires the original admitted Turn binding"
)
if successor_settlement.identity.failure is not None:
raise ValueError(successor_settlement.identity.failure.reason)
selected = (successor_settlement.semantic_replan_guard or {}).get(
"selected_obligation_id"
)
if selected != replan_obligation_id:
raise ValueError(
"replan successor does not match the original Turn obligation"
)
payload = add_goal_todo(
add_todo = partial(
add_goal_todo,
operation_id=args.operation_id,
registry_path=registry_path,
runtime_root_arg=runtime_root_arg,
Expand Down Expand Up @@ -350,8 +328,81 @@ def handle_todo_command(
if value is not None
},
**_todo_path_args(args),
dry_run=bool(args.dry_run),
)
successor_settlement = None
runtime_root = None
if replan_obligation_id and args.turn_instance_id and not args.dry_run:
# A failed Todo validation must not leave an otherwise ordinary
# Turn receipt irreversibly bound to a successor that was never
# created. Preview through the same mutation owner first.
preview = add_todo(dry_run=True)
if preview.get("ok") is not True:
raise ValueError(
str(
preview.get("error")
or "replan successor could not be validated"
)
)
runtime_root = resolve_runtime_root(
load_registry(registry_path), runtime_root_arg
)
successor_settlement = read_heartbeat_settlement(
runtime_root,
goal_id=args.goal_id,
agent_id=args.claimed_by,
todo_id=None,
turn_instance_id=args.turn_instance_id,
resolve_original_binding=True,
registry_path=registry_path,
goal_ref=goal_ref,
)
if (
successor_settlement is not None
and successor_settlement.identity.value is None
and successor_settlement.identity.failure is not None
and successor_settlement.identity.failure.kind
is SettlementFailureKind.RECEIPT_UNBOUND
):
bind_replan_successor_heartbeat_receipt(
runtime_root,
goal_id=args.goal_id,
agent_id=args.claimed_by,
turn_instance_id=args.turn_instance_id,
replan_obligation_id=replan_obligation_id,
goal_ref=goal_ref,
)
successor_settlement = read_heartbeat_settlement(
runtime_root,
goal_id=args.goal_id,
agent_id=args.claimed_by,
todo_id=None,
turn_instance_id=args.turn_instance_id,
resolve_original_binding=True,
registry_path=registry_path,
goal_ref=goal_ref,
)
if successor_settlement is None or successor_settlement.identity.value is None:
raise ValueError(
"replan successor requires the original admitted Turn binding"
)
if successor_settlement.identity.failure is not None:
raise ValueError(successor_settlement.identity.failure.reason)
identity = successor_settlement.identity.value
if (
identity.binding_kind is not SettlementBindingKind.AUTONOMOUS_REPLAN
or identity.replan_obligation_id != replan_obligation_id
):
raise ValueError(
"replan successor has a different settlement identity"
)
selected = (successor_settlement.semantic_replan_guard or {}).get(
"selected_obligation_id"
)
if selected != replan_obligation_id:
raise ValueError(
"replan successor does not match the original Turn obligation"
)
payload = add_todo(dry_run=bool(args.dry_run))
if replan_obligation_id and payload.get("ok"):
payload["replan_transition"] = {
"schema_version": "replan_successor_transition_v0",
Expand All @@ -365,6 +416,7 @@ def handle_todo_command(
if successor_settlement is None:
payload["host_action"] = "end_current_heartbeat"
else:
assert runtime_root is not None
identity = successor_settlement.identity.value
assert identity is not None
payload["settlement_identity"] = identity.as_dict()
Expand Down
26 changes: 21 additions & 5 deletions loopx/control_plane/goals/activation_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ def set_goal_activation_state(
runtime_root_override: str | None = None,
expected_state_fingerprint: str | None = None,
actor_kind: str | None = None,
owner_resume_action: bool = False,
execute: bool = False,
) -> dict[str, Any]:
"""Preview or apply one reversible Goal activation transition."""
Expand All @@ -280,6 +281,13 @@ def set_goal_activation_state(
raise ValueError("goal id is required")
actor = normalize_owner_controller_actor(actor_kind, required=execute)
target_state = normalize_goal_activation_state(state)
if owner_resume_action and not (
target_state is GoalActivationState.ACTIVE
and actor is OwnerControllerActorKind.OWNER
):
raise ValueError(
"owner resume action requires active state and the owner actor"
)
authority_route = _source_and_target(
registry_path=registry_path,
goal_id=normalized_goal_id,
Expand Down Expand Up @@ -313,6 +321,7 @@ def set_goal_activation_state(
)
before_state = goal_activation_state(source_goal)
changed = before_state is not target_state
write_required = changed or owner_resume_action
actor_label = actor.value if actor is not None else "owner"
default_reason = (
f"Stopped by {actor_label}"
Expand All @@ -335,6 +344,8 @@ def set_goal_activation_state(
"before_state": before_state.value,
"after_state": target_state.value,
"changed": changed,
"owner_resume_action": owner_resume_action,
"owner_resume_advanced": False,
"written": False,
"partial_write": False,
"source_registry": str(source_registry),
Expand All @@ -350,8 +361,8 @@ def set_goal_activation_state(
"actor_kind": actor.value if actor is not None else None,
"readback": {
"schema_version": GOAL_ACTIVATION_READBACK_SCHEMA_VERSION,
"status": "not_executed" if changed else "not_required",
"verified": not changed,
"status": "not_executed" if write_required else "not_required",
"verified": not write_required,
},
}
if (
Expand Down Expand Up @@ -476,14 +487,17 @@ def set_goal_activation_state(
)
return payload
owner_resume_id = goal_owner_resume_id(locked_goal)
if changed:
if write_required:
# Preserve the owner resume across later lifecycle writes.
# Mint it inside the source lock for an actual owner resume.
# Mint it inside the source lock for an actual owner resume,
# including an explicit host resume while the LoopX Goal is
# already active. Ordinary guard entry never sets this flag.
if (
target_state is GoalActivationState.ACTIVE
and actor is OwnerControllerActorKind.OWNER
):
owner_resume_id = uuid4().hex
payload["owner_resume_advanced"] = True
if owner_resume_id is not None:
proposed_activation["owner_resume_id"] = owner_resume_id
locked_goal["activation"] = proposed_activation
Expand Down Expand Up @@ -520,7 +534,9 @@ def set_goal_activation_state(
payload["ok"] = bool(sync_ok and readback.get("verified"))
payload["partial_write"] = bool(payload["written"] and not payload["ok"])
payload["projection_reconciled"] = bool(
not changed and registries_are_distinct and readback.get("verified")
not write_required
and registries_are_distinct
and readback.get("verified")
)
if not payload["ok"]:
payload["error"] = "goal activation shared registry readback did not verify"
Expand Down
Loading
Loading