diff --git a/loopx/capabilities/native_chat/session_calendar_tasks.py b/loopx/capabilities/native_chat/session_calendar_tasks.py index a552d9d07b..346facf62d 100644 --- a/loopx/capabilities/native_chat/session_calendar_tasks.py +++ b/loopx/capabilities/native_chat/session_calendar_tasks.py @@ -7,9 +7,12 @@ """ from __future__ import annotations +from collections.abc import Mapping, Sequence from datetime import datetime, timezone import json +from pathlib import Path import re +from typing import cast from ...agent_registry import load_goal_from_registry from ...control_plane.digest_envelope import sha256_envelope @@ -28,23 +31,32 @@ from ..periodic_report.private_generation import attempt_directory from .steward_commands import native_command from .steward_reports import ManagedSessionReports +from .steward_turn_common import as_dict, as_dict_list, as_mapping, as_optional_dict, steward_monitor_for class SessionCalendarTasks(ManagedSessionReports): - def subscription(self, session_id, *, expected_revision=None): - actor = self.selected(session_id)["actor"] - goal = load_goal_from_registry(self.controller.registry_path, actor["goal_id"]) - config = configuration_summary(goal) + def subscription( + self, + session_id: str, + *, + expected_revision: str | None = None, + expected_actor: dict[str, object] | None = None, + ) -> dict[str, object] | None: + actor = as_mapping(self.selected(session_id)["actor"]) + if expected_actor is not None and actor != expected_actor: + return None + goal = load_goal_from_registry(cast(Path, self.controller.registry_path), str(actor["goal_id"])) + config = as_optional_dict(configuration_summary(goal or {})) if (not config or config.get("profile_preset") != "session-task" or config.get("route_ref") != "managed-session:" + session_id): return None - subscription = resolve_active_goal_periodic_report_subscription(goal) + subscription = as_optional_dict(resolve_active_goal_periodic_report_subscription(goal or {})) if subscription and expected_revision is not None and subscription["effective_revision"] != expected_revision: return None return subscription - def _definition(self, window): - path = attempt_directory(self.root, window) / "task.json" + def _definition(self, window: Mapping[str, object]) -> dict[str, object] | None: + path = attempt_directory(self.root, dict(window)) / "task.json" if not path.is_file(): return None value = json.loads(path.read_text(encoding="utf-8")) @@ -52,58 +64,80 @@ def _definition(self, window): {k: v for k, v in value.items() if k != "digest"})): raise ValueError("the frozen calendar task changed") actor = value.get("actor") - if not isinstance(actor, dict) or self.selected(actor.get("session_id"))["actor"] != actor: + if not isinstance(actor, dict) or self.selected(cast(str, actor.get("session_id")))["actor"] != actor: raise ValueError("the original calendar task actor changed") - return value + return {str(k): v for k, v in value.items()} - def _frozen_actor(self, window): + def _frozen_actor(self, window: dict[str, object]) -> dict[str, object] | None: value = self._definition(window) - return value["actor"] if value else None + return as_dict(value["actor"]) if value else None - def _todo(self, actor, window): - from .steward_monitor import StewardMonitor + def _todo(self, actor: Mapping[str, object], window: Mapping[str, object]) -> dict[str, object] | None: from ...control_plane.todos.list_readback import list_goal_todos - rows = [row for row in StewardMonitor(self.controller).todos(actor) - if row.get("target_key") == window["window_id"]] + rows: list[dict[str, object]] = [ + dict(row) for row in steward_monitor_for(self.controller).todos(actor) + if row.get("target_key") == window["window_id"] + ] if not rows: # Active-list absence never permits another execution. A finished # task may already be in the canonical completed-history view. - history = list_goal_todos(registry_path=self.controller.registry_path, goal_id=actor["goal_id"], - runtime_root_arg=str(self.root), role="agent", status="done", read_scope="completed_history", limit=None) - rows = [row for row in history["todos"] if row.get("target_key") == window["window_id"]] + history = as_mapping(list_goal_todos( + registry_path=cast(Path, self.controller.registry_path), goal_id=str(actor["goal_id"]), + runtime_root_arg=str(self.root), role="agent", status="done", read_scope="completed_history", limit=None, + )) + rows = [row for row in as_dict_list(history["todos"]) if row.get("target_key") == window["window_id"]] if len(rows) > 1: raise ValueError("the calendar window has conflicting original Tasks") return rows[0] if rows else None - def source_task(self, actor, task): + def source_task( + self, actor: Mapping[str, object], task: Mapping[str, object], + ) -> tuple[dict[str, object] | None, dict[str, object]]: """Read a completed native Task; configuration supplies no host argv.""" from ...control_plane.todos.list_readback import list_goal_todos - row = list_goal_todos(registry_path=self.controller.registry_path, goal_id=actor["goal_id"], - runtime_root_arg=str(self.root), todo_id=task["source_todo_id"], role="agent").get("todo") + reg_path = cast(Path, self.controller.registry_path) + goal_id = str(actor["goal_id"]) + source_todo_id = str(task["source_todo_id"]) + row = as_optional_dict(list_goal_todos( + registry_path=reg_path, goal_id=goal_id, + runtime_root_arg=str(self.root), todo_id=source_todo_id, role="agent", + ).get("todo")) if row is None: - row = list_goal_todos(registry_path=self.controller.registry_path, goal_id=actor["goal_id"], - runtime_root_arg=str(self.root), todo_id=task["source_todo_id"], role="agent", - status="done", read_scope="completed_history").get("todo") + row = as_optional_dict(list_goal_todos( + registry_path=reg_path, goal_id=goal_id, + runtime_root_arg=str(self.root), todo_id=source_todo_id, role="agent", + status="done", read_scope="completed_history", + ).get("todo")) return row, self._source_validation(actor, row) @staticmethod - def _source_candidate(actor, row): - return bool(row and row.get("status") == "done" and row.get("claimed_by") == actor["agent_id"] + def _source_candidate(actor: Mapping[str, object], row: Mapping[str, object] | None) -> bool: + if not row: + return False + excluded = row.get("excluded_agents") + excluded_list = excluded if isinstance(excluded, Sequence) and not isinstance(excluded, (str, bytes)) else () + target_key = row.get("target_key") + return bool(row.get("status") == "done" and row.get("claimed_by") == actor["agent_id"] and row.get("task_class") == "advancement_task" and row.get("completion_validation_required") is True and row.get("action_kind") != "generate_periodic_report" - and not re.fullmatch(r"cadence_[a-f0-9]{64}", row.get("target_key") or "") - and actor["agent_id"] not in row.get("excluded_agents", [])) + and not re.fullmatch(r"cadence_[a-f0-9]{64}", target_key if isinstance(target_key, str) else "") + and actor["agent_id"] not in excluded_list) - def _source_validation(self, actor, row): - if not self._source_candidate(actor, row): + def _source_validation(self, actor: Mapping[str, object], row: Mapping[str, object] | None) -> dict[str, object]: + if not self._source_candidate(actor, row) or row is None: raise ValueError("select this Agent's existing completed Task with independent argv validation") - declaration = read_completion_validation_declaration(runtime_root=self.root, - goal_id=actor["goal_id"], todo_id=row["todo_id"], expected_digest=row["completion_validation_sha256"]) + expected_digest = row["completion_validation_sha256"] + declaration = as_optional_dict(read_completion_validation_declaration( + runtime_root=self.root, + goal_id=str(actor["goal_id"]), + todo_id=str(row["todo_id"]), + expected_digest=expected_digest if isinstance(expected_digest, str) else None, + )) if not declaration or not declaration.get("validation_command_argv"): raise ValueError("the existing source task has no independent argv validation") return declaration - def source_options(self, session_id): + def source_options(self, session_id: str) -> dict[str, object]: """Discover references through the same source admission, without enrolling work. Completed-history reads include active and archived native Tasks. The @@ -112,11 +146,13 @@ def source_options(self, session_id): """ from ...control_plane.todos.list_readback import list_goal_todos try: - actor = self.selected(session_id)["actor"] - snapshot = list_goal_todos(registry_path=self.controller.registry_path, goal_id=actor["goal_id"], - runtime_root_arg=str(self.root), role="agent", status="done", read_scope="completed_history", limit=None) - sources = [] - for row in snapshot["todos"]: + actor = as_mapping(self.selected(session_id)["actor"]) + snapshot = as_mapping(list_goal_todos( + registry_path=cast(Path, self.controller.registry_path), goal_id=str(actor["goal_id"]), + runtime_root_arg=str(self.root), role="agent", status="done", read_scope="completed_history", limit=None, + )) + sources: list[dict[str, object]] = [] + for row in as_dict_list(snapshot["todos"]): if not self._source_candidate(actor, row): continue # An unreadable or changed declaration must fail the read instead @@ -132,9 +168,9 @@ def source_options(self, session_id): except OSError as exc: raise RuntimeError("Original managed Task sources are temporarily unreadable") from exc - def admission(self, request): - actor = request["actor"] - subscription, window = self.current_window(actor["session_id"]) + def admission(self, request: Mapping[str, object]) -> dict[str, object]: + actor = as_mapping(request["actor"]) + subscription, window = self.current_window(str(actor["session_id"])) if (not subscription or not window or window["window_id"] != request["schedule_window_id"] or subscription["effective_revision"] != window["subscription_revision"]): raise ValueError("the original calendar task subscription changed") @@ -142,62 +178,75 @@ def admission(self, request): todo = self._todo(actor, window) if not definition or not todo: raise ValueError("the original finite calendar task is unavailable") - source_task, validation = self.source_task(actor, subscription["task"]) - declaration = read_completion_validation_declaration(runtime_root=self.root, - goal_id=actor["goal_id"], todo_id=todo["todo_id"], - expected_digest=todo.get("completion_validation_sha256")) + source_task, validation = self.source_task(actor, as_mapping(subscription["task"])) + expected_digest = todo.get("completion_validation_sha256") + declaration = as_optional_dict(read_completion_validation_declaration( + runtime_root=self.root, + goal_id=str(actor["goal_id"]), + todo_id=str(todo["todo_id"]), + expected_digest=expected_digest if isinstance(expected_digest, str) else None, + )) if not declaration or declaration != validation or declaration != definition["validation"]: raise ValueError("the original calendar task's independent validation changed") return {"subscription": subscription, "window": window, "definition": definition, "todo": todo, "source_task": source_task} - def _completion(self, window): + def _completion(self, window: Mapping[str, object]) -> dict[str, str] | None: """Task DONE alone is insufficient: read the original native commit/body.""" definition = self._definition(window) if not definition: return None - actor = definition["actor"] + actor = as_mapping(definition["actor"]) todo = self._todo(actor, window) - completed_key = (todo or {}).get("completion_turn_key") + completed_key = todo.get("completion_turn_key") if todo else None client = ("managed." + completed_key.removeprefix("managed-session.") if isinstance(completed_key, str) and completed_key.startswith("managed-session.") - else "managed.task." + window["window_id"]) - turn = self.controller.store.turn_for_client(actor["session_id"], client) - request = (turn or {}).get("loopx_request") or {} - response = (turn or {}).get("response") or {} + else "managed.task." + str(window["window_id"])) + session_id = str(actor["session_id"]) + turn = as_optional_dict(self.controller.store.turn_for_client(session_id, client)) + request = as_mapping((turn or {}).get("loopx_request")) + response = as_mapping((turn or {}).get("response")) + native = as_mapping(response.get("native_loopx")) if (not todo or not turn or turn["status"] != "completed" or todo["status"] != "done" or request.get("work_kind") != "scheduled_task" or request.get("actor") != actor or request.get("todo_id") != todo["todo_id"] or request.get("schedule_window_id") != window["window_id"] or request.get("schedule_subscription_revision") != window["subscription_revision"] or todo.get("completion_turn_key") != request.get("turn_instance_id") - or (response.get("native_loopx") or {}).get("status") != "committed"): + or native.get("status") != "committed"): return None - results = [row["payload"] for row in self.controller.store.events_after(actor["session_id"], turn["turn_id"], None) + turn_id = str(turn["turn_id"]) + results = [row["payload"] for row in self.controller.store.events_after(session_id, turn_id, None) if row["kind"] == "native_loopx.result"] if results != [response["native_loopx"]]: return None body = response.get("message") # Tolerant transcript rendering cannot establish a unique complete # return: an unreadable record could contain a conflicting reply. - rows = [row for row in self.controller.store.messages(actor["session_id"], strict=True) - if row["message_id"] == "managed." + turn["turn_id"] + ".completed"] + rows = [row for row in self.controller.store.messages(session_id, strict=True) + if row["message_id"] == "managed." + turn_id + ".completed"] if (not isinstance(body, str) or not body.strip() or len(rows) != 1 - or rows[0]["role"] != "agent" or rows[0]["turn_id"] != turn["turn_id"] or rows[0]["text"] != body): + or rows[0]["role"] != "agent" or rows[0]["turn_id"] != turn_id or rows[0]["text"] != body): return None - return {"todo_id": todo["todo_id"], "turn_instance_id": request["turn_instance_id"], + return cast(dict[str, str], {"todo_id": todo["todo_id"], "turn_instance_id": request["turn_instance_id"], "message_id": rows[0]["message_id"], "message_sha256": sha256_envelope(body.encode("utf-8")), - "completed_at": rows[0]["created_at"]} + "completed_at": rows[0]["created_at"]}) - def _published_window(self, window): + def _published_window(self, window: dict[str, object]) -> bool: # Compatibility with the shared configuration fence; this remains a # Task completion, never an invented report/provider publication. return self._completion(window) is not None - def _known_generation_failure(self, actor, window): - turn = self.controller.store.turn_for_client(actor["session_id"], "managed.task." + window["window_id"]) - request = (turn or {}).get("loopx_request") or {} - native = ((turn or {}).get("response") or {}).get("native_loopx") or {} + def _known_generation_failure( + self, actor: dict[str, object], window: dict[str, object], + ) -> dict[str, str] | None: + turn = as_optional_dict(self.controller.store.turn_for_client( + str(actor["session_id"]), "managed.task." + str(window["window_id"]), + )) + request = as_mapping((turn or {}).get("loopx_request")) + native = as_mapping(as_mapping((turn or {}).get("response")).get("native_loopx")) todo = self._todo(actor, window) - validation, receipt, effects = native.get("validation") or {}, native.get("receipt") or {}, native.get("effects") or {} + validation = as_mapping(native.get("validation")) + receipt = as_mapping(native.get("receipt")) + effects = as_mapping(native.get("effects")) if (turn and turn["status"] == "completed" and native.get("status") == "failed" and todo and todo.get("status") in {"open", "blocked"} and native.get("result_kind") == "validation_failed" and native.get("validation_stage") == "task_postcondition" @@ -211,76 +260,97 @@ def _known_generation_failure(self, actor, window): and request.get("todo_id") == todo["todo_id"] and request.get("schedule_window_id") == window["window_id"] and request.get("schedule_subscription_revision") == window["subscription_revision"]): - return {"turn_id": turn["turn_id"], "todo_id": request["todo_id"]} + return {"turn_id": str(turn["turn_id"]), "todo_id": str(request["todo_id"])} return None - def _cancel_failed_window(self, actor, window, failure, *, cadence_locked=False): + def _cancel_failed_window( + self, actor: dict[str, object], window: dict[str, object], failure: dict[str, str], *, cadence_locked: bool = False, + ) -> None: from ..periodic_report.cadence_journal import ( _retire_failed_cadence_window_locked, retire_failed_cadence_window, ) if self._known_generation_failure(actor, window) != failure: raise ValueError("the original failed calendar task changed before cancellation") - native_command(self.controller, ["todo", "update", "--goal-id", actor["goal_id"], - "--todo-id", failure["todo_id"], "--agent-id", actor["agent_id"], - "--update-operation-id", "cancel.task." + window["window_id"], "--status", "blocked", + goal_id = str(actor["goal_id"]) + agent_id = str(actor["agent_id"]) + native_command(self.controller, ["todo", "update", "--goal-id", goal_id, + "--todo-id", failure["todo_id"], "--agent-id", agent_id, + "--update-operation-id", "cancel.task." + str(window["window_id"]), "--status", "blocked", "--clear-resume-when", "--reason", "Owner cancelled this known failed calendar task; retain original work, effects and failure evidence, not completion.", "--execute"]) retire = _retire_failed_cadence_window_locked if cadence_locked else retire_failed_cadence_window - retire(runtime_root=self.root, goal_id=actor["goal_id"], expected_window_id=window["window_id"], + retire(runtime_root=self.root, goal_id=goal_id, expected_window_id=str(window["window_id"]), source_receipt_id=failure["turn_id"], reason="owner_cancelled_failed_task") - def frontier(self, session_id): + def frontier(self, session_id: str) -> tuple[dict[str, object] | None, bool]: from .steward_managed_mode import ManagedSessionTurn - actor = self.selected(session_id)["actor"] + actor = as_dict(self.selected(session_id)["actor"]) + goal_id = str(actor["goal_id"]) + agent_id = str(actor["agent_id"]) subscription = self.subscription(session_id) if not subscription or not subscription.get("schedule"): return None, False - journal = read_cadence_journal(runtime_root=self.root, goal_id=actor["goal_id"]) - if (journal and not journal.get("task_completion") - and journal["window"]["profile_ref"]["profile_id"] == "session_task"): - receipt = self._completion(journal["window"]) - if receipt: - record_cadence_task_completion(runtime_root=self.root, goal_id=actor["goal_id"], - expected_window_id=journal["window"]["window_id"], receipt=receipt) - admitted = admit_cadence_window(runtime_root=self.root, goal_id=actor["goal_id"], - agent_id=actor["agent_id"], subscription=subscription, now=datetime.now(timezone.utc), - subscription_resolver=lambda: self.subscription(session_id)) + journal = as_optional_dict(read_cadence_journal(runtime_root=self.root, goal_id=goal_id)) + if journal and not journal.get("task_completion"): + journal_window = as_dict(journal["window"]) + if as_mapping(journal_window["profile_ref"]).get("profile_id") == "session_task": + receipt = self._completion(journal_window) + if receipt: + record_cadence_task_completion(runtime_root=self.root, goal_id=goal_id, + expected_window_id=str(journal_window["window_id"]), receipt=receipt) + admitted = as_mapping(admit_cadence_window(runtime_root=self.root, goal_id=goal_id, + agent_id=agent_id, subscription=subscription, now=datetime.now(timezone.utc), + subscription_resolver=lambda: self.subscription(session_id))) if admitted["status"] != "pending": return None, False - window = admitted["window"] - with exclusive_file_lock(cadence_journal_path(self.root, actor["goal_id"]), operation="prepare_calendar_task"): - current = self.subscription(session_id, expected_revision=window["subscription_revision"]) - live_journal = read_cadence_journal(runtime_root=self.root, goal_id=actor["goal_id"]) + window = as_dict(admitted["window"]) + window_id = str(window["window_id"]) + with exclusive_file_lock(cadence_journal_path(self.root, goal_id), operation="prepare_calendar_task"): + current = self.subscription(session_id, expected_revision=str(window["subscription_revision"])) + live_journal = as_optional_dict(read_cadence_journal(runtime_root=self.root, goal_id=goal_id)) if current is None or not live_journal or live_journal["window"] != window: return None, False - source_task, validation = self.source_task(actor, current["task"]) + source_task, validation = self.source_task(actor, as_mapping(current["task"])) + if source_task is None: + raise ValueError("select this Agent's existing completed Task with independent argv validation") path = attempt_directory(self.root, window) / "task.json" definition = self._definition(window) if definition is None: - text = compact_todo_text(f"[{source_task.get('priority') or 'P1'}] Scheduled task for {window['start_at']} to {window['due_at']}: {source_task.get('title') or source_task['text']}") + priority = source_task.get("priority") + priority_label = str(priority) if priority else "P1" + text = compact_todo_text(f"[{priority_label}] Scheduled task for {window['start_at']} to {window['due_at']}: {source_task.get('title') or source_task['text']}") definition = {"actor": actor, "window": window, "task": current["task"], "todo_text": text, "source_task": source_task, "validation": validation} definition["digest"] = _canonical_digest(definition) atomic_write_json(path, definition) todo = self._todo(actor, window) if todo is None: - argv = ["todo", "add", "--goal-id", actor["goal_id"], "--role", "agent", - "--operation-id", window["window_id"], "--text", definition["todo_text"], - "--claimed-by", actor["agent_id"], - "--priority", source_task.get("priority") or "P1", "--task-class", "advancement_task", - "--target-key", window["window_id"], "--continuation-policy", "same_agent_non_delivery", - "--validation-command-json", json.dumps(definition["validation"]["validation_command_argv"]), "--execute"] + def_validation = as_mapping(definition["validation"]) + priority = source_task.get("priority") + argv: list[str] = ["todo", "add", "--goal-id", goal_id, "--role", "agent", + "--operation-id", window_id, "--text", str(definition["todo_text"]), + "--claimed-by", agent_id, + "--priority", str(priority) if priority else "P1", "--task-class", "advancement_task", + "--target-key", window_id, "--continuation-policy", "same_agent_non_delivery", + "--validation-command-json", json.dumps(def_validation["validation_command_argv"]), "--execute"] for key, flag in {"action_kind": "--action-kind", "task_domain": "--task-domain", "task_repository": "--task-repository", "capability_binding_ref": "--capability-binding-ref"}.items(): - if source_task.get(key): - argv += [flag, source_task[key]] + val = source_task.get(key) + if val: + argv += [flag, str(val)] for key, flag in {"required_write_scopes": "--required-write-scope", "required_capabilities": "--required-capability", "target_capabilities": "--target-capability", "excluded_agents": "--excluded-agent"}.items(): - for item in source_task.get(key, []): - argv += [flag, item] - for scope in source_task.get("required_decision_scopes", []): - argv += ["--required-decision-scope", decision_scope_metadata_value(scope)] + items = source_task.get(key) + if isinstance(items, Sequence) and not isinstance(items, (str, bytes)): + for item in items: + argv += [flag, str(item)] + scopes = source_task.get("required_decision_scopes") + if isinstance(scopes, Sequence) and not isinstance(scopes, (str, bytes)): + for scope in scopes: + scope_value = decision_scope_metadata_value(cast(str | Mapping[str, object], scope)) + if scope_value is not None: + argv += ["--required-decision-scope", scope_value] for key, flag in {"validation_label": "--validation-label", "validation_timeout_seconds": "--validation-timeout-seconds"}.items(): if validation.get(key) is not None: argv += [flag, str(validation[key])] @@ -288,30 +358,38 @@ def frontier(self, session_id): todo = self._todo(actor, window) if not todo or todo["status"] != "open": return None, False - return ManagedSessionTurn(self.controller).submit(session_id, agent_id=actor["agent_id"], - operation_id="task." + window["window_id"], todo_id=todo["todo_id"], scheduled_window=window) + submitted, created = ManagedSessionTurn(self.controller).submit( + session_id, agent_id=agent_id, + operation_id="task." + window_id, todo_id=str(todo["todo_id"]), scheduled_window=window, + ) + return as_optional_dict(submitted), bool(created) - def health(self, session_id): + def health(self, session_id: str) -> dict[str, object]: configured = False try: - actor = self.selected(session_id)["actor"] - goal = load_goal_from_registry(self.controller.registry_path, actor["goal_id"]) - config = configuration_summary(goal) + actor = as_mapping(self.selected(session_id)["actor"]) + goal_id = str(actor["goal_id"]) + goal = load_goal_from_registry(cast(Path, self.controller.registry_path), goal_id) + config = as_optional_dict(configuration_summary(goal or {})) if not config or config.get("profile_preset") != "session-task" or config.get("route_ref") != "managed-session:" + session_id: return {"available": True, "configured": False, "enabled": False} configured = True - journal = read_cadence_journal(runtime_root=self.root, goal_id=actor["goal_id"]) - receipt = self._completion(journal["window"]) if journal else None - client = ("managed." + receipt["turn_instance_id"].removeprefix("managed-session.") - if receipt else "managed.task." + journal["window"]["window_id"] if journal else None) - turn = self.controller.store.turn_for_client(session_id, client) if client else None - native = ((turn or {}).get("response") or {}).get("native_loopx") or {} + journal = as_optional_dict(read_cadence_journal(runtime_root=self.root, goal_id=goal_id)) + journal_window = as_dict(journal["window"]) if journal else None + receipt = self._completion(journal_window) if journal_window else None + client = ("managed." + str(receipt["turn_instance_id"]).removeprefix("managed-session.") + if receipt else "managed.task." + str(journal_window["window_id"]) if journal_window else None) + turn = as_optional_dict(self.controller.store.turn_for_client(session_id, client)) if client else None + request = as_mapping((turn or {}).get("loopx_request")) + native = as_mapping(as_mapping((turn or {}).get("response")).get("native_loopx")) + schedule_raw = config.get("schedule") + schedule_cfg = dict(schedule_raw) if isinstance(schedule_raw, Mapping) else None return {"available": True, "configured": True, "enabled": bool(self.subscription(session_id)), - "schedule": config.get("schedule"), "task": config.get("task"), - "next_due_at": report_cadence_next_due_at(config.get("schedule"), now=datetime.now(timezone.utc)) if config.get("enabled") else None, - "retained_window_due_at": journal["window"]["due_at"] if journal else None, + "schedule": schedule_raw, "task": config.get("task"), + "next_due_at": report_cadence_next_due_at(schedule_cfg, now=datetime.now(timezone.utc)) if config.get("enabled") and schedule_cfg is not None else None, + "retained_window_due_at": journal_window["due_at"] if journal_window else None, "completion_verified": bool(receipt), "completion": receipt, - "task_id": (turn or {}).get("loopx_request", {}).get("todo_id"), + "task_id": request.get("todo_id"), "turn_id": (turn or {}).get("turn_id"), "native_result_status": native.get("status"), "result_kind": native.get("result_kind")} except (OSError, ValueError, KeyError, TypeError): diff --git a/loopx/capabilities/native_chat/steward_reports.py b/loopx/capabilities/native_chat/steward_reports.py index 13426d2992..a7b999bcee 100644 --- a/loopx/capabilities/native_chat/steward_reports.py +++ b/loopx/capabilities/native_chat/steward_reports.py @@ -6,11 +6,16 @@ """ from __future__ import annotations -from datetime import datetime, timezone +from collections.abc import Callable, Iterator, Mapping from contextlib import contextmanager +from datetime import datetime, timezone import json +from pathlib import Path import sys -from typing import Any +from typing import TYPE_CHECKING, Protocol, cast + +if TYPE_CHECKING: + from ...chat_store import ChatSessionStore from ...agent_registry import load_goal_from_registry from ...file_lock import exclusive_file_lock, try_exclusive_file_lock @@ -19,10 +24,25 @@ from ..periodic_report.goal_configuration import configuration_summary, normalize_configuration from ..periodic_report.machine_defaults import resolve_active_goal_periodic_report_subscription from ..periodic_report.private_generation import ( - attempt_directory, freeze_private_report, prepare_private_report, report_prompt, + attempt_directory, + freeze_private_report, + prepare_private_report, + report_prompt, ) from .steward_commands import native_command from .steward_managed_mode import ManagedSessionTurn, StewardManagedMode +from .steward_turn_common import ( + StewardBindingsProtocol, + StewardControllerProtocol, + StewardManagedProtocol, + StewardStoreProtocol, + as_dict, + as_dict_list, + as_mapping, + as_optional_dict, + monitor_controller_for, + steward_monitor_for, +) PRESET = "portfolio-progress" @@ -31,112 +51,167 @@ class PendingStewardReportError(ValueError): pass -class StewardReports: - def __init__(self, controller: Any) -> None: - self.controller = controller - self.bindings = controller.project_contexts.conversation_bindings - self.managed = StewardManagedMode(controller, self.bindings) - self.root = controller.coordination_runtime_root +class _ReportsStoreProtocol(StewardStoreProtocol, Protocol): + def queued_turns( + self, session_id: str, *, strict: bool = False, include_reserved: bool = False, + ) -> list[dict[str, object]]: ... + + def append_message( + self, session_id: str, *, role: str, text: str, turn_id: str, message_id: str, + ) -> object: ... + + +class _ReportsManagedProtocol(StewardManagedProtocol, Protocol): + def _session(self, binding_id: str, actor: Mapping[str, object] | None) -> dict[str, object]: ... + + +class _InterruptControllerProtocol(Protocol): + def interrupt_turn(self, *, session_id: str, turn_id: str) -> dict[str, object]: ... + + +class _ReportRouteProviderProtocol(Protocol): + def route_proof(self, binding: Mapping[str, object], actor: Mapping[str, object]) -> dict[str, object]: ... + + +class _CalendarSourceTaskProtocol(Protocol): + def source_task(self, actor: dict[str, object], task: dict[str, object]) -> object: ... + + +class _WindowGuardTargetProtocol(Protocol): + def _published_window(self, window: dict[str, object]) -> bool: ... + def _frozen_actor(self, window: dict[str, object]) -> dict[str, object] | None: ... + def _known_generation_failure(self, actor: dict[str, object], window: dict[str, object]) -> dict[str, str] | None: ... + def _cancel_failed_window( + self, actor: dict[str, object], window: dict[str, object], failure: dict[str, str], *, cadence_locked: bool = False, + ) -> None: ... + + +class _StewardReportsBase: + def __init__(self, controller: StewardControllerProtocol) -> None: + self.controller: StewardControllerProtocol = controller + self.bindings: StewardBindingsProtocol = cast( + StewardBindingsProtocol, controller.project_contexts.conversation_bindings, + ) + self.managed: _ReportsManagedProtocol = cast( + _ReportsManagedProtocol, StewardManagedMode(controller, self.bindings), + ) + self.root: Path = controller.coordination_runtime_root @staticmethod - def route_ref(binding: dict[str, Any], actor: dict[str, Any]) -> str: + def route_ref(binding: Mapping[str, object], actor: Mapping[str, object]) -> str: return f"steward-private:{binding['binding_id']}:{actor['source_ref']}" - def selected(self, binding_id: str) -> dict[str, Any]: - session = self.managed._session(binding_id, None) - saved = session["steward_context"] - selected = self.bindings.resolve(binding_id=binding_id, session=session, - include_observation=True, origin="web", source_ref=saved["source_ref"], - sender_ref=saved["operator_ref"], private_human_message=False, session_context=saved) - actor = selected["binding"].get("managed_actor") - if not actor or actor["session_id"] != session["session_id"]: - raise ValueError("prepare the original steward before configuring reports") - return {**selected, "actor": actor, "session": session} + def selected(self, owner_key: str) -> dict[str, object]: raise NotImplementedError + def subscription(self, owner_key: str, *, expected_revision: str | None = None, expected_actor: dict[str, object] | None = None) -> dict[str, object] | None: raise NotImplementedError + def _submit(self, owner_key: str, actor: dict[str, object], window: dict[str, object], todo: dict[str, object]) -> tuple[dict[str, object], bool]: raise NotImplementedError + def prepare(self, request: Mapping[str, object], adapter: object, *, authorization_scope_id: str) -> str: raise NotImplementedError + def delivery_current(self, owner_key: str, window: dict[str, object]) -> bool: raise NotImplementedError + def publish(self, session_id: str, window: Mapping[str, object]) -> bool: raise NotImplementedError - def subscription(self, binding_id: str, *, expected_revision: str | None = None, - expected_actor: dict[str, Any] | None = None) -> dict[str, Any] | None: - selected = self.selected(binding_id) - actor, binding = selected["actor"], selected["binding"] - if expected_actor is not None and actor != expected_actor: + @staticmethod + def _read_reporting_rules(rules: Path, default_text_fn: Callable[[], str]) -> str: + if rules.is_symlink(): + raise ValueError("the original reporting criteria changed source") + return rules.read_text(encoding="utf-8") if rules.exists() else default_text_fn() + + @staticmethod + def _build_health_schedule(config: Mapping[str, object]) -> tuple[dict[str, object] | None, object]: + schedule_cfg = as_optional_dict(config.get("schedule")) + next_due = ( + report_cadence_next_due_at(schedule_cfg, now=datetime.now(timezone.utc)) + if config.get("enabled") and schedule_cfg is not None + else None + ) + return schedule_cfg, next_due + + @staticmethod + def _has_attempt_source_only(folder: Path) -> bool: + if any(path.is_symlink() or not path.is_file() for path in (folder / "source.json", folder / "editorial-request.json")): + return False + for name in ( + "editorial-response.json", "generation-bundle.json", "report.md", + "publication-candidate.json", "private-generation.json", "private-delivery.json", + ): + try: + (folder / name).lstat() + except FileNotFoundError: + continue + return False + return True + + def _matched_report_parts( + self, actor: Mapping[str, object], window: Mapping[str, object], turn: dict[str, object] | None, + ) -> tuple[Mapping[str, object], Mapping[str, object]] | None: + if not turn: return None - goal = load_goal_from_registry(self.controller.registry_path, actor["goal_id"]) - subscription = resolve_active_goal_periodic_report_subscription(goal) - if (subscription is None or subscription.get("profile_preset") != PRESET - or subscription.get("route_ref") != self.route_ref(binding, actor) - or expected_revision is not None and subscription["effective_revision"] != expected_revision): + request = as_mapping(turn.get("loopx_request")) + if ( + request.get("actor") != actor + or request.get("work_kind") != "report" + or request.get("report_window_id") != window["window_id"] + or request.get("report_subscription_revision") != window["subscription_revision"] + ): return None - return subscription + return request, as_mapping(as_mapping(turn.get("response")).get("native_loopx")) - def _published_window(self, window: dict[str, Any]) -> bool: + def _published_window(self, window: dict[str, object]) -> bool: from ..periodic_report.incremental import read_periodic_report_publication_cursor from ..periodic_report.post_writeback_hook import evaluate_periodic_report_trigger_evaluation_intent - cursor = read_periodic_report_publication_cursor(runtime_root=self.root, - goal_id=window["goal_id"], agent_id=window["agent_id"]) + + cursor = as_optional_dict(read_periodic_report_publication_cursor(runtime_root=self.root, goal_id=str(window["goal_id"]), agent_id=str(window["agent_id"]))) trigger = evaluate_periodic_report_trigger_evaluation_intent(cadence_intent(window)) - return bool(cursor and trigger["selected_trigger_id"] in cursor["covered_trigger_ids"]) + covered = cursor.get("covered_trigger_ids") if cursor else None + return bool(cursor and isinstance(covered, list) and trigger["selected_trigger_id"] in covered) - def _known_generation_failure(self, actor: dict[str, Any], window: dict[str, Any]) -> dict[str, str] | None: + def _known_generation_failure(self, actor: dict[str, object], window: dict[str, object]) -> dict[str, str] | None: from .steward_turn import report_turn + folder = attempt_directory(self.root, window) - if (not (folder / "editorial-response.json").is_file() - or (folder / "private-generation.json").exists() or (folder / "private-delivery.json").exists()): + if not (folder / "editorial-response.json").is_file() or (folder / "private-generation.json").exists() or (folder / "private-delivery.json").exists(): return None turn = report_turn(self.controller.store, actor, window) - request = (turn or {}).get("loopx_request") or {} - native = ((turn or {}).get("response") or {}).get("native_loopx") or {} - if (turn and turn.get("status") == "completed" and native.get("status") == "failed" - and request.get("actor") == actor and request.get("work_kind") == "report" - and request.get("report_window_id") == window["window_id"] - and request.get("report_subscription_revision") == window["subscription_revision"]): - return {"turn_id": turn["turn_id"], "todo_id": request["todo_id"]} + parts = self._matched_report_parts(actor, window, turn) + if turn and parts and turn.get("status") == "completed" and parts[1].get("status") == "failed": + return {"turn_id": str(turn["turn_id"]), "todo_id": str(parts[0]["todo_id"])} return None - def _cancellable_failed_window(self, actor: dict[str, Any], window: dict[str, Any]) -> dict[str, str] | None: + def _cancellable_failed_window(self, actor: dict[str, object], window: dict[str, object]) -> dict[str, str] | None: """Identify a terminal failed report attempt that owner cancel may retire.""" known = self._known_generation_failure(actor, window) if known is not None: return known from .steward_turn import report_turn - folder = attempt_directory(self.root, window) - if any(path.is_symlink() or not path.is_file() - for path in (folder / "source.json", folder / "editorial-request.json")): - return None - for name in ("editorial-response.json", "generation-bundle.json", "report.md", - "publication-candidate.json", "private-generation.json", "private-delivery.json"): - try: - (folder / name).lstat() - except FileNotFoundError: - continue + + if not self._has_attempt_source_only(attempt_directory(self.root, window)): return None turn = report_turn(self.controller.store, actor, window) - request = (turn or {}).get("loopx_request") or {} - native = ((turn or {}).get("response") or {}).get("native_loopx") or {} - failure = native.get("host_failure") or {} - if (turn and turn.get("status") == "completed" and native.get("status") == "failed" - and native.get("result_kind") == "host_failure" and failure.get("retryable") is False - and native.get("effects") == {"host_invoked": True, "state_written": False, - "quota_spent": False, "scheduler_acknowledged": False} - and request.get("actor") == actor and request.get("work_kind") == "report" - and request.get("report_window_id") == window["window_id"] - and request.get("report_subscription_revision") == window["subscription_revision"] - and isinstance(request.get("todo_id"), str) and bool(request["todo_id"])): - return {"turn_id": turn["turn_id"], "todo_id": request["todo_id"]} + parts = self._matched_report_parts(actor, window, turn) + if not turn or not parts: + return None + request, native = parts + failure = as_mapping(native.get("host_failure")) + todo_id = request.get("todo_id") + if ( + turn.get("status") == "completed" and native.get("status") == "failed" + and native.get("result_kind") == "host_failure" and failure.get("retryable") is False + and native.get("effects") == {"host_invoked": True, "state_written": False, "quota_spent": False, "scheduler_acknowledged": False} + and isinstance(todo_id, str) and bool(todo_id) + ): + return {"turn_id": str(turn["turn_id"]), "todo_id": todo_id} return None - def _execution_failed(self, actor: dict[str, Any], window: dict[str, Any]) -> bool: + def _execution_failed(self, actor: dict[str, object], window: dict[str, object]) -> bool: """Observe the current attempt; this grants no cancellation or retry.""" from .steward_turn import report_turn + turn = report_turn(self.controller.store, actor, window) - request = (turn or {}).get("loopx_request") or {} - native = ((turn or {}).get("response") or {}).get("native_loopx") or {} - return bool(turn and request.get("actor") == actor and request.get("work_kind") == "report" - and request.get("report_window_id") == window["window_id"] - and request.get("report_subscription_revision") == window["subscription_revision"] - and (turn.get("status") in {"failed", "interrupted", "timed_out"} - or native.get("status") == "failed")) + parts = self._matched_report_parts(actor, window, turn) + return bool( + turn and parts and (turn.get("status") in {"failed", "interrupted", "timed_out"} or parts[1].get("status") == "failed") + ) def _failed_without_generation( - self, actor: dict[str, Any], window: dict[str, Any], *, + self, actor: dict[str, object], window: dict[str, object], *, generation_locked: bool = False, require_recovery_exhausted: bool = False, ) -> bool: """Read a terminal report failure under the original execution fence. @@ -150,353 +225,453 @@ def _failed_without_generation( from ...control_plane.turn_driver.turn_journal_runtime import interpret_turn_journal_projection from .steward_turn import StewardTurnHost, report_turn - store = self.controller.store - folder = attempt_directory(self.root, window) - if any(path.is_symlink() or not path.is_file() - for path in (folder / "source.json", folder / "editorial-request.json")): - return False - for name in ("editorial-response.json", "generation-bundle.json", "report.md", - "publication-candidate.json", "private-generation.json", "private-delivery.json"): - try: - (folder / name).lstat() - except FileNotFoundError: - continue + store = cast(_ReportsStoreProtocol, self.controller.store) + if not self._has_attempt_source_only(attempt_directory(self.root, window)): return False - sid = actor["session_id"] + sid = str(actor["session_id"]) turn = report_turn(store, actor, window) if not turn or turn.get("status") != "completed" or not turn.get("upstream_turn_id"): return False - with try_exclusive_file_lock(store.turn_execution_lock_path(sid, turn["turn_id"]), - operation="observe_failed_report_window", preserve_holder=True) as ownership: + turn_id = str(turn["turn_id"]) + with try_exclusive_file_lock( + store.turn_execution_lock_path(sid, turn_id), operation="observe_failed_report_window", preserve_holder=True, + ) as ownership: session = store.load_session(sid) - if (ownership is None or not session or session.get("active_turn_id") - or store.queued_turns(sid, strict=True, include_reserved=True) - or report_turn(store, actor, window) != turn): + if ( + ownership is None or not session or session.get("active_turn_id") + or store.queued_turns(sid, strict=True, include_reserved=True) + or report_turn(store, actor, window) != turn + ): + return False + parts = self._matched_report_parts(actor, window, turn) + if not parts: return False - request = turn.get("loopx_request") or {} - result = (turn.get("response") or {}).get("native_loopx") or {} - receipt = result.get("receipt") or {} - failure = result.get("host_failure") or {} - operation = "report." + window["window_id"] + request, result = parts + receipt = as_mapping(result.get("receipt")) + failure = as_mapping(result.get("host_failure")) + operation = "report." + str(window["window_id"]) if actor.get("schema_version") == "loopx_managed_session_actor_v0": - operation = ManagedSessionTurn(self.controller)._request(sid, actor["agent_id"], operation)["turn_instance_id"] + managed_req = as_mapping(ManagedSessionTurn(self.controller)._request(sid, str(actor["agent_id"]), operation)) + operation = str(managed_req["turn_instance_id"]) allowed_instances = ( {operation + ".quota-recovery", operation + ".timeout-recovery"} if require_recovery_exhausted else {operation, operation + ".quota-recovery", operation + ".timeout-recovery"} ) - if (turn.get("origin") != "native_loopx" or turn.get("loopx_execution") is not True - or turn.get("session_id") != sid or request.get("actor") != actor - or request.get("work_kind") != "report" or request.get("report_window_id") != window["window_id"] - or request.get("report_subscription_revision") != window["subscription_revision"] - or request.get("turn_instance_id") not in allowed_instances - or not request.get("todo_id") or result.get("status") != "failed" - or result.get("result_kind") != "host_failure" or failure.get("retryable") is not False - or receipt.get("ok") is not True or receipt.get("failed_phase") != "host_execute" - or receipt.get("completed_phases") != [] - or result.get("effects") != {"host_invoked": True, "state_written": False, - "quota_spent": False, "scheduler_acknowledged": False}): + if ( + turn.get("origin") != "native_loopx" or turn.get("loopx_execution") is not True + or turn.get("session_id") != sid + or request.get("turn_instance_id") not in allowed_instances or not request.get("todo_id") + or result.get("status") != "failed" or result.get("result_kind") != "host_failure" + or failure.get("retryable") is not False or receipt.get("ok") is not True + or receipt.get("failed_phase") != "host_execute" or receipt.get("completed_phases") != [] + or result.get("effects") != { + "host_invoked": True, "state_written": False, + "quota_spent": False, "scheduler_acknowledged": False, + } + ): return False - events = _read_jsonl(store._event_path(sid, turn["turn_id"]), raise_on_error=True, strict=True) + events = _read_jsonl(store._event_path(sid, turn_id), raise_on_error=True, strict=True) results = [event["payload"] for event in events if event["kind"] == "native_loopx.result"] - if results != [result]: + if results != [dict(result)]: return False - goal_id, agent_id = actor["goal_id"], actor["agent_id"] - key = result["resume_turn_key"] + goal_id, agent_id = str(actor["goal_id"]), str(actor["agent_id"]) + key = str(result["resume_turn_key"]) path = turn_journal_path(self.root, goal_id=goal_id, turn_key=key) with try_exclusive_file_lock(path, operation="observe_failed_report_turn", preserve_holder=True) as locked: - journal = load_turn_journal(path) if locked is not None else None - if (not journal or journal.get("status") != "failed" or journal.get("receipt") != receipt - or journal.get("host_failure") != failure): + journal = as_optional_dict(load_turn_journal(path)) if locked is not None else None + if ( + not journal or journal.get("status") != "failed" + or journal.get("receipt") != receipt or journal.get("host_failure") != failure + ): return False - identity = journal["plan"]["transaction"]["settlement_plan"]["identity"] - if (identity.get("todo_id") != request["todo_id"] - or identity.get("turn_instance_id") != request["turn_instance_id"]): + plan = as_mapping(journal.get("plan")) + settlement_plan = as_mapping(as_mapping(plan.get("transaction")).get("settlement_plan")) + identity = as_mapping(settlement_plan.get("identity")) + if identity.get("todo_id") != request["todo_id"] or identity.get("turn_instance_id") != request["turn_instance_id"]: return False inspection = interpret_turn_journal_projection(journal, goal_id=goal_id, agent_id=agent_id, turn_key=key) - return (inspection.get("journal_consistent") is True + return bool( + inspection.get("journal_consistent") is True and inspection.get("completed_phases") == [] - and StewardTurnHost(self.controller).report_window_failure_verified( - turn, window, generation_locked=generation_locked, - )) - - def _cancel_failed_window(self, actor: dict[str, Any], window: dict[str, Any], - failure: dict[str, str], *, cadence_locked: bool = False) -> None: - from ..periodic_report.cadence_journal import ( - _retire_failed_cadence_window_locked, retire_failed_cadence_window, - ) + and StewardTurnHost(self.controller).report_window_failure_verified(turn, window, generation_locked=generation_locked) + ) + + def _cancel_failed_window( + self, actor: dict[str, object], window: dict[str, object], failure: dict[str, str], *, cadence_locked: bool = False, + ) -> None: + from ..periodic_report.cadence_journal import _retire_failed_cadence_window_locked, retire_failed_cadence_window + if self._cancellable_failed_window(actor, window) != failure: raise ValueError("the original failed report changed before cancellation") - native_command(self.controller, ["todo", "update", "--goal-id", actor["goal_id"], - "--todo-id", failure["todo_id"], "--agent-id", actor["agent_id"], - "--update-operation-id", "cancel.report." + window["window_id"], "--status", "blocked", - "--clear-resume-when", "--reason", - "Owner cancelled a known failed report window; retain the failed task, costs and evidence, not completed or delivered.", "--execute"]) + native_command( + self.controller, + [ + "todo", "update", "--goal-id", str(actor["goal_id"]), "--todo-id", failure["todo_id"], + "--agent-id", str(actor["agent_id"]), "--update-operation-id", "cancel.report." + str(window["window_id"]), + "--status", "blocked", "--clear-resume-when", "--reason", + "Owner cancelled a known failed report window; retain the failed task, costs and evidence, not completed or delivered.", + "--execute", + ], + ) retire = _retire_failed_cadence_window_locked if cadence_locked else retire_failed_cadence_window - retire(runtime_root=self.root, goal_id=actor["goal_id"], - expected_window_id=window["window_id"], source_receipt_id=failure["turn_id"]) + retire( + runtime_root=self.root, goal_id=str(actor["goal_id"]), + expected_window_id=str(window["window_id"]), source_receipt_id=failure["turn_id"], + ) + + def current_window(self, binding_id: str) -> tuple[dict[str, object] | None, dict[str, object] | None]: + subscription = self.subscription(binding_id) + if subscription is None: + return None, None + actor = as_mapping(self.selected(binding_id)["actor"]) + journal = as_optional_dict(read_cadence_journal(runtime_root=self.root, goal_id=str(actor["goal_id"]))) + return subscription, as_dict(journal["window"]) if journal else None + + def _frontier(self, owner_key: str, actor: dict[str, object]) -> tuple[dict[str, object] | None, bool]: + from .steward_turn import StewardTurnHost + + subscription = self.subscription(owner_key) + if subscription is None or subscription.get("schedule") is None: + return None, False + actor_goal_id, actor_agent_id = str(actor["goal_id"]), str(actor["agent_id"]) + admitted = as_mapping( + admit_cadence_window( + runtime_root=self.root, goal_id=actor_goal_id, agent_id=actor_agent_id, + subscription=subscription, now=datetime.now(timezone.utc), + subscription_resolver=lambda: self.subscription(owner_key, expected_actor=actor), + can_replace_failed_window=lambda win: self._failed_without_generation(actor, win, generation_locked=True), + can_replace_exhausted_failed_window=lambda win: self._failed_without_generation( + actor, win, generation_locked=True, require_recovery_exhausted=True, + ), + ) + ) + if admitted.get("status") != "pending": + return None, False + window = as_dict(admitted["window"]) + window_id = str(window["window_id"]) + rows = [row for row in as_dict_list(steward_monitor_for(self.controller).todos(actor)) if row.get("target_key") == window_id] + if len(rows) > 1: + raise ValueError("report window has conflicting native tasks") + if not rows: + native_command( + self.controller, + [ + "todo", "add", "--goal-id", actor_goal_id, "--role", "agent", "--operation-id", window_id, + "--text", ( + f"[P1] Author the configured original Session report ending {window['due_at']}; retain evidence and coverage gaps. Generation is separate from verified delivery." + if actor.get("schema_version") == "loopx_managed_session_actor_v0" + else f"[P1] Author the authorized portfolio report ending {window['due_at']}; retain counterevidence and coverage gaps. Generation is separate from verified private delivery." + ), + "--claimed-by", actor_agent_id, "--action-kind", "generate_periodic_report", + "--target-key", window_id, "--continuation-policy", "same_agent_non_delivery", "--execute", + ], + ) + rows = [row for row in as_dict_list(steward_monitor_for(self.controller).todos(actor)) if row.get("target_key") == window_id] + folder = attempt_directory(self.root, window) + if len(rows) == 1 and ( + rows[0]["status"] == "done" + or rows[0]["status"] == "open" + and ((folder / "private-generation.json").exists() or StewardTurnHost(self.controller).has_recoverable_stopped_report(actor, window, rows[0])) + ): + StewardTurnHost(self.controller).recover_report_settlement(actor, window, rows[0]) + return None, False + if len(rows) != 1 or rows[0]["status"] != "open": + return None, False + return self._submit(owner_key, actor, window, rows[0]) + + def freeze(self, request: Mapping[str, object], candidate: dict[str, object]) -> dict[str, object]: + _, owner_key = report_service(self.controller, as_mapping(request["actor"])) + _, window = self.current_window(owner_key) + if not window or window["window_id"] != request["report_window_id"]: + raise ValueError("the original report was paused, cancelled or changed") + response = candidate.pop("editorial_response", None) + if not isinstance(response, dict): + raise ValueError("the original reporting Agent returned no editorial response") + return as_dict(freeze_private_report(root=self.root, window=window, response=response, require_current_window=True)) + - def configure(self, binding_id: str, *, operation: str, schedule: dict[str, Any] | None = None, - expected_plan_id: str | None = None, execute: bool = False) -> dict[str, Any]: +class StewardReports(_StewardReportsBase): + def selected(self, binding_id: str) -> dict[str, object]: + session = as_dict(self.managed._session(binding_id, None)) + saved = as_dict(session["steward_context"]) + selected = self.bindings.resolve( + binding_id=binding_id, session=session, include_observation=True, origin="web", + source_ref=str(saved["source_ref"]), sender_ref=str(saved["operator_ref"]), + private_human_message=False, session_context=saved, + ) + actor = as_optional_dict(as_mapping(selected["binding"]).get("managed_actor")) + if not actor or actor.get("session_id") != session["session_id"]: + raise ValueError("prepare the original steward before configuring reports") + return {**selected, "actor": actor, "session": session} + + def subscription( + self, binding_id: str, *, expected_revision: str | None = None, expected_actor: dict[str, object] | None = None, + ) -> dict[str, object] | None: + selected = self.selected(binding_id) + actor, binding = as_mapping(selected["actor"]), as_mapping(selected["binding"]) + if expected_actor is not None and actor != expected_actor: + return None + goal = load_goal_from_registry(cast(Path, self.controller.registry_path), str(actor["goal_id"])) + subscription = as_optional_dict(resolve_active_goal_periodic_report_subscription(goal)) + if ( + subscription is None or subscription.get("profile_preset") != PRESET + or subscription.get("route_ref") != self.route_ref(binding, actor) + or expected_revision is not None and subscription.get("effective_revision") != expected_revision + ): + return None + return subscription + + def configure( + self, binding_id: str, *, operation: str, schedule: dict[str, object] | None = None, + expected_plan_id: str | None = None, execute: bool = False, + ) -> dict[str, object]: from ...configure_goal import configure_goal selected = self.selected(binding_id) - binding, actor, session = selected["binding"], selected["actor"], selected["session"] - provider = getattr(self.controller, "steward_report_provider", None) + binding, actor, session = as_dict(selected["binding"]), as_dict(selected["actor"]), as_dict(selected["session"]) + provider = cast(_ReportRouteProviderProtocol | None, getattr(self.controller, "steward_report_provider", None)) if provider is None: raise ValueError("the original private report provider is unavailable") route = provider.route_proof(binding, actor) + actor_goal_id = str(actor["goal_id"]) with self.controller.lock, exclusive_file_lock(self.bindings.path, operation="configure_steward_report"): current = self.selected(binding_id) if current["binding"] != binding: raise ValueError("the original steward authorization changed") - goal = load_goal_from_registry(self.controller.registry_path, actor["goal_id"]) - before = configuration_summary(goal) - effective_schedule = schedule if operation == "enable" else (before or {}).get("schedule") + goal = load_goal_from_registry(cast(Path, self.controller.registry_path), actor_goal_id) + before = as_optional_dict(configuration_summary(goal or {})) + effective_schedule = schedule if operation == "enable" else as_optional_dict((before or {}).get("schedule")) if effective_schedule is None: raise ValueError("select the daily or weekly report time and first date") - proposed = normalize_configuration({"enabled": operation == "enable", "profile_preset": PRESET, - "route_ref": self.route_ref(binding, actor), "timezone": effective_schedule["timezone"], - "schedule": effective_schedule}) - active_proposed = resolve_active_goal_periodic_report_subscription( - {**goal, "control_plane": {"periodic_report": {**proposed, "enabled": True}}}) - journal = read_cadence_journal(runtime_root=self.root, goal_id=actor["goal_id"]) - pending = None - failure = None + proposed = as_dict(normalize_configuration({ + "enabled": operation == "enable", "profile_preset": PRESET, + "route_ref": self.route_ref(binding, actor), + "timezone": effective_schedule["timezone"], "schedule": effective_schedule, + })) + active_proposed = as_optional_dict(resolve_active_goal_periodic_report_subscription( + {**(goal or {}), "control_plane": {"periodic_report": {**proposed, "enabled": True}}} + )) + journal = as_optional_dict(read_cadence_journal(runtime_root=self.root, goal_id=actor_goal_id)) + pending: dict[str, object] | None = None + failure: dict[str, str] | None = None if journal: - failure = self._cancellable_failed_window(actor, journal["window"]) - pending = {"subscription_revision": journal["window"]["subscription_revision"], - "prepared": (attempt_directory(self.root, journal["window"]) / "editorial-request.json").exists(), - "verified_publication": self._published_window(journal["window"]), + journal_window = as_dict(journal["window"]) + failure = self._cancellable_failed_window(actor, journal_window) + pending = { + "subscription_revision": journal_window["subscription_revision"], + "prepared": (attempt_directory(self.root, journal_window) / "editorial-request.json").exists(), + "verified_publication": self._published_window(journal_window), "retired": bool(journal.get("retirement")), - "failure_ref": failure["turn_id"] if failure else None} - plan = self.bindings._core("collaboration.steward.report.plan", { + "failure_ref": failure["turn_id"] if failure else None, + } + plan = as_dict(self.bindings._core("collaboration.steward.report.plan", { **current, "workspace_path": str(self.managed._workspace(session)), - "goal": self.managed._goal(actor["goal_id"]), - "goal_active": bool(active_proposed), "pending_report": pending, + "goal": self.managed._goal(actor_goal_id), "goal_active": bool(active_proposed), + "pending_report": pending, "proposed_subscription_revision": active_proposed["effective_revision"] if active_proposed else None, - "configuration": before, "proposed": proposed, "operation": operation, "route": route}) + "configuration": before, "proposed": proposed, "operation": operation, "route": route, + })) if plan.get("gate") == "report_window_pending": raise PendingStewardReportError("the original frozen report still requires verified private delivery") if not execute: return {"ok": True, "applied": False, "plan": plan} if expected_plan_id != plan["plan_id"]: raise ValueError("refresh the original report preview before applying") - result = configure_goal(registry_path=self.controller.registry_path, goal_id=actor["goal_id"], - periodic_report_configuration=plan["configuration"], execute=True) + result = as_mapping(configure_goal( + registry_path=cast(Path, self.controller.registry_path), goal_id=actor_goal_id, + periodic_report_configuration=as_mapping(plan["configuration"]), execute=True, + )) if result.get("ok") is not True: raise ValueError("native report configuration was not committed") - if configuration_summary(load_goal_from_registry(self.controller.registry_path, actor["goal_id"])) != proposed: + if configuration_summary(load_goal_from_registry(cast(Path, self.controller.registry_path), actor_goal_id) or {}) != proposed: raise ValueError("native report configuration readback changed") - if plan["retires_failed_window"]: - self._cancel_failed_window(actor, journal["window"], failure) + if plan["retires_failed_window"] and journal and failure is not None: + self._cancel_failed_window(actor, as_dict(journal["window"]), failure) from .steward_monitor_pump import clear_steward_monitor_check_hints - clear_steward_monitor_check_hints(self.controller, binding_id) - receipt = {"ok": True, "applied": True, "plan": plan, "report": self.health(binding_id), - "model_invoked": False, "external_writes_performed": False} + clear_steward_monitor_check_hints(monitor_controller_for(self.controller), binding_id) + receipt: dict[str, object] = { + "ok": True, "applied": True, "plan": plan, "report": self.health(binding_id), + "model_invoked": False, "external_writes_performed": False, + } if operation == "cancel": # Stop only this original report, outside the configuration fence; # unrelated user/monitor work is never interrupted by this setting. - current_session = self.controller.store.load_session(actor["session_id"]) - turn_id = (current_session or {}).get("active_turn_id") - turn = self.controller.store.load_turn(actor["session_id"], turn_id) if turn_id else None - request = (turn or {}).get("loopx_request") or {} - if request.get("work_kind") == "report" and request.get("actor") == actor: + actor_session_id = str(actor["session_id"]) + current_session = self.controller.store.load_session(actor_session_id) + raw_turn_id = (current_session or {}).get("active_turn_id") + turn_id = str(raw_turn_id) if isinstance(raw_turn_id, str) and raw_turn_id else None + turn = self.controller.store.load_turn(actor_session_id, turn_id) if turn_id else None + request = as_mapping((turn or {}).get("loopx_request")) + if turn_id and request.get("work_kind") == "report" and request.get("actor") == actor: try: - stopped = self.controller.interrupt_turn(session_id=actor["session_id"], turn_id=turn_id) + interrupt_ctrl = cast(_InterruptControllerProtocol, self.controller) + stopped = as_mapping(interrupt_ctrl.interrupt_turn(session_id=actor_session_id, turn_id=turn_id)) receipt["stop_status"] = stopped.get("status", "unconfirmed") except (OSError, ValueError, RuntimeError): receipt["stop_status"] = "unconfirmed" return receipt - def delivery_current(self, binding_id: str, window: dict[str, Any]) -> bool: + def delivery_current(self, binding_id: str, window: dict[str, object]) -> bool: """Recheck the exact original read grant before every outbound part.""" from ...chat_manager_context import manager_authorization_scope_id_for_registry from ..periodic_report.pending_intent import _canonical_digest + subscription, current = self.current_window(binding_id) - if (subscription is None or subscription["effective_revision"] != window["subscription_revision"] - or current != window): + if subscription is None or subscription["effective_revision"] != window["subscription_revision"] or current != window: return False selected = self.selected(binding_id) - session = selected["session"] + session = as_dict(selected["session"]) folder = attempt_directory(self.root, window) - expected = json.loads((folder / "editorial-request.json").read_text(encoding="utf-8")) - source = json.loads((folder / "source.json").read_text(encoding="utf-8")) + expected = as_mapping(json.loads((folder / "editorial-request.json").read_text(encoding="utf-8"))) + source = as_mapping(json.loads((folder / "source.json").read_text(encoding="utf-8"))) frozen_ids = source.get("goal_ids") current_ids = self.bindings.steward_scope(session) - if (expected.get("request_digest") != _canonical_digest( - {k: v for k, v in expected.items() if k != "request_digest"}) - or expected.get("source_artifact_sha256") != _canonical_digest(source) - or not isinstance(frozen_ids, list) or not all(isinstance(value, str) for value in frozen_ids) - or current_ids is None or not set(frozen_ids).issubset(current_ids)): + if ( + expected.get("request_digest") != _canonical_digest({k: v for k, v in expected.items() if k != "request_digest"}) + or expected.get("source_artifact_sha256") != _canonical_digest(dict(source)) + or not isinstance(frozen_ids, list) or not all(isinstance(value, str) for value in frozen_ids) + or current_ids is None or not set(frozen_ids).issubset(current_ids) + ): return False - def scope_id(ids): - return manager_authorization_scope_id_for_registry(self.controller.registry_path, - ids, runtime_root=self.root, channel_id=session["channel_id"]) + typed_frozen_ids = [str(value) for value in frozen_ids] + + def scope_id(ids: list[str]) -> str: + return str( + manager_authorization_scope_id_for_registry( + cast(Path, self.controller.registry_path), ids, runtime_root=self.root, channel_id=session["channel_id"], + ) + ) + if "authorization_goal_ids" in expected: authority_ids = expected["authorization_goal_ids"] - if (not isinstance(authority_ids, list) - or any(not isinstance(value, str) or not value for value in authority_ids) - or not set(frozen_ids).issubset(authority_ids) - or not set(authority_ids).issubset(current_ids)): + if ( + not isinstance(authority_ids, list) + or any(not isinstance(value, str) or not value for value in authority_ids) + or not set(typed_frozen_ids).issubset(authority_ids) + or not set(authority_ids).issubset(current_ids) + ): return False - return scope_id(authority_ids) == expected["authorization_scope_id"] + return scope_id([str(value) for value in authority_ids]) == expected["authorization_scope_id"] # Old requests froze the whole authorization hash, but only recorded # readable Goals. Full-coverage history can still tolerate scope growth. # Partial history without an identity witness requires the entire live # scope to match exactly; never infer missing identities or rewrite it. - return (scope_id(frozen_ids) == expected["authorization_scope_id"] - or scope_id(current_ids) == expected["authorization_scope_id"]) + return scope_id(typed_frozen_ids) == expected["authorization_scope_id"] or scope_id(current_ids) == expected["authorization_scope_id"] - def health(self, binding_id: str) -> dict[str, Any]: + def health(self, binding_id: str) -> dict[str, object]: """Content-free metadata, never a source/provider verification receipt.""" try: - binding = next(row for row in self.bindings.read()["bindings"] if row["binding_id"] == binding_id) - actor = binding.get("managed_actor") + binding = next(row for row in as_dict_list(self.bindings.read().get("bindings")) if row.get("binding_id") == binding_id) + actor = as_optional_dict(binding.get("managed_actor")) if not actor: return {"available": True, "enabled": False, "configured": False} - goal = load_goal_from_registry(self.controller.registry_path, actor["goal_id"]) - config = configuration_summary(goal) + actor_goal_id = str(actor["goal_id"]) + goal = load_goal_from_registry(cast(Path, self.controller.registry_path), actor_goal_id) + config = as_optional_dict(configuration_summary(goal or {})) if not config or config.get("profile_preset") != PRESET: return {"available": True, "enabled": False, "configured": False} - journal = read_cadence_journal(runtime_root=self.root, goal_id=actor["goal_id"]) - generation, delivery = None, None + journal = as_optional_dict(read_cadence_journal(runtime_root=self.root, goal_id=actor_goal_id)) + generation: object = None + delivery: object = None if journal: - folder = attempt_directory(self.root, journal["window"]) - for name in ["private-generation.json", "private-delivery.json"]: + journal_window = as_dict(journal["window"]) + folder = attempt_directory(self.root, journal_window) + for name in ("private-generation.json", "private-delivery.json"): path = folder / name if path.is_file(): - value = json.loads(path.read_text(encoding="utf-8")) - if name == "private-generation.json": - generation = value["generation_id"] - else: + value = as_mapping(json.loads(path.read_text(encoding="utf-8"))) + generation = value["generation_id"] if name == "private-generation.json" else generation + if name != "private-generation.json": delivery = value.get("delivery_status", "pending") if journal.get("retirement"): delivery = "generation_cancelled" - elif self._known_generation_failure(actor, journal["window"]): + elif self._known_generation_failure(actor, journal_window): delivery = "generation_failed" active = resolve_active_goal_periodic_report_subscription(goal) - return {"available": True, "configured": True, "enabled": bool(active), - "schedule": config.get("schedule"), "next_due_at": report_cadence_next_due_at( - config.get("schedule"), now=datetime.now(timezone.utc)) if config.get("enabled") else None, - "retained_window_due_at": journal["window"]["due_at"] if journal else None, + schedule_cfg, next_due = self._build_health_schedule(config) + return { + "available": True, "configured": True, "enabled": bool(active), "schedule": schedule_cfg, + "next_due_at": next_due, + "retained_window_due_at": as_mapping(journal["window"])["due_at"] if journal else None, "generation_id": generation, "delivery_status": delivery or "not_generated", - "execution_failed": bool(journal and self._execution_failed(actor, journal["window"])), - "publication_verified": bool(journal and self._published_window(journal["window"])), - "destination": "original_owner_private_chat_full_body"} + "execution_failed": bool(journal and self._execution_failed(actor, as_dict(journal["window"]))), + "publication_verified": bool(journal and self._published_window(as_dict(journal["window"]))), + "destination": "original_owner_private_chat_full_body", + } except (OSError, ValueError, TypeError, KeyError, StopIteration): return {"available": False, "error_code": "steward_report_unavailable"} - def current_window(self, binding_id: str) -> tuple[dict[str, Any] | None, dict[str, Any] | None]: - subscription = self.subscription(binding_id) - if subscription is None: - return None, None - actor = self.selected(binding_id)["actor"] - journal = read_cadence_journal(runtime_root=self.root, goal_id=actor["goal_id"]) - return subscription, journal["window"] if journal else None - - def frontier(self, binding: dict[str, Any]) -> tuple[dict[str, Any] | None, bool]: + def frontier(self, binding: dict[str, object]) -> tuple[dict[str, object] | None, bool]: """Called only by the original host pump after its idle/cache checks.""" - return self._frontier(binding["binding_id"], binding["managed_actor"]) + return self._frontier(str(binding["binding_id"]), as_dict(binding["managed_actor"])) - def _submit(self, owner_key: str, actor: dict[str, Any], window: dict[str, Any], todo: dict[str, Any]): - from .steward_turn import StewardTurnHost - folder = attempt_directory(self.root, window) - validator = [sys.executable, "-c", "from pathlib import Path; from loopx.capabilities.periodic_report.private_generation import validate_private_generation; " - + f"validate_private_generation(Path({str(folder)!r}))"] - return StewardTurnHost(self.controller).submit(owner_key, - turn_instance_id="report." + window["window_id"], todo_id=todo["todo_id"], - work_kind="report", report_window=window, validation_command=validator) - - def _frontier(self, owner_key: str, actor: dict[str, Any]) -> tuple[dict[str, Any] | None, bool]: - from .steward_monitor import StewardMonitor + def _submit( + self, owner_key: str, actor: dict[str, object], window: dict[str, object], todo: dict[str, object], + ) -> tuple[dict[str, object], bool]: from .steward_turn import StewardTurnHost - subscription = self.subscription(owner_key) - if subscription is None or subscription.get("schedule") is None: - return None, False - admitted = admit_cadence_window(runtime_root=self.root, goal_id=actor["goal_id"], - agent_id=actor["agent_id"], subscription=subscription, now=datetime.now(timezone.utc), - subscription_resolver=lambda: self.subscription(owner_key, expected_actor=actor), - can_replace_failed_window=lambda window: self._failed_without_generation( - actor, window, generation_locked=True, - ), - can_replace_exhausted_failed_window=lambda window: self._failed_without_generation( - actor, window, generation_locked=True, require_recovery_exhausted=True, - )) - if admitted["status"] != "pending": - return None, False - window = admitted["window"] - rows = [row for row in StewardMonitor(self.controller).todos(actor) if row.get("target_key") == window["window_id"]] - if len(rows) > 1: - raise ValueError("report window has conflicting native tasks") - if not rows: - native_command(self.controller, ["todo", "add", "--goal-id", actor["goal_id"], - "--role", "agent", "--operation-id", window["window_id"], - "--text", (f"[P1] Author the configured original Session report ending {window['due_at']}; retain evidence and coverage gaps. Generation is separate from verified delivery." - if actor.get("schema_version") == "loopx_managed_session_actor_v0" else - f"[P1] Author the authorized portfolio report ending {window['due_at']}; retain counterevidence and coverage gaps. Generation is separate from verified private delivery."), - "--claimed-by", actor["agent_id"], "--action-kind", "generate_periodic_report", - "--target-key", window["window_id"], "--continuation-policy", "same_agent_non_delivery", - "--execute"]) - rows = [row for row in StewardMonitor(self.controller).todos(actor) if row.get("target_key") == window["window_id"]] folder = attempt_directory(self.root, window) - if len(rows) == 1 and (rows[0]["status"] == "done" - or rows[0]["status"] == "open" and ((folder / "private-generation.json").exists() - or StewardTurnHost(self.controller).has_recoverable_stopped_report(actor, window, rows[0]))): - StewardTurnHost(self.controller).recover_report_settlement(actor, window, rows[0]) - return None, False - if len(rows) != 1 or rows[0]["status"] != "open": - return None, False - return self._submit(owner_key, actor, window, rows[0]) + validator = [ + sys.executable, "-c", + "from pathlib import Path; from loopx.capabilities.periodic_report.private_generation import validate_private_generation; " + + f"validate_private_generation(Path({str(folder)!r}))", + ] + return StewardTurnHost(self.controller).submit( + owner_key, turn_instance_id="report." + str(window["window_id"]), + todo_id=str(todo["todo_id"]), work_kind="report", report_window=window, validation_command=validator, + ) - def prepare(self, request: dict[str, Any], adapter: Any, *, authorization_scope_id: str) -> str: + def prepare(self, request: Mapping[str, object], adapter: object, *, authorization_scope_id: str) -> str: from ..manager_context.inspection import TOOL_NAME - _, window = self.current_window(request["actor"]["goal_id"].removeprefix("steward-agent-")) + + request_actor = as_mapping(request["actor"]) + _, window = self.current_window(str(request_actor["goal_id"]).removeprefix("steward-agent-")) if not window or window["window_id"] != request["report_window_id"]: raise ValueError("the admitted original report window is unavailable") - reader = (getattr(adapter.session, "read_tool_handler", None) - if hasattr(adapter, "session") else getattr(adapter, "_steward_report_reader", None)) - if reader is None or not authorization_scope_id: + session_obj = getattr(adapter, "session", None) + reader_raw = getattr(session_obj, "read_tool_handler", None) if session_obj is not None else getattr(adapter, "_steward_report_reader", None) + if not callable(reader_raw) or not authorization_scope_id: raise ValueError("the original scoped report reader is unavailable") - session = self.controller.store.load_session(request["actor"]["session_id"]) + reader = cast(Callable[[str, dict[str, object]], dict[str, object]], reader_raw) + session = self.controller.store.load_session(str(request_actor["session_id"])) + if session is None: + raise ValueError("the original steward Session is unavailable") from ...chat_manager_context import manager_authorization_scope_id_for_registry + authority_ids = self.bindings.steward_scope(session) - if (authority_ids is None or manager_authorization_scope_id_for_registry( - self.controller.registry_path, authority_ids, runtime_root=self.root, - channel_id=session["channel_id"]) != authorization_scope_id): + if ( + authority_ids is None + or manager_authorization_scope_id_for_registry( + cast(Path, self.controller.registry_path), authority_ids, + runtime_root=self.root, channel_id=session["channel_id"], + ) != authorization_scope_id + ): raise ValueError("the original report authorization changed before collection") from ...chat_manager import manager_reporting_text - rules = self.managed._workspace(session) / "REPORTING.md" - if rules.is_symlink(): - raise ValueError("the original reporting criteria changed source") - reporting = rules.read_text(encoding="utf-8") if rules.exists() else manager_reporting_text() - frozen = prepare_private_report(root=self.root, window=window, read=lambda query: reader(TOOL_NAME, query), - authorization_scope_id=authorization_scope_id, reporting=reporting, - authorization_goal_ids=authority_ids) - return report_prompt(frozen, attempt_directory(self.root, window)) - - def freeze(self, request: dict[str, Any], candidate: dict[str, Any]) -> dict[str, Any]: - _, owner_key = report_service(self.controller, request["actor"]) - _, window = self.current_window(owner_key) - if not window or window["window_id"] != request["report_window_id"]: - raise ValueError("the original report was paused, cancelled or changed") - response = candidate.pop("editorial_response", None) - if not isinstance(response, dict): - raise ValueError("the original reporting Agent returned no editorial response") - return freeze_private_report(root=self.root, window=window, response=response, require_current_window=True) + + reporting = self._read_reporting_rules(Path(self.managed._workspace(session)) / "REPORTING.md", manager_reporting_text) + frozen = prepare_private_report( + root=self.root, window=window, read=lambda query: reader(TOOL_NAME, query), + authorization_scope_id=authorization_scope_id, reporting=reporting, authorization_goal_ids=authority_ids, + ) + return str(report_prompt(frozen, attempt_directory(self.root, window))) -def report_service(controller: Any, actor: dict[str, Any]): +def report_service( + controller: StewardControllerProtocol, actor: Mapping[str, object], +) -> tuple[_StewardReportsBase, str]: """Select the existing source/return adapter, never another execution actor.""" if actor.get("schema_version") == "loopx_managed_session_actor_v0": - return ManagedSessionReports(controller), actor["session_id"] - return StewardReports(controller), actor["goal_id"].removeprefix("steward-agent-") + return ManagedSessionReports(controller), str(actor["session_id"]) + return StewardReports(controller), str(actor["goal_id"]).removeprefix("steward-agent-") @contextmanager -def session_report_configuration_guard(controller: Any, goal_id: str, proposed: dict[str, Any] | None): +def session_report_configuration_guard( + controller: StewardControllerProtocol, goal_id: str, proposed: Mapping[str, object] | None, +) -> Iterator[Callable[[], None] | None]: """Keep the existing settings transaction and native window in one ordering. Preparing source artifacts takes the same Goal-local calendar lock. A @@ -504,165 +679,201 @@ def session_report_configuration_guard(controller: Any, goal_id: str, proposed: failed generation retires only that attempt after a verified settings apply; previews and pauses retain it. Other destinations keep their old path. """ - from ..periodic_report.goal_configuration import managed_session_report_destination from ..periodic_report.cadence_journal import cadence_journal_path - current = configuration_summary(load_goal_from_registry(controller.registry_path, goal_id) or {}) or {} - if (not managed_session_report_destination(current) and not managed_session_report_destination(proposed or {}) - and (current or proposed is not None)): - yield + from ..periodic_report.goal_configuration import managed_session_report_destination + + reg_path = cast(Path, controller.registry_path) + current = as_dict(configuration_summary(load_goal_from_registry(reg_path, goal_id) or {}) or {}) + if ( + not managed_session_report_destination(current) + and not managed_session_report_destination(dict(proposed or {})) + and (current or proposed is not None) + ): + yield None return - with exclusive_file_lock(cadence_journal_path(controller.coordination_runtime_root, goal_id), - operation="configure_session_report"): - current = configuration_summary(load_goal_from_registry(controller.registry_path, goal_id) or {}) or {} - destination = managed_session_report_destination(proposed or {}) + with exclusive_file_lock(cadence_journal_path(controller.coordination_runtime_root, goal_id), operation="configure_session_report"): + current = as_dict(configuration_summary(load_goal_from_registry(reg_path, goal_id) or {}) or {}) + destination = managed_session_report_destination(dict(proposed or {})) if proposed and proposed.get("enabled") and destination: - actor = ManagedSessionReports(controller).selected(destination)["actor"] + actor = as_mapping(ManagedSessionReports(controller).selected(str(destination))["actor"]) if actor["goal_id"] != goal_id: raise ValueError("select the original managed Agent Session in this Goal") if proposed.get("profile_preset") == "session-task": from .session_calendar_tasks import SessionCalendarTasks - SessionCalendarTasks(controller).source_task(actor, proposed.get("task") or {}) - journal = read_cadence_journal(runtime_root=controller.coordination_runtime_root, goal_id=goal_id) - cancellation = None - if journal and journal["publication"] is None and not journal.get("retirement"): - window = journal["window"] - reports = ManagedSessionReports(controller) + + cast(_CalendarSourceTaskProtocol, SessionCalendarTasks(controller)).source_task( + dict(actor), as_dict(proposed.get("task") or {}), + ) + journal = as_optional_dict(read_cadence_journal(runtime_root=controller.coordination_runtime_root, goal_id=goal_id)) + cancellation: tuple[dict[str, object], dict[str, object], dict[str, str]] | None = None + report_target: _WindowGuardTargetProtocol = ManagedSessionReports(controller) + if journal and journal.get("publication") is None and not journal.get("retirement"): + window = as_dict(journal["window"]) + profile_ref = as_mapping(window.get("profile_ref")) folder = attempt_directory(controller.coordination_runtime_root, window) - if window["profile_ref"]["profile_id"] == "session_task": + if profile_ref.get("profile_id") == "session_task": from .session_calendar_tasks import SessionCalendarTasks - reports = SessionCalendarTasks(controller) - if folder.exists() and not reports._published_window(window): + + task_reports = SessionCalendarTasks(controller) + report_target = cast(_WindowGuardTargetProtocol, task_reports) + cancellable_reader: Callable[[dict[str, object], dict[str, object]], dict[str, str] | None] = task_reports._known_generation_failure + else: + managed_reports = ManagedSessionReports(controller) + report_target = managed_reports + cancellable_reader = managed_reports._cancellable_failed_window + if folder.exists() and not report_target._published_window(window): before = {k: v for k, v in current.items() if k != "enabled"} after = {k: v for k, v in (proposed or {}).items() if k != "enabled"} if before != after or not current and proposed is None: - actor = reports._frozen_actor(window) - failure = (reports._cancellable_failed_window(actor, window) - if hasattr(reports, "_cancellable_failed_window") - else reports._known_generation_failure(actor, window)) if actor else None + frozen_actor = report_target._frozen_actor(window) + failure = cancellable_reader(frozen_actor, window) if frozen_actor else None if (proposed is not None or not failure) and (current or proposed is not None): - if window["profile_ref"]["profile_id"] == "session_task": + if profile_ref.get("profile_id") == "session_task": raise PendingStewardReportError("This calendar task is unfinished or its result is unconfirmed. Pause or restore its original plan; only a known failed independent validation can be cleared.") raise PendingStewardReportError("The original frozen report still requires verified delivery. Pause or restore the same plan; clear a known failed generation before changing its schedule or conversation.") - if failure: - cancellation = actor, window, failure - def after_verified_apply(): - if configuration_summary(load_goal_from_registry(controller.registry_path, goal_id)) is not None: + if frozen_actor is not None and failure: + cancellation = frozen_actor, window, failure + + def after_verified_apply() -> None: + assert cancellation is not None + target_actor, target_window, target_failure = cancellation + if configuration_summary(load_goal_from_registry(reg_path, goal_id) or {}) is not None: raise ValueError("the original report configuration was not cleared") - if reports._frozen_actor(cancellation[1]) != cancellation[0]: + if report_target._frozen_actor(target_window) != target_actor: raise ValueError("the original failed report actor changed before cancellation") - reports._cancel_failed_window(*cancellation, cadence_locked=True) + report_target._cancel_failed_window(target_actor, target_window, target_failure, cadence_locked=True) + yield after_verified_apply if cancellation else None -class ManagedSessionReports(StewardReports): +class ManagedSessionReports(_StewardReportsBase): """Local source and Core return adapter for the shared report/Turn lifecycle. An explicit Goal configuration pins one existing Agent Session. Its native calendar, generation Task, frozen artifacts and publication cursor remain the existing periodic-report owners. No private steward binding is needed. """ - def selected(self, session_id: str) -> dict[str, Any]: - from pathlib import Path + + def selected(self, session_id: str) -> dict[str, object]: from .steward_managed_mode import managed_session_identity + session = self.controller.store.load_session(session_id) if not session or not session.get("managed_agent_id"): raise ValueError("select the original registered Agent Session") - request = ManagedSessionTurn(self.controller)._request(session_id, session["managed_agent_id"], "report-identity") - actor = request["actor"] - managed_session_identity(self.controller, goal_id=actor["goal_id"], agent_id=actor["agent_id"], - workspace=Path(actor["workspace_path"]), session=session) + request = as_mapping(ManagedSessionTurn(self.controller)._request(session_id, str(session["managed_agent_id"]), "report-identity")) + actor = as_dict(request["actor"]) + managed_session_identity( + self.controller, goal_id=str(actor["goal_id"]), agent_id=str(actor["agent_id"]), + workspace=Path(str(actor["workspace_path"])), session=session, + ) return {"session": session, "actor": actor} - def subscription(self, session_id: str, *, expected_revision: str | None = None, - expected_actor: dict[str, Any] | None = None) -> dict[str, Any] | None: - actor = self.selected(session_id)["actor"] + def subscription( + self, session_id: str, *, expected_revision: str | None = None, expected_actor: dict[str, object] | None = None, + ) -> dict[str, object] | None: + actor = as_mapping(self.selected(session_id)["actor"]) if expected_actor is not None and actor != expected_actor: return None - goal = load_goal_from_registry(self.controller.registry_path, actor["goal_id"]) + goal = load_goal_from_registry(cast(Path, self.controller.registry_path), str(actor["goal_id"])) # Only an explicit Goal override can choose this exact Session; a # machine default cannot implicitly enroll another Goal/conversation. - config = configuration_summary(goal) + config = as_optional_dict(configuration_summary(goal or {})) if not config or config.get("profile_preset") != "weekly-progress" or config.get("route_ref") != "managed-session:" + session_id: return None - subscription = resolve_active_goal_periodic_report_subscription(goal) - if subscription and expected_revision is not None and subscription["effective_revision"] != expected_revision: + subscription = as_optional_dict(resolve_active_goal_periodic_report_subscription(goal)) + if subscription and expected_revision is not None and subscription.get("effective_revision") != expected_revision: return None return subscription - def _submit(self, owner_key: str, actor: dict[str, Any], window: dict[str, Any], todo: dict[str, Any]): - return ManagedSessionTurn(self.controller).submit(owner_key, agent_id=actor["agent_id"], - operation_id="report." + window["window_id"], todo_id=todo["todo_id"], report_window=window) + def _submit( + self, owner_key: str, actor: dict[str, object], window: dict[str, object], todo: dict[str, object], + ) -> tuple[dict[str, object], bool]: + return ManagedSessionTurn(self.controller).submit( + owner_key, agent_id=str(actor["agent_id"]), operation_id="report." + str(window["window_id"]), + todo_id=str(todo["todo_id"]), report_window=window, + ) - def frontier(self, session_id: str) -> tuple[dict[str, Any] | None, bool]: - from .steward_monitor import StewardMonitor + def frontier(self, session_id: str) -> tuple[dict[str, object] | None, bool]: from .steward_turn import StewardTurnHost - actor = self.selected(session_id)["actor"] + + actor = as_dict(self.selected(session_id)["actor"]) subscription, window = self.current_window(session_id) if subscription is None: return None, False if window: - todo = next((row for row in StewardMonitor(self.controller).todos(actor) - if row.get("target_key") == window["window_id"]), None) - if todo and ((attempt_directory(self.root, window) / "private-generation.json").exists() - or StewardTurnHost(self.controller).has_recoverable_stopped_report(actor, window, todo)): + window_id = str(window["window_id"]) + todo = next((row for row in as_dict_list(steward_monitor_for(self.controller).todos(actor)) if row.get("target_key") == window_id), None) + if todo and ( + (attempt_directory(self.root, window) / "private-generation.json").exists() + or StewardTurnHost(self.controller).has_recoverable_stopped_report(actor, window, todo) + ): StewardTurnHost(self.controller).recover_report_settlement(actor, window, todo) self.publish(session_id, window) return self._frontier(session_id, actor) - def prepare(self, request: dict[str, Any], adapter: Any, *, authorization_scope_id: str | None = None) -> str: - from pathlib import Path + def prepare(self, request: Mapping[str, object], adapter: object, *, authorization_scope_id: str | None = None) -> str: from ...control_plane.todos.list_readback import list_goal_todos + from ..periodic_report.cadence_journal import cadence_journal_path from ..periodic_report.pending_intent import _canonical_digest from ..periodic_report.private_generation import prepare_session_report - from ..periodic_report.cadence_journal import cadence_journal_path - actor = self.selected(request["actor"]["session_id"])["actor"] - _, window = self.current_window(actor["session_id"]) - if actor != request["actor"] or not window or window["window_id"] != request["report_window_id"]: + + request_actor = as_mapping(request["actor"]) + actor = as_dict(self.selected(str(request_actor["session_id"]))["actor"]) + actor_session_id, actor_goal_id = str(actor["session_id"]), str(actor["goal_id"]) + _, window = self.current_window(actor_session_id) + if actor != request_actor or not window or window["window_id"] != request["report_window_id"]: raise ValueError("the admitted original Session report changed") - def read(): - active = list_goal_todos(registry_path=self.controller.registry_path, goal_id=actor["goal_id"], - runtime_root_arg=str(self.root), limit=None) - history = list_goal_todos(registry_path=self.controller.registry_path, goal_id=actor["goal_id"], - runtime_root_arg=str(self.root), role="agent", status="done", read_scope="completed_history", limit=None) - rows = {row["todo_id"]: row for row in [*active["todos"], *history["todos"]]} - source = {"goal_id": actor["goal_id"], "observed_at": datetime.now(timezone.utc).isoformat(), + def read() -> dict[str, object]: + reg_path = cast(Path, self.controller.registry_path) + active = as_mapping(list_goal_todos(registry_path=reg_path, goal_id=actor_goal_id, runtime_root_arg=str(self.root), limit=None)) + history = as_mapping(list_goal_todos(registry_path=reg_path, goal_id=actor_goal_id, runtime_root_arg=str(self.root), role="agent", status="done", read_scope="completed_history", limit=None)) + rows = {str(row["todo_id"]): row for row in [*as_dict_list(active.get("todos")), *as_dict_list(history.get("todos"))]} + source = { + "goal_id": actor_goal_id, "observed_at": datetime.now(timezone.utc).isoformat(), "rows": [rows[key] for key in sorted(rows)], "complete_native_task_read": True, - "artifact_contents_independently_read": False, "as_of_window_reconstruction": False} + "artifact_contents_independently_read": False, "as_of_window_reconstruction": False, + } return {**source, "source_revision": _canonical_digest(source)} from ...chat_manager import session_reporting_text - rules = Path(actor["workspace_path"]) / "REPORTING.md" - if rules.is_symlink(): - raise ValueError("the original reporting criteria changed source") - reporting = rules.read_text(encoding="utf-8") if rules.exists() else session_reporting_text() - with exclusive_file_lock(cadence_journal_path(self.root, actor["goal_id"]), operation="freeze_session_report_source"): - if self.subscription(actor["session_id"], expected_revision=window["subscription_revision"]) is None: + + reporting = self._read_reporting_rules(Path(str(actor["workspace_path"])) / "REPORTING.md", session_reporting_text) + with exclusive_file_lock(cadence_journal_path(self.root, actor_goal_id), operation="freeze_session_report_source"): + if self.subscription(actor_session_id, expected_revision=str(window["subscription_revision"])) is None: raise ValueError("the original report configuration changed before collection") frozen = prepare_session_report(root=self.root, window=window, actor=actor, read=read, reporting=reporting) - return report_prompt(frozen, attempt_directory(self.root, window)) + return str(report_prompt(frozen, attempt_directory(self.root, window))) - def _frozen_actor(self, window: dict[str, Any]) -> dict[str, Any] | None: + def _frozen_actor(self, window: dict[str, object]) -> dict[str, object] | None: from ..periodic_report.pending_intent import _canonical_digest + path = attempt_directory(self.root, window) / "editorial-request.json" if not path.is_file(): return None - frozen = json.loads(path.read_text(encoding="utf-8")) + frozen = as_mapping(json.loads(path.read_text(encoding="utf-8"))) saved = frozen.get("managed_session_actor") if not isinstance(saved, dict): return None - actor = self.selected(saved.get("session_id"))["actor"] - return actor if (actor == saved and frozen.get("window") == window - and actor["goal_id"] == window["goal_id"] and actor["agent_id"] == window["agent_id"] - and frozen.get("request_digest") == _canonical_digest({k: v for k, v in frozen.items() if k != "request_digest"})) else None + actor = as_dict(self.selected(str(saved.get("session_id")))["actor"]) + return ( + actor + if ( + actor == saved and frozen.get("window") == window + and actor["goal_id"] == window["goal_id"] and actor["agent_id"] == window["agent_id"] + and frozen.get("request_digest") == _canonical_digest({k: v for k, v in frozen.items() if k != "request_digest"}) + ) + else None + ) - def delivery_current(self, session_id: str, window: dict[str, Any]) -> bool: + def delivery_current(self, session_id: str, window: dict[str, object]) -> bool: subscription, current = self.current_window(session_id) - return (subscription is not None and subscription["effective_revision"] == window["subscription_revision"] - and current == window - and self._frozen_actor(window) == self.selected(session_id)["actor"]) + return ( + subscription is not None and subscription["effective_revision"] == window["subscription_revision"] + and current == window and self._frozen_actor(window) == self.selected(session_id)["actor"] + ) - def publish(self, session_id: str, window: dict[str, Any]) -> bool: + def publish(self, session_id: str, window: Mapping[str, object]) -> bool: """Read the original native commit, then publish/read back one Core message. Core's explicit message identity reconciles an unknown append; a lost @@ -670,88 +881,113 @@ def publish(self, session_id: str, window: dict[str, Any]) -> bool: There is no external send and no second Chat/model Turn. """ import hashlib - from ..periodic_report.private_generation import validate_private_generation + + from ...control_plane.goals.first_party_host_admission import FirstPartyHostGoalAdmission, capture_first_party_host_goal_ref + from ..periodic_report.cadence_journal import cadence_journal_path from ..periodic_report.incremental import commit_periodic_report_publication_cursor + from ..periodic_report.private_generation import validate_private_generation from .steward_turn import report_turn - actor = self.selected(session_id)["actor"] - turn = report_turn(self.controller.store, actor, window) + + typed_window = dict(window) + actor = as_mapping(self.selected(session_id)["actor"]) + actor_goal_id = str(actor["goal_id"]) + turn = report_turn(self.controller.store, actor, typed_window) if not turn: return False - request = turn.get("loopx_request") or {} - if (request.get("actor") != actor or request.get("report_window_id") != window["window_id"] - or request.get("report_subscription_revision") != window["subscription_revision"]): + request = as_mapping(turn.get("loopx_request")) + window_id = str(typed_window["window_id"]) + if ( + request.get("actor") != actor or request.get("report_window_id") != window_id + or request.get("report_subscription_revision") != typed_window["subscription_revision"] + ): raise ValueError("the original report return changed identity") - if not any(row["kind"] == "native_loopx.result" and row["payload"].get("status") == "committed" - for row in self.controller.store.events_after(session_id, turn["turn_id"], None)): + turn_id = str(turn["turn_id"]) + if not any( + row.get("kind") == "native_loopx.result" and as_mapping(row.get("payload")).get("status") == "committed" + for row in self.controller.store.events_after(session_id, turn_id, None) + ): return False - folder = attempt_directory(self.root, window) - from ..periodic_report.cadence_journal import cadence_journal_path - from ...control_plane.goals.first_party_host_admission import FirstPartyHostGoalAdmission, capture_first_party_host_goal_ref - with exclusive_file_lock(cadence_journal_path(self.root, actor["goal_id"]), operation="publish_session_report"): - admission = FirstPartyHostGoalAdmission.for_plan(registry_path=self.controller.registry_path, - goal_id=actor["goal_id"], planned_goal_ref=capture_first_party_host_goal_ref( - registry_path=self.controller.registry_path, goal_id=actor["goal_id"])) + folder = attempt_directory(self.root, typed_window) + reg_path = cast(Path, self.controller.registry_path) + store = cast(_ReportsStoreProtocol, self.controller.store) + with exclusive_file_lock(cadence_journal_path(self.root, actor_goal_id), operation="publish_session_report"): + admission = FirstPartyHostGoalAdmission.for_plan( + registry_path=reg_path, goal_id=actor_goal_id, + planned_goal_ref=capture_first_party_host_goal_ref(registry_path=reg_path, goal_id=actor_goal_id), + ) with self.controller.lock, admission.launch_lifetime(operation="return_session_report"), exclusive_file_lock( - folder / "delivery.lock", operation="return_session_report"): - generation = validate_private_generation(folder) - if not self.delivery_current(session_id, window): + folder / "delivery.lock", operation="return_session_report" + ): + generation = as_mapping(validate_private_generation(folder)) + if not self.delivery_current(session_id, typed_window): return False body = (folder / "report.md").read_text(encoding="utf-8") - config = configuration_summary(load_goal_from_registry(self.controller.registry_path, actor["goal_id"])) + config = as_optional_dict(configuration_summary(load_goal_from_registry(reg_path, actor_goal_id) or {})) if config and config.get("review_required") is True: from ..periodic_report.review import request_report_review - request_report_review(registry_path=self.controller.registry_path, runtime_root=self.root, - goal_id=actor["goal_id"], agent_id=actor["agent_id"], session_id=session_id, - session_store=self.controller.store, execute=True, - bundle=json.loads((folder / "generation-bundle.json").read_text(encoding="utf-8"))) - message_id = "managed." + turn["turn_id"] + ".completed" - messages = self.controller.store.messages(session_id) - existing = next((row for row in messages if row["message_id"] == message_id), None) + + request_report_review( + registry_path=reg_path, runtime_root=self.root, goal_id=actor_goal_id, + agent_id=str(actor["agent_id"]), session_id=session_id, + session_store=cast("ChatSessionStore", self.controller.store), execute=True, + bundle=json.loads((folder / "generation-bundle.json").read_text(encoding="utf-8")), + ) + message_id = "managed." + turn_id + ".completed" + existing = next((row for row in store.messages(session_id) if row.get("message_id") == message_id), None) # A retained earlier partial/failed outer answer stays immutable. # Only the newly recovered native commit permits the full report. if existing and existing.get("text") != body: - message_id = "report." + window["window_id"] - self.controller.store.append_message(session_id, role="agent", text=body, - turn_id=turn["turn_id"], message_id=message_id) - readback = [row for row in self.controller.store.messages(session_id) if row["message_id"] == message_id] - if (len(readback) != 1 or readback[0]["text"] != body or readback[0]["role"] != "agent" - or readback[0]["turn_id"] != turn["turn_id"] or not self.delivery_current(session_id, window)): + message_id = "report." + window_id + store.append_message(session_id, role="agent", text=body, turn_id=turn_id, message_id=message_id) + readback = [row for row in store.messages(session_id) if row.get("message_id") == message_id] + if ( + len(readback) != 1 or readback[0].get("text") != body or readback[0].get("role") != "agent" + or readback[0].get("turn_id") != turn_id or not self.delivery_current(session_id, typed_window) + ): raise ValueError("the complete original report message did not verify") candidate = json.loads((folder / "publication-candidate.json").read_text(encoding="utf-8")) - identity = [session_id, window["window_id"], generation["generation_id"], message_id, generation["body_sha256"]] - commit_periodic_report_publication_cursor(runtime_root=self.root, candidate=candidate, + identity = [session_id, window_id, generation["generation_id"], message_id, generation["body_sha256"]] + commit_periodic_report_publication_cursor( + runtime_root=self.root, candidate=candidate, publication_id="session-report-" + hashlib.sha256(json.dumps(identity).encode()).hexdigest(), - delivered_at=readback[0]["created_at"], covered_until=window["due_at"]) + delivered_at=str(readback[0]["created_at"]), covered_until=str(typed_window["due_at"]), + ) return True - def health(self, session_id: str) -> dict[str, Any]: + def health(self, session_id: str) -> dict[str, object]: try: - actor = self.selected(session_id)["actor"] - goal = load_goal_from_registry(self.controller.registry_path, actor["goal_id"]) - config = configuration_summary(goal) + actor = as_mapping(self.selected(session_id)["actor"]) + actor_goal_id = str(actor["goal_id"]) + reg_path = cast(Path, self.controller.registry_path) + goal = load_goal_from_registry(reg_path, actor_goal_id) + config = as_optional_dict(configuration_summary(goal or {})) if not config or config.get("route_ref") != "managed-session:" + session_id: return {"available": True, "configured": False, "enabled": False} - journal = read_cadence_journal(runtime_root=self.root, goal_id=actor["goal_id"]) - window = journal["window"] if journal else None + journal = as_optional_dict(read_cadence_journal(runtime_root=self.root, goal_id=actor_goal_id)) + window = as_dict(journal["window"]) if journal else None folder = attempt_directory(self.root, window) if window else None from .steward_turn import report_turn + turn = report_turn(self.controller.store, actor, window) if window else None - failed = bool(window and self._execution_failed(actor, window)) + failed = bool(window and self._execution_failed(dict(actor), window)) published = bool(window and self._published_window(window)) - returned = [] + returned: list[dict[str, object]] = [] if published and turn and folder and (folder / "report.md").is_file(): body = (folder / "report.md").read_text(encoding="utf-8") - returned = [row for row in self.controller.store.messages(session_id) - if row["role"] == "agent" and row["turn_id"] == turn["turn_id"] and row["text"] == body] + expected_turn_id = str(turn["turn_id"]) + returned = [ + row for row in self.controller.store.messages(session_id) + if row.get("role") == "agent" and row.get("turn_id") == expected_turn_id and row.get("text") == body + ] verified = published and len(returned) == 1 - return {"available": True, "configured": True, "enabled": bool(self.subscription(session_id)), - "scheduled": bool(config.get("schedule")), - "schedule": config.get("schedule"), "next_due_at": report_cadence_next_due_at( - config.get("schedule"), now=datetime.now(timezone.utc)) if config.get("enabled") else None, + schedule_cfg, next_due = self._build_health_schedule(config) + return { + "available": True, "configured": True, "enabled": bool(self.subscription(session_id)), + "scheduled": bool(schedule_cfg), "schedule": schedule_cfg, "next_due_at": next_due, "retained_window_due_at": window["due_at"] if window else None, "generation_complete": bool(folder and (folder / "private-generation.json").exists()), - "execution_failed": failed, - "publication_verified": verified, - "report_message_id": returned[0]["message_id"] if verified else None} + "execution_failed": failed, "publication_verified": verified, + "report_message_id": returned[0]["message_id"] if verified else None, + } except (OSError, ValueError, KeyError, TypeError): return {"available": False, "error_code": "managed_session_report_unavailable"} diff --git a/loopx/capabilities/native_chat/steward_turn.py b/loopx/capabilities/native_chat/steward_turn.py index b1492dde04..0f64b784bf 100644 --- a/loopx/capabilities/native_chat/steward_turn.py +++ b/loopx/capabilities/native_chat/steward_turn.py @@ -7,21 +7,17 @@ """ from __future__ import annotations -from collections.abc import Callable, Mapping, Sequence -from contextlib import contextmanager, ExitStack, nullcontext -from datetime import datetime, timezone -import hashlib -import json +from collections.abc import Callable, Iterator, Mapping, Sequence +from contextlib import AbstractContextManager, contextmanager from pathlib import Path -import re -import shlex -import time -from typing import Any +from typing import TYPE_CHECKING, cast + +if TYPE_CHECKING: + from ...chat_runtime import ChatRuntimeAdapter + from ...chat_store import ChatSessionStore -from ...control_plane.effect_runtime import EffectRuntimeRejected from ...control_plane.goals.activation import goal_is_stopped -from ...control_plane.goals.first_party_host_admission import FirstPartyHostRuntimeRejected -from ...file_lock import LOCK_ACQUIRE_TIMEOUT_ERROR_CODE, exclusive_file_lock +from ...file_lock import exclusive_file_lock from .report_failure_proof import ( build_report_quota_request, build_report_timeout_request, @@ -29,310 +25,207 @@ observe_report_failure, verify_report_window_failure, ) -from .steward_managed_mode import ManagedSessionTurn, ManagedTaskValidationUnavailable, StewardManagedMode +from .steward_managed_mode import ManagedSessionTurn, StewardManagedMode from .steward_monitor import ( STEWARD_BACKGROUND_CHANNEL_PREFIX as STEWARD_BACKGROUND_CHANNEL_PREFIX, STEWARD_BACKGROUND_SESSION_PREFIX as STEWARD_BACKGROUND_SESSION_PREFIX, - actor_steward_binding_id, ensure_steward_background_session, - load_steward_monitor_turn_by_id, lookup_steward_monitor_turn, steward_background_channel_id, steward_background_session_id, ) +from .steward_turn_common import ( + MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS as MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS, + MonitorRestartCarrier, + StewardBindingsProtocol, + StewardControllerProtocol, + StewardManagedProtocol, + StewardStoreProtocol, + _FILE_LOCK_TIMEOUT_ERROR_RE as _FILE_LOCK_TIMEOUT_ERROR_RE, + _POST_CONTEXT_WATCH_ERRORS as _POST_CONTEXT_WATCH_ERRORS, + _REPORT_VALIDATOR_PREFIX as _REPORT_VALIDATOR_PREFIX, + _USER_ACTION_DEDUPE_KEY as _USER_ACTION_DEDUPE_KEY, + _WORKER_EXITED_ERROR as _WORKER_EXITED_ERROR, + append_bounded_ellipsis, + as_dict, + as_dict_list, + as_mapping, + as_optional_dict, + as_optional_str, + iso_timestamp_seconds, + is_zero_effect_replan_selection_deferral as _is_zero_effect_replan_selection_deferral, + monitor_store_for, + native_steward_client_id as native_steward_client_id, + normalize_report_kernel_candidate as _normalize_report_kernel_candidate, + normalize_steward_advancement_kernel_candidate as _normalize_steward_advancement_kernel_candidate, + report_turn as report_turn, + steward_monitor_for, + same_report_validator_command as _same_report_validator_command, + split_bounded_evidence_items, + split_evidence_text_chunks, +) -MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS = 300 -_WORKER_EXITED_ERROR = ( - "The LoopX Chat execution worker exited before this turn finished. " - "Your conversation is saved; execution may have occurred. This turn was not retried automatically." +from .steward_turn_context import ( + apply_steward_user_actions, + governance_replan_context, + normalize_steward_actions, + steward_followup_context, ) -_POST_CONTEXT_WATCH_ERRORS = frozenset({ - "steward monitor external signal source temporarily unavailable", - "the portfolio scope changed after observation", - "disk I/O error", - _WORKER_EXITED_ERROR, -}) -_FILE_LOCK_TIMEOUT_ERROR_RE = re.compile( - r"^file lock acquisition timed out \((?:recorded holder pid [1-9]\d*|lock busy, current holder unknown)\)$") -_USER_ACTION_DEDUPE_KEY = re.compile(r"^[a-z0-9][a-z0-9._:@/-]{0,119}$") -_REPORT_VALIDATOR_PREFIX = ( - "from pathlib import Path; from loopx.capabilities.periodic_report.private_generation import validate_private_generation; " - "validate_private_generation(Path(" +from .steward_turn_execution import execute_steward_turn +from .steward_turn_recovery import ( + build_replay_runner, + cleared_replan_guard, + frozen_report_contract_recovery, + has_recoverable_stopped_report, + monitor_restart_basis, + monitor_restart_carrier, + monitor_restart_request, + monitor_selection_failed_before_poll, + recover_report_settlement, + report_continuation_basis, + report_launch_recovery, + report_selection_recovery, + settle_stopped_report_candidate, + stopped_report_candidate_recovery, ) - -def _iso_timestamp_seconds(value: Any) -> float | None: - if not isinstance(value, str) or not value.strip(): - return None - try: - parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00")) - except ValueError: - return None - if parsed.tzinfo is None: - parsed = parsed.replace(tzinfo=timezone.utc) - return parsed.timestamp() - - -def _same_report_validator_command(frozen_cmd: Any, request_cmd: Any) -> bool: - """Allow report validation commands whose only drift is the host Python path.""" - return (isinstance(frozen_cmd, list) and isinstance(request_cmd, list) - and len(frozen_cmd) == 3 and len(request_cmd) == 3 - and all(isinstance(part, str) and bool(part) for part in [*frozen_cmd, *request_cmd]) - and frozen_cmd[1] == "-c" and request_cmd[1] == "-c" - and frozen_cmd[2] == request_cmd[2] and frozen_cmd[2].startswith(_REPORT_VALIDATOR_PREFIX) - and frozen_cmd[2].endswith("))")) - - -def native_steward_client_id(actor: Mapping[str, Any], turn_instance_id: str) -> str: - """The original native request identity, shared by dispatch and readback.""" - if actor.get("schema_version") == "loopx_managed_session_actor_v0": - return "managed." + turn_instance_id - return "native." + hashlib.sha256(json.dumps([actor, turn_instance_id], sort_keys=True).encode()).hexdigest()[:40] - - -def report_turn(store: Any, actor: Mapping[str, Any], window: Mapping[str, Any]) -> dict[str, Any] | None: - """Read the one bounded continuation, retaining the original failed Turn.""" - operation = "report." + window["window_id"] - original = store.turn_for_client(actor["session_id"], native_steward_client_id(actor, operation)) - quota = store.turn_for_client(actor["session_id"], native_steward_client_id(actor, operation + ".quota-recovery")) - timeout_retry = store.turn_for_client(actor["session_id"], native_steward_client_id(actor, operation + ".timeout-recovery")) - if quota is not None and timeout_retry is not None: - raise ValueError("conflicting report continuations exist") - for suffix, key, label, continued in ( - (".quota-recovery", "report_quota_recovery", "quota", quota), - (".timeout-recovery", "report_timeout_recovery", "timeout", timeout_retry), - ): - if continued is None: - continue - request = continued.get("loopx_request") or {} - if (not original or (request.get(key) or {}).get("original_turn_id") != original["turn_id"] - or request.get("turn_instance_id") != original["loopx_request"]["turn_instance_id"] + suffix): - raise ValueError(f"the report {label} continuation changed its original identity") - return continued - return original - - -def _normalize_report_kernel_candidate(candidate: Mapping[str, Any]) -> dict[str, Any]: - """Normalize a verified report candidate to canonical Turn settlement fields.""" - normalized = dict(candidate) - normalized.pop("editorial_response", None) - # This finite task's postcondition is the complete validated generation, not - # the model's choice of progress wording or profile-minimum shorthand. - normalized["result_kind"] = "validated_completion" - if normalized.get("delivery_batch_scale") == "multi_surface_or_implementation": - normalized["delivery_batch_scale"] = "multi_surface" - return normalized - - -def _split_evidence_text_chunks(text: str, max_item_chars: int) -> list[str]: - """Split a single normalized evidence string cleanly at natural boundaries.""" - if len(text) <= max_item_chars: - return [text] - chunks: list[str] = [] - rest = text - delimiters = ("; ", ". ", ";", "。", ", ", ",", " ") - while len(rest) > max_item_chars: - split_at = -1 - matched_delim = "" - for delim in delimiters: - pos = rest.rfind(delim, 1, max_item_chars) - if pos > 0: - split_at = pos - matched_delim = delim - break - if split_at <= 0: - chunks.append(rest[:max_item_chars]) - rest = rest[max_item_chars:].lstrip() - elif matched_delim in (";", "。", ","): - end = min(split_at + len(matched_delim), max_item_chars) - chunks.append(rest[:end].strip()) - rest = rest[end:].lstrip() - else: - head = rest[:split_at].rstrip() - if matched_delim == ". " and len(head) + 1 <= max_item_chars: - head += "." - chunks.append(head) - rest = rest[split_at + len(matched_delim) :].lstrip() - if rest: - chunks.append(rest) - return [chunk for chunk in chunks if chunk] - - -def _append_bounded_ellipsis(text: str, limit: int) -> str: - if limit <= 0: - return "" - if limit <= 3: - return text[:limit] - if len(text) + 3 <= limit and not text.endswith("..."): - return text + "..." - trimmed = text[: max(1, limit - 3)].rstrip() - return (trimmed or text[: max(1, limit - 3)]) + "..." - - -def _split_bounded_evidence_items( - raw: Any, - *, - max_items: int = 8, - max_item_chars: int = 240, - max_total_chars: int = 1_200, -) -> Any: - """Split over-long Steward evidence strings without masking invalid shapes.""" - if not isinstance(raw, list) or not raw: - return raw - if not all(isinstance(item, str) and item.strip() for item in raw): - return raw - chunks: list[str] = [] - for item in raw: - normalized = " ".join(item.split()).strip() - chunks.extend(_split_evidence_text_chunks(normalized, max_item_chars)) - if len(chunks) > max_items: - merged: list[str] = [] - for chunk in chunks: - if merged and len(merged[-1]) + 2 + len(chunk) <= max_item_chars: - merged[-1] = f"{merged[-1]}; {chunk}" - else: - merged.append(chunk) - chunks = merged - clipped = len(chunks) > max_items - if clipped: - chunks = chunks[:max_items] - bounded: list[str] = [] - used = 0 - for idx, chunk in enumerate(chunks): - remaining = max_total_chars - used - if remaining <= 0: - clipped = True - break - if len(chunk) > remaining or len(chunk) > max_item_chars: - cap = min(max_item_chars, remaining) - bounded.append(_append_bounded_ellipsis(chunk, cap)) - used += len(bounded[-1]) - clipped = True - break - bounded.append(chunk) - used += len(chunk) - if clipped and bounded and not bounded[-1].endswith("..."): - room = min(max_item_chars, len(bounded[-1]) + (max_total_chars - used)) - bounded[-1] = _append_bounded_ellipsis(bounded[-1], room) - return bounded - - -def _normalize_steward_advancement_kernel_candidate(candidate: Mapping[str, Any]) -> dict[str, Any]: - """Keep Steward advancement evidence within kernel per-item and total limits.""" - normalized = dict(candidate) - if normalized.get("delivery_batch_scale") == "multi_surface_or_implementation": - normalized["delivery_batch_scale"] = "multi_surface" - for field in ("work_evidence", "validation_evidence"): - if field in normalized: - normalized[field] = _split_bounded_evidence_items(normalized[field]) - return normalized - - -def _is_zero_effect_replan_selection_deferral(result: Mapping[str, Any]) -> bool: - """Identify a zero-effect pre-host autonomous_replan selection refusal.""" - if result.get("ok") is not False or result.get("error_code") != "turn_todo_selection_deferred": - return False - refusal = result.get("selection_rejection") - if (not isinstance(refusal, Mapping) or refusal.get("state") != "deferred" - or refusal.get("reason_code") != "autonomous_replan" - or refusal.get("recovery_action") != "reenter_guard_without_selection"): - return False - effects = result.get("effects") - if not isinstance(effects, Mapping): - return False - return all( - effects.get(key) is False - for key in ("host_invoked", "state_written", "quota_spent", "scheduler_acknowledged") - ) +_iso_timestamp_seconds = iso_timestamp_seconds +_append_bounded_ellipsis = append_bounded_ellipsis +_split_bounded_evidence_items = split_bounded_evidence_items +_split_evidence_text_chunks = split_evidence_text_chunks class StewardTurnHost: - def __init__(self, controller: Any) -> None: - self.controller = controller - self.store = controller.store - self.bindings = controller.project_contexts.conversation_bindings - self.managed = StewardManagedMode(controller, self.bindings) + """Host bridge preserving original-Session identity across admission, recovery, and execution.""" + + def __init__(self, controller: StewardControllerProtocol) -> None: + self.controller: StewardControllerProtocol = controller + self.store: StewardStoreProtocol = controller.store + self.bindings: StewardBindingsProtocol | None = controller.project_contexts.conversation_bindings + self.managed: StewardManagedProtocol = cast(StewardManagedProtocol, StewardManagedMode(controller, self.bindings)) @staticmethod def background_session_id(binding_id: str) -> str: - return steward_background_session_id(binding_id) + return str(steward_background_session_id(binding_id)) @staticmethod def background_channel_id(binding_id: str) -> str: - return steward_background_channel_id(binding_id) - - def _lookup_monitor_turn(self, binding_id: str, actor: Mapping[str, Any], client_id: str) -> dict[str, Any] | None: - return lookup_steward_monitor_turn(self.store, binding_id, actor["session_id"], client_id) - - def _ensure_background_session(self, binding_id: str, parent_session: Mapping[str, Any]) -> dict[str, Any]: - return ensure_steward_background_session(self.store, binding_id, parent_session) - - def _monitor_selection_failed_before_poll(self, turn: dict[str, Any]) -> bool: - # The earlier adapter lost the command's structured rejection at the - # Chat boundary. Recognize only this exact pre-poll failure, never an - # unknown execution/commit failure or a report/business Turn. - expected = ("the native steward operation was not committed: quota_action_selection_rejected: " - "explicit action selection is not currently eligible: auxiliary_monitor_not_selectable_in_advancement_lane") - return (turn.get("status") == "failed" and turn.get("error_code") == "runtime_error" - and turn.get("error") == expected and turn.get("delta_count") == 0 - and turn.get("upstream_turn_id") is None and turn.get("response") is None - and not any(row["kind"] == "native_loopx.monitor_poll" - for row in self.store.events_after(turn["session_id"], turn["turn_id"], None))) - - def _observe(self, actor: Mapping[str, Any]) -> dict[str, Any] | None: + return str(steward_background_channel_id(binding_id)) + + def _lookup_monitor_turn( + self, binding_id: str, actor: Mapping[str, object], client_id: str + ) -> dict[str, object] | None: + return as_optional_dict( + lookup_steward_monitor_turn(monitor_store_for(self.store), binding_id, str(actor["session_id"]), client_id) + ) + + def _ensure_background_session( + self, binding_id: str, parent_session: Mapping[str, object] + ) -> dict[str, object]: + return as_dict(ensure_steward_background_session(monitor_store_for(self.store), binding_id, parent_session)) + + def _monitor_selection_failed_before_poll(self, turn: Mapping[str, object]) -> bool: + return monitor_selection_failed_before_poll(self.store, turn) + + def _observe(self, actor: Mapping[str, object]) -> dict[str, object] | None: """Verify provider identity before entering publication/effect fences.""" if actor.get("schema_version") == "loopx_managed_session_actor_v0": return None if self.bindings is None: raise ValueError("the original steward binding is unavailable") - session = self.store.load_session(actor["session_id"]) + session = self.store.load_session(str(actor["session_id"])) if not session or not session.get("steward_context"): raise ValueError("the original steward Session is unavailable") - saved = session["steward_context"] - return self.bindings.resolve(binding_id=saved["binding_id"], session=session, - include_observation=True, origin="web", source_ref=saved["source_ref"], - sender_ref=saved["operator_ref"], private_human_message=False, session_context=saved) - - def _admit(self, request: dict[str, Any], *, turn: dict[str, Any] | None = None, - observed: dict[str, Any] | None = None, carrier_session: dict[str, Any] | None = None, - prepare_context: bool = False, settlement_recovery: dict[str, Any] | None = None, - frozen_contract_recovery: dict[str, Any] | None = None, - launch_recovery: dict[str, Any] | None = None, - selection_recovery: dict[str, Any] | None = None) -> dict[str, Any]: + saved = as_mapping(session["steward_context"]) + return self.bindings.resolve( + binding_id=str(saved["binding_id"]), + session=session, + include_observation=True, + origin="web", + source_ref=str(saved["source_ref"]), + sender_ref=str(saved["operator_ref"]), + private_human_message=False, + session_context=dict(saved), + ) + + def _admit( + self, + request: dict[str, object], + *, + turn: dict[str, object] | None = None, + observed: dict[str, object] | None = None, + carrier_session: dict[str, object] | None = None, + prepare_context: bool = False, + settlement_recovery: dict[str, object] | None = None, + frozen_contract_recovery: dict[str, object] | None = None, + launch_recovery: dict[str, object] | None = None, + selection_recovery: dict[str, object] | None = None, + ) -> dict[str, object]: if self.controller.closed.is_set(): raise ValueError("the original Chat host is stopped") - actor = request["actor"] + actor = as_mapping(request["actor"]) if actor.get("schema_version") == "loopx_managed_session_actor_v0": - return ManagedSessionTurn(self.controller).admit(request, turn=turn, - settlement_recovery=settlement_recovery, - frozen_contract_recovery=frozen_contract_recovery, - selection_recovery=selection_recovery) + return as_dict( + ManagedSessionTurn(self.controller).admit( + request, + turn=turn, + settlement_recovery=settlement_recovery, + frozen_contract_recovery=frozen_contract_recovery, + selection_recovery=selection_recovery, + ) + ) if self.bindings is None: raise ValueError("the original steward binding is unavailable") observed = observed if observed is not None else self._observe(actor) - session = self.store.load_session(actor["session_id"]) + if observed is None: + raise ValueError("the original steward observation is unavailable") + session = self.store.load_session(str(actor["session_id"])) if not session or not session.get("steward_context"): raise ValueError("the original steward Session is unavailable") - saved = session["steward_context"] + saved = as_mapping(session["steward_context"]) current = self.bindings.read() - binding = next((row for row in current["bindings"] if row["binding_id"] == saved["binding_id"]), None) - if binding != observed["binding"]: + binding = next( + (row for row in as_dict_list(current.get("bindings")) if row.get("binding_id") == saved.get("binding_id")), + None, + ) + if binding != observed.get("binding"): raise ValueError("the original steward authorization changed during identity verification") # Identity IO may have waited. - - selected = {**self.bindings._resolve_observed(current, binding, observed["observation"], { - "source_ref": saved["source_ref"], "sender_ref": saved["operator_ref"], - "private_human_message": False, "origin": "web", "session_context": saved, - "session": self.bindings._session_observation(session)}), "observation": observed["observation"]} + selected: dict[str, object] = { + **self.bindings._resolve_observed( + current, + binding or {}, + as_dict(observed.get("observation")), + { + "source_ref": saved["source_ref"], + "sender_ref": saved["operator_ref"], + "private_human_message": False, + "origin": "web", + "session_context": saved, + "session": self.bindings._session_observation(session), + }, + ), + "observation": observed.get("observation"), + } from ...agent_registry import load_goal_from_registry - goal = load_goal_from_registry(self.controller.registry_path, actor["goal_id"]) - from .steward_monitor import StewardMonitor - canonical_actor = selected["binding"].get("managed_actor") - monitor = (next((row for row in StewardMonitor(self.controller).todos(canonical_actor) - if row["todo_id"] == request.get("todo_id") and row.get("task_class") == "continuous_monitor"), None) - if canonical_actor and request.get("work_kind") == "monitor" and request.get("todo_id") else None) + + goal_id = str(actor["goal_id"]) + goal = as_optional_dict(load_goal_from_registry(cast(Path, self.controller.registry_path), goal_id)) + canonical_actor = as_optional_dict(as_mapping(selected.get("binding")).get("managed_actor")) + monitor = ( + next( + ( + row + for row in as_dict_list(steward_monitor_for(self.controller).todos(dict(canonical_actor))) + if row.get("todo_id") == request.get("todo_id") and row.get("task_class") == "continuous_monitor" + ), + None, + ) + if canonical_actor is not None and request.get("work_kind") == "monitor" and request.get("todo_id") + else None + ) if request.get("work_kind") == "monitor" and carrier_session is None: - bg_sid = self.background_session_id(saved["binding_id"]) + bg_sid = self.background_session_id(str(saved["binding_id"])) if turn is not None and turn.get("session_id") == bg_sid: carrier_session = self.store.load_session(bg_sid) if carrier_session is None: @@ -341,819 +234,512 @@ def _admit(self, request: dict[str, Any], *, turn: dict[str, Any] | None = None, existing_bg = self.store.load_session(bg_sid) if existing_bg is not None and isinstance(existing_bg.get("steward_background_context"), Mapping): carrier_session = existing_bg - report = {} + report: dict[str, object] = {} if request.get("work_kind") == "report": from .steward_reports import StewardReports - subscription, window = StewardReports(self.controller).current_window(saved["binding_id"]) - todos = StewardMonitor(self.controller).todos(canonical_actor) if canonical_actor else [] - report = {"report_window": window, "report_subscription": subscription, - "report_todo": next((row for row in todos if row["todo_id"] == request.get("todo_id")), None)} - scope, observed_scope_id = None, None + + subscription, window = StewardReports(self.controller).current_window(str(saved["binding_id"])) + todos = ( + as_dict_list(steward_monitor_for(self.controller).todos(dict(canonical_actor))) + if canonical_actor + else [] + ) + report = { + "report_window": window, + "report_subscription": subscription, + "report_todo": next((row for row in todos if row.get("todo_id") == request.get("todo_id")), None), + } + scope: dict[str, str] | None = None + observed_scope_id: str | None = None if turn is not None: from ...chat_manager_context import manager_authorization_scope_id_for_registry + goal_ids = self.bindings.steward_scope(session) if goal_ids is None: raise ValueError("the original portfolio scope is unavailable") - def scope_id(ids, *, channel_id=session["channel_id"]): - return manager_authorization_scope_id_for_registry(self.controller.registry_path, ids, - runtime_root=self.controller.coordination_runtime_root, channel_id=channel_id) - scope = {"current": scope_id(goal_ids), - "without_actor": scope_id([value for value in goal_ids if value != actor["goal_id"]])} - observed_scope_id = (scope_id(goal_ids, channel_id=carrier_session["channel_id"]) - if carrier_session is not None else scope["current"]) - admitted = self.bindings._core("collaboration.steward.managed_turn.admit", { - "binding": selected["binding"], "session": session, "observation": selected["observation"], - "workspace_path": str(self.managed._workspace(session)), - "queued_turn_count": len(self.store.queued_turns(session["session_id"])), - "goal": self.managed._goal(actor["goal_id"]), "goal_active": bool(goal and goal.get("status") == "active" and not goal_is_stopped(goal)), - "request": request, "turn": turn, "scope": scope, "monitor_todo": monitor, - **({"carrier_session": carrier_session, - "carrier_queued_turn_count": len(self.store.queued_turns(carrier_session["session_id"]))} - if carrier_session is not None else {}), - **({"report_settlement_recovery": settlement_recovery} if settlement_recovery is not None else {}), - **({"report_frozen_contract_recovery": frozen_contract_recovery} if frozen_contract_recovery is not None else {}), - **({"report_launch_recovery": launch_recovery} if launch_recovery is not None else {}), - **({"report_selection_recovery": selection_recovery} if selection_recovery is not None else {}), - **self.report_quota_basis(request), - **self.report_timeout_basis(request), - **self.monitor_restart_basis(request), - **({"preparing_model_context": True} if prepare_context else {}), **report}) - if admitted["refresh_original_scope"] and scope is not None: - self.store.update_session(session["session_id"], manager_authorization_scope_id=scope["current"]) + + default_channel_id = session["channel_id"] + + def scope_id(ids: list[str], *, channel_id: object = default_channel_id) -> str: + return str( + manager_authorization_scope_id_for_registry( + cast(Path, self.controller.registry_path), + ids, + runtime_root=self.controller.coordination_runtime_root, + channel_id=channel_id, + ) + ) + + scope = { + "current": scope_id(goal_ids), + "without_actor": scope_id([value for value in goal_ids if value != actor["goal_id"]]), + } + observed_scope_id = ( + scope_id(goal_ids, channel_id=carrier_session["channel_id"]) + if carrier_session is not None + else scope["current"] + ) + admitted = self.bindings._core( + "collaboration.steward.managed_turn.admit", + { + "binding": selected["binding"], + "session": session, + "observation": selected["observation"], + "workspace_path": str(self.managed._workspace(session)), + "queued_turn_count": len(self.store.queued_turns(str(session["session_id"]))), + "goal": self.managed._goal(goal_id), + "goal_active": bool(goal and goal.get("status") == "active" and not goal_is_stopped(goal)), + "request": request, + "turn": turn, + "scope": scope, + "monitor_todo": monitor, + **( + { + "carrier_session": carrier_session, + "carrier_queued_turn_count": len(self.store.queued_turns(str(carrier_session["session_id"]))), + } + if carrier_session is not None + else {} + ), + **({"report_settlement_recovery": settlement_recovery} if settlement_recovery is not None else {}), + **({"report_frozen_contract_recovery": frozen_contract_recovery} if frozen_contract_recovery is not None else {}), + **({"report_launch_recovery": launch_recovery} if launch_recovery is not None else {}), + **({"report_selection_recovery": selection_recovery} if selection_recovery is not None else {}), + **self.report_quota_basis(request), + **self.report_timeout_basis(request), + **self.monitor_restart_basis(request), + **({"preparing_model_context": True} if prepare_context else {}), + **report, + }, + ) + if admitted.get("refresh_original_scope") and scope is not None: + self.store.update_session(str(session["session_id"]), manager_authorization_scope_id=scope["current"]) if carrier_session is not None and observed_scope_id: - self.store.update_session(carrier_session["session_id"], manager_authorization_scope_id=observed_scope_id) + self.store.update_session(str(carrier_session["session_id"]), manager_authorization_scope_id=observed_scope_id) return {**admitted, "observed_scope_id": observed_scope_id if scope else None} - def monitor_restart_basis(self, request: Mapping[str, Any]) -> dict[str, Any]: - """Read original worker/journals without dispatching or repairing effects. - - Any pending, committed, unreadable or legacy poll evidence withholds a - new carrier. The shared typed admission owner interprets these facts. - """ - recovery = request.get("monitor_restart_recovery") - if recovery is None: - return {} - from ...chat_store import _read_jsonl - from ...control_plane.quota.monitor_poll import _monitor_poll_effect_id, _monitor_poll_receipt_path - from .steward_commands import native_command - actor = request["actor"] - original = load_steward_monitor_turn_by_id(self.store, actor, recovery["original_turn_id"]) - if original is None: - raise ValueError("the original stopped watch is unavailable") - original_session_id = str(original["session_id"]) - root = self.controller.coordination_runtime_root - with exclusive_file_lock(self.store.turn_execution_lock_path(original_session_id, original["turn_id"]), - timeout_seconds=0, operation="observe_stopped_native_watch"): - # Strict reads are essential: an unreadable/compacted journal is - # unknown, never an empty observation or proof that work did not run. - events = _read_jsonl(self.store._event_path(original_session_id, original["turn_id"]), - raise_on_error=True, strict=True) - rows = _read_jsonl(root / "goals" / actor["goal_id"] / "runs" / "index.jsonl", - raise_on_error=True, strict=True) - present = any(row.get("classification") == "quota_monitor_poll" - and row.get("turn_instance_id") == request["turn_instance_id"] for row in rows) - from .steward_monitor import TARGET, StewardMonitor - target = ("managed-session-watch." + actor["session_id"] - if actor.get("schema_version") == "loopx_managed_session_actor_v0" else TARGET) - if actor.get("schema_version") != "loopx_managed_session_actor_v0": - matched = next((row for row in StewardMonitor(self.controller).todos(actor) - if row.get("todo_id") == request.get("todo_id")), None) - if matched and matched.get("target_key"): - target = matched["target_key"] - for todo, key in [(request["todo_id"], target), (None, target), (None, None)]: - effect = _monitor_poll_effect_id(runtime_root=root, goal_id=actor["goal_id"], - agent_id=actor["agent_id"], turn_instance_id=request["turn_instance_id"], - todo_id=todo, target_key=key, goal_ref=None) - present = present or _monitor_poll_receipt_path(root, actor["goal_id"], effect).exists() - lease = native_command(self.controller, ["task-lease", "inspect", "--goal-id", actor["goal_id"], - "--todo-id", request["todo_id"]]) - held = lease.get("lease") or {} - available = lease.get("active") is False or (held.get("owner") == actor["agent_id"] - and held.get("idempotency_key") == "monitor-recovery." + original["turn_id"]) - return {"monitor_restart_basis": {"original": original, - "event_kinds": [row["kind"] for row in events], "poll_absent": not present, - "contexts": [row["payload"] for row in events if row["kind"] == "manager.context"], - "phases": [row["payload"] for row in events if row["kind"] == "agent.phase"], - "old_worker_excluded": True, "lease_available": available, - "observed_at": time.time()}} + def monitor_restart_basis(self, request: Mapping[str, object]) -> dict[str, object]: + """Read original worker/journals without dispatching or repairing effects.""" + return monitor_restart_basis(self, request) @staticmethod - def monitor_restart_request(original: Mapping[str, Any], *, now: float | None = None) -> dict[str, Any] | None: + def monitor_restart_request( + original: Mapping[str, object], *, now: float | None = None + ) -> dict[str, object] | None: """Prepare correlation only; current typed admission decides recovery.""" - prior = original.get("loopx_request") or {} - error = original.get("error_code") - if (original.get("status") != "failed" - or error not in {"server_restarted", "runtime_error", "runtime_unavailable", LOCK_ACQUIRE_TIMEOUT_ERROR_CODE} - or prior.get("work_kind") != "monitor"): - return None - if prior.get("monitor_restart_recovery") is not None and error != "server_restarted": - msg = original.get("error") - post_context_error = error in {"runtime_unavailable", LOCK_ACQUIRE_TIMEOUT_ERROR_CODE} or ( - error == "runtime_error" - and (msg in _POST_CONTEXT_WATCH_ERRORS or (isinstance(msg, str) and _FILE_LOCK_TIMEOUT_ERROR_RE.fullmatch(msg) is not None)) - ) - completed_ts = _iso_timestamp_seconds(original.get("completed_at")) - current_ts = time.time() if now is None else now - if (not post_context_error or completed_ts is None - or current_ts - completed_ts < MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS): - return None - return {**prior, "monitor_restart_recovery": {"original_turn_id": original["turn_id"]}} - - def monitor_restart_carrier(self, original: dict[str, Any], client_id: str) -> dict[str, Any] | None: + return monitor_restart_request(original, now=now) + + def monitor_restart_carrier( + self, original: Mapping[str, object], client_id: str + ) -> MonitorRestartCarrier | None: """Find the latest carrier for the same observation; typed admission proves a safe restart.""" - request = self.monitor_restart_request(original) - if request is None: - return None - actor = (original.get("loopx_request") or {}).get("actor") - binding_id = actor_steward_binding_id(actor) if isinstance(actor, Mapping) else None - base = client_id + ".restart-recovery" - next_client_id = base - while (carrier := lookup_steward_monitor_turn(self.store, binding_id, original["session_id"], next_client_id)) is not None: - if ((carrier.get("loopx_request") or {}).get("monitor_restart_recovery") - != request["monitor_restart_recovery"]): - raise ValueError("native watch continuation identity conflict") - request = self.monitor_restart_request(carrier) - if request is None: - return {"turn": carrier} - next_client_id = base + "." + carrier["turn_id"] - return {"request": request, "client_id": next_client_id} - - def _report_continuation_basis(self, request: Mapping[str, Any], *, - recovery_key: str, basis_key: str) -> dict[str, Any]: - """Transport original journal observations; the typed owner admits work.""" - recovery = request.get(recovery_key) - if recovery is None: - return {} - from ...control_plane.turn_driver import inspect_loopx_turn_journal - from ..periodic_report.private_generation import attempt_directory - from .steward_reports import report_service - actor = request["actor"] - original = self.store.load_turn(actor["session_id"], recovery["original_turn_id"]) - result = ((original or {}).get("response") or {}).get("native_loopx") or {} - reports, owner = report_service(self.controller, actor) - _, window = reports.current_window(owner) - folder = attempt_directory(reports.root, window) if window else None - return {basis_key: {"original": original, - "inspection": inspect_loopx_turn_journal(reports.root, goal_id=actor["goal_id"], - agent_id=actor["agent_id"], turn_key=result["resume_turn_key"]), - "generation_present": folder is None or any((folder / name).exists() for name in - ("editorial-response.json", "private-generation.json", "private-delivery.json")), - "observed_at": time.time()}} - - def report_quota_basis(self, request: Mapping[str, Any]) -> dict[str, Any]: - return self._report_continuation_basis(request, recovery_key="report_quota_recovery", - basis_key="report_quota_basis") - - def report_timeout_basis(self, request: Mapping[str, Any]) -> dict[str, Any]: - return self._report_continuation_basis(request, recovery_key="report_timeout_recovery", - basis_key="report_timeout_basis") - - def report_failure_observation(self, original: Mapping[str, Any]) -> dict[str, Any] | None: + return monitor_restart_carrier(self, original, client_id) + + def _report_continuation_basis( + self, request: Mapping[str, object], *, recovery_key: str, basis_key: str + ) -> dict[str, object]: + return report_continuation_basis(self, request, recovery_key=recovery_key, basis_key=basis_key) + + def report_quota_basis(self, request: Mapping[str, object]) -> dict[str, object]: + return self._report_continuation_basis( + request, recovery_key="report_quota_recovery", basis_key="report_quota_basis" + ) + + def report_timeout_basis(self, request: Mapping[str, object]) -> dict[str, object]: + return self._report_continuation_basis( + request, recovery_key="report_timeout_recovery", basis_key="report_timeout_basis" + ) + + def report_failure_observation(self, original: Mapping[str, object]) -> dict[str, object] | None: """Read the original native failure without starting or resuming work.""" - return observe_report_failure(self.controller, self.store, original) + return as_optional_dict(observe_report_failure(self.controller, self.store, original)) def report_window_failure_verified( - self, original: Mapping[str, Any], window: dict[str, Any], *, generation_locked: bool = False, + self, original: Mapping[str, object], window: dict[str, object], *, generation_locked: bool = False ) -> bool: """Query live provider history first; fall back to retained proof only if unavailable.""" - return verify_report_window_failure( - self.controller, self.store, original, window, generation_locked=generation_locked, + return bool( + verify_report_window_failure( + self.controller, self.store, original, window, generation_locked=generation_locked + ) ) - def report_failure_contradicted(self, original: Mapping[str, Any], window: dict[str, Any]) -> bool: + def report_failure_contradicted(self, original: Mapping[str, object], window: dict[str, object]) -> bool: """Return True when a prior live observation contradicted this Turn's failure proof.""" - return is_report_failure_contradicted(self.controller.coordination_runtime_root, original, window) + return bool(is_report_failure_contradicted(self.controller.coordination_runtime_root, original, window)) - def report_quota_request(self, original: Mapping[str, Any], *, - report_window: dict[str, Any] | None = None) -> dict[str, Any] | None: + def report_quota_request( + self, original: Mapping[str, object], *, report_window: dict[str, object] | None = None + ) -> dict[str, object] | None: """Observe quota recovery, never resume or rewrite the failed native Turn.""" fallback = ( None if getattr(self.report_failure_observation, "__func__", None) is _DEFAULT_REPORT_FAILURE_OBSERVATION else self.report_failure_observation ) - return build_report_quota_request( - self.controller, self.store, original, report_window=report_window, fallback_observe_fn=fallback, + return as_optional_dict( + build_report_quota_request( + self.controller, self.store, original, report_window=report_window, fallback_observe_fn=fallback + ) ) - def report_timeout_request(self, original: Mapping[str, Any]) -> dict[str, Any] | None: + def report_timeout_request(self, original: Mapping[str, object]) -> dict[str, object] | None: """Observe idle Antigravity timeout for one bounded isolated-cascade retry.""" - return build_report_timeout_request(original, observe_fn=self.report_failure_observation) + return as_optional_dict(build_report_timeout_request(original, observe_fn=self.report_failure_observation)) - def report_selection_recovery(self, original: dict[str, Any], *, - probe_turn: dict[str, Any] | None = None) -> dict[str, Any] | None: + def report_selection_recovery( + self, original: dict[str, object], *, probe_turn: dict[str, object] | None = None + ) -> dict[str, object] | None: """The typed owner qualifies this observation before any new worker.""" - result = (original.get("response") or {}).get("native_loopx") or {} - refusal = result.get("selection_rejection") - if (result.get("error_code") != "turn_todo_selection_deferred" or not isinstance(refusal, Mapping) - or refusal.get("reason_code") != "autonomous_replan" - or refusal.get("recovery_action") != "reenter_guard_without_selection"): - return None - from ..periodic_report.private_generation import attempt_directory - from .steward_reports import report_service - request = original["loopx_request"] - reports, owner = report_service(self.controller, request["actor"]) - _, window = reports.current_window(owner) - proof = {"original": original, "generation_present": window is None - or window["window_id"] != request["report_window_id"] - or (attempt_directory(reports.root, window) / "private-generation.json").exists()} - if probe_turn is not None: - from ...control_plane.turn_driver.executor import inspect_loopx_turn_journal - from ...control_plane.turn_driver.journal_store import load_turn_journal, turn_journal_path - actor = request["actor"] - keys = {row["payload"].get("resume_turn_key") - for row in self.store.events_after(actor["session_id"], probe_turn["turn_id"], None) - if row.get("kind") == "native_loopx.replan_result"} - if len(keys) != 1 or not isinstance(next(iter(keys)), str): - return None - key = keys.pop() - from ...control_plane.effect_runtime import source_number_tokens - journal = load_turn_journal(turn_journal_path(reports.root, goal_id=actor["goal_id"], turn_key=key)) - if not isinstance(journal, Mapping): - return None - current_guard, journal_status = None, journal.get("status") - if (journal_status == "failed" and journal.get("result_kind") == "validation_failed" - and journal.get("validation_stage") in {"host_result_contract", "task_postcondition"}): - current_guard = self._cleared_replan_guard(actor) - if current_guard is None: - return None - elif journal_status != "stopped": - return None - # Transport canonical observations to the shared typed admission owner. - proof["probe"] = {"turn": probe_turn, - "inspection": inspect_loopx_turn_journal(reports.root, goal_id=actor["goal_id"], - agent_id=actor["agent_id"], turn_key=key), - "journal": journal, - "source_number_tokens": source_number_tokens((journal.get("plan") or {}).get("work_contract")), - **({"current_guard": current_guard} if current_guard is not None else {})} - return proof - - def _cleared_replan_guard(self, actor: Mapping[str, Any]) -> dict[str, Any] | None: - """Read-only guard check proving an earlier autonomous_replan obligation was cleared.""" - from ...control_plane.quota.effective_action import EffectiveAction - from .steward_commands import NativeStewardCommandError, native_command - try: - raw = native_command(self.controller, [ - "quota", "should-run", "--goal-id", actor["goal_id"], "--agent-id", actor["agent_id"], "--dry-run", - ]) - except (NativeStewardCommandError, OSError, ValueError, RuntimeError): - return None - payload: Mapping[str, Any] = raw - if payload.get("effective_action") is None and isinstance(payload.get("reference_file"), str): - try: - ref = json.loads(Path(payload["reference_file"]).read_text(encoding="utf-8")) - target = Path(str(ref.get("path") or payload["reference_file"])) - loaded = json.loads(target.read_text(encoding="utf-8")) - except (OSError, ValueError): - return None - if isinstance(loaded, Mapping): - payload = loaded - current = { - "effective_action": payload.get("effective_action"), - "replan_action_packet": payload.get("replan_action_packet"), - } - if (current["effective_action"] != EffectiveAction.NORMAL_RUN.value - or current["replan_action_packet"] is not None): - return None - return current + return report_selection_recovery(self, original, probe_turn=probe_turn) - def _report_launch_recovery(self, original: dict[str, Any]) -> dict[str, Any] | None: - """Read the original typed launch refusal and its canonical transaction. + def _cleared_replan_guard(self, actor: Mapping[str, object]) -> dict[str, object] | None: + return cleared_replan_guard(self, actor) - Missing model events alone prove nothing. Only the native launch - owner's specific pre-publication rejection can qualify this path; - the typed conversation owner checks it with the current journal. - """ - result = (original.get("response") or {}).get("native_loopx") or {} - if (result.get("host_failure") or {}).get("kind") != "contract_rejected": - return None - from ...control_plane.turn_driver import inspect_loopx_turn_journal - from ...control_plane.turn_driver.journal_store import ( - find_loopx_turn_key_by_settlement_identity, load_turn_journal, turn_journal_path, - ) - from ..periodic_report.private_generation import attempt_directory - from .steward_reports import StewardReports - request = original["loopx_request"] - actor = request["actor"] - root = self.controller.coordination_runtime_root - key = find_loopx_turn_key_by_settlement_identity(root, goal_id=actor["goal_id"], - agent_id=actor["agent_id"], todo_id=request["todo_id"], turn_instance_id=request["turn_instance_id"]) - if key is None: - raise ValueError("the original launch rejection has no canonical Turn") - inspection = inspect_loopx_turn_journal(root, goal_id=actor["goal_id"], - agent_id=actor["agent_id"], turn_key=key, retry_failed=True) - journal = load_turn_journal(turn_journal_path(root, goal_id=actor["goal_id"], turn_key=key)) - _, window = StewardReports(self.controller).current_window(actor["goal_id"].removeprefix("steward-agent-")) - return {"original": original, "inspection": inspection, "journal": journal, "turn_key": key, - "host_attempt_count": (journal or {}).get("host_attempt_count"), - "generation_present": window is None or (attempt_directory(root, window) / "private-generation.json").exists()} - - def _report_validator(self, request: Mapping[str, Any]): - """Validate with the owning installed package, outside model execution. - - An embedded host may import LoopX through its bootstrap rather than the - Python interpreter's site-packages. Its bare child interpreter is not - an independent installation of the same package. - """ - def validate(_plan: Mapping[str, Any], _result: Mapping[str, Any]) -> dict[str, Any]: + def _report_launch_recovery(self, original: dict[str, object]) -> dict[str, object] | None: + return report_launch_recovery(self, original) + + def _report_validator( + self, request: Mapping[str, object] + ) -> Callable[[Mapping[str, object], Mapping[str, object]], dict[str, object]]: + """Validate with the owning installed package, outside model execution.""" + + def validate(_plan: Mapping[str, object], _result: Mapping[str, object]) -> dict[str, object]: from ..periodic_report.private_generation import attempt_directory, validate_private_generation from .steward_reports import report_service - reports, owner_key = report_service(self.controller, request["actor"]) + + reports, owner_key = report_service(self.controller, dict(as_mapping(request["actor"]))) try: subscription, window = reports.current_window(owner_key) - if (not subscription or not window or window["window_id"] != request["report_window_id"] - or window["subscription_revision"] != request["report_subscription_revision"]): + if ( + not subscription + or not window + or window["window_id"] != request["report_window_id"] + or window["subscription_revision"] != request["report_subscription_revision"] + ): raise ValueError("the original report window changed") validate_private_generation(attempt_directory(reports.root, window)) if not reports.delivery_current(owner_key, window): raise ValueError("the original report authorization changed") except (OSError, ValueError, RuntimeError): - return {"status": "failed", "validator_kind": "callback", - "summary": "independent original report validation failed", "recovery_kind": "repair_required"} - return {"status": "passed", "validator_kind": "callback", - "summary": "independent original report validation passed"} + return { + "status": "failed", + "validator_kind": "callback", + "summary": "independent original report validation failed", + "recovery_kind": "repair_required", + } + return { + "status": "passed", + "validator_kind": "callback", + "summary": "independent original report validation passed", + } + return validate - def _report_fence(self, request: Mapping[str, Any]): - if request["actor"].get("schema_version") == "loopx_managed_session_actor_v0": + def _report_fence(self, request: Mapping[str, object]) -> AbstractContextManager[object]: + actor = as_mapping(request["actor"]) + if actor.get("schema_version") == "loopx_managed_session_actor_v0": from ...attached_session import managed_session_goal_commit - return managed_session_goal_commit(store=self.store, registry_path=self.controller.registry_path, - session_id=request["actor"]["session_id"])() - return exclusive_file_lock(self.bindings.path, operation="original_report_effect") - def _task_lease_proof(self, request: Mapping[str, Any], lease: Mapping[str, Any] | None) -> dict[str, Any]: + return managed_session_goal_commit( + store=cast("ChatSessionStore", self.store), + registry_path=cast(Path, self.controller.registry_path), + session_id=str(actor["session_id"]), + )() + if self.bindings is None: + raise ValueError("the original steward binding is unavailable") + return cast( + AbstractContextManager[object], + exclusive_file_lock(self.bindings.path, operation="original_report_effect"), + ) + + def _task_lease_proof( + self, request: Mapping[str, object], lease: Mapping[str, object] | None + ) -> dict[str, object]: from .steward_commands import native_command - observed = native_command(self.controller, ["task-lease", "inspect", "--goal-id", request["actor"]["goal_id"], - "--todo-id", request["todo_id"]]).get("lease") - if (not lease or not observed or observed.get("status") != "active" - or any(observed.get(key) != lease.get(key) for key in - ("owner", "idempotency_key", "lease_epoch", "version"))): + + actor = as_mapping(request["actor"]) + observed = as_optional_dict( + as_mapping( + native_command( + self.controller, + ["task-lease", "inspect", "--goal-id", str(actor["goal_id"]), "--todo-id", str(request["todo_id"])], + ) + ).get("lease") + ) + if ( + not lease + or not observed + or observed.get("status") != "active" + or any(observed.get(key) != lease.get(key) for key in ("owner", "idempotency_key", "lease_epoch", "version")) + ): raise ValueError("the original task execution lease changed") - return {"task_lease_idempotency_key": observed["idempotency_key"], - "task_lease_expected_version": observed["version"]} + return { + "task_lease_idempotency_key": observed["idempotency_key"], + "task_lease_expected_version": observed["version"], + } @contextmanager - def _task_execution_lease(self, request: Mapping[str, Any], turn_id: str, *, recovery: bool = False, - admission_retry: bool = False, claim_args: list[str] | None = None, - retain_for_retry: Callable[[], bool] | None = None): + def _task_execution_lease( + self, + request: Mapping[str, object], + turn_id: str, + *, + recovery: bool = False, + admission_retry: bool = False, + claim_args: list[str] | None = None, + retain_for_retry: Callable[[], bool] | None = None, + ) -> Iterator[dict[str, object]]: """Both generation and cached validation use the original Todo owner.""" from .steward_commands import acquire_steward_task_lease, native_command - actor = request["actor"] - lease = acquire_steward_task_lease(self.controller, request, turn_id, - recovery=recovery, admission_retry=admission_retry, claim_args=claim_args) + actor = as_mapping(request["actor"]) + goal_id = str(actor["goal_id"]) + lease = as_dict( + acquire_steward_task_lease( + self.controller, + request, + turn_id, + recovery=recovery, + admission_retry=admission_retry, + claim_args=claim_args, + ) + ) try: yield lease finally: if retain_for_retry is None or not retain_for_retry(): - # Completion retires this lease. Never release a later owner's. try: - retained = native_command(self.controller, ["task-lease", "inspect", "--goal-id", actor["goal_id"], - "--todo-id", request["todo_id"]]).get("lease") + retained = as_optional_dict( + as_mapping( + native_command( + self.controller, + ["task-lease", "inspect", "--goal-id", goal_id, "--todo-id", str(request["todo_id"])], + ) + ).get("lease") + ) if retained and retained.get("status") == "active": proof = self._task_lease_proof(request, lease) - native_command(self.controller, ["task-lease", "release", "--goal-id", actor["goal_id"], - "--todo-id", request["todo_id"], "--owner", actor["agent_id"], - "--idempotency-key", proof["task_lease_idempotency_key"], - "--expected-version", str(proof["task_lease_expected_version"])]) + native_command( + self.controller, + [ + "task-lease", "release", "--goal-id", goal_id, "--todo-id", str(request["todo_id"]), + "--owner", str(actor["agent_id"]), + "--idempotency-key", str(proof["task_lease_idempotency_key"]), + "--expected-version", str(proof["task_lease_expected_version"]), + ], + ) except (OSError, ValueError, RuntimeError): - self.store.append_event(actor["session_id"], turn_id, kind="native_loopx.task_lease_release_unconfirmed", - payload={"todo_id": request["todo_id"], "lease_epoch": lease["lease_epoch"]}) + self.store.append_event( + str(actor["session_id"]), + turn_id, + kind="native_loopx.task_lease_release_unconfirmed", + payload={"todo_id": request["todo_id"], "lease_epoch": lease["lease_epoch"]}, + ) def _frozen_report_contract_recovery( self, - actor: Mapping[str, Any], - window: Mapping[str, Any], - original: Mapping[str, Any], + actor: Mapping[str, object], + window: Mapping[str, object], + original: Mapping[str, object], *, key: str, - generation: Mapping[str, Any], + generation: Mapping[str, object], root: Path, - ) -> tuple[dict[str, Any], dict[str, Any]] | None: - """Recover only a already-frozen report whose host candidate hit host_result_contract.""" - from ...control_plane.turn_driver.host_candidate import parse_model_json - from ...control_plane.turn_driver.journal_store import load_turn_journal, turn_journal_path - - journal = load_turn_journal(turn_journal_path(root, goal_id=actor["goal_id"], turn_key=key)) - if ( - not isinstance(journal, Mapping) - or journal.get("status") != "failed" - or journal.get("result_kind") != "validation_failed" - or journal.get("validation_stage") != "host_result_contract" - or journal.get("host_attempt_count") != 1 - ): - return None - resumed = self.store.turn_for_client( - actor["session_id"], - native_steward_client_id(actor, "report." + window["window_id"] + ".admission-resume"), - ) - retry = self.store.turn_for_client( - actor["session_id"], - native_steward_client_id(actor, "report." + window["window_id"] + ".admission-retry"), + ) -> tuple[dict[str, object], dict[str, object]] | None: + return frozen_report_contract_recovery( + self, + actor, + window, + original, + key=key, + generation=generation, + root=root, + normalize_report_candidate=_normalize_report_kernel_candidate, ) - seen_turn_ids: set[str] = set() - candidates: list[Mapping[str, Any]] = [] - for candidate_turn in (resumed, retry, original): - if isinstance(candidate_turn, Mapping): - tid = candidate_turn.get("turn_id") - if isinstance(tid, str) and tid not in seen_turn_ids: - seen_turn_ids.add(tid) - candidates.append(candidate_turn) - for candidate_turn in candidates: - events = self.store.events_after(actor["session_id"], candidate_turn["turn_id"], None) - native_failed = any( - row.get("kind") == "native_loopx.result" - and isinstance(row.get("payload"), Mapping) - and row["payload"].get("resume_turn_key") == key - and row["payload"].get("status") == "failed" - and row["payload"].get("result_kind") == "validation_failed" - and row["payload"].get("validation_stage") == "host_result_contract" - for row in events - ) - if not native_failed: - continue - for row in reversed(events): - if row.get("kind") != "answer.final": - continue - message = (((row.get("payload") or {}).get("response") or {}).get("message")) - parsed = parse_model_json(str(message or "")) - if not isinstance(parsed, dict): - continue - if parsed.get("result_kind") not in {"validated_progress", "validated_completion"}: - continue - editorial = parsed.get("editorial_response") - if not isinstance(editorial, Mapping) or editorial.get("request_digest") != generation.get("request_digest"): - continue - proof = { - "turn_key": key, - "result_kind": "validation_failed", - "validation_stage": "host_result_contract", - "host_attempt_count": 1, - "generation_verified": True, - "saved_candidate_verified": True, - } - return proof, _normalize_report_kernel_candidate(parsed) - return None def _stopped_report_candidate_recovery( self, - actor: Mapping[str, Any], - window: Mapping[str, Any], - original: Mapping[str, Any], + actor: Mapping[str, object], + window: Mapping[str, object], + original: Mapping[str, object], *, key: str, folder: Path, root: Path, - ) -> tuple[dict[str, Any], dict[str, Any]] | None: - """Recover a stopped report Turn only when its saved final answer already holds a valid candidate.""" - from ...control_plane.turn_driver.host_candidate import parse_model_json - from ...control_plane.turn_driver.journal_store import load_turn_journal, turn_journal_path - - req_path = folder / "editorial-request.json" - if not req_path.is_file() or not (folder / "source.json").is_file(): - return None - if (folder / "editorial-response.json").exists() and not (folder / "private-generation.json").exists(): - return None - try: - request_digest = json.loads(req_path.read_text(encoding="utf-8")).get("request_digest") - except (OSError, ValueError): - return None - if not isinstance(request_digest, str) or not request_digest: - return None - journal = load_turn_journal(turn_journal_path(root, goal_id=actor["goal_id"], turn_key=key)) - if ( - not isinstance(journal, Mapping) - or journal.get("status") != "stopped" - or journal.get("result_kind") != "wait" - or journal.get("host_attempt_count") != 1 - or (journal.get("host_result") or {}).get("classification") != "no_typed_host_result" - ): - return None - events = self.store.events_after(actor["session_id"], original["turn_id"], None) - stopped_event = any( - row.get("kind") == "native_loopx.result" - and isinstance(row.get("payload"), Mapping) - and row["payload"].get("resume_turn_key") == key - and row["payload"].get("status") == "stopped" - and row["payload"].get("result_kind") == "wait" - for row in events - ) - if not stopped_event: - return None - for row in reversed(events): - if row.get("kind") != "answer.final": - continue - message = ((row.get("payload") or {}).get("response") or {}).get("message") - parsed = parse_model_json(str(message or "")) - if not isinstance(parsed, dict) or parsed.get("result_kind") not in {"validated_progress", "validated_completion"}: - continue - editorial = parsed.get("editorial_response") - if not isinstance(editorial, Mapping) or editorial.get("request_digest") != request_digest: - continue - proof = { - "turn_key": key, - "result_kind": "wait", - "classification": "no_typed_host_result", - "host_attempt_count": 1, - "generation_verified": True, - "saved_candidate_verified": True, - } - return proof, dict(parsed) - return None + ) -> tuple[dict[str, object], dict[str, object]] | None: + return stopped_report_candidate_recovery(self, actor, window, original, key=key, folder=folder, root=root) def has_recoverable_stopped_report( - self, - actor: Mapping[str, Any], - window: Mapping[str, Any], - todo: Mapping[str, Any], + self, actor: Mapping[str, object], window: Mapping[str, object], todo: Mapping[str, object] ) -> bool: """Read-only gate check before acquiring the recovery fence.""" - if todo.get("status") != "open": - return False - original = report_turn(self.store, actor, window) - if not original: - return False - if any(row.get("kind") == "native_loopx.result" and (row.get("payload") or {}).get("status") == "committed" - for row in self.store.events_after(actor["session_id"], original["turn_id"], None)): - return False - request = original.get("loopx_request") or {} - turn_instance_id = request.get("turn_instance_id") - if not isinstance(turn_instance_id, str) or not turn_instance_id: - return False - from ...control_plane.turn_driver.journal_store import find_loopx_turn_key_by_settlement_identity - from ..periodic_report.private_generation import attempt_directory - from .steward_reports import report_service - reports, _ = report_service(self.controller, dict(actor)) - folder = attempt_directory(reports.root, dict(window)) - saved_key = find_loopx_turn_key_by_settlement_identity( - reports.root, goal_id=actor["goal_id"], agent_id=actor["agent_id"], - todo_id=todo["todo_id"], turn_instance_id=turn_instance_id + ".saved-candidate", - ) - if saved_key is not None and (folder / "private-generation.json").exists(): - return True - key = find_loopx_turn_key_by_settlement_identity( - reports.root, goal_id=actor["goal_id"], agent_id=actor["agent_id"], - todo_id=todo["todo_id"], turn_instance_id=turn_instance_id, - ) - return bool(key is not None and self._stopped_report_candidate_recovery( - actor, window, original, key=key, folder=folder, root=reports.root, - ) is not None) + return has_recoverable_stopped_report(self, actor, window, todo, report_turn_fn=report_turn) @staticmethod - def _build_replay_runner(normalized_candidate: Mapping[str, Any]): - from ...control_plane.turn_driver.host_candidate import build_result - - replayed = False - - def replay_frozen_candidate(native_request: Mapping[str, Any], _launch_scope: Any) -> dict[str, Any]: - nonlocal replayed - if replayed: - raise ValueError("frozen report candidate replay may execute at most once") - replayed = True - return build_result(native_request, dict(normalized_candidate), host_name="Codex app-server", allow_completion=True) - - return replay_frozen_candidate + def _build_replay_runner( + normalized_candidate: Mapping[str, object] + ) -> Callable[[Mapping[str, object], object], dict[str, object]]: + return build_replay_runner(normalized_candidate) def _settle_stopped_report_candidate( self, *, - actor: Mapping[str, Any], - window: Mapping[str, Any], - todo: Mapping[str, Any], - original: Mapping[str, Any], - request: dict[str, Any], - observed: dict[str, Any] | None, - reports: Any, + actor: Mapping[str, object], + window: Mapping[str, object], + todo: Mapping[str, object], + original: Mapping[str, object], + request: dict[str, object], + observed: dict[str, object] | None, + reports: object, owner_key: str, folder: Path, original_key: str, - stopped_proof: dict[str, Any], - raw_candidate: dict[str, Any], - ) -> dict[str, Any]: - from ...cli_runtime import _build_selected_parser - from ...cli_commands.turn import handle_turn_command - from ...control_plane.turn_driver import inspect_loopx_turn_journal - from ..periodic_report.private_generation import validate_private_generation - - inspection = inspect_loopx_turn_journal( - reports.root, goal_id=actor["goal_id"], agent_id=actor["agent_id"], - turn_key=original_key, retry_failed=True, + stopped_proof: dict[str, object], + raw_candidate: dict[str, object], + ) -> dict[str, object]: + return settle_stopped_report_candidate( + self, + actor=actor, + window=window, + todo=todo, + original=original, + request=request, + observed=observed, + reports=reports, + owner_key=owner_key, + folder=folder, + original_key=original_key, + stopped_proof=stopped_proof, + raw_candidate=raw_candidate, + normalize_report_candidate=_normalize_report_kernel_candidate, ) - admitted = self._admit( - request, observed=observed, settlement_recovery=inspection, - frozen_contract_recovery=stopped_proof, + + def recover_report_settlement( + self, actor: dict[str, object], window: dict[str, object], todo: dict[str, object] + ) -> None: + """Resume only cached, validated native effects of the original report.""" + recover_report_settlement(self, actor, window, todo, report_turn_fn=report_turn) + + def _submission_binding(self, binding_id: str) -> dict[str, object] | None: + if self.bindings is None: + return None + return next( + (row for row in as_dict_list(self.bindings.read().get("bindings")) if row.get("binding_id") == binding_id), + None, ) - if not (folder / "private-generation.json").exists(): - reports.freeze(request, dict(raw_candidate)) - generation = validate_private_generation(folder) - if raw_candidate["editorial_response"]["request_digest"] != generation["request_digest"]: - raise ValueError("the recovered candidate digest does not match the frozen report") - if not reports.delivery_current(owner_key, window): - raise ValueError("the original report authorization changed before settlement recovery") - saved_instance_id = request["turn_instance_id"] + ".saved-candidate" - argv = ["turn", "run-once", "--goal-id", actor["goal_id"], "--agent-id", actor["agent_id"], - "--project", admitted["workspace_path"], "--host", "generic-cli", - "--turn-instance-id", saved_instance_id, "--todo-id", todo["todo_id"], "--execute"] - if request.get("validation_command") is not None: - argv += ["--validation-command-json", json.dumps(request["validation_command"])] - args = _build_selected_parser("turn").parse_args(argv) - args.host, args.session_scope = "codex-app-server", "agent" - result: dict[str, Any] = {} - host_runner = self._build_replay_runner(_normalize_report_kernel_candidate(raw_candidate)) - with self._task_execution_lease(request, original["turn_id"], recovery=True) as lease: - handle_turn_command( - args, registry_path=self.controller.registry_path, - runtime_root_arg=str(reports.root), output_format=lambda *_a, **_kw: "json", - print_payload=lambda value, *_a: result.update(value), native_host_runner=host_runner, - native_session_binding_resolver=lambda _envelope: { - "schema_version": "loopx_turn_session_binding_v0", - "goal_id": actor["goal_id"], "agent_id": actor["agent_id"], - }, - native_task_validator=self._report_validator(request), - native_completion_lease_resolver=lambda: self._task_lease_proof(request, lease), - ) - return result - - def recover_report_settlement(self, actor: dict[str, Any], window: dict[str, Any], todo: dict[str, Any]) -> None: - """Resume only cached, validated native effects of the original report. - - Neither Todo DONE nor outer Chat completion is a native commit. The - journal owner must authorize a no-host continuation; its existing - effect readbacks reconcile ambiguous writeback/debit outcomes. - """ - from ...cli_runtime import _build_selected_parser - from ...cli_commands.turn import handle_turn_command - from ...control_plane.turn_driver import inspect_loopx_turn_journal - from ...control_plane.turn_driver.journal_store import find_loopx_turn_key_by_settlement_identity - from ..periodic_report.private_generation import attempt_directory, validate_private_generation - from .steward_reports import report_service - observed = self._observe(actor) - with self.controller.lock, self._report_fence({"actor": actor}): - original = report_turn(self.store, actor, window) - if not original: - return - request = original.get("loopx_request") or {} - if (request.get("actor") != actor or request.get("report_window_id") != window["window_id"] - or request.get("todo_id") != todo["todo_id"]): - raise ValueError("the original report settlement identity changed") - if any(row["kind"] == "native_loopx.result" and row["payload"].get("status") == "committed" - for row in self.store.events_after(actor["session_id"], original["turn_id"], None)): - return - reports, owner_key = report_service(self.controller, actor) - folder = attempt_directory(reports.root, window) - saved_key = find_loopx_turn_key_by_settlement_identity( - reports.root, goal_id=actor["goal_id"], agent_id=actor["agent_id"], - todo_id=todo["todo_id"], turn_instance_id=request["turn_instance_id"] + ".saved-candidate", - ) - key = saved_key or find_loopx_turn_key_by_settlement_identity( - reports.root, goal_id=actor["goal_id"], agent_id=actor["agent_id"], - todo_id=todo["todo_id"], turn_instance_id=request["turn_instance_id"], - ) - if key is None: - return - if saved_key is None: - stopped_recovery = self._stopped_report_candidate_recovery( - actor, window, original, key=key, folder=folder, root=reports.root, - ) - if stopped_recovery is not None: - result = self._settle_stopped_report_candidate( - actor=actor, window=window, todo=todo, original=original, request=request, - observed=observed, reports=reports, owner_key=owner_key, folder=folder, - original_key=key, stopped_proof=stopped_recovery[0], raw_candidate=stopped_recovery[1], - ) - self.store.append_event(actor["session_id"], original["turn_id"], kind="native_loopx.result", payload=result) - return - generation = validate_private_generation(folder) - if not reports.delivery_current(owner_key, window): - raise ValueError("the original report authorization changed before settlement recovery") - inspection = inspect_loopx_turn_journal(reports.root, goal_id=actor["goal_id"], - agent_id=actor["agent_id"], turn_key=key, retry_failed=True) - contract_recovery = ( - self._frozen_report_contract_recovery( - actor, window, original, key=key, generation=generation, root=reports.root, - ) - if (inspection.get("recovery_decision") or {}).get("reinvoke_host") is True - else None - ) - admitted = self._admit( - request, - observed=observed, - settlement_recovery=inspection, - frozen_contract_recovery=contract_recovery[0] if contract_recovery else None, - ) - def no_model(*_args): - raise ValueError("report settlement recovery must never invoke a model") - host_runner = ( - self._build_replay_runner(contract_recovery[1]) - if contract_recovery is not None - else no_model - ) - args = _build_selected_parser("turn").parse_args(["turn", "run-once", "--goal-id", actor["goal_id"], - "--agent-id", actor["agent_id"], "--project", admitted["workspace_path"], - "--host", "generic-cli", "--resume-turn-key", key, "--retry-failed-turn", "--execute"]) - args.host, args.session_scope = "codex-app-server", "agent" - result: dict[str, Any] = {} - with (self._task_execution_lease(request, original["turn_id"], recovery=True) - if todo["status"] == "open" else nullcontext(None)) as lease: - handle_turn_command(args, registry_path=self.controller.registry_path, - runtime_root_arg=str(reports.root), output_format=lambda *_a, **_kw: "json", - print_payload=lambda value, *_a: result.update(value), native_host_runner=host_runner, - native_session_binding_resolver=lambda _envelope: {"schema_version": "loopx_turn_session_binding_v0", - "goal_id": actor["goal_id"], "agent_id": actor["agent_id"]}, - native_task_validator=self._report_validator(request), - **({"native_completion_lease_resolver": lambda: self._task_lease_proof(request, lease)} if lease else {})) - # Retain the historical outer failure. The actual native owner - # supplies the new event; no status or publication proof is forged. - self.store.append_event(actor["session_id"], original["turn_id"], kind="native_loopx.result", payload=result) - - def _submission_binding(self, binding_id: str) -> dict[str, Any] | None: - return next((row for row in self.bindings.read()["bindings"] if row["binding_id"] == binding_id), None) - - def _prepare_submission(self, binding: dict[str, Any] | None, *, turn_instance_id: str, todo_id: str | None, - validation_command: Sequence[str] | None, work_kind: str, - monitor_deadline: str | None, report_window: dict[str, Any] | None, - quota_observation: dict[str, Any] | None = None) -> dict[str, Any]: + + def _prepare_submission( + self, + binding: dict[str, object] | None, + *, + turn_instance_id: str, + todo_id: str | None, + validation_command: Sequence[str] | None, + work_kind: str, + monitor_deadline: str | None, + report_window: dict[str, object] | None, + quota_observation: dict[str, object] | None = None, + ) -> dict[str, object]: """Read original request/recovery identity without accepting any work.""" if binding is None: raise ValueError("the original steward binding is unavailable") - actor = binding.get("managed_actor") + actor = as_optional_dict(binding.get("managed_actor")) if not actor: raise ValueError("prepare the original steward identity first") - request = {"operation": "native_turn", "host": "codex-app-server", "actor": actor, - "turn_instance_id": turn_instance_id, "todo_id": todo_id, + session_id = str(actor["session_id"]) + request: dict[str, object] = { + "operation": "native_turn", + "host": "codex-app-server", + "actor": actor, + "turn_instance_id": turn_instance_id, + "todo_id": todo_id, "work_kind": work_kind, - "validation_command": list(validation_command) if validation_command is not None else None} + "validation_command": list(validation_command) if validation_command is not None else None, + } if work_kind == "report": if not report_window: raise ValueError("a report requires its original admitted calendar window") - request.update(report_window_id=report_window["window_id"], - report_subscription_revision=report_window["subscription_revision"]) + request.update( + report_window_id=report_window["window_id"], + report_subscription_revision=report_window["subscription_revision"], + ) client_id = native_steward_client_id(actor, turn_instance_id) existing = ( - self._lookup_monitor_turn(binding["binding_id"], actor, client_id) + self._lookup_monitor_turn(str(binding["binding_id"]), actor, client_id) if work_kind == "monitor" - else self.store.turn_for_client(actor["session_id"], client_id) + else self.store.turn_for_client(session_id, client_id) ) if quota_observation is not None: if binding != quota_observation["binding"]: raise ValueError("the original steward authorization changed during quota observation") - # Refence execution evidence after slow metadata IO; ordinary SSE - # read counters do not change the original request or its effects. - original = quota_observation["original"] - if existing is None or any(existing.get(key) != original.get(key) for key in ( + original = as_mapping(quota_observation["original"]) + if existing is None or any( + existing.get(key) != original.get(key) + for key in ( "turn_id", "client_turn_id", "status", "loopx_request", "response", - "upstream_turn_id", "delta_count", "error_code", "error", "loopx_execution")): + "upstream_turn_id", "delta_count", "error_code", "error", "loopx_execution", + ) + ): raise ValueError("the original report changed during quota observation") - launch_recovery = None - selection_recovery = None + launch_recovery: dict[str, object] | None = None + selection_recovery: dict[str, object] | None = None if existing is not None: - # Never replay a failed/unknown model Turn. A committed Chat - # request is observed; native journal recovery remains separate. - frozen = {key: value for key, value in (existing.get("loopx_request") or {}).items() - if key not in {"monitor_lease_version", "monitor_deadline"}} + frozen = { + key: value + for key, value in as_mapping(existing.get("loopx_request")).items() + if key not in {"monitor_lease_version", "monitor_deadline"} + } frozen.setdefault("work_kind", "native_turn") comparable_frozen = ( {**frozen, "validation_command": request["validation_command"]} - if work_kind == "report" and _same_report_validator_command( - frozen.get("validation_command"), request.get("validation_command")) + if work_kind == "report" + and _same_report_validator_command(frozen.get("validation_command"), request.get("validation_command")) else frozen ) - if comparable_frozen != request or work_kind == "monitor" and existing["loopx_request"].get("monitor_deadline") != monitor_deadline: + if ( + comparable_frozen != request + or work_kind == "monitor" + and as_mapping(existing.get("loopx_request")).get("monitor_deadline") != monitor_deadline + ): raise ValueError("native steward request identity conflict") if work_kind == "report": + assert report_window is not None retained = report_turn(self.store, actor, report_window) if retained is not None and retained["turn_id"] != existing["turn_id"]: return {"turn": retained} if quota_observation is None: return {"turn": existing, "quota_probe": {"original": existing, "binding": binding}} - quota_request = quota_observation["request"] + quota_request = as_optional_dict(quota_observation.get("request")) if quota_request is not None: - if _same_report_validator_command(quota_request.get("validation_command"), request.get("validation_command")): + if _same_report_validator_command( + quota_request.get("validation_command"), request.get("validation_command") + ): quota_request = {**quota_request, "validation_command": request["validation_command"]} request = quota_request - client_id = native_steward_client_id(actor, request["turn_instance_id"]) + client_id = native_steward_client_id(actor, str(request["turn_instance_id"])) existing = None if existing is not None: - # Keep the separately proven legacy admission-refusal route - # below ahead of broader runtime-error observation candidates. - recovery = (self.monitor_restart_carrier(existing, client_id) - if work_kind == "monitor" and not self._monitor_selection_failed_before_poll(existing) else None) + recovery = ( + self.monitor_restart_carrier(existing, client_id) + if work_kind == "monitor" and not self._monitor_selection_failed_before_poll(existing) + else None + ) if recovery is not None: if "turn" in recovery: - return recovery - request, client_id, existing = recovery["request"], recovery["client_id"], None + return {"turn": recovery["turn"]} + request = as_dict(recovery["request"]) + client_id = str(recovery["client_id"]) + existing = None if existing is not None: monitor_retry = work_kind == "monitor" and self._monitor_selection_failed_before_poll(existing) if not monitor_retry and work_kind != "report": return {"turn": existing} - # One separately correlated retry after the proven admission - # failure. Retain the failed Chat Turn and original native - # observation identity; that poll's owner remains idempotent. client_id = native_steward_client_id(actor, turn_instance_id + ".admission-retry") retry = ( - self._lookup_monitor_turn(binding["binding_id"], actor, client_id) + self._lookup_monitor_turn(str(binding["binding_id"]), actor, client_id) if work_kind == "monitor" - else self.store.turn_for_client(actor["session_id"], client_id) + else self.store.turn_for_client(session_id, client_id) ) if retry is not None: if work_kind != "report": @@ -1162,7 +748,7 @@ def _prepare_submission(self, binding: dict[str, Any] | None, *, turn_instance_i if selection_recovery is None or "probe" not in selection_recovery: return {"turn": retry} client_id = native_steward_client_id(actor, turn_instance_id + ".admission-resume") - resumed = self.store.turn_for_client(actor["session_id"], client_id) + resumed = self.store.turn_for_client(session_id, client_id) if resumed is not None: return {"turn": resumed} if work_kind == "report" and selection_recovery is None: @@ -1171,829 +757,212 @@ def _prepare_submission(self, binding: dict[str, Any] | None, *, turn_instance_i launch_recovery = self._report_launch_recovery(existing) if launch_recovery is None: return {"turn": existing} - request["resume_turn_key"] = existing["response"]["native_loopx"].get("resume_turn_key") - return {"request": request, "client_id": client_id, - "launch_recovery": launch_recovery, "selection_recovery": selection_recovery} - - def submit(self, binding_id: str, *, turn_instance_id: str, todo_id: str | None = None, - validation_command: Sequence[str] | None = None, - work_kind: str = "native_turn", monitor_deadline: str | None = None, - report_window: dict[str, Any] | None = None) -> tuple[dict[str, Any], bool]: - """Internal host entrypoint; busy conversations retain work with caller. - - No HTTP or model tool exposes this method. Calendar/monitor admission - remains with its native owner; preparing identity never calls submit. - """ + request["resume_turn_key"] = as_mapping(as_mapping(existing.get("response")).get("native_loopx")).get( + "resume_turn_key" + ) + return { + "request": request, + "client_id": client_id, + "launch_recovery": launch_recovery, + "selection_recovery": selection_recovery, + } + + def submit( + self, + binding_id: str, + *, + turn_instance_id: str, + todo_id: str | None = None, + validation_command: Sequence[str] | None = None, + work_kind: str = "native_turn", + monitor_deadline: str | None = None, + report_window: dict[str, object] | None = None, + ) -> tuple[dict[str, object], bool]: + """Internal host entrypoint; busy conversations retain work with caller.""" controller = self.controller - parameters = dict(turn_instance_id=turn_instance_id, todo_id=todo_id, - validation_command=validation_command, work_kind=work_kind, - monitor_deadline=monitor_deadline, report_window=report_window) - - def inspect_submission(quota_observation: dict[str, Any] | None = None) -> dict[str, Any]: - # History and recovery reads can be slow. Inspect one atomic - # binding snapshot without blocking input, and check it again even - # if this only returns an existing Turn. Admission is fenced below. + + def inspect_submission(quota_observation: dict[str, object] | None = None) -> dict[str, object]: binding = self._submission_binding(binding_id) - inspected = self._prepare_submission(binding, **parameters, quota_observation=quota_observation) + inspected = self._prepare_submission( + binding, + turn_instance_id=turn_instance_id, + todo_id=todo_id, + validation_command=validation_command, + work_kind=work_kind, + monitor_deadline=monitor_deadline, + report_window=report_window, + quota_observation=quota_observation, + ) if binding != self._submission_binding(binding_id): raise ValueError("the original steward authorization changed during submission inspection") return inspected prepared = inspect_submission() - quota_observation = None + quota_observation: dict[str, object] | None = None if "quota_probe" in prepared: - quota_observation = prepared["quota_probe"] - original_turn = quota_observation["original"] + quota_observation = as_dict(prepared["quota_probe"]) + original_turn = as_mapping(quota_observation["original"]) quota_observation["request"] = ( self.report_quota_request(original_turn, report_window=report_window) or self.report_timeout_request(original_turn) ) prepared = inspect_submission(quota_observation) if "turn" in prepared: - return prepared["turn"], False - observed = self._observe(prepared["request"]["actor"]) - retained = None + return as_dict(prepared["turn"]), False + observed = self._observe(as_mapping(as_mapping(prepared["request"])["actor"])) + retained: dict[str, object] | None = None if work_kind == "monitor": from .steward_commands import native_command + if not todo_id or not monitor_deadline: raise ValueError("a native watch requires its original Todo and deadline") - retained = native_command(controller, ["task-lease", "inspect", "--goal-id", prepared["request"]["actor"]["goal_id"], - "--todo-id", todo_id]).get("lease") + actor_goal = str(as_mapping(as_mapping(prepared["request"])["actor"])["goal_id"]) + retained = as_optional_dict( + as_mapping( + native_command(controller, ["task-lease", "inspect", "--goal-id", actor_goal, "--todo-id", todo_id]) + ).get("lease") + ) + if self.bindings is None: + raise ValueError("the original steward binding is unavailable") with controller.lock, exclusive_file_lock(self.bindings.path, operation="admit_native_steward_turn"): - current = self._prepare_submission(self._submission_binding(binding_id), **parameters, - quota_observation=quota_observation) + current = self._prepare_submission( + self._submission_binding(binding_id), + turn_instance_id=turn_instance_id, + todo_id=todo_id, + validation_command=validation_command, + work_kind=work_kind, + monitor_deadline=monitor_deadline, + report_window=report_window, + quota_observation=quota_observation, + ) if "turn" in current: - return current["turn"], False + return as_dict(current["turn"]), False if current["request"] != prepared["request"] or current["client_id"] != prepared["client_id"]: raise ValueError("the original native steward submission changed during identity verification") - request, client_id = current["request"], current["client_id"] - actor = request["actor"] - session = self.store.load_session(actor["session_id"]) + request = as_dict(current["request"]) + client_id = str(current["client_id"]) + actor = as_mapping(request["actor"]) + session_id = str(actor["session_id"]) + session = self.store.load_session(session_id) if not session or not session.get("steward_context"): raise ValueError("the original steward Session is unavailable") carrier = self._ensure_background_session(binding_id, session) if work_kind == "monitor" else None if work_kind == "monitor": - request.update(monitor_deadline=monitor_deadline, - monitor_lease_version=retained["version"] if retained else 0) - admitted = self._admit(request, observed=observed, carrier_session=carrier, - launch_recovery=current["launch_recovery"], selection_recovery=current["selection_recovery"]) + request.update( + monitor_deadline=monitor_deadline, + monitor_lease_version=retained["version"] if retained else 0, + ) + admitted = self._admit( + request, + observed=observed, + carrier_session=carrier, + launch_recovery=as_optional_dict(current.get("launch_recovery")), + selection_recovery=as_optional_dict(current.get("selection_recovery")), + ) target_session = carrier if carrier is not None else session - target_session_id = target_session["session_id"] - accepted = self.store.accept_managed_turn(target_session_id, client_turn_id=client_id, + target_session_id = str(target_session["session_id"]) + accepted = self.store.accept_managed_turn( + target_session_id, + client_turn_id=client_id, message="Advance the currently admitted native LoopX work.", - display_message="检查授权工作状态。" if work_kind == "monitor" else - "生成本期授权项目日报。" if work_kind == "report" else "推进管家的 LoopX 任务。", origin="native_loopx", - loopx_execution=True, loopx_request=request) + display_message=( + "检查授权工作状态。" if work_kind == "monitor" + else "生成本期授权项目日报。" if work_kind == "report" + else "推进管家的 LoopX 任务。" + ), + origin="native_loopx", + loopx_execution=True, + loopx_request=request, + ) try: - if (not admitted["observation_only"] and work_kind != "report" - and actor.get("schema_version") == "loopx_steward_managed_actor_v0" - and session and session.get("steward_context")): + if ( + not admitted["observation_only"] + and work_kind != "report" + and actor.get("schema_version") == "loopx_steward_managed_actor_v0" + and session.get("steward_context") + ): from ..manager_context import register_ingress - register_ingress(self.controller.coordination_runtime_root, - session_id=actor["session_id"], client_turn_id=client_id, - channel=session["channel_id"], sender_id=session["steward_context"]["operator_ref"], - message=accepted.turn["message"], + register_ingress( + self.controller.coordination_runtime_root, + session_id=session_id, + client_turn_id=client_id, + channel=str(session["channel_id"]), + sender_id=str(as_mapping(session["steward_context"])["operator_ref"]), + message=str(accepted.turn["message"]), source_id=f"native_steward:{actor['goal_id']}:{request['turn_instance_id']}", - origin="native_loopx") + origin="native_loopx", + ) if admitted["observation_only"]: from .steward_monitor import StewardObservationAdapter - adapter = StewardObservationAdapter(target_session.get("upstream_thread_id")) + + adapter: object = StewardObservationAdapter(as_optional_str(target_session.get("upstream_thread_id"))) else: - adapter = controller._ensure_adapter_locked(session, - work_dir=Path(admitted["workspace_path"]), + adapter = controller._ensure_adapter_locked( + session, + work_dir=Path(str(admitted["workspace_path"])), objective="Maintain the original steward's authorized monitoring work.", - accepted_turn_id=accepted.turn["turn_id"]) - controller._start_accepted_turn_worker(session_id=target_session_id, - turn_id=accepted.turn["turn_id"], message=accepted.turn["message"], - attachments=[], adapter=adapter, loopx_execution=True) + accepted_turn_id=str(accepted.turn["turn_id"]), + ) + controller._start_accepted_turn_worker( + session_id=target_session_id, + turn_id=str(accepted.turn["turn_id"]), + message=str(accepted.turn["message"]), + attachments=[], + adapter=cast("ChatRuntimeAdapter", adapter), + loopx_execution=True, + ) except Exception as exc: - controller._fail_queue_preparation(target_session_id, accepted.turn["turn_id"], exc) + controller._fail_queue_preparation(target_session_id, str(accepted.turn["turn_id"]), exc) raise return accepted.turn, accepted.created - def _steward_followup_context(self, actor: Mapping[str, Any], session_id: str, - request: Mapping[str, Any], authority: Mapping[str, Any]) -> dict[str, Any]: - from ...control_plane.todos.list_readback import list_goal_todos - from .steward_monitor import FOLLOWUP_TARGET_PREFIX, steward_monitor_snapshot_path - todo_id = (authority.get("_work_identity") or {}).get("todo_id") or request.get("todo_id") - agent_todos = list_goal_todos(registry_path=self.controller.registry_path, - runtime_root_arg=str(self.controller.coordination_runtime_root), - goal_id=actor["goal_id"], agent_id=actor["agent_id"], role="agent").get("todos", []) - selected = next((row for row in agent_todos if row.get("todo_id") == todo_id), None) - payload: dict[str, Any] = {"selected_todo": selected} - target_key = str((selected or {}).get("target_key") or "") - if target_key.startswith(FOLLOWUP_TARGET_PREFIX): - source_id = target_key.removeprefix(FOLLOWUP_TARGET_PREFIX) - payload["source_monitor"] = next((row for row in agent_todos if row.get("todo_id") == source_id), None) - snap = steward_monitor_snapshot_path(self.controller.coordination_runtime_root, actor["goal_id"], source_id) - if snap.is_file(): - try: - payload["signal_snapshot"] = json.loads(snap.read_text(encoding="utf-8")) - except (OSError, ValueError): - payload["signal_snapshot"] = None - user_todos = list_goal_todos(registry_path=self.controller.registry_path, - runtime_root_arg=str(self.controller.coordination_runtime_root), - goal_id=actor["goal_id"], role="user").get("todos", []) - payload["open_user_todos"] = [ - {k: row.get(k) for k in ("todo_id", "status", "priority", "text", "updated_at")} - for row in user_todos if row.get("status") == "open" - ][:40] - prior: list[dict[str, Any]] = [] - for msg in reversed(self.store.messages(session_id)[-30:]): - tid = msg.get("turn_id") - if not tid: - continue - turn_row = self.store.load_turn(session_id, tid) - resp = (turn_row or {}).get("response") or {} - receipts = list(resp.get("context_handoff_receipts") or []) - if resp.get("context_handoff_receipt"): - receipts.append(resp["context_handoff_receipt"]) - for receipt in receipts: - if isinstance(receipt, dict): - prior.append({k: receipt.get(k) for k in ("goal_id", "agent_id", "source_id", "request_id", "delivered_at")}) - payload["prior_handoff_receipts"] = prior[:40] - return payload - - def _governance_replan_context(self, actor: Mapping[str, Any], authority: Mapping[str, Any]) -> dict[str, Any]: - """Project public-safe review/writeback/vision context for text-only Steward replanning.""" - from ...cli_runtime import _build_selected_parser - from ...cli_commands.quota_native_context import read_replan_view - from ...control_plane.goals.goal_frontier import latest_agent_vision_from_status_payload - from ...control_plane.todos.list_readback import list_goal_todos - from .steward_commands import NativeStewardCommandError, native_command - - model_input = authority.get("_model_input") - detail_ref = model_input.get("detail_ref") if isinstance(model_input, Mapping) else None - detail_packet = detail_ref.get("replan_action_packet") if isinstance(detail_ref, Mapping) else None - auth_packet = authority.get("replan_action_packet") - packet = ( - detail_packet - if isinstance(detail_packet, Mapping) and ("review" in detail_packet or "writeback" in detail_packet) - else auth_packet - ) + def _steward_followup_context( + self, + actor: Mapping[str, object], + session_id: str, + request: Mapping[str, object], + authority: Mapping[str, object], + ) -> dict[str, object]: + return steward_followup_context(self, actor, session_id, request, authority) + + def _governance_replan_context( + self, actor: Mapping[str, object], authority: Mapping[str, object] + ) -> dict[str, object]: + return governance_replan_context(self, actor, authority) - def _read_stage(cmd_str: Any) -> dict[str, Any] | None: - if not isinstance(cmd_str, str) or not cmd_str.strip(): - return None - try: - tokens = shlex.split(cmd_str) - q_idx = tokens.index("quota") - parsed = _build_selected_parser("quota").parse_args(tokens[q_idx:]) - view = read_replan_view(parsed) - if isinstance(view, Mapping) and view.get("ok") is True: - return dict(view) - except (OSError, ValueError, KeyError, TypeError, RuntimeError, EffectRuntimeRejected, SystemExit): - return None - return None + @staticmethod + def _normalize_steward_actions( + candidate: Mapping[str, object], context: Mapping[str, object] + ) -> dict[str, object]: + return normalize_steward_actions(candidate, context) - payload: dict[str, Any] = {} - if isinstance(packet, Mapping): - review_view = _read_stage(packet.get("review")) - if review_view is not None: - core_goal = review_view.get("core_goal") - payload["review"] = { - "obligation_id": review_view.get("obligation_id"), - "context_id": review_view.get("context_id"), - "objective": core_goal.get("objective") if isinstance(core_goal, Mapping) else None, - "triggers": review_view.get("triggers"), - "recent_evidence": list(review_view.get("evidence") or [])[:12], - "decision_followthrough": review_view.get("decision_followthrough"), - } - writeback_view = _read_stage(packet.get("writeback")) - if writeback_view is not None: - payload["writeback"] = { - "obligation_id": writeback_view.get("obligation_id"), - "context_id": writeback_view.get("context_id"), - "required_outcome": writeback_view.get("required_outcome"), - "writeback_contract": writeback_view.get("writeback_contract"), - "stride_control": writeback_view.get("stride_control"), - } - try: - status_payload = native_command(self.controller, ["status", "--goal-id", actor["goal_id"]]) - latest_vision = latest_agent_vision_from_status_payload( - status_payload, goal_id=actor["goal_id"], agent_id=actor["agent_id"], - ) - if isinstance(latest_vision, Mapping): - payload["current_agent_vision"] = { - k: latest_vision.get(k) - for k in ("schema_version", "state", "vision_patch", "todo_delta") - if latest_vision.get(k) is not None - } - except (NativeStewardCommandError, OSError, ValueError, KeyError, TypeError, RuntimeError): - pass - try: - agent_todos = list_goal_todos( - registry_path=self.controller.registry_path, - runtime_root_arg=str(self.controller.coordination_runtime_root), - goal_id=actor["goal_id"], - role="agent", - ).get("todos", []) - payload["open_agent_todos"] = [ - {k: row.get(k) for k in ("todo_id", "task_class", "priority", "target_key", "title")} - for row in agent_todos - if row.get("status") == "open" - ][:16] - except (NativeStewardCommandError, OSError, ValueError, KeyError, TypeError, RuntimeError): - pass - return payload + def _apply_steward_user_actions( + self, actor: Mapping[str, object], actions: Sequence[Mapping[str, str]], turn_instance_id: str + ) -> list[dict[str, object]]: + return apply_steward_user_actions(self, actor, actions, turn_instance_id) - @staticmethod - def _normalize_steward_actions(candidate: Mapping[str, Any], context: Mapping[str, Any]) -> dict[str, Any]: - from ...control_plane.collaboration.inbox import normalize_handoff - state: dict[str, Any] = {"context_handoff": None, "user_actions": [], "owner_report": None, "validation_error": None} - allowed_targets = { - (row["goal_id"], row["agent_id"]) - for row in ((context.get("context_delegation") or {}).get("targets") or []) - if isinstance(row, Mapping) and row.get("goal_id") and row.get("agent_id") - } - raw_handoff = candidate.get("context_handoff") - if raw_handoff is not None: - try: - normalized = normalize_handoff(raw_handoff) - except ValueError as exc: - state["validation_error"] = f"invalid context_handoff: {exc}" - return state - if normalized: - items = normalized if isinstance(normalized, list) else [normalized] - for item in items: - if (item["goal_id"], item["agent_id"]) not in allowed_targets: - state["validation_error"] = f"unauthorized context_handoff recipient: {item['goal_id']}/{item['agent_id']}" - return state - state["context_handoff"] = normalized - raw_actions = candidate.get("steward_user_actions") - if raw_actions is not None: - if not isinstance(raw_actions, list) or len(raw_actions) > 16: - state["validation_error"] = "steward_user_actions must be a bounded list of at most 16 items" - return state - cleaned: list[dict[str, str]] = [] - seen_keys: set[str] = set() - for item in raw_actions: - if not isinstance(item, Mapping): - state["validation_error"] = "each steward_user_actions entry must be an object" - return state - key = str(item.get("dedupe_key") or "").strip().lower() - text = " ".join(str(item.get("text") or "").split()).strip() - prio = str(item.get("priority") or "P1").strip().upper() - if (not _USER_ACTION_DEDUPE_KEY.fullmatch(key) or key in seen_keys - or not text or len(text) > 800 or prio not in {"P0", "P1", "P2"}): - state["validation_error"] = "invalid steward_user_actions entry" - return state - seen_keys.add(key) - cleaned.append({"dedupe_key": key, "priority": prio, "text": text}) - state["user_actions"] = cleaned - raw_report = candidate.get("steward_owner_report") - if raw_report is not None: - markdown = raw_report.get("markdown") if isinstance(raw_report, Mapping) else raw_report - if not isinstance(markdown, str): - state["validation_error"] = "steward_owner_report must be a markdown string or {markdown}" - return state - normalized_report = markdown.strip() - if not normalized_report or len(normalized_report) > 24000: - state["validation_error"] = "steward_owner_report markdown must be 1..24000 characters" - return state - state["owner_report"] = normalized_report - return state - - def _apply_steward_user_actions(self, actor: Mapping[str, Any], actions: Sequence[Mapping[str, str]], - turn_instance_id: str) -> list[dict[str, Any]]: - if not actions: - return [] - from ...control_plane.todos.list_readback import list_goal_todos - from .steward_commands import native_command - existing = list_goal_todos(registry_path=self.controller.registry_path, - runtime_root_arg=str(self.controller.coordination_runtime_root), - goal_id=actor["goal_id"], role="user").get("todos", []) - open_by_key: dict[str, tuple[dict[str, Any], str]] = {} - for row in existing: - if row.get("status") != "open": - continue - title = str(row.get("title") or "").strip() or re.sub( - r"^\[p\d\]\s*", "", str(row.get("text") or ""), flags=re.IGNORECASE, - ).strip() - if title.startswith("[") and "]" in title: - open_by_key[title[1:title.index("]")].strip().lower()] = (row, title) - receipts: list[dict[str, Any]] = [] - for idx, action in enumerate(actions): - key, prio, body = action["dedupe_key"], action["priority"], action["text"] - rendered = f"[{key}] {body}" - op_id = "steward-ua." + hashlib.sha256(f"{turn_instance_id}:{idx}:{key}".encode()).hexdigest()[:24] - matched = open_by_key.get(key) - if matched is not None: - prior, prior_title = matched - if prior_title == rendered and str(prior.get("priority") or "") == prio: - receipts.append({"dedupe_key": key, "action": "unchanged", "todo_id": prior["todo_id"]}) - continue - res = native_command(self.controller, ["todo", "update", "--goal-id", actor["goal_id"], - "--role", "user", "--agent-id", actor["agent_id"], "--todo-id", prior["todo_id"], - "--text", rendered, - *(["--note", f"Priority: {prio}"] if str(prior.get("priority") or "") != prio else []), - "--update-operation-id", op_id, "--execute"]) - receipts.append({"dedupe_key": key, "action": "updated", "todo_id": prior["todo_id"], "ok": res.get("ok")}) - else: - res = native_command(self.controller, ["todo", "add", "--goal-id", actor["goal_id"], - "--role", "user", "--task-class", "user_action", "--priority", prio, - "--text", rendered, "--bound-agent", actor["agent_id"], - "--operation-id", op_id, "--execute"]) - receipts.append({"dedupe_key": key, "action": "added", "todo_id": res.get("todo_id"), "ok": res.get("ok")}) - return receipts - - def execute(self, *, session_id: str, turn_id: str, adapter: Any, - event_sink: Any, context: dict[str, Any]) -> dict[str, Any]: + def execute( + self, + *, + session_id: str, + turn_id: str, + adapter: object, + event_sink: object, + context: dict[str, object], + ) -> dict[str, object]: """Run in the original Chat worker, through all native settlement owners.""" - from ...cli_runtime import _build_selected_parser - from ...cli_commands.turn import handle_turn_command - from ...control_plane.turn_driver.host_candidate import extract_turn_authority, render_prompt, parse_model_json, build_result - from .antigravity_adapter import AntigravityAdapter - from .codex_adapter import CodexAppServerAdapter - - turn = self.store.load_turn(session_id, turn_id) - request = turn["loopx_request"] - original_client = ("managed." + request["turn_instance_id"].removeprefix("managed-session.") - if request["actor"].get("schema_version") == "loopx_managed_session_actor_v0" - else native_steward_client_id(request["actor"], request["turn_instance_id"])) - original = self.store.turn_for_client(session_id, original_client) if request.get("work_kind") == "report" else None - selection_recovery = (self.report_selection_recovery(original) - if original and original["turn_id"] != turn_id else None) - resumed_client = (original_client + ".admission-resume" - if request["actor"].get("schema_version") == "loopx_managed_session_actor_v0" - else native_steward_client_id(request["actor"], request["turn_instance_id"] + ".admission-resume")) - if selection_recovery and turn["client_turn_id"] == resumed_client: - retry_client = (original_client + ".admission-retry" - if request["actor"].get("schema_version") == "loopx_managed_session_actor_v0" - else native_steward_client_id(request["actor"], request["turn_instance_id"] + ".admission-retry")) - retry = self.store.turn_for_client(session_id, retry_client) - if retry is None: - raise ValueError("the original admission probe is unavailable") - selection_recovery = self.report_selection_recovery(original, probe_turn=retry) - if selection_recovery is None: - raise ValueError("the original admission probe has no canonical journal") - admitted = self._admit(request, turn=turn, selection_recovery=selection_recovery) - actor = admitted["actor"] - local_session = actor.get("schema_version") == "loopx_managed_session_actor_v0" - report_work = request.get("work_kind") == "report" - steward_advancement = not local_session and not report_work - managed_turn = ManagedSessionTurn(self.controller) if local_session and not report_work else None - if admitted["observation_only"]: - from .steward_monitor import StewardMonitor - monitor = StewardMonitor(self.controller) - todo = next((row for row in monitor.todos(actor) if row["todo_id"] == request["todo_id"]), None) - return monitor.observe(host=self, request=request, turn=turn, context=context, todo=todo) - if local_session and not isinstance(adapter, CodexAppServerAdapter): - raise ValueError("native steward work requires the original Codex app-server adapter") - if not local_session and not isinstance(adapter, (CodexAppServerAdapter, AntigravityAdapter)): - raise ValueError("native steward work requires the original Codex app-server or Antigravity adapter") - original_thread = adapter.upstream_thread_id - from .steward_reports import report_service - reports, report_owner_key = report_service(self.controller, actor) if report_work else (None, None) - report_context = "" - governance_work = False - report_launch_rejected = False - managed_answer = "" - managed_lease, managed_lease_request = None, None - preparation_status = None - steward_actions_state: dict[str, Any] = {"context_handoff": None, "user_actions": [], "owner_report": None, "validation_error": None} - - def report_lease_proof(): - return self._task_lease_proof(request, report_lease) - - def current(observed=None): - fresh = self.store.load_turn(session_id, turn_id) - self._admit(request, turn=fresh, observed=observed, selection_recovery=selection_recovery) - if adapter.upstream_thread_id != original_thread: - raise ValueError("the original steward native thread changed") - if report_lease: - report_lease_proof() - if managed_lease: - self._task_lease_proof(managed_lease_request, managed_lease) - - def session_binding(envelope: Mapping[str, Any]) -> dict[str, Any]: - current() - identity = (envelope.get("agent_identity") if envelope.get("schema_version") == "loopx_turn_envelope_v1" - else envelope) - if (envelope.get("goal_id") != actor["goal_id"] or not isinstance(identity, Mapping) - or identity.get("agent_id") != actor["agent_id"]): - raise ValueError("native Turn belongs to another actor") - return {"schema_version": "loopx_turn_session_binding_v0", - "goal_id": actor["goal_id"], "agent_id": actor["agent_id"]} - - def prepare_native_task(decision: Mapping[str, Any]) -> str | None: - nonlocal managed_lease, managed_lease_request, preparation_status - from ...control_plane.turn_driver.codex_execution_preparation import compact_execution_preparation_request - - preparation = compact_execution_preparation_request(decision) - if preparation is None: - return None - todo_id = preparation["todo_id"] - if (preparation["goal_id"] != actor["goal_id"] or preparation["agent_id"] != actor["agent_id"] - or preparation.get("turn_instance_id", request["turn_instance_id"]) != request["turn_instance_id"] - or (request["todo_id"] is not None and todo_id != request["todo_id"])): - raise ValueError("native task preparation belongs to another Turn or Todo") - current() - if managed_turn is not None: - try: - managed_turn.prepare_validation(request, {"work_contract": decision}) - except ManagedTaskValidationUnavailable: - managed_turn.validation_unavailable = True - preparation_status = "stopped" - raise - except ValueError: - preparation_status = "failed" - raise - managed_lease_request = {**request, "todo_id": todo_id} - managed_lease = managed_leases.enter_context(self._task_execution_lease( - managed_lease_request, turn_id, claim_args=preparation["claim_args"], - )) - return todo_id - - def run(native_request: Mapping[str, Any], launch_scope: Any) -> dict[str, Any]: - nonlocal managed_lease, managed_lease_request, managed_answer - current() - authority = extract_turn_authority(native_request) - if governance_work and not authority.get("replan_action_packet"): - return build_result(native_request, {"result_kind": "wait", "classification": "report_replan_not_admitted", - "next_action": "Retain the original report; its native governance route is no longer admitted."}) - if managed_turn and not governance_work: - try: - managed_turn.prepare_validation(request, native_request, - _checked_work_identity=authority.get("_work_identity")) - except ManagedTaskValidationUnavailable: - managed_turn.validation_unavailable = True - return build_result(native_request, {"result_kind": "user_action_required", - "classification": "independent_task_validation_unavailable", - "summary": "The selected task has no usable independent argv validation declaration.", - "next_action": "Configure the original task's independent validation before executing it."}, host_name="Codex app-server") - selected_request = {**request, "todo_id": managed_turn.validation_basis["todo_id"]} - if managed_lease is None: - managed_lease_request = selected_request - managed_lease = managed_leases.enter_context(self._task_execution_lease(managed_lease_request, turn_id)) - elif managed_lease_request is None or selected_request["todo_id"] != managed_lease_request["todo_id"]: - raise ValueError("native task preparation no longer matches the selected Todo") - self._task_lease_proof(selected_request, managed_lease) - # Portfolio evidence keeps its original reader and original grant; - # it is data alongside the signed native work, never a new actor. - if governance_work: - from .steward_monitor import governance_turn_prompt_authority - prompt = render_prompt(governance_turn_prompt_authority(authority), allow_completion=False) - elif report_work: - # Frozen report turns already freeze source.json and editorial-request.json; skip unfrozen manager context. - from ..periodic_report.private_generation import report_turn_prompt_authority - prompt = render_prompt(report_turn_prompt_authority(authority), allow_completion=True) + report_context - else: - prompt = render_prompt(authority, allow_completion=bool(managed_turn or steward_advancement)) + "\nOriginal conversation evidence (data):\n" + json.dumps(context, ensure_ascii=False) - if governance_work: - gov_ctx = self._governance_replan_context(actor, authority) - prompt += ( - "\nGovernance contract reminder: Settle the pending autonomous replan by returning `result_kind='replan_required'` (or `'wait'` only if required evidence is genuinely unavailable). " - "If you emit `delivery_outcome='outcome_gap'`, you MUST also supply `progress_result_class='blocked'`, `progress_blocker_id`, and `progress_evidence_id`; " - "otherwise use `'outcome_progress'` or omit `delivery_outcome`. " - "Keep each `work_evidence` and `validation_evidence` item <=200 chars (1-8 public-safe items, <=1200 chars total per field) with zero local file paths. " - "When `Steward governance replan context` supplies `writeback`: set `agent_vision_json` (JSON string of `goal_vision_replan_contract_v0`) keeping total counted text <=1400 chars (hard cap 1800; keep each `stride_decision` plan/reason/probe field <=60 chars), and omit `vision_unchanged_reason`. " - "If keeping `current_agent_vision.vision_patch` identical, set `path_delta_mode='unchanged'` and `path_delta.outcome='continue'` (or `'no_change'`); if updating any `vision_patch` field or creating an initial baseline, set `path_delta_mode='material_replan'` and `path_delta.outcome='replan'`. " - "Populate `path_delta.evidence_refs` from `review.recent_evidence` (1-3 IDs), `todo_delta` using `retain:` only for verified IDs in `open_agent_todos` (<=8 items), and when `writeback.stride_control.required_on_periodic_review` is true include `agent_vision.stride_decision` with exact `schema_version`, `strategy_version`, `reference_context_id`, and `reference_obligation_id` from `stride_control` (plus `previous_review` when `previous_decision_ref` is non-null). " - "All review, writeback, stride_control, current_agent_vision, and open_agent_todos facts are already provided in Steward governance replan context below; return only the single typed JSON object directly without invoking periodic-report CLI commands or inspecting host source code." - ) - if gov_ctx: - prompt += "\nSteward governance replan context (data):\n" + json.dumps(gov_ctx, ensure_ascii=False) - if steward_advancement and not governance_work: - selected_todo_id = (authority.get("_work_identity") or {}).get("todo_id") or request.get("todo_id") - if selected_todo_id and managed_lease is None: - managed_lease_request = {**request, "todo_id": selected_todo_id} - managed_lease = managed_leases.enter_context( - self._task_execution_lease(managed_lease_request, turn_id)) - followup_ctx = self._steward_followup_context(actor, session_id, request, authority) - prompt += ( - "\nSteward advancement instructions: Evaluate the monitor prompt and signal snapshot against authorized recipients (`context_delegation.targets`), prior receipts (`prior_handoff_receipts`, avoid duplicate delivery for unchanged PR@headRefOid), and open user todos (`open_user_todos`). " - "When `signal_snapshot.repository_snapshot.items` is present, each PR carries `mergeable`, `checks_summary`, `bypassed_gates`, `stalled_since`, `author_replied_after_request_changes`, optional `stalled_bucket` (`awaiting_maintainer_reply` | `under_24h` | `24h_to_72h` | `72h_plus` | `7d_plus`), and `review_summary` (`effective_verdict`, `has_review_conflict`, `stale_review_count`, `latest_request_changes_review_id`, `stalled_since`, `author_replied_after_request_changes`, `exact_head_reviews` with `reviewer_declaration`, `valid_verdict_review`, `author_owned_fallback`). Keep triage read-only; never execute merges here. " - "You may include optional top-level JSON fields alongside the normal kernel fields: " - "`context_handoff` (single object or array <=32 of {goal_id, agent_id, brief} with `schema_version='collaboration_brief_v0'` and `inputs=[]` when referencing URLs/PRs, restricted to `context_delegation.targets`), " - "`steward_owner_report` (optional non-empty Markdown string <=24000 chars or `{markdown}` delivered once directly to the bound Steward App and Feishu conversation; omit or set `null` when silent/no report should be sent), " - "and `steward_user_actions` (array <=16 of {dedupe_key, priority:'P0'|'P1'|'P2', text}; do NOT emit per-PR `steward_user_actions` when the monitor prompt asks for an aggregated report). Keep each `work_evidence` and `validation_evidence` item <=200 chars (1-8 items, <=1200 chars total per field). Set `result_kind='validated_completion'` when triage/handoff/report/user-action preparation is complete.\n" - "Steward monitor & dedupe context (data):\n" + json.dumps(followup_ctx, ensure_ascii=False) - ) - if request.get("work_kind") == "scheduled_task": - from .session_calendar_tasks import SessionCalendarTasks - basis = SessionCalendarTasks(self.controller).admission(request) - # Read the completed source Task's criteria and referenced permitted - # artifacts. Calendar configuration cannot install host argv - # or enlarge the original Task's execution scope. - prompt += "\nOriginal native calendar task criteria; existing Goal/Task authority and stop conditions still apply:\n" + json.dumps({ - "task": basis["definition"]["source_task"]["text"], - "source_todo_id": basis["definition"]["source_task"]["todo_id"], - "window_start": basis["window"]["start_at"], "window_end": basis["window"]["due_at"], - }, ensure_ascii=False) - guard_owner = adapter.session if isinstance(adapter, CodexAppServerAdapter) else adapter - previous_guard = guard_owner._launch_guard - - @contextmanager - def launch(): - nonlocal report_launch_rejected - # The existing app-server request owner holds this fence only - # through turn/start publication, never through model waiting. - observed = self._observe(actor) - with ExitStack() as stack: - try: - if previous_guard is not None: - stack.enter_context(previous_guard()) - stack.enter_context(launch_scope()) - stack.enter_context(nullcontext() if actor.get("schema_version") == "loopx_managed_session_actor_v0" - else exclusive_file_lock(self.bindings.path, operation="native_steward_launch")) - current(observed) - except FirstPartyHostRuntimeRejected as exc: - if not report_work or exc.code != "stale_goal_authority": - raise - # Only guard entry is before publication. Let the - # existing native executor durably record its typed - # failure; exceptions after yield remain unknown. - if not local_session and not governance_work and original and original["turn_id"] == turn_id: - report_launch_rejected = True - from ...control_plane.turn_driver.host_failure import BuiltInHostError - raise BuiltInHostError(str(exc), failure_kind="contract_rejected") from exc - yield - - guard_owner._launch_guard = launch - try: - if managed_turn and not governance_work: - from ...control_plane.effect_runtime import effect_runtime_result - policy = effect_runtime_result("collaboration.session.managed_turn.sandbox_policy", { - "host": request["host"], "actor": actor, "authority": authority, - "validation": managed_turn.validation_basis["plan"], "task_lease": managed_lease}) - response = adapter.start_native_task_turn(prompt, event_sink, policy) - else: - # Inline governance (.replan) shares the outer Chat turn_id; suppress - # terminal answer and native-result capture so the primary turn keeps - # the sole immutable native-results/{turn_id}.json and visible stream. - invocation_sink = ( - ( - lambda kind, payload: event_sink(kind, payload) - if kind not in {"answer.delta", "answer.final", "turn.native_result"} - else None - ) - if (governance_work and event_sink is not None) - else event_sink - ) - if (report_work or steward_advancement or governance_work) and isinstance(adapter, AntigravityAdapter): - from .antigravity_adapter import ANTIGRAVITY_IDLE_TIMEOUT_SEC - response = adapter.start_turn( - prompt, - invocation_sink, - isolated_cascade=True, - raw_prompt=True, - idle_timeout_sec=( - adapter.idle_timeout_sec - if adapter.idle_timeout_sec is not None - else ANTIGRAVITY_IDLE_TIMEOUT_SEC - ), - ) - else: - response = adapter.start_turn(prompt, invocation_sink) - finally: - guard_owner._launch_guard = previous_guard - current() # Revocation/stop/retarget after a long model call wins. - candidate = parse_model_json(str(response.get("message") or "")) - kernel_candidate = dict(candidate) if candidate is not None else None - if steward_advancement and not governance_work and kernel_candidate is not None: - steward_actions_state.update(self._normalize_steward_actions(kernel_candidate, context)) - kernel_candidate.pop("context_handoff", None) - kernel_candidate.pop("steward_user_actions", None) - kernel_candidate.pop("steward_owner_report", None) - kernel_candidate = _normalize_steward_advancement_kernel_candidate(kernel_candidate) - elif governance_work and kernel_candidate is not None: - kernel_candidate.pop("context_handoff", None) - kernel_candidate.pop("steward_user_actions", None) - kernel_candidate.pop("steward_owner_report", None) - kernel_candidate = _normalize_steward_advancement_kernel_candidate(kernel_candidate) - if governance_work and kernel_candidate and kernel_candidate.get("result_kind") not in {"replan_required", "wait", "user_action_required", "iteration_failed"}: - kernel_candidate = {"result_kind": "wait", "classification": "report_replan_not_settled", - "next_action": "Retain the original report until its native semantic replan is settled."} - if report_work and not governance_work and kernel_candidate and kernel_candidate.get("result_kind") in {"validated_progress", "validated_completion"}: - observed = self._observe(actor) - with self.controller.lock, self._report_fence(request): - current(observed) - reports.freeze(request, kernel_candidate) - # This finite task's postcondition is the complete validated - # generation, not the model's choice of progress wording. - # The kernel still runs its independent validator and lease - # fence before closing only this window's generation Todo. - kernel_candidate = _normalize_report_kernel_candidate(kernel_candidate) - built = build_result(native_request, kernel_candidate, - host_name="Antigravity" if isinstance(adapter, AntigravityAdapter) else "Codex app-server", - **({"allow_completion": True} if (report_work or managed_turn or steward_advancement) and not governance_work else {})) - managed_answer = str(built.get("summary") or "") if (managed_turn or steward_advancement) else "" - return built - - argv = ["turn", "run-once", "--goal-id", actor["goal_id"], "--agent-id", actor["agent_id"], - "--project", admitted["workspace_path"], "--host", "generic-cli", "--execute"] - if request.get("resume_turn_key"): - # Keep the original plan, Todo, native Turn and settlement identity. - # The kernel rechecks its journal and current launch authority. - argv += ["--resume-turn-key", request["resume_turn_key"], "--retry-failed-turn"] - else: - argv += ["--turn-instance-id", request["turn_instance_id"]] - if request["todo_id"] is not None and not request.get("resume_turn_key"): - argv += ["--todo-id", request["todo_id"]] - if request["validation_command"] is not None: - argv += ["--validation-command-json", json.dumps(request["validation_command"])] - args = _build_selected_parser("turn").parse_args(argv) - # This connection is host-owned, not a command path supplied by a model. - # The kernel records the actual app-server host and independent profile. - args.host, args.session_scope = "codex-app-server", "agent" - result: dict[str, Any] = {} - - def retain_report_lease() -> bool: - failure = result.get("host_failure") or {} - return report_launch_rejected and failure.get("kind") == "contract_rejected" and failure.get("attempt") == 1 - - with ExitStack() as managed_leases, (self._task_execution_lease(request, turn_id, - admission_retry=bool(selection_recovery), retain_for_retry=retain_report_lease) - if report_work else nullcontext(None)) as report_lease: - if not report_work and request.get("todo_id") and not request.get("resume_turn_key"): - # The selected Task's existing lease must precede the kernel's - # delivery guard. Taking it in the model callback is too late: - # the guard correctly withholds a Host launch without it. - from .steward_commands import native_command - selected = native_command(self.controller, ["todo", "list", "--goal-id", actor["goal_id"], - "--todo-id", request["todo_id"], "--agent-id", actor["agent_id"]]) - # Unknown work still reaches the kernel's structured selection - # refusal. An unavailable authority never looks like a miss. - if selected.get("matched") is True: - managed_lease_request = dict(request) - managed_lease = managed_leases.enter_context(self._task_execution_lease(request, turn_id)) - if selection_recovery and "probe" not in selection_recovery: - governance_work = True - - def probe_governance(todo_id: str | None) -> dict[str, Any]: - governance_args = type(args)(**vars(args)) - governance_args.todo_id, governance_args.validation_command_json = todo_id, None - governance_args.turn_instance_id = request["turn_instance_id"] + ".replan" - observed: dict[str, Any] = {} - handle_turn_command(governance_args, registry_path=self.controller.registry_path, - runtime_root_arg=str(self.controller.coordination_runtime_root), - output_format=lambda *_a, **_kw: "json", print_payload=lambda value, *_a: observed.update(value), - native_host_runner=run, native_session_binding_resolver=session_binding) - return observed - - # Probe the original report first. Unbound selection can - # otherwise stop on an unrelated task needing its own lease. - # Only a current typed replan refusal opens the unbound route. - governance = probe_governance(request["todo_id"]) - if (governance.get("error_code") == "turn_todo_selection_deferred" - and (governance.get("selection_rejection") or {}).get("reason_code") == "autonomous_replan"): - governance = probe_governance(None) - self.store.append_event(session_id, turn_id, kind="native_loopx.replan_result", payload=governance) - if governance.get("status") != "committed" or governance.get("result_kind") != "replan_required": - probe = self.report_selection_recovery(original, probe_turn=self.store.load_turn(session_id, turn_id)) - try: - if probe is None or "probe" not in probe: - raise ValueError("no canonical admission probe") - self._admit(request, turn=self.store.load_turn(session_id, turn_id), selection_recovery=probe) - except (OSError, ValueError, RuntimeError): - retained = selection_recovery["original"]["response"]["native_loopx"] - self.store.append_event(session_id, turn_id, kind="native_loopx.result", payload=retained) - return {"schema_version": "loopx_chat_agent_response_v0", "message": "原生重规划尚未完成;保留原报告及执行证据。", - "proposals": [], "gate": None, "native_loopx": retained} - selection_recovery = probe - governance_work = False - if report_work: - # Portfolio collection can take minutes and legitimately see - # registry updates. Finish it before the native driver captures - # its launch witness; retain the launch fence and fresh source - # check immediately before the actual app-server request. - current() - report_context = reports.prepare(request, adapter, - authorization_scope_id=admitted.get("observed_scope_id")) - current() - def steward_validator(_plan: Mapping[str, Any], candidate_result: Mapping[str, Any]) -> dict[str, Any]: - if steward_actions_state.get("validation_error"): - return {"status": "failed", "validator_kind": "callback", - "summary": str(steward_actions_state["validation_error"]), - "recovery_kind": "repair_required"} - if candidate_result.get("result_kind") in {"validated_progress", "validated_completion"}: - return {"status": "passed", "validator_kind": "callback", - "summary": "steward advancement actions passed validation"} - return {"status": "passed", "validator_kind": "callback", - "summary": "steward advancement non-completion result recorded"} - - def run_primary_turn() -> None: - result.clear() - handle_turn_command(args, registry_path=self.controller.registry_path, - runtime_root_arg=str(self.controller.coordination_runtime_root), - output_format=lambda *_a, **_kw: "json", - print_payload=lambda value, *_a: result.update(value), - native_host_runner=run, native_session_binding_resolver=session_binding, - native_execution_preparer=prepare_native_task if not report_work else None, - **({"native_completion_lease_resolver": report_lease_proof, - "native_task_validator": self._report_validator(request)} if report_work else - {"native_task_validator": managed_turn.validator(request, turn_id=turn_id), - "native_completion_lease_resolver": lambda: self._task_lease_proof(managed_lease_request, managed_lease)} if managed_turn else - {"native_task_validator": steward_validator, - "native_completion_lease_resolver": lambda: self._task_lease_proof(managed_lease_request, managed_lease)} if steward_advancement else {})) - - run_primary_turn() - if (steward_advancement and request.get("todo_id") and not request.get("resume_turn_key") - and _is_zero_effect_replan_selection_deferral(result)): - governance_args = type(args)(**vars(args)) - governance_args.todo_id, governance_args.validation_command_json = None, None - governance_args.turn_instance_id = request["turn_instance_id"] + ".replan" - governance: dict[str, Any] = {} - governance_work = True - try: - handle_turn_command(governance_args, registry_path=self.controller.registry_path, - runtime_root_arg=str(self.controller.coordination_runtime_root), - output_format=lambda *_a, **_kw: "json", - print_payload=lambda value, *_a: governance.update(value), - native_host_runner=run, native_session_binding_resolver=session_binding) - finally: - governance_work = False - self.store.append_event(session_id, turn_id, kind="native_loopx.replan_result", payload=governance) - replan_cleared = ( - governance.get("status") == "committed" - and governance.get("result_kind") == "replan_required" - ) or ( - governance.get("status") == "stopped" - and isinstance(governance.get("host_result"), Mapping) - and governance["host_result"].get("classification") == "report_replan_not_admitted" - and self._cleared_replan_guard(actor) is not None - ) - if replan_cleared: - run_primary_turn() - elif isinstance(governance.get("effects"), Mapping): - merged_effects = dict(result.get("effects") or {}) - for key in ("host_invoked", "state_written", "quota_spent", "scheduler_acknowledged"): - if governance["effects"].get(key) is True: - merged_effects[key] = True - result["effects"] = merged_effects - if preparation_status is not None: - # Validation stopped preparation before the claim or model call. - result["status"] = preparation_status - if preparation_status == "stopped": - result.update(ok=True, result_kind="user_action_required") - try: - self.store.append_event(session_id, turn_id, kind="native_loopx.result", payload=result) - except OSError: - # The native transaction already owns execution and settlement. - # A lost Chat append acknowledgment must not discard its answer - # when this exact committed event is independently readable. - # Reuse the store's ordered readback without re-entering native work. - if result.get("ok") is not True or result.get("status") != "committed": - raise - recorded = [row for row in self.store.events_after(session_id, turn_id, None) - if row["kind"] == "native_loopx.result"] - if len(recorded) != 1 or recorded[0]["payload"] != result: - raise - if request.get("work_kind") == "report" and result.get("status") == "committed": - from ..periodic_report.private_generation import attempt_directory, validate_private_generation - subscription, window = reports.current_window(report_owner_key) - if not subscription or not window or window["window_id"] != request["report_window_id"]: - raise ValueError("report publication was cancelled after native settlement") - folder = attempt_directory(self.controller.coordination_runtime_root, window) - generation = validate_private_generation(folder) - delivered = reports.publish(session_id, window) if local_session else False - if local_session and not delivered: - return {"schema_version": "loopx_chat_agent_response_v0", "message": "本期报告已生成,原会话送达条件尚未满足;保留原结果等待核验。", - "proposals": [], "gate": None, "native_loopx": result} - return {"schema_version": "loopx_chat_agent_response_v0", "message": (folder / "report.md").read_text(encoding="utf-8"), - "proposals": [], "gate": None, "native_loopx": result, - "periodic_report": {"window_id": window["window_id"], "generation_id": generation["generation_id"], - "delivery_verified": delivered}} - user_action_receipts: list[dict[str, Any]] = [] - if steward_advancement and result.get("status") == "committed" and steward_actions_state["user_actions"]: - observed = self._observe(actor) - with self.controller.lock: - self._admit(request, turn=self.store.load_turn(session_id, turn_id), - observed=observed, selection_recovery=selection_recovery) - user_action_receipts = self._apply_steward_user_actions( - actor, steward_actions_state["user_actions"], request["turn_instance_id"]) - owner_report = (steward_actions_state["owner_report"] - if steward_advancement and result.get("status") == "committed" else None) - if owner_report: - from ...registry import atomic_write_json - from .steward_monitor import steward_monitor_delivery_dir - delivery_path = steward_monitor_delivery_dir(self.controller.coordination_runtime_root, actor["goal_id"]) / f"{turn_id}.json" - atomic_write_json(delivery_path, { - "schema_version": "steward_monitor_report_delivery_v0", - "goal_id": actor["goal_id"], - "agent_id": actor["agent_id"], - "session_id": actor["session_id"], - "turn_id": turn_id, - "turn_instance_id": request["turn_instance_id"], - "todo_id": (managed_lease_request or request).get("todo_id"), - "markdown": owner_report, - "created_at": datetime.now(timezone.utc).isoformat(), - "delivery_status": "pending", - "deliveries": {}, - }) - committed_handoff = (steward_actions_state["context_handoff"] - if steward_advancement and result.get("status") == "committed" else None) - return {"schema_version": "loopx_chat_agent_response_v0", "message": - "当前没有可执行且已配置独立验收的原生任务,尚未启动模型;请检查原任务的验收配置。" if managed_turn and managed_turn.validation_unavailable else - (owner_report or managed_answer or "本轮任务已完成结果回写。") if result.get("status") == "committed" else - "本轮等待后续执行条件。" if result.get("status") == "stopped" and result.get("result_kind") == "wait" else - "本轮任务尚未完成;执行状态已保留。", - "proposals": [], "gate": None, "native_loopx": result, - **({"context_handoff": committed_handoff} if committed_handoff else {}), - **({"steward_owner_report_queued": True} if owner_report else {}), - **({"steward_user_action_receipts": user_action_receipts} if user_action_receipts else {})} + return execute_steward_turn( + self, + session_id=session_id, + turn_id=turn_id, + adapter=adapter, + event_sink=event_sink, + context=context, + normalize_advancement=_normalize_steward_advancement_kernel_candidate, + normalize_report=_normalize_report_kernel_candidate, + is_replan_deferral=_is_zero_effect_replan_selection_deferral, + ) _DEFAULT_REPORT_FAILURE_OBSERVATION = StewardTurnHost.report_failure_observation diff --git a/loopx/capabilities/native_chat/steward_turn_common.py b/loopx/capabilities/native_chat/steward_turn_common.py new file mode 100644 index 0000000000..ef8bc17743 --- /dev/null +++ b/loopx/capabilities/native_chat/steward_turn_common.py @@ -0,0 +1,625 @@ +"""Shared typed protocols, narrowing helpers, and evidence utilities for StewardTurnHost.""" +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from contextlib import AbstractContextManager +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import re +from typing import TYPE_CHECKING, Protocol, TypedDict, cast + +if TYPE_CHECKING: + from ...chat_runtime import ChatRuntimeAdapter + from .steward_monitor import StewardMonitor + from .steward_monitor_turns import ( + StewardControllerProtocol as _MonitorControllerProtocol, + StewardSessionStoreProtocol as _MonitorStoreProtocol, + ) + +MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS = 300 +_WORKER_EXITED_ERROR = ( + "The LoopX Chat execution worker exited before this turn finished. " + "Your conversation is saved; execution may have occurred. This turn was not retried automatically." +) +_POST_CONTEXT_WATCH_ERRORS = frozenset({ + "steward monitor external signal source temporarily unavailable", + "the portfolio scope changed after observation", + "disk I/O error", + _WORKER_EXITED_ERROR, +}) +_FILE_LOCK_TIMEOUT_ERROR_RE = re.compile( + r"^file lock acquisition timed out \((?:recorded holder pid [1-9]\d*|lock busy, current holder unknown)\)$" +) +_USER_ACTION_DEDUPE_KEY = re.compile(r"^[a-z0-9][a-z0-9._:@/-]{0,119}$") +_REPORT_VALIDATOR_PREFIX = ( + "from pathlib import Path; from loopx.capabilities.periodic_report.private_generation import validate_private_generation; " + "validate_private_generation(Path(" +) + + +class ClosedFlagProtocol(Protocol): + """Minimal shutdown flag surface exposed by the Chat controller.""" + + def is_set(self) -> bool: ... + + +class AcceptedTurnProtocol(Protocol): + """Minimal accepted-turn result returned by store.accept_managed_turn.""" + + @property + def turn(self) -> dict[str, object]: ... + + @property + def created(self) -> bool: ... + + +class MonitorRestartCarrier(TypedDict, total=False): + """Typed carrier returned by monitor_restart_carrier while preserving dict keys.""" + + turn: dict[str, object] + request: dict[str, object] + client_id: str + + +class StewardStoreProtocol(Protocol): + """Chat turn/session persistence surface consumed by StewardTurnHost.""" + + def load_session(self, session_id: str) -> dict[str, object] | None: ... + + def update_session( + self, + session_id: str, + *, + expected_statuses: set[str] | None = None, + expected_upstream_thread_id: str | None = None, + metadata_review: bool = False, + quota_recovery: bool = False, + answer_review_admission: bool = False, + **changes: object, + ) -> object: ... + + def load_turn(self, session_id: str, turn_id: str) -> dict[str, object] | None: ... + + def turn_for_client(self, session_id: str, client_turn_id: str) -> dict[str, object] | None: ... + + def events_after(self, session_id: str, turn_id: str, event_id: str | None) -> list[dict[str, object]]: ... + + def messages(self, session_id: str, *, strict: bool = False) -> list[dict[str, object]]: ... + + def queued_turns(self, session_id: str) -> list[dict[str, object]]: ... + + def accept_managed_turn( + self, + session_id: str, + *, + client_turn_id: str, + message: str, + display_message: str | None = None, + origin: str = "web", + loopx_execution: bool = False, + loopx_request: dict[str, object] | None = None, + ) -> AcceptedTurnProtocol: ... + + def append_event( + self, + session_id: str, + turn_id: str, + *, + kind: str, + payload: dict[str, object], + ) -> object: ... + + def turn_execution_lock_path(self, session_id: str, turn_id: str) -> Path: ... + + def _event_path(self, session_id: str, turn_id: str) -> Path: ... + + +class StewardBindingsProtocol(Protocol): + """Conversation-bindings registry surface consumed by StewardTurnHost.""" + + @property + def path(self) -> Path: ... + + def read(self) -> dict[str, object]: ... + + def resolve( + self, + *, + binding_id: str, + source_ref: str, + sender_ref: str, + private_human_message: bool, + session_context: dict[str, object] | None = None, + include_observation: bool = False, + origin: str | None = None, + session: dict[str, object] | None = None, + ) -> dict[str, object]: ... + + def _resolve_observed( + self, + current: dict[str, object], + row: dict[str, object], + observation: dict[str, object], + source: dict[str, object], + ) -> dict[str, object]: ... + + def _session_observation(self, session: dict[str, object]) -> object: ... + + def steward_scope(self, session: dict[str, object]) -> list[str] | None: ... + + def _core(self, operation: str, payload: dict[str, object]) -> dict[str, object]: ... + + +class StewardProjectContextsProtocol(Protocol): + """Project-context container carrying optional conversation bindings.""" + + @property + def conversation_bindings(self) -> StewardBindingsProtocol | None: ... + + +class StewardManagedProtocol(Protocol): + """Managed-mode helper surface attached to StewardTurnHost.""" + + def _workspace(self, session: Mapping[str, object]) -> Path | str: ... + + def _goal(self, goal_id: str) -> dict[str, object] | None: ... + + +class StewardControllerProtocol(Protocol): + """Outer Chat controller surface consumed by StewardTurnHost.""" + + @property + def registry_path(self) -> Path | None: ... + + @property + def coordination_runtime_root(self) -> Path: ... + + @property + def lock(self) -> AbstractContextManager[object]: ... + + @property + def closed(self) -> ClosedFlagProtocol: ... + + @property + def store(self) -> StewardStoreProtocol: ... + + @property + def project_contexts(self) -> StewardProjectContextsProtocol: ... + + @property + def codex_bin(self) -> str: ... + + @property + def codex_home(self) -> Path: ... + + def _ensure_adapter_locked( + self, + session: dict[str, object], + *, + work_dir: Path, + objective: str, + accepted_turn_id: str | None = None, + ) -> object: ... + + def _start_accepted_turn_worker( + self, + *, + session_id: str, + turn_id: str, + message: str, + attachments: list[dict[str, object]], + adapter: ChatRuntimeAdapter, + loopx_execution: bool, + ) -> object: ... + + def _fail_queue_preparation(self, session_id: str, turn_id: str, error: Exception) -> None: ... + + +class StewardTurnHostProtocol(Protocol): + """Internal host protocol decoupling recovery/execution helpers from StewardTurnHost.""" + + controller: StewardControllerProtocol + store: StewardStoreProtocol + bindings: StewardBindingsProtocol | None + managed: StewardManagedProtocol + + def _observe(self, actor: Mapping[str, object]) -> dict[str, object] | None: ... + + def _admit( + self, + request: dict[str, object], + *, + turn: dict[str, object] | None = None, + observed: dict[str, object] | None = None, + carrier_session: dict[str, object] | None = None, + prepare_context: bool = False, + settlement_recovery: dict[str, object] | None = None, + frozen_contract_recovery: dict[str, object] | None = None, + launch_recovery: dict[str, object] | None = None, + selection_recovery: dict[str, object] | None = None, + ) -> dict[str, object]: ... + + def report_failure_observation(self, original: Mapping[str, object]) -> dict[str, object] | None: ... + + def report_selection_recovery( + self, + original: dict[str, object], + *, + probe_turn: dict[str, object] | None = None, + ) -> dict[str, object] | None: ... + + def _cleared_replan_guard(self, actor: Mapping[str, object]) -> dict[str, object] | None: ... + + def _report_validator( + self, + request: Mapping[str, object], + ) -> Callable[[Mapping[str, object], Mapping[str, object]], dict[str, object]]: ... + + def _report_fence(self, request: Mapping[str, object]) -> AbstractContextManager[object]: ... + + def _task_lease_proof( + self, + request: Mapping[str, object], + lease: Mapping[str, object] | None, + ) -> dict[str, object]: ... + + def _task_execution_lease( + self, + request: Mapping[str, object], + turn_id: str, + *, + recovery: bool = False, + admission_retry: bool = False, + claim_args: list[str] | None = None, + retain_for_retry: Callable[[], bool] | None = None, + ) -> AbstractContextManager[dict[str, object]]: ... + + def _frozen_report_contract_recovery( + self, + actor: Mapping[str, object], + window: Mapping[str, object], + original: Mapping[str, object], + *, + key: str, + generation: Mapping[str, object], + root: Path, + ) -> tuple[dict[str, object], dict[str, object]] | None: ... + + def _stopped_report_candidate_recovery( + self, + actor: Mapping[str, object], + window: Mapping[str, object], + original: Mapping[str, object], + *, + key: str, + folder: Path, + root: Path, + ) -> tuple[dict[str, object], dict[str, object]] | None: ... + + def _settle_stopped_report_candidate( + self, + *, + actor: Mapping[str, object], + window: Mapping[str, object], + todo: Mapping[str, object], + original: Mapping[str, object], + request: dict[str, object], + observed: dict[str, object] | None, + reports: object, + owner_key: str, + folder: Path, + original_key: str, + stopped_proof: dict[str, object], + raw_candidate: dict[str, object], + ) -> dict[str, object]: ... + + def _steward_followup_context( + self, + actor: Mapping[str, object], + session_id: str, + request: Mapping[str, object], + authority: Mapping[str, object], + ) -> dict[str, object]: ... + + def _governance_replan_context( + self, + actor: Mapping[str, object], + authority: Mapping[str, object], + ) -> dict[str, object]: ... + + def _apply_steward_user_actions( + self, + actor: Mapping[str, object], + actions: Sequence[Mapping[str, str]], + turn_instance_id: str, + ) -> list[dict[str, object]]: ... + + @staticmethod + def _build_replay_runner( + normalized_candidate: Mapping[str, object], + ) -> Callable[[Mapping[str, object], object], dict[str, object]]: ... + + @staticmethod + def _normalize_steward_actions( + candidate: Mapping[str, object], + context: Mapping[str, object], + ) -> dict[str, object]: ... + + +def as_mapping(value: object) -> Mapping[str, object]: + """Return value as a typed string-keyed Mapping without copying dicts.""" + if isinstance(value, Mapping): + return cast(Mapping[str, object], value) + return {} + + +def as_dict(value: object) -> dict[str, object]: + """Return value as a mutable string-keyed dict, preserving dict identity.""" + if isinstance(value, dict): + return cast(dict[str, object], value) + if isinstance(value, Mapping): + return {str(k): v for k, v in cast(Mapping[object, object], value).items()} + return {} + + +def as_optional_dict(value: object) -> dict[str, object] | None: + """Return value as a typed dict when Mapping, otherwise None.""" + if isinstance(value, Mapping): + return as_dict(value) + return None + + +def as_dict_list(value: object) -> list[dict[str, object]]: + """Extract Mapping items from a sequence/list into typed dicts.""" + if not isinstance(value, Sequence) or isinstance(value, (str, bytes, bytearray)): + return [] + return [as_dict(item) for item in value if isinstance(item, Mapping)] + + +def as_str(value: object, default: str = "") -> str: + """Return value when it is a str, otherwise default.""" + return value if isinstance(value, str) else default + + +def as_optional_str(value: object) -> str | None: + """Return value when it is a str, otherwise None.""" + return value if isinstance(value, str) else None + + +def as_str_list(value: object) -> list[str]: + """Extract string items from a sequence/list.""" + if not isinstance(value, Sequence) or isinstance(value, (str, bytes, bytearray)): + return [] + return [item for item in value if isinstance(item, str)] + + +def as_int(value: object, default: int = 0) -> int: + """Return value when it is a non-bool int, otherwise default.""" + return value if isinstance(value, int) and not isinstance(value, bool) else default + + +def iso_timestamp_seconds(value: object) -> float | None: + """Parse an ISO-8601 timestamp into UTC epoch seconds, or None.""" + if not isinstance(value, str) or not value.strip(): + return None + try: + parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00")) + except ValueError: + return None + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=timezone.utc) + return parsed.timestamp() + + +def same_report_validator_command(frozen_cmd: object, request_cmd: object) -> bool: + """Allow report validation commands whose only drift is the host Python path.""" + return ( + isinstance(frozen_cmd, list) + and isinstance(request_cmd, list) + and len(frozen_cmd) == 3 + and len(request_cmd) == 3 + and all(isinstance(part, str) and bool(part) for part in [*frozen_cmd, *request_cmd]) + and frozen_cmd[1] == "-c" + and request_cmd[1] == "-c" + and frozen_cmd[2] == request_cmd[2] + and frozen_cmd[2].startswith(_REPORT_VALIDATOR_PREFIX) + and frozen_cmd[2].endswith("))") + ) + + +def native_steward_client_id(actor: Mapping[str, object], turn_instance_id: str) -> str: + """The original native request identity, shared by dispatch and readback.""" + if actor.get("schema_version") == "loopx_managed_session_actor_v0": + return "managed." + turn_instance_id + return "native." + hashlib.sha256(json.dumps([actor, turn_instance_id], sort_keys=True).encode()).hexdigest()[:40] + + +def report_turn( + store: StewardStoreProtocol, + actor: Mapping[str, object], + window: Mapping[str, object], +) -> dict[str, object] | None: + """Read the one bounded continuation, retaining the original failed Turn.""" + session_id = str(actor["session_id"]) + operation = "report." + str(window["window_id"]) + original = store.turn_for_client(session_id, native_steward_client_id(actor, operation)) + quota = store.turn_for_client(session_id, native_steward_client_id(actor, operation + ".quota-recovery")) + timeout_retry = store.turn_for_client(session_id, native_steward_client_id(actor, operation + ".timeout-recovery")) + if quota is not None and timeout_retry is not None: + raise ValueError("conflicting report continuations exist") + for suffix, key, label, continued in ( + (".quota-recovery", "report_quota_recovery", "quota", quota), + (".timeout-recovery", "report_timeout_recovery", "timeout", timeout_retry), + ): + if continued is None: + continue + request = as_mapping(continued.get("loopx_request")) + recovery = as_mapping(request.get(key)) + original_req = as_mapping((original or {}).get("loopx_request")) if original else {} + if ( + not original + or recovery.get("original_turn_id") != original.get("turn_id") + or request.get("turn_instance_id") != str(original_req.get("turn_instance_id") or "") + suffix + ): + raise ValueError(f"the report {label} continuation changed its original identity") + return continued + return original + + +def normalize_report_kernel_candidate(candidate: Mapping[str, object]) -> dict[str, object]: + """Normalize a verified report candidate to canonical Turn settlement fields.""" + normalized = dict(candidate) + normalized.pop("editorial_response", None) + # This finite task's postcondition is the complete validated generation, not + # the model's choice of progress wording or profile-minimum shorthand. + normalized["result_kind"] = "validated_completion" + if normalized.get("delivery_batch_scale") == "multi_surface_or_implementation": + normalized["delivery_batch_scale"] = "multi_surface" + return normalized + + +def split_evidence_text_chunks(text: str, max_item_chars: int) -> list[str]: + """Split a single normalized evidence string cleanly at natural boundaries.""" + if len(text) <= max_item_chars: + return [text] + chunks: list[str] = [] + rest = text + delimiters = ("; ", ". ", ";", "。", ", ", ",", " ") + while len(rest) > max_item_chars: + split_at = -1 + matched_delim = "" + for delim in delimiters: + pos = rest.rfind(delim, 1, max_item_chars) + if pos > 0: + split_at = pos + matched_delim = delim + break + if split_at <= 0: + chunks.append(rest[:max_item_chars]) + rest = rest[max_item_chars:].lstrip() + elif matched_delim in (";", "。", ","): + end = min(split_at + len(matched_delim), max_item_chars) + chunks.append(rest[:end].strip()) + rest = rest[end:].lstrip() + else: + head = rest[:split_at].rstrip() + if matched_delim == ". " and len(head) + 1 <= max_item_chars: + head += "." + chunks.append(head) + rest = rest[split_at + len(matched_delim) :].lstrip() + if rest: + chunks.append(rest) + return [chunk for chunk in chunks if chunk] + + +def append_bounded_ellipsis(text: str, limit: int) -> str: + """Append '...' to text while respecting the exact character cap.""" + if limit <= 0: + return "" + if limit <= 3: + return text[:limit] + if len(text) + 3 <= limit and not text.endswith("..."): + return text + "..." + trimmed = text[: max(1, limit - 3)].rstrip() + return (trimmed or text[: max(1, limit - 3)]) + "..." + + +def split_bounded_evidence_items( + raw: object, + *, + max_items: int = 8, + max_item_chars: int = 240, + max_total_chars: int = 1_200, +) -> object: + """Split over-long Steward evidence strings without masking invalid shapes.""" + if not isinstance(raw, list) or not raw: + return raw + items = cast(list[object], raw) + if not all(isinstance(item, str) and bool(item.strip()) for item in items): + return raw + str_items = [cast(str, item) for item in items] + chunks: list[str] = [] + for item in str_items: + normalized = " ".join(item.split()).strip() + chunks.extend(split_evidence_text_chunks(normalized, max_item_chars)) + if len(chunks) > max_items: + merged: list[str] = [] + for chunk in chunks: + if merged and len(merged[-1]) + 2 + len(chunk) <= max_item_chars: + merged[-1] = f"{merged[-1]}; {chunk}" + else: + merged.append(chunk) + chunks = merged + clipped = len(chunks) > max_items + if clipped: + chunks = chunks[:max_items] + bounded: list[str] = [] + used = 0 + for chunk in chunks: + remaining = max_total_chars - used + if remaining <= 0: + clipped = True + break + if len(chunk) > remaining or len(chunk) > max_item_chars: + cap = min(max_item_chars, remaining) + bounded.append(append_bounded_ellipsis(chunk, cap)) + used += len(bounded[-1]) + clipped = True + break + bounded.append(chunk) + used += len(chunk) + if clipped and bounded and not bounded[-1].endswith("..."): + room = min(max_item_chars, len(bounded[-1]) + (max_total_chars - used)) + bounded[-1] = append_bounded_ellipsis(bounded[-1], room) + return bounded + + +def normalize_steward_advancement_kernel_candidate(candidate: Mapping[str, object]) -> dict[str, object]: + """Keep Steward advancement evidence within kernel per-item and total limits.""" + normalized = dict(candidate) + if normalized.get("delivery_batch_scale") == "multi_surface_or_implementation": + normalized["delivery_batch_scale"] = "multi_surface" + for field in ("work_evidence", "validation_evidence"): + if field in normalized: + normalized[field] = split_bounded_evidence_items(normalized[field]) + return normalized + + +def is_zero_effect_replan_selection_deferral(result: Mapping[str, object]) -> bool: + """Identify a zero-effect pre-host autonomous_replan selection refusal.""" + if result.get("ok") is not False or result.get("error_code") != "turn_todo_selection_deferred": + return False + refusal = result.get("selection_rejection") + if ( + not isinstance(refusal, Mapping) + or refusal.get("state") != "deferred" + or refusal.get("reason_code") != "autonomous_replan" + or refusal.get("recovery_action") != "reenter_guard_without_selection" + ): + return False + effects = result.get("effects") + if not isinstance(effects, Mapping): + return False + return all( + effects.get(key) is False + for key in ("host_invoked", "state_written", "quota_spent", "scheduler_acknowledged") + ) + + +def monitor_controller_for(controller: StewardControllerProtocol) -> _MonitorControllerProtocol: + """Adapt the outer Chat controller protocol to the monitor controller boundary.""" + return cast("_MonitorControllerProtocol", controller) + + +def steward_monitor_for(controller: StewardControllerProtocol) -> StewardMonitor: + """Adapt the outer Chat controller protocol to the StewardMonitor helper boundary.""" + from .steward_monitor import StewardMonitor + + return StewardMonitor(monitor_controller_for(controller)) + + +def monitor_store_for(store: StewardStoreProtocol) -> _MonitorStoreProtocol: + """Adapt the narrowed Steward store protocol to the monitor turn store protocol.""" + return cast("_MonitorStoreProtocol", store) diff --git a/loopx/capabilities/native_chat/steward_turn_context.py b/loopx/capabilities/native_chat/steward_turn_context.py new file mode 100644 index 0000000000..c392c74678 --- /dev/null +++ b/loopx/capabilities/native_chat/steward_turn_context.py @@ -0,0 +1,585 @@ +"""Steward followup/governance context projection, action validation, and prompt helpers.""" +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import re +import shlex +from typing import Protocol, cast + +from ...control_plane.effect_runtime import EffectRuntimeRejected +from .steward_turn_common import ( + StewardTurnHostProtocol, + _USER_ACTION_DEDUPE_KEY, + as_dict, + as_dict_list, + as_mapping, + as_optional_dict, + as_str, +) + +_GOVERNANCE_CONTRACT_REMINDER = ( + "\nGovernance contract reminder: Settle the pending autonomous replan by returning `result_kind='replan_required'` (or `'wait'` only if required evidence is genuinely unavailable). " + "If you emit `delivery_outcome='outcome_gap'`, you MUST also supply `progress_result_class='blocked'`, `progress_blocker_id`, and `progress_evidence_id`; " + "otherwise use `'outcome_progress'` or omit `delivery_outcome`. " + "Keep each `work_evidence` and `validation_evidence` item <=200 chars (1-8 public-safe items, <=1200 chars total per field) with zero local file paths. " + "When `Steward governance replan context` supplies `writeback`: set `agent_vision_json` (JSON string of `goal_vision_replan_contract_v0`) keeping total counted text <=1400 chars (hard cap 1800; keep each `stride_decision` plan/reason/probe field <=60 chars), and omit `vision_unchanged_reason`. " + "If keeping `current_agent_vision.vision_patch` identical, set `path_delta_mode='unchanged'` and `path_delta.outcome='continue'` (or `'no_change'`); if updating any `vision_patch` field or creating an initial baseline, set `path_delta_mode='material_replan'` and `path_delta.outcome='replan'`. " + "Populate `path_delta.evidence_refs` from `review.recent_evidence` (1-3 IDs), `todo_delta` using `retain:` only for verified IDs in `open_agent_todos` (<=8 items), and when `writeback.stride_control.required_on_periodic_review` is true include `agent_vision.stride_decision` with exact `schema_version`, `strategy_version`, `reference_context_id`, and `reference_obligation_id` from `stride_control` (plus `previous_review` when `previous_decision_ref` is non-null). " + "All review, writeback, stride_control, current_agent_vision, and open_agent_todos facts are already provided in Steward governance replan context below; return only the single typed JSON object directly without invoking periodic-report CLI commands or inspecting host source code." +) + +_STEWARD_ADVANCEMENT_INSTRUCTIONS = ( + "\nSteward advancement instructions: Evaluate the monitor prompt and signal snapshot against authorized recipients (`context_delegation.targets`), prior receipts (`prior_handoff_receipts`, avoid duplicate delivery for unchanged PR@headRefOid), and open user todos (`open_user_todos`). " + "When `signal_snapshot.repository_snapshot.items` is present, each PR carries `mergeable`, `checks_summary`, `bypassed_gates`, `stalled_since`, `author_replied_after_request_changes`, optional `stalled_bucket` (`awaiting_maintainer_reply` | `under_24h` | `24h_to_72h` | `72h_plus` | `7d_plus`), and `review_summary` (`effective_verdict`, `has_review_conflict`, `stale_review_count`, `latest_request_changes_review_id`, `stalled_since`, `author_replied_after_request_changes`, `exact_head_reviews` with `reviewer_declaration`, `valid_verdict_review`, `author_owned_fallback`). Keep triage read-only; never execute merges here. " + "You may include optional top-level JSON fields alongside the normal kernel fields: " + "`context_handoff` (single object or array <=32 of {goal_id, agent_id, brief} with `schema_version='collaboration_brief_v0'` and `inputs=[]` when referencing URLs/PRs, restricted to `context_delegation.targets`), " + "`steward_owner_report` (optional non-empty Markdown string <=24000 chars or `{markdown}` delivered once directly to the bound Steward App and Feishu conversation; omit or set `null` when silent/no report should be sent), " + "and `steward_user_actions` (array <=16 of {dedupe_key, priority:'P0'|'P1'|'P2', text}; do NOT emit per-PR `steward_user_actions` when the monitor prompt asks for an aggregated report). Keep each `work_evidence` and `validation_evidence` item <=200 chars (1-8 items, <=1200 chars total per field). Set `result_kind='validated_completion'` when triage/handoff/report/user-action preparation is complete.\n" + "Steward monitor & dedupe context (data):\n" +) + + +class _CalendarTasksProtocol(Protocol): + def admission(self, request: Mapping[str, object]) -> dict[str, object]: ... + + +class ExecutionReportServiceProtocol(Protocol): + """Periodic report service surface used during Turn execution and delivery.""" + + def current_window(self, owner_key: str) -> tuple[dict[str, object] | None, dict[str, object] | None]: ... + + def prepare( + self, + request: Mapping[str, object], + adapter: object, + *, + authorization_scope_id: object, + ) -> str: ... + + def freeze(self, request: Mapping[str, object], candidate: Mapping[str, object]) -> object: ... + + def publish(self, session_id: str, window: Mapping[str, object]) -> bool: ... + + +def steward_followup_context( + host: StewardTurnHostProtocol, + actor: Mapping[str, object], + session_id: str, + request: Mapping[str, object], + authority: Mapping[str, object], +) -> dict[str, object]: + """Assemble selected-todo, monitor snapshot, open user todos, and handoff receipt dedupe context.""" + from ...control_plane.todos.list_readback import list_goal_todos + from .steward_monitor import FOLLOWUP_TARGET_PREFIX, steward_monitor_snapshot_path + + goal_id = str(actor["goal_id"]) + agent_id = str(actor["agent_id"]) + todo_id = as_mapping(authority.get("_work_identity")).get("todo_id") or request.get("todo_id") + agent_todos = as_dict_list( + as_mapping( + list_goal_todos( + registry_path=cast(Path, host.controller.registry_path), + runtime_root_arg=str(host.controller.coordination_runtime_root), + goal_id=goal_id, + agent_id=agent_id, + role="agent", + ) + ).get("todos") + ) + selected = next((row for row in agent_todos if row.get("todo_id") == todo_id), None) + payload: dict[str, object] = {"selected_todo": selected} + target_key = as_str((selected or {}).get("target_key")) + if target_key.startswith(FOLLOWUP_TARGET_PREFIX): + source_id = target_key.removeprefix(FOLLOWUP_TARGET_PREFIX) + payload["source_monitor"] = next((row for row in agent_todos if row.get("todo_id") == source_id), None) + snap = steward_monitor_snapshot_path(host.controller.coordination_runtime_root, goal_id, source_id) + if snap.is_file(): + try: + payload["signal_snapshot"] = json.loads(snap.read_text(encoding="utf-8")) + except (OSError, ValueError): + payload["signal_snapshot"] = None + user_todos = as_dict_list( + as_mapping( + list_goal_todos( + registry_path=cast(Path, host.controller.registry_path), + runtime_root_arg=str(host.controller.coordination_runtime_root), + goal_id=goal_id, + role="user", + ) + ).get("todos") + ) + payload["open_user_todos"] = [ + {k: row.get(k) for k in ("todo_id", "status", "priority", "text", "updated_at")} + for row in user_todos + if row.get("status") == "open" + ][:40] + prior: list[dict[str, object]] = [] + for msg in reversed(host.store.messages(session_id)[-30:]): + tid = msg.get("turn_id") + if not isinstance(tid, str) or not tid: + continue + turn_row = host.store.load_turn(session_id, tid) + resp = as_mapping((turn_row or {}).get("response")) + receipts: list[dict[str, object]] = as_dict_list(resp.get("context_handoff_receipts")) + single = as_optional_dict(resp.get("context_handoff_receipt")) + if single is not None: + receipts.append(single) + for receipt in receipts: + prior.append({k: receipt.get(k) for k in ("goal_id", "agent_id", "source_id", "request_id", "delivered_at")}) + payload["prior_handoff_receipts"] = prior[:40] + return payload + + +def governance_replan_context( + host: StewardTurnHostProtocol, + actor: Mapping[str, object], + authority: Mapping[str, object], +) -> dict[str, object]: + """Project public-safe review/writeback/vision context for text-only Steward replanning.""" + from ...cli_runtime import _build_selected_parser + from ...cli_commands.quota_native_context import read_replan_view + from ...control_plane.goals.goal_frontier.semantic_history import latest_agent_vision_from_status_payload + from ...control_plane.todos.list_readback import list_goal_todos + from .steward_commands import NativeStewardCommandError, native_command + + model_input = as_optional_dict(authority.get("_model_input")) + detail_ref = as_optional_dict(model_input.get("detail_ref")) if model_input is not None else None + detail_packet = as_optional_dict(detail_ref.get("replan_action_packet")) if detail_ref is not None else None + auth_packet = as_optional_dict(authority.get("replan_action_packet")) + packet = ( + detail_packet + if detail_packet is not None and ("review" in detail_packet or "writeback" in detail_packet) + else auth_packet + ) + + def _read_stage(cmd_str: object) -> dict[str, object] | None: + if not isinstance(cmd_str, str) or not cmd_str.strip(): + return None + try: + tokens = shlex.split(cmd_str) + q_idx = tokens.index("quota") + parsed = _build_selected_parser("quota").parse_args(tokens[q_idx:]) + view = read_replan_view(parsed) + if isinstance(view, Mapping) and view.get("ok") is True: + return as_dict(view) + except (OSError, ValueError, KeyError, TypeError, RuntimeError, EffectRuntimeRejected, SystemExit): + return None + return None + + payload: dict[str, object] = {} + if packet is not None: + review_view = _read_stage(packet.get("review")) + if review_view is not None: + core_goal = as_optional_dict(review_view.get("core_goal")) + evidence_raw = review_view.get("evidence") + recent_evidence = ( + list(evidence_raw)[:12] + if isinstance(evidence_raw, Sequence) and not isinstance(evidence_raw, (str, bytes)) + else [] + ) + payload["review"] = { + "obligation_id": review_view.get("obligation_id"), + "context_id": review_view.get("context_id"), + "objective": core_goal.get("objective") if core_goal is not None else None, + "triggers": review_view.get("triggers"), + "recent_evidence": recent_evidence, + "decision_followthrough": review_view.get("decision_followthrough"), + } + writeback_view = _read_stage(packet.get("writeback")) + if writeback_view is not None: + payload["writeback"] = { + "obligation_id": writeback_view.get("obligation_id"), + "context_id": writeback_view.get("context_id"), + "required_outcome": writeback_view.get("required_outcome"), + "writeback_contract": writeback_view.get("writeback_contract"), + "stride_control": writeback_view.get("stride_control"), + } + goal_id = str(actor["goal_id"]) + agent_id = str(actor["agent_id"]) + try: + status_payload = native_command(host.controller, ["status", "--goal-id", goal_id]) + latest_vision = latest_agent_vision_from_status_payload(status_payload, goal_id=goal_id, agent_id=agent_id) + if isinstance(latest_vision, Mapping): + typed_vision = as_dict(latest_vision) + payload["current_agent_vision"] = { + k: typed_vision.get(k) + for k in ("schema_version", "state", "vision_patch", "todo_delta") + if typed_vision.get(k) is not None + } + except (NativeStewardCommandError, OSError, ValueError, KeyError, TypeError, RuntimeError): + pass + try: + agent_todos = as_dict_list( + as_mapping( + list_goal_todos( + registry_path=cast(Path, host.controller.registry_path), + runtime_root_arg=str(host.controller.coordination_runtime_root), + goal_id=goal_id, + role="agent", + ) + ).get("todos") + ) + payload["open_agent_todos"] = [ + {k: row.get(k) for k in ("todo_id", "task_class", "priority", "target_key", "title")} + for row in agent_todos + if row.get("status") == "open" + ][:16] + except (NativeStewardCommandError, OSError, ValueError, KeyError, TypeError, RuntimeError): + pass + return payload + + +def normalize_steward_actions( + candidate: Mapping[str, object], + context: Mapping[str, object], +) -> dict[str, object]: + """Validate optional context_handoff, steward_user_actions, and steward_owner_report fields.""" + from ...control_plane.collaboration.inbox import normalize_handoff + + state: dict[str, object] = { + "context_handoff": None, + "user_actions": [], + "owner_report": None, + "validation_error": None, + } + delegation = as_mapping(context.get("context_delegation")) + allowed_targets = { + (str(row["goal_id"]), str(row["agent_id"])) + for row in as_dict_list(delegation.get("targets")) + if row.get("goal_id") and row.get("agent_id") + } + raw_handoff = candidate.get("context_handoff") + if raw_handoff is not None: + try: + normalized = normalize_handoff(raw_handoff) + except ValueError as exc: + state["validation_error"] = f"invalid context_handoff: {exc}" + return state + if normalized: + items = as_dict_list(normalized) if isinstance(normalized, list) else [as_dict(normalized)] + for item in items: + pair = (str(item.get("goal_id") or ""), str(item.get("agent_id") or "")) + if pair not in allowed_targets: + state["validation_error"] = f"unauthorized context_handoff recipient: {item['goal_id']}/{item['agent_id']}" + return state + state["context_handoff"] = normalized + raw_actions = candidate.get("steward_user_actions") + if raw_actions is not None: + if not isinstance(raw_actions, list) or len(raw_actions) > 16: + state["validation_error"] = "steward_user_actions must be a bounded list of at most 16 items" + return state + cleaned: list[dict[str, str]] = [] + seen_keys: set[str] = set() + for raw_item in cast(list[object], raw_actions): + if not isinstance(raw_item, Mapping): + state["validation_error"] = "each steward_user_actions entry must be an object" + return state + action_item = as_mapping(raw_item) + key = str(action_item.get("dedupe_key") or "").strip().lower() + text = " ".join(str(action_item.get("text") or "").split()).strip() + prio = str(action_item.get("priority") or "P1").strip().upper() + if ( + not _USER_ACTION_DEDUPE_KEY.fullmatch(key) + or key in seen_keys + or not text + or len(text) > 800 + or prio not in {"P0", "P1", "P2"} + ): + state["validation_error"] = "invalid steward_user_actions entry" + return state + seen_keys.add(key) + cleaned.append({"dedupe_key": key, "priority": prio, "text": text}) + state["user_actions"] = cleaned + raw_report = candidate.get("steward_owner_report") + if raw_report is not None: + markdown = as_mapping(raw_report).get("markdown") if isinstance(raw_report, Mapping) else raw_report + if not isinstance(markdown, str): + state["validation_error"] = "steward_owner_report must be a markdown string or {markdown}" + return state + normalized_report = markdown.strip() + if not normalized_report or len(normalized_report) > 24000: + state["validation_error"] = "steward_owner_report markdown must be 1..24000 characters" + return state + state["owner_report"] = normalized_report + return state + + +def apply_steward_user_actions( + host: StewardTurnHostProtocol, + actor: Mapping[str, object], + actions: Sequence[Mapping[str, str]], + turn_instance_id: str, +) -> list[dict[str, object]]: + """Idempotently add or update dedupe-keyed user_action Todos via native_command.""" + if not actions: + return [] + from ...control_plane.todos.list_readback import list_goal_todos + from .steward_commands import native_command + + goal_id = str(actor["goal_id"]) + agent_id = str(actor["agent_id"]) + existing = as_dict_list( + as_mapping( + list_goal_todos( + registry_path=cast(Path, host.controller.registry_path), + runtime_root_arg=str(host.controller.coordination_runtime_root), + goal_id=goal_id, + role="user", + ) + ).get("todos") + ) + open_by_key: dict[str, tuple[dict[str, object], str]] = {} + for row in existing: + if row.get("status") != "open": + continue + title = str(row.get("title") or "").strip() or re.sub( + r"^\[p\d\]\s*", "", str(row.get("text") or ""), flags=re.IGNORECASE + ).strip() + if title.startswith("[") and "]" in title: + open_by_key[title[1 : title.index("]")].strip().lower()] = (row, title) + receipts: list[dict[str, object]] = [] + for idx, action in enumerate(actions): + key, prio, body = action["dedupe_key"], action["priority"], action["text"] + rendered = f"[{key}] {body}" + op_id = "steward-ua." + hashlib.sha256(f"{turn_instance_id}:{idx}:{key}".encode()).hexdigest()[:24] + matched = open_by_key.get(key) + if matched is not None: + prior, prior_title = matched + if prior_title == rendered and str(prior.get("priority") or "") == prio: + receipts.append({"dedupe_key": key, "action": "unchanged", "todo_id": prior["todo_id"]}) + continue + res = as_mapping( + native_command( + host.controller, + [ + "todo", "update", "--goal-id", goal_id, "--role", "user", + "--agent-id", agent_id, "--todo-id", str(prior["todo_id"]), + "--text", rendered, + *(["--note", f"Priority: {prio}"] if str(prior.get("priority") or "") != prio else []), + "--update-operation-id", op_id, "--execute", + ], + ) + ) + receipts.append({"dedupe_key": key, "action": "updated", "todo_id": prior["todo_id"], "ok": res.get("ok")}) + else: + res = as_mapping( + native_command( + host.controller, + [ + "todo", "add", "--goal-id", goal_id, "--role", "user", + "--task-class", "user_action", "--priority", prio, "--text", rendered, + "--bound-agent", agent_id, "--operation-id", op_id, "--execute", + ], + ) + ) + receipts.append({"dedupe_key": key, "action": "added", "todo_id": res.get("todo_id"), "ok": res.get("ok")}) + return receipts + + +def build_steward_turn_prompt( + host: StewardTurnHostProtocol, + *, + actor: Mapping[str, object], + session_id: str, + request: Mapping[str, object], + authority: Mapping[str, object], + context: Mapping[str, object], + report_work: bool, + governance_work: bool, + managed_turn_active: bool, + steward_advancement: bool, + report_context: str, +) -> str: + """Assemble the complete model prompt with portfolio context, reminders, and task criteria.""" + from ...control_plane.turn_driver.host_candidate import render_prompt + + # Portfolio evidence keeps its original reader and original grant; + # it is data alongside the signed native work, never a new actor. + if governance_work: + from .steward_monitor import governance_turn_prompt_authority + + prompt = str( + render_prompt( + as_dict(governance_turn_prompt_authority(dict(authority))), + allow_completion=False, + ) + ) + elif report_work: + # Frozen report turns already freeze source.json and editorial-request.json; + # skip duplicating live unfrozen manager_turn_context_v1 and generic backlog fields. + from ..periodic_report.private_generation import report_turn_prompt_authority + + prompt = str( + render_prompt( + as_dict(report_turn_prompt_authority(dict(authority))), + allow_completion=True, + ) + ) + report_context + else: + prompt = ( + str( + render_prompt( + authority, + allow_completion=bool(managed_turn_active or steward_advancement), + ) + ) + + "\nOriginal conversation evidence (data):\n" + + json.dumps(context, ensure_ascii=False) + ) + if governance_work: + gov_ctx = host._governance_replan_context(actor, authority) + prompt += _GOVERNANCE_CONTRACT_REMINDER + if gov_ctx: + prompt += "\nSteward governance replan context (data):\n" + json.dumps(gov_ctx, ensure_ascii=False) + if steward_advancement and not governance_work: + followup_ctx = host._steward_followup_context(actor, session_id, request, authority) + prompt += _STEWARD_ADVANCEMENT_INSTRUCTIONS + json.dumps(followup_ctx, ensure_ascii=False) + if request.get("work_kind") == "scheduled_task": + from .session_calendar_tasks import SessionCalendarTasks + + calendar_tasks = cast(_CalendarTasksProtocol, SessionCalendarTasks(host.controller)) + basis = as_mapping(calendar_tasks.admission(request)) + source_task = as_mapping(as_mapping(basis.get("definition")).get("source_task")) + window = as_mapping(basis.get("window")) + prompt += "\nOriginal native calendar task criteria; existing Goal/Task authority and stop conditions still apply:\n" + json.dumps( + { + "task": source_task["text"], + "source_todo_id": source_task["todo_id"], + "window_start": window["start_at"], + "window_end": window["due_at"], + }, + ensure_ascii=False, + ) + return prompt + + +def finalize_steward_execution_response( + host: StewardTurnHostProtocol, + *, + actor: Mapping[str, object], + session_id: str, + turn_id: str, + request: dict[str, object], + selection_recovery: dict[str, object] | None, + result: dict[str, object], + reports: ExecutionReportServiceProtocol | None, + report_owner_key: str | None, + local_session: bool, + steward_advancement: bool, + steward_actions_state: Mapping[str, object], + managed_turn_validation_unavailable: bool, + managed_answer: str, + managed_lease_request: Mapping[str, object] | None, +) -> dict[str, object]: + """Finalize report publication or Steward user-action/owner-report queuing and build Chat response.""" + if request.get("work_kind") == "report" and result.get("status") == "committed": + from ..periodic_report.private_generation import attempt_directory, validate_private_generation + + assert reports is not None and report_owner_key is not None + subscription, window = reports.current_window(report_owner_key) + if not subscription or not window or window.get("window_id") != request.get("report_window_id"): + raise ValueError("report publication was cancelled after native settlement") + folder = attempt_directory(host.controller.coordination_runtime_root, window) + generation = as_mapping(validate_private_generation(folder)) + delivered = reports.publish(session_id, window) if local_session else False + if local_session and not delivered: + return { + "schema_version": "loopx_chat_agent_response_v0", + "message": "本期报告已生成,原会话送达条件尚未满足;保留原结果等待核验。", + "proposals": [], + "gate": None, + "native_loopx": result, + } + return { + "schema_version": "loopx_chat_agent_response_v0", + "message": (folder / "report.md").read_text(encoding="utf-8"), + "proposals": [], + "gate": None, + "native_loopx": result, + "periodic_report": { + "window_id": window["window_id"], + "generation_id": generation["generation_id"], + "delivery_verified": delivered, + }, + } + user_action_receipts: list[dict[str, object]] = [] + raw_user_actions = steward_actions_state.get("user_actions") + typed_user_actions: list[dict[str, str]] = ( + [ + {str(k): str(v) for k, v in as_mapping(item).items()} + for item in cast(list[object], raw_user_actions) + if isinstance(item, Mapping) + ] + if isinstance(raw_user_actions, list) + else [] + ) + if steward_advancement and result.get("status") == "committed" and typed_user_actions: + observed = host._observe(actor) + with host.controller.lock: + host._admit( + request, + turn=host.store.load_turn(session_id, turn_id), + observed=observed, + selection_recovery=selection_recovery, + ) + user_action_receipts = host._apply_steward_user_actions( + actor, + typed_user_actions, + str(request["turn_instance_id"]), + ) + raw_owner_report = steward_actions_state.get("owner_report") + owner_report = ( + raw_owner_report + if steward_advancement and result.get("status") == "committed" and isinstance(raw_owner_report, str) and raw_owner_report + else None + ) + if owner_report: + from ...registry import atomic_write_json + from .steward_monitor import steward_monitor_delivery_dir + + delivery_path = ( + steward_monitor_delivery_dir(host.controller.coordination_runtime_root, str(actor["goal_id"])) / f"{turn_id}.json" + ) + atomic_write_json( + delivery_path, + { + "schema_version": "steward_monitor_report_delivery_v0", + "goal_id": actor["goal_id"], + "agent_id": actor["agent_id"], + "session_id": actor["session_id"], + "turn_id": turn_id, + "turn_instance_id": request["turn_instance_id"], + "todo_id": (managed_lease_request or request).get("todo_id"), + "markdown": owner_report, + "created_at": datetime.now(timezone.utc).isoformat(), + "delivery_status": "pending", + "deliveries": {}, + }, + ) + committed_handoff = ( + steward_actions_state.get("context_handoff") + if steward_advancement and result.get("status") == "committed" + else None + ) + return { + "schema_version": "loopx_chat_agent_response_v0", + "message": ( + "当前没有可执行且已配置独立验收的原生任务,尚未启动模型;请检查原任务的验收配置。" + if managed_turn_validation_unavailable + else (owner_report or managed_answer or "本轮任务已完成结果回写。") + if result.get("status") == "committed" + else "本轮等待后续执行条件。" + if result.get("status") == "stopped" and result.get("result_kind") == "wait" + else "本轮任务尚未完成;执行状态已保留。" + ), + "proposals": [], + "gate": None, + "native_loopx": result, + **({"context_handoff": committed_handoff} if committed_handoff else {}), + **({"steward_owner_report_queued": True} if owner_report else {}), + **({"steward_user_action_receipts": user_action_receipts} if user_action_receipts else {}), + } diff --git a/loopx/capabilities/native_chat/steward_turn_execution.py b/loopx/capabilities/native_chat/steward_turn_execution.py new file mode 100644 index 0000000000..a08b4e08d8 --- /dev/null +++ b/loopx/capabilities/native_chat/steward_turn_execution.py @@ -0,0 +1,688 @@ +"""Execution orchestration for native Steward Turn workers.""" +from __future__ import annotations + +from collections.abc import Callable, Iterator, Mapping +from contextlib import AbstractContextManager, ExitStack, contextmanager, nullcontext +import json +from pathlib import Path +from typing import Protocol, cast + +from ...control_plane.goals.first_party_host_admission import FirstPartyHostRuntimeRejected +from ...file_lock import exclusive_file_lock +from .steward_turn_common import ( + StewardTurnHostProtocol, + as_dict, + as_dict_list, + as_mapping, + as_optional_dict, + native_steward_client_id, + steward_monitor_for, +) +from .steward_turn_context import ( + ExecutionReportServiceProtocol, + build_steward_turn_prompt, + finalize_steward_execution_response, +) + + +class _GuardOwnerProtocol(Protocol): + _launch_guard: Callable[[], AbstractContextManager[None]] | None + + +class _TurnAdapterProtocol(Protocol): + def start_turn( + self, + message: str, + event_sink: Callable[[str, dict[str, object]], None] | None = None, + ) -> dict[str, object]: ... + + def start_native_task_turn( + self, + message: str, + event_sink: Callable[[str, dict[str, object]], None] | None, + policy: dict[str, object], + ) -> dict[str, object]: ... + + +def _resolve_turn_selection_recovery( + host: StewardTurnHostProtocol, + *, + session_id: str, + turn_id: str, + turn: Mapping[str, object], + request: Mapping[str, object], +) -> tuple[dict[str, object] | None, dict[str, object] | None]: + actor = as_mapping(request["actor"]) + turn_instance_id = str(request["turn_instance_id"]) + original_client = ( + "managed." + turn_instance_id.removeprefix("managed-session.") + if actor.get("schema_version") == "loopx_managed_session_actor_v0" + else native_steward_client_id(actor, turn_instance_id) + ) + original = host.store.turn_for_client(session_id, original_client) if request.get("work_kind") == "report" else None + selection_recovery = ( + host.report_selection_recovery(original) if original and original.get("turn_id") != turn_id else None + ) + resumed_client = ( + original_client + ".admission-resume" + if actor.get("schema_version") == "loopx_managed_session_actor_v0" + else native_steward_client_id(actor, turn_instance_id + ".admission-resume") + ) + if selection_recovery and turn.get("client_turn_id") == resumed_client: + retry_client = ( + original_client + ".admission-retry" + if actor.get("schema_version") == "loopx_managed_session_actor_v0" + else native_steward_client_id(actor, turn_instance_id + ".admission-retry") + ) + retry = host.store.turn_for_client(session_id, retry_client) + if retry is None: + raise ValueError("the original admission probe is unavailable") + if original is None: + raise ValueError("the original report Turn is unavailable") + selection_recovery = host.report_selection_recovery(original, probe_turn=retry) + if selection_recovery is None: + raise ValueError("the original admission probe has no canonical journal") + return original, selection_recovery + + +def _finalize_candidate_and_build_result( + host: StewardTurnHostProtocol, + *, + native_request: Mapping[str, object], + response: Mapping[str, object], + actor: Mapping[str, object], + request: Mapping[str, object], + context: Mapping[str, object], + adapter: object, + reports: ExecutionReportServiceProtocol | None, + governance_work: bool, + report_work: bool, + managed_turn_active: bool, + steward_advancement: bool, + steward_actions_state: dict[str, object], + current_fn: Callable[[dict[str, object] | None], None], + normalize_advancement: Callable[[Mapping[str, object]], dict[str, object]], + normalize_report: Callable[[Mapping[str, object]], dict[str, object]], +) -> dict[str, object]: + from ...control_plane.turn_driver.host_candidate import build_result, parse_model_json + from .antigravity_adapter import AntigravityAdapter + + candidate = parse_model_json(str(response.get("message") or "")) + kernel_candidate = as_dict(candidate) if isinstance(candidate, Mapping) else None + if steward_advancement and not governance_work and kernel_candidate is not None: + steward_actions_state.update(host._normalize_steward_actions(kernel_candidate, context)) + kernel_candidate.pop("context_handoff", None) + kernel_candidate.pop("steward_user_actions", None) + kernel_candidate.pop("steward_owner_report", None) + kernel_candidate = normalize_advancement(kernel_candidate) + elif governance_work and kernel_candidate is not None: + kernel_candidate.pop("context_handoff", None) + kernel_candidate.pop("steward_user_actions", None) + kernel_candidate.pop("steward_owner_report", None) + kernel_candidate = normalize_advancement(kernel_candidate) + if ( + governance_work + and kernel_candidate + and kernel_candidate.get("result_kind") not in {"replan_required", "wait", "user_action_required", "iteration_failed"} + ): + kernel_candidate = { + "result_kind": "wait", + "classification": "report_replan_not_settled", + "next_action": "Retain the original report until its native semantic replan is settled.", + } + if ( + report_work + and not governance_work + and kernel_candidate + and kernel_candidate.get("result_kind") in {"validated_progress", "validated_completion"} + ): + observed = host._observe(actor) + with host.controller.lock, host._report_fence(request): + current_fn(observed) + assert reports is not None + reports.freeze(request, kernel_candidate) + # This finite task's postcondition is the complete validated + # generation, not the model's choice of progress wording. + # The kernel still runs its independent validator and lease + # fence before closing only this window's generation Todo. + kernel_candidate = normalize_report(kernel_candidate) + built = build_result( + native_request, + kernel_candidate, + host_name="Antigravity" if isinstance(adapter, AntigravityAdapter) else "Codex app-server", + allow_completion=bool((report_work or managed_turn_active or steward_advancement) and not governance_work), + ) + return as_dict(built) + + +def _append_native_result_with_readback( + host: StewardTurnHostProtocol, + *, + session_id: str, + turn_id: str, + result: Mapping[str, object], +) -> None: + try: + host.store.append_event(session_id, turn_id, kind="native_loopx.result", payload=dict(result)) + except OSError: + # The native transaction already owns execution and settlement. + # A lost Chat append acknowledgment must not discard its answer + # when this exact committed event is independently readable. + # Reuse the store's ordered readback without re-entering native work. + if result.get("ok") is not True or result.get("status") != "committed": + raise + recorded = [row for row in host.store.events_after(session_id, turn_id, None) if row.get("kind") == "native_loopx.result"] + if len(recorded) != 1 or recorded[0].get("payload") != result: + raise + + +def execute_steward_turn( + host: StewardTurnHostProtocol, + *, + session_id: str, + turn_id: str, + adapter: object, + event_sink: object, + context: dict[str, object], + normalize_advancement: Callable[[Mapping[str, object]], dict[str, object]], + normalize_report: Callable[[Mapping[str, object]], dict[str, object]], + is_replan_deferral: Callable[[Mapping[str, object]], bool], +) -> dict[str, object]: + """Run in the original Chat worker, through all native settlement owners.""" + from ...cli_runtime import _build_selected_parser + from ...cli_commands.turn import handle_turn_command + from ...control_plane.turn_driver.host_candidate import build_result, extract_turn_authority + from .antigravity_adapter import ANTIGRAVITY_IDLE_TIMEOUT_SEC, AntigravityAdapter + from .codex_adapter import CodexAppServerAdapter + from .steward_managed_mode import ManagedSessionTurn, ManagedTaskValidationUnavailable + from .steward_reports import report_service + + turn_raw = host.store.load_turn(session_id, turn_id) + if turn_raw is None: + raise ValueError("the accepted Turn is unavailable") + turn = as_dict(turn_raw) + request = as_dict(turn["loopx_request"]) + original, selection_recovery = _resolve_turn_selection_recovery( + host, session_id=session_id, turn_id=turn_id, turn=turn, request=request + ) + admitted = host._admit(request, turn=turn, selection_recovery=selection_recovery) + actor = as_mapping(admitted["actor"]) + local_session = actor.get("schema_version") == "loopx_managed_session_actor_v0" + report_work = request.get("work_kind") == "report" + steward_advancement = not local_session and not report_work + managed_turn = ManagedSessionTurn(host.controller) if local_session and not report_work else None + if admitted["observation_only"]: + monitor = steward_monitor_for(host.controller) + todo = next( + (row for row in as_dict_list(monitor.todos(dict(actor))) if row.get("todo_id") == request.get("todo_id")), + None, + ) + if todo is None: + raise ValueError("the original steward monitor Todo is unavailable") + return as_dict(monitor.observe(host=host, request=request, turn=turn, context=context, todo=todo)) + if local_session and not isinstance(adapter, CodexAppServerAdapter): + raise ValueError("native steward work requires the original Codex app-server adapter") + if not local_session and not isinstance(adapter, (CodexAppServerAdapter, AntigravityAdapter)): + raise ValueError("native steward work requires the original Codex app-server or Antigravity adapter") + + original_thread = getattr(adapter, "upstream_thread_id", None) + reports_pair = report_service(host.controller, dict(actor)) if report_work else (None, None) + reports = cast(ExecutionReportServiceProtocol | None, reports_pair[0]) + report_owner_key: str | None = reports_pair[1] + report_context = "" + governance_work = False + report_launch_rejected = False + managed_answer = "" + managed_lease: dict[str, object] | None = None + managed_lease_request: dict[str, object] | None = None + preparation_status: str | None = None + report_lease: dict[str, object] | None = None + steward_actions_state: dict[str, object] = { + "context_handoff": None, + "user_actions": [], + "owner_report": None, + "validation_error": None, + } + managed_leases = ExitStack() + + def report_lease_proof() -> dict[str, object]: + return host._task_lease_proof(request, report_lease) + + def current(observed: dict[str, object] | None = None) -> None: + fresh = host.store.load_turn(session_id, turn_id) + host._admit(request, turn=fresh, observed=observed, selection_recovery=selection_recovery) + if getattr(adapter, "upstream_thread_id", None) != original_thread: + raise ValueError("the original steward native thread changed") + if report_lease: + report_lease_proof() + if managed_lease and managed_lease_request is not None: + host._task_lease_proof(managed_lease_request, managed_lease) + + def session_binding(envelope: Mapping[str, object]) -> dict[str, object]: + current(None) + identity = envelope.get("agent_identity") if envelope.get("schema_version") == "loopx_turn_envelope_v1" else envelope + if ( + envelope.get("goal_id") != actor["goal_id"] + or not isinstance(identity, Mapping) + or identity.get("agent_id") != actor["agent_id"] + ): + raise ValueError("native Turn belongs to another actor") + return { + "schema_version": "loopx_turn_session_binding_v0", + "goal_id": actor["goal_id"], + "agent_id": actor["agent_id"], + } + + def prepare_native_task(decision: Mapping[str, object]) -> str | None: + nonlocal managed_lease, managed_lease_request, preparation_status + from ...control_plane.turn_driver.codex_execution_preparation import compact_execution_preparation_request + + preparation = as_optional_dict(compact_execution_preparation_request(decision)) + if preparation is None: + return None + todo_id = str(preparation["todo_id"]) + if ( + preparation["goal_id"] != actor["goal_id"] + or preparation["agent_id"] != actor["agent_id"] + or preparation.get("turn_instance_id", request["turn_instance_id"]) != request["turn_instance_id"] + or (request["todo_id"] is not None and todo_id != request["todo_id"]) + ): + raise ValueError("native task preparation belongs to another Turn or Todo") + current(None) + if managed_turn is not None: + try: + managed_turn.prepare_validation(dict(request), {"work_contract": decision}) + except ManagedTaskValidationUnavailable: + managed_turn.validation_unavailable = True + preparation_status = "stopped" + raise + except ValueError: + preparation_status = "failed" + raise + managed_lease_request = {**request, "todo_id": todo_id} + managed_lease = managed_leases.enter_context( + host._task_execution_lease(managed_lease_request, turn_id, claim_args=cast(list[str], preparation["claim_args"])) + ) + return todo_id + + def run(native_request: Mapping[str, object], launch_scope: Callable[[], AbstractContextManager[None]]) -> dict[str, object]: + nonlocal managed_lease, managed_lease_request, managed_answer + current(None) + authority = as_mapping(extract_turn_authority(native_request)) + if governance_work and not authority.get("replan_action_packet"): + return as_dict( + build_result( + native_request, + { + "result_kind": "wait", + "classification": "report_replan_not_admitted", + "next_action": "Retain the original report; its native governance route is no longer admitted.", + }, + ) + ) + if managed_turn and not governance_work: + raw_work_identity = authority.get("_work_identity") + checked_identity = ( + {str(k): str(v) for k, v in as_mapping(raw_work_identity).items()} + if isinstance(raw_work_identity, Mapping) + else None + ) + try: + managed_turn.prepare_validation( + dict(request), + dict(native_request), + _checked_work_identity=checked_identity, + ) + except ManagedTaskValidationUnavailable: + managed_turn.validation_unavailable = True + return as_dict( + build_result( + native_request, + { + "result_kind": "user_action_required", + "classification": "independent_task_validation_unavailable", + "summary": "The selected task has no usable independent argv validation declaration.", + "next_action": "Configure the original task's independent validation before executing it.", + }, + host_name="Codex app-server", + ) + ) + validation_basis = as_mapping(managed_turn.validation_basis) + selected_request = {**request, "todo_id": validation_basis["todo_id"]} + if managed_lease is None: + managed_lease_request = selected_request + managed_lease = managed_leases.enter_context(host._task_execution_lease(managed_lease_request, turn_id)) + elif managed_lease_request is None or selected_request["todo_id"] != managed_lease_request["todo_id"]: + raise ValueError("native task preparation no longer matches the selected Todo") + host._task_lease_proof(selected_request, managed_lease) + + prompt = build_steward_turn_prompt( + host, + actor=actor, + session_id=session_id, + request=request, + authority=authority, + context=context, + report_work=report_work, + governance_work=governance_work, + managed_turn_active=managed_turn is not None, + steward_advancement=steward_advancement, + report_context=report_context, + ) + if steward_advancement and not governance_work: + selected_todo_id = as_mapping(authority.get("_work_identity")).get("todo_id") or request.get("todo_id") + if selected_todo_id and managed_lease is None: + managed_lease_request = {**request, "todo_id": selected_todo_id} + managed_lease = managed_leases.enter_context(host._task_execution_lease(managed_lease_request, turn_id)) + + raw_owner = getattr(adapter, "session", None) if isinstance(adapter, CodexAppServerAdapter) else adapter + guard_owner = cast(_GuardOwnerProtocol, raw_owner) + previous_guard = guard_owner._launch_guard + + @contextmanager + def launch() -> Iterator[None]: + nonlocal report_launch_rejected + observed = host._observe(actor) + with ExitStack() as stack: + try: + if previous_guard is not None: + stack.enter_context(previous_guard()) + stack.enter_context(launch_scope()) + stack.enter_context( + nullcontext() + if actor.get("schema_version") == "loopx_managed_session_actor_v0" or host.bindings is None + else exclusive_file_lock(host.bindings.path, operation="native_steward_launch") + ) + current(observed) + except FirstPartyHostRuntimeRejected as exc: + if not report_work or exc.code != "stale_goal_authority": + raise + if not local_session and not governance_work and original and original.get("turn_id") == turn_id: + report_launch_rejected = True + from ...control_plane.turn_driver.host_failure import BuiltInHostError + + raise BuiltInHostError(str(exc), failure_kind="contract_rejected") from exc + yield + + guard_owner._launch_guard = launch + try: + typed_adapter = cast(_TurnAdapterProtocol, adapter) + sink_fn = cast(Callable[[str, dict[str, object]], None] | None, event_sink) + if managed_turn and not governance_work: + from ...control_plane.effect_runtime import effect_runtime_result + + validation_basis = as_mapping(managed_turn.validation_basis) + policy = as_dict( + effect_runtime_result( + "collaboration.session.managed_turn.sandbox_policy", + { + "host": request["host"], + "actor": actor, + "authority": authority, + "validation": validation_basis["plan"], + "task_lease": managed_lease, + }, + ) + ) + response = as_mapping(typed_adapter.start_native_task_turn(prompt, sink_fn, policy)) + else: + invocation_sink = ( + ( + lambda kind, payload: sink_fn(kind, payload) + if kind not in {"answer.delta", "answer.final", "turn.native_result"} + else None + ) + if (governance_work and sink_fn is not None) + else sink_fn + ) + if (report_work or steward_advancement or governance_work) and isinstance(adapter, AntigravityAdapter): + response = as_mapping( + adapter.start_turn( + prompt, + invocation_sink, + isolated_cascade=True, + raw_prompt=True, + idle_timeout_sec=( + adapter.idle_timeout_sec + if adapter.idle_timeout_sec is not None + else ANTIGRAVITY_IDLE_TIMEOUT_SEC + ), + ) + ) + else: + response = as_mapping(typed_adapter.start_turn(prompt, invocation_sink)) + finally: + guard_owner._launch_guard = previous_guard + current(None) + built = _finalize_candidate_and_build_result( + host, + native_request=native_request, + response=response, + actor=actor, + request=request, + context=context, + adapter=adapter, + reports=reports, + governance_work=governance_work, + report_work=report_work, + managed_turn_active=managed_turn is not None, + steward_advancement=steward_advancement, + steward_actions_state=steward_actions_state, + current_fn=current, + normalize_advancement=normalize_advancement, + normalize_report=normalize_report, + ) + if managed_turn or steward_advancement: + managed_answer = str(built.get("summary") or "") + return built + + argv = [ + "turn", "run-once", "--goal-id", str(actor["goal_id"]), "--agent-id", str(actor["agent_id"]), + "--project", str(admitted["workspace_path"]), "--host", "generic-cli", "--execute", + ] + if request.get("resume_turn_key"): + argv += ["--resume-turn-key", str(request["resume_turn_key"]), "--retry-failed-turn"] + else: + argv += ["--turn-instance-id", str(request["turn_instance_id"])] + if request.get("todo_id") is not None and not request.get("resume_turn_key"): + argv += ["--todo-id", str(request["todo_id"])] + if request.get("validation_command") is not None: + argv += ["--validation-command-json", json.dumps(request["validation_command"])] + args = _build_selected_parser("turn").parse_args(argv) + args.host, args.session_scope = "codex-app-server", "agent" + result: dict[str, object] = {} + + def retain_report_lease() -> bool: + failure = as_mapping(result.get("host_failure")) + return report_launch_rejected and failure.get("kind") == "contract_rejected" and failure.get("attempt") == 1 + + with ( + managed_leases, + ( + host._task_execution_lease( + request, + turn_id, + admission_retry=bool(selection_recovery), + retain_for_retry=retain_report_lease, + ) + if report_work + else nullcontext(None) + ) as entered_report_lease, + ): + report_lease = as_optional_dict(entered_report_lease) + if not report_work and request.get("todo_id") and not request.get("resume_turn_key"): + from .steward_commands import native_command + + selected = as_mapping( + native_command( + host.controller, + ["todo", "list", "--goal-id", str(actor["goal_id"]), "--todo-id", str(request["todo_id"]), "--agent-id", str(actor["agent_id"])], + ) + ) + if selected.get("matched") is True: + managed_lease_request = dict(request) + managed_lease = managed_leases.enter_context(host._task_execution_lease(request, turn_id)) + if selection_recovery and "probe" not in selection_recovery: + governance_work = True + + def probe_governance(todo_id: object) -> dict[str, object]: + governance_args = type(args)(**vars(args)) + governance_args.todo_id, governance_args.validation_command_json = todo_id, None + governance_args.turn_instance_id = str(request["turn_instance_id"]) + ".replan" + observed_gov: dict[str, object] = {} + handle_turn_command( + governance_args, + registry_path=cast(Path, host.controller.registry_path), + runtime_root_arg=str(host.controller.coordination_runtime_root), + output_format=lambda *_a, **_kw: "json", + print_payload=lambda value, *_a: observed_gov.update(as_mapping(value)), + native_host_runner=run, + native_session_binding_resolver=session_binding, + ) + return observed_gov + + governance = probe_governance(request["todo_id"]) + if ( + governance.get("error_code") == "turn_todo_selection_deferred" + and as_mapping(governance.get("selection_rejection")).get("reason_code") == "autonomous_replan" + ): + governance = probe_governance(None) + host.store.append_event(session_id, turn_id, kind="native_loopx.replan_result", payload=governance) + if governance.get("status") != "committed" or governance.get("result_kind") != "replan_required": + assert original is not None + probe = host.report_selection_recovery(original, probe_turn=host.store.load_turn(session_id, turn_id)) + try: + if probe is None or "probe" not in probe: + raise ValueError("no canonical admission probe") + host._admit(request, turn=host.store.load_turn(session_id, turn_id), selection_recovery=probe) + except (OSError, ValueError, RuntimeError): + retained = as_dict(as_mapping(as_mapping(selection_recovery["original"]).get("response")).get("native_loopx")) + host.store.append_event(session_id, turn_id, kind="native_loopx.result", payload=retained) + return { + "schema_version": "loopx_chat_agent_response_v0", + "message": "原生重规划尚未完成;保留原报告及执行证据。", + "proposals": [], + "gate": None, + "native_loopx": retained, + } + selection_recovery = probe + governance_work = False + if report_work: + assert reports is not None + current(None) + report_context = reports.prepare(request, adapter, authorization_scope_id=admitted.get("observed_scope_id")) + current(None) + + def steward_validator(_plan: Mapping[str, object], candidate_result: Mapping[str, object]) -> dict[str, object]: + if steward_actions_state.get("validation_error"): + return { + "status": "failed", + "validator_kind": "callback", + "summary": str(steward_actions_state["validation_error"]), + "recovery_kind": "repair_required", + } + if candidate_result.get("result_kind") in {"validated_progress", "validated_completion"}: + return { + "status": "passed", + "validator_kind": "callback", + "summary": "steward advancement actions passed validation", + } + return { + "status": "passed", + "validator_kind": "callback", + "summary": "steward advancement non-completion result recorded", + } + + def managed_completion_lease_proof() -> dict[str, object]: + return host._task_lease_proof(managed_lease_request or request, managed_lease) + + task_validator: Callable[[Mapping[str, object], Mapping[str, object]], Mapping[str, object]] | None = None + completion_lease_resolver: Callable[[], Mapping[str, object]] | None = None + if report_work: + task_validator = host._report_validator(request) + completion_lease_resolver = report_lease_proof + elif managed_turn is not None: + task_validator = managed_turn.validator(dict(request), turn_id=turn_id) + completion_lease_resolver = managed_completion_lease_proof + elif steward_advancement: + task_validator = steward_validator + completion_lease_resolver = managed_completion_lease_proof + + def run_primary_turn() -> None: + result.clear() + handle_turn_command( + args, + registry_path=cast(Path, host.controller.registry_path), + runtime_root_arg=str(host.controller.coordination_runtime_root), + output_format=lambda *_a, **_kw: "json", + print_payload=lambda value, *_a: result.update(as_mapping(value)), + native_host_runner=run, + native_session_binding_resolver=session_binding, + native_execution_preparer=prepare_native_task if not report_work else None, + native_completion_lease_resolver=completion_lease_resolver, + native_task_validator=task_validator, + ) + + run_primary_turn() + if ( + steward_advancement + and request.get("todo_id") + and not request.get("resume_turn_key") + and is_replan_deferral(result) + ): + governance_args = type(args)(**vars(args)) + governance_args.todo_id, governance_args.validation_command_json = None, None + governance_args.turn_instance_id = str(request["turn_instance_id"]) + ".replan" + adv_governance: dict[str, object] = {} + governance_work = True + try: + handle_turn_command( + governance_args, + registry_path=cast(Path, host.controller.registry_path), + runtime_root_arg=str(host.controller.coordination_runtime_root), + output_format=lambda *_a, **_kw: "json", + print_payload=lambda value, *_a: adv_governance.update(as_mapping(value)), + native_host_runner=run, + native_session_binding_resolver=session_binding, + ) + finally: + governance_work = False + host.store.append_event(session_id, turn_id, kind="native_loopx.replan_result", payload=adv_governance) + replan_cleared = ( + adv_governance.get("status") == "committed" and adv_governance.get("result_kind") == "replan_required" + ) or ( + adv_governance.get("status") == "stopped" + and as_mapping(adv_governance.get("host_result")).get("classification") == "report_replan_not_admitted" + and host._cleared_replan_guard(actor) is not None + ) + if replan_cleared: + run_primary_turn() + elif isinstance(adv_governance.get("effects"), Mapping): + gov_effects = as_mapping(adv_governance["effects"]) + merged_effects = dict(as_mapping(result.get("effects"))) + for key in ("host_invoked", "state_written", "quota_spent", "scheduler_acknowledged"): + if gov_effects.get(key) is True: + merged_effects[key] = True + result["effects"] = merged_effects + if preparation_status is not None: + result["status"] = preparation_status + if preparation_status == "stopped": + result.update(ok=True, result_kind="user_action_required") + _append_native_result_with_readback(host, session_id=session_id, turn_id=turn_id, result=result) + return finalize_steward_execution_response( + host, + actor=actor, + session_id=session_id, + turn_id=turn_id, + request=request, + selection_recovery=selection_recovery, + result=result, + reports=reports, + report_owner_key=report_owner_key, + local_session=local_session, + steward_advancement=steward_advancement, + steward_actions_state=steward_actions_state, + managed_turn_validation_unavailable=bool(managed_turn and managed_turn.validation_unavailable), + managed_answer=managed_answer, + managed_lease_request=managed_lease_request, + ) diff --git a/loopx/capabilities/native_chat/steward_turn_recovery.py b/loopx/capabilities/native_chat/steward_turn_recovery.py new file mode 100644 index 0000000000..04b13ec892 --- /dev/null +++ b/loopx/capabilities/native_chat/steward_turn_recovery.py @@ -0,0 +1,904 @@ +"""Monitor restart and frozen/stopped report recovery helpers for StewardTurnHost.""" +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from contextlib import nullcontext +import json +from pathlib import Path +import time +from typing import Protocol, cast + +from ...file_lock import LOCK_ACQUIRE_TIMEOUT_ERROR_CODE, exclusive_file_lock +from .steward_monitor import ( + actor_steward_binding_id, + load_steward_monitor_turn_by_id, + lookup_steward_monitor_turn, +) +from .steward_turn_common import ( + MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS, + MonitorRestartCarrier, + StewardStoreProtocol, + StewardTurnHostProtocol, + _FILE_LOCK_TIMEOUT_ERROR_RE, + _POST_CONTEXT_WATCH_ERRORS, + as_dict, + as_dict_list, + as_mapping, + as_optional_dict, + as_optional_str, + iso_timestamp_seconds, + monitor_store_for, + native_steward_client_id, + steward_monitor_for, +) + +_MONITOR_PRE_POLL_ERROR = ( + "the native steward operation was not committed: quota_action_selection_rejected: " + "explicit action selection is not currently eligible: auxiliary_monitor_not_selectable_in_advancement_lane" +) + + +class _ReportServiceProtocol(Protocol): + @property + def root(self) -> Path: ... + + def current_window(self, owner_key: str) -> tuple[dict[str, object] | None, dict[str, object] | None]: ... + + def freeze(self, request: Mapping[str, object], candidate: Mapping[str, object]) -> object: ... + + def delivery_current(self, owner_key: str, window: Mapping[str, object]) -> bool: ... + + +def monitor_selection_failed_before_poll( + store: StewardStoreProtocol, + turn: Mapping[str, object], +) -> bool: + """Recognize only the legacy pre-poll monitor selection failure at the Chat boundary.""" + return ( + turn.get("status") == "failed" + and turn.get("error_code") == "runtime_error" + and turn.get("error") == _MONITOR_PRE_POLL_ERROR + and turn.get("delta_count") == 0 + and turn.get("upstream_turn_id") is None + and turn.get("response") is None + and not any( + row.get("kind") == "native_loopx.monitor_poll" + for row in store.events_after(str(turn["session_id"]), str(turn["turn_id"]), None) + ) + ) + + +def monitor_restart_basis( + host: StewardTurnHostProtocol, + request: Mapping[str, object], +) -> dict[str, object]: + """Read original worker/journals without dispatching or repairing effects. + + Any pending, committed, unreadable or legacy poll evidence withholds a + new carrier. The shared typed admission owner interprets these facts. + """ + recovery = as_optional_dict(request.get("monitor_restart_recovery")) + if recovery is None: + return {} + from ...chat_store import _read_jsonl + from ...control_plane.quota.monitor_poll import _monitor_poll_effect_id, _monitor_poll_receipt_path + from .steward_commands import native_command + from .steward_monitor import TARGET + + actor = as_mapping(request["actor"]) + original_raw = load_steward_monitor_turn_by_id(monitor_store_for(host.store), actor, str(recovery["original_turn_id"])) + if original_raw is None: + raise ValueError("the original stopped watch is unavailable") + original = as_dict(original_raw) + original_session_id = str(original["session_id"]) + original_turn_id = str(original["turn_id"]) + root = host.controller.coordination_runtime_root + goal_id = str(actor["goal_id"]) + agent_id = str(actor["agent_id"]) + todo_id = request["todo_id"] + turn_instance_id = str(request["turn_instance_id"]) + with exclusive_file_lock( + host.store.turn_execution_lock_path(original_session_id, original_turn_id), + timeout_seconds=0, + operation="observe_stopped_native_watch", + ): + # Strict reads are essential: an unreadable/compacted journal is + # unknown, never an empty observation or proof that work did not run. + events = as_dict_list( + _read_jsonl( + host.store._event_path(original_session_id, original_turn_id), + raise_on_error=True, + strict=True, + ) + ) + rows = as_dict_list( + _read_jsonl( + root / "goals" / goal_id / "runs" / "index.jsonl", + raise_on_error=True, + strict=True, + ) + ) + present = any( + row.get("classification") == "quota_monitor_poll" + and row.get("turn_instance_id") == turn_instance_id + for row in rows + ) + target = ( + "managed-session-watch." + str(actor["session_id"]) + if actor.get("schema_version") == "loopx_managed_session_actor_v0" + else TARGET + ) + if actor.get("schema_version") != "loopx_managed_session_actor_v0": + matched = next( + ( + row + for row in as_dict_list(steward_monitor_for(host.controller).todos(dict(actor))) + if row.get("todo_id") == todo_id + ), + None, + ) + if matched and matched.get("target_key"): + target = str(matched["target_key"]) + for probe_todo, probe_key in [(todo_id, target), (None, target), (None, None)]: + effect = _monitor_poll_effect_id( + runtime_root=root, + goal_id=goal_id, + agent_id=agent_id, + turn_instance_id=turn_instance_id, + todo_id=as_optional_str(probe_todo), + target_key=probe_key, + goal_ref=None, + ) + present = present or _monitor_poll_receipt_path(root, goal_id, effect).exists() + lease = as_dict( + native_command( + host.controller, + ["task-lease", "inspect", "--goal-id", goal_id, "--todo-id", str(todo_id)], + ) + ) + held = as_mapping(lease.get("lease")) + available = lease.get("active") is False or ( + held.get("owner") == agent_id + and held.get("idempotency_key") == "monitor-recovery." + original_turn_id + ) + return { + "monitor_restart_basis": { + "original": original, + "event_kinds": [row["kind"] for row in events], + "poll_absent": not present, + "contexts": [row["payload"] for row in events if row["kind"] == "manager.context"], + "phases": [row["payload"] for row in events if row["kind"] == "agent.phase"], + "old_worker_excluded": True, + "lease_available": available, + "observed_at": time.time(), + } + } + + +def monitor_restart_request( + original: Mapping[str, object], + *, + now: float | None = None, +) -> dict[str, object] | None: + """Prepare correlation only; current typed admission decides recovery.""" + prior = as_dict(original.get("loopx_request")) + error = original.get("error_code") + if ( + original.get("status") != "failed" + or error not in {"server_restarted", "runtime_error", "runtime_unavailable", LOCK_ACQUIRE_TIMEOUT_ERROR_CODE} + or prior.get("work_kind") != "monitor" + ): + return None + if prior.get("monitor_restart_recovery") is not None and error != "server_restarted": + msg = original.get("error") + post_context_error = error in {"runtime_unavailable", LOCK_ACQUIRE_TIMEOUT_ERROR_CODE} or ( + error == "runtime_error" + and ( + msg in _POST_CONTEXT_WATCH_ERRORS + or (isinstance(msg, str) and _FILE_LOCK_TIMEOUT_ERROR_RE.fullmatch(msg) is not None) + ) + ) + completed_ts = iso_timestamp_seconds(original.get("completed_at")) + current_ts = time.time() if now is None else now + if ( + not post_context_error + or completed_ts is None + or current_ts - completed_ts < MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS + ): + return None + return {**prior, "monitor_restart_recovery": {"original_turn_id": original["turn_id"]}} + + +def monitor_restart_carrier( + host: StewardTurnHostProtocol, + original: Mapping[str, object], + client_id: str, +) -> MonitorRestartCarrier | None: + """Find the latest carrier for the same observation; typed admission proves a safe restart.""" + request = monitor_restart_request(original) + if request is None: + return None + actor = as_optional_dict(as_mapping(original.get("loopx_request")).get("actor")) + binding_id = actor_steward_binding_id(actor) if actor is not None else None + base = client_id + ".restart-recovery" + next_client_id = base + session_id = str(original["session_id"]) + while True: + raw_carrier = lookup_steward_monitor_turn(monitor_store_for(host.store), binding_id, session_id, next_client_id) + if raw_carrier is None: + break + carrier = as_dict(raw_carrier) + if as_mapping(carrier.get("loopx_request")).get("monitor_restart_recovery") != request["monitor_restart_recovery"]: + raise ValueError("native watch continuation identity conflict") + request = monitor_restart_request(carrier) + if request is None: + return {"turn": carrier} + next_client_id = base + "." + str(carrier["turn_id"]) + return {"request": request, "client_id": next_client_id} + + +def report_continuation_basis( + host: StewardTurnHostProtocol, + request: Mapping[str, object], + *, + recovery_key: str, + basis_key: str, +) -> dict[str, object]: + """Transport original journal observations; the typed owner admits work.""" + recovery = as_optional_dict(request.get(recovery_key)) + if recovery is None: + return {} + from ...control_plane.turn_driver import inspect_loopx_turn_journal + from ..periodic_report.private_generation import attempt_directory + from .steward_reports import report_service + + actor = as_mapping(request["actor"]) + original = host.store.load_turn(str(actor["session_id"]), str(recovery["original_turn_id"])) + result = as_mapping(as_mapping((original or {}).get("response")).get("native_loopx")) + reports, owner = report_service(host.controller, dict(actor)) + _, window = reports.current_window(owner) + folder = attempt_directory(reports.root, window) if window else None + return { + basis_key: { + "original": original, + "inspection": inspect_loopx_turn_journal( + reports.root, + goal_id=actor["goal_id"], + agent_id=actor["agent_id"], + turn_key=result["resume_turn_key"], + ), + "generation_present": folder is None + or any((folder / name).exists() for name in ("editorial-response.json", "private-generation.json", "private-delivery.json")), + "observed_at": time.time(), + } + } + + +def cleared_replan_guard( + host: StewardTurnHostProtocol, + actor: Mapping[str, object], +) -> dict[str, object] | None: + """Read-only guard check proving an earlier autonomous_replan obligation was cleared.""" + from ...control_plane.quota.effective_action import EffectiveAction + from .steward_commands import NativeStewardCommandError, native_command + + try: + raw = native_command( + host.controller, + ["quota", "should-run", "--goal-id", str(actor["goal_id"]), "--agent-id", str(actor["agent_id"]), "--dry-run"], + ) + except (NativeStewardCommandError, OSError, ValueError, RuntimeError): + return None + payload = as_mapping(raw) + ref_file = payload.get("reference_file") + if payload.get("effective_action") is None and isinstance(ref_file, str): + try: + ref = as_mapping(json.loads(Path(ref_file).read_text(encoding="utf-8"))) + target = Path(str(ref.get("path") or ref_file)) + loaded = json.loads(target.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + if isinstance(loaded, Mapping): + payload = as_mapping(loaded) + current: dict[str, object] = { + "effective_action": payload.get("effective_action"), + "replan_action_packet": payload.get("replan_action_packet"), + } + if current["effective_action"] != EffectiveAction.NORMAL_RUN.value or current["replan_action_packet"] is not None: + return None + return current + + +def report_selection_recovery( + host: StewardTurnHostProtocol, + original: Mapping[str, object], + *, + probe_turn: Mapping[str, object] | None = None, +) -> dict[str, object] | None: + """The typed owner qualifies this observation before any new worker.""" + result = as_mapping(as_mapping(original.get("response")).get("native_loopx")) + refusal = as_optional_dict(result.get("selection_rejection")) + if ( + result.get("error_code") != "turn_todo_selection_deferred" + or refusal is None + or refusal.get("reason_code") != "autonomous_replan" + or refusal.get("recovery_action") != "reenter_guard_without_selection" + ): + return None + from ..periodic_report.private_generation import attempt_directory + from .steward_reports import report_service + + request = as_mapping(original["loopx_request"]) + actor = as_mapping(request["actor"]) + reports, owner = report_service(host.controller, dict(actor)) + _, window = reports.current_window(owner) + proof: dict[str, object] = { + "original": original, + "generation_present": window is None + or window["window_id"] != request["report_window_id"] + or (attempt_directory(reports.root, window) / "private-generation.json").exists(), + } + if probe_turn is not None: + from ...control_plane.effect_runtime import source_number_tokens + from ...control_plane.turn_driver.executor import inspect_loopx_turn_journal + from ...control_plane.turn_driver.journal_store import load_turn_journal, turn_journal_path + + keys = { + as_mapping(row.get("payload")).get("resume_turn_key") + for row in host.store.events_after(str(actor["session_id"]), str(probe_turn["turn_id"]), None) + if row.get("kind") == "native_loopx.replan_result" + } + if len(keys) != 1: + return None + key_obj = keys.pop() + if not isinstance(key_obj, str): + return None + goal_id = str(actor["goal_id"]) + agent_id = str(actor["agent_id"]) + journal = as_optional_dict(load_turn_journal(turn_journal_path(reports.root, goal_id=goal_id, turn_key=key_obj))) + if journal is None: + return None + current_guard: dict[str, object] | None = None + journal_status = journal.get("status") + if ( + journal_status == "failed" + and journal.get("result_kind") == "validation_failed" + and journal.get("validation_stage") in {"host_result_contract", "task_postcondition"} + ): + current_guard = host._cleared_replan_guard(actor) + if current_guard is None: + return None + elif journal_status != "stopped": + return None + # Transport canonical observations to the shared typed admission owner. + proof["probe"] = { + "turn": probe_turn, + "inspection": inspect_loopx_turn_journal(reports.root, goal_id=goal_id, agent_id=agent_id, turn_key=key_obj), + "journal": journal, + "source_number_tokens": source_number_tokens(as_mapping(journal.get("plan")).get("work_contract")), + **({"current_guard": current_guard} if current_guard is not None else {}), + } + return proof + + +def report_launch_recovery( + host: StewardTurnHostProtocol, + original: Mapping[str, object], +) -> dict[str, object] | None: + """Read the original typed launch refusal and its canonical transaction.""" + result = as_mapping(as_mapping(original.get("response")).get("native_loopx")) + if as_mapping(result.get("host_failure")).get("kind") != "contract_rejected": + return None + from ...control_plane.turn_driver import inspect_loopx_turn_journal + from ...control_plane.turn_driver.journal_store import ( + find_loopx_turn_key_by_settlement_identity, + load_turn_journal, + turn_journal_path, + ) + from ..periodic_report.private_generation import attempt_directory + from .steward_reports import StewardReports + + request = as_mapping(original["loopx_request"]) + actor = as_mapping(request["actor"]) + goal_id = str(actor["goal_id"]) + agent_id = str(actor["agent_id"]) + root = host.controller.coordination_runtime_root + key = find_loopx_turn_key_by_settlement_identity( + root, + goal_id=goal_id, + agent_id=agent_id, + todo_id=as_optional_str(request.get("todo_id")), + turn_instance_id=str(request["turn_instance_id"]), + ) + if key is None: + raise ValueError("the original launch rejection has no canonical Turn") + inspection = inspect_loopx_turn_journal(root, goal_id=goal_id, agent_id=agent_id, turn_key=key, retry_failed=True) + journal = as_optional_dict(load_turn_journal(turn_journal_path(root, goal_id=goal_id, turn_key=key))) + _, window = StewardReports(host.controller).current_window(goal_id.removeprefix("steward-agent-")) + return { + "original": original, + "inspection": inspection, + "journal": journal, + "turn_key": key, + "host_attempt_count": (journal or {}).get("host_attempt_count"), + "generation_present": window is None or (attempt_directory(root, window) / "private-generation.json").exists(), + } + + +def _find_matching_editorial_candidate( + events: Sequence[Mapping[str, object]], + *, + expected_digest: object, +) -> dict[str, object] | None: + from ...control_plane.turn_driver.host_candidate import parse_model_json + + for row in reversed(events): + if row.get("kind") != "answer.final": + continue + message = as_mapping(as_mapping(row.get("payload")).get("response")).get("message") + parsed_raw = parse_model_json(str(message or "")) + if not isinstance(parsed_raw, dict): + continue + parsed = as_dict(parsed_raw) + if parsed.get("result_kind") not in {"validated_progress", "validated_completion"}: + continue + editorial = as_optional_dict(parsed.get("editorial_response")) + if editorial is None or editorial.get("request_digest") != expected_digest: + continue + return parsed + return None + + +def frozen_report_contract_recovery( + host: StewardTurnHostProtocol, + actor: Mapping[str, object], + window: Mapping[str, object], + original: Mapping[str, object], + *, + key: str, + generation: Mapping[str, object], + root: Path, + normalize_report_candidate: Callable[[Mapping[str, object]], dict[str, object]], +) -> tuple[dict[str, object], dict[str, object]] | None: + """Recover only an already-frozen report whose host candidate hit host_result_contract.""" + from ...control_plane.turn_driver.journal_store import load_turn_journal, turn_journal_path + + goal_id = str(actor["goal_id"]) + session_id = str(actor["session_id"]) + window_id = str(window["window_id"]) + journal = as_optional_dict(load_turn_journal(turn_journal_path(root, goal_id=goal_id, turn_key=key))) + if ( + journal is None + or journal.get("status") != "failed" + or journal.get("result_kind") != "validation_failed" + or journal.get("validation_stage") != "host_result_contract" + or journal.get("host_attempt_count") != 1 + ): + return None + resumed = host.store.turn_for_client(session_id, native_steward_client_id(actor, "report." + window_id + ".admission-resume")) + retry = host.store.turn_for_client(session_id, native_steward_client_id(actor, "report." + window_id + ".admission-retry")) + seen_turn_ids: set[str] = set() + candidates: list[Mapping[str, object]] = [] + for candidate_turn in (resumed, retry, original): + if isinstance(candidate_turn, Mapping): + tid = candidate_turn.get("turn_id") + if isinstance(tid, str) and tid not in seen_turn_ids: + seen_turn_ids.add(tid) + candidates.append(candidate_turn) + for candidate_turn in candidates: + events = host.store.events_after(session_id, str(candidate_turn["turn_id"]), None) + native_failed = any( + row.get("kind") == "native_loopx.result" + and isinstance(row.get("payload"), Mapping) + and as_mapping(row["payload"]).get("resume_turn_key") == key + and as_mapping(row["payload"]).get("status") == "failed" + and as_mapping(row["payload"]).get("result_kind") == "validation_failed" + and as_mapping(row["payload"]).get("validation_stage") == "host_result_contract" + for row in events + ) + if not native_failed: + continue + parsed = _find_matching_editorial_candidate(events, expected_digest=generation.get("request_digest")) + if parsed is None: + continue + proof: dict[str, object] = { + "turn_key": key, + "result_kind": "validation_failed", + "validation_stage": "host_result_contract", + "host_attempt_count": 1, + "generation_verified": True, + "saved_candidate_verified": True, + } + return proof, normalize_report_candidate(parsed) + return None + + +def stopped_report_candidate_recovery( + host: StewardTurnHostProtocol, + actor: Mapping[str, object], + window: Mapping[str, object], + original: Mapping[str, object], + *, + key: str, + folder: Path, + root: Path, +) -> tuple[dict[str, object], dict[str, object]] | None: + """Recover a stopped report Turn only when its saved final answer already holds a valid candidate.""" + from ...control_plane.turn_driver.journal_store import load_turn_journal, turn_journal_path + + del window + req_path = folder / "editorial-request.json" + if not req_path.is_file() or not (folder / "source.json").is_file(): + return None + if (folder / "editorial-response.json").exists() and not (folder / "private-generation.json").exists(): + return None + try: + request_digest = as_mapping(json.loads(req_path.read_text(encoding="utf-8"))).get("request_digest") + except (OSError, ValueError): + return None + if not isinstance(request_digest, str) or not request_digest: + return None + journal = as_optional_dict(load_turn_journal(turn_journal_path(root, goal_id=str(actor["goal_id"]), turn_key=key))) + if ( + journal is None + or journal.get("status") != "stopped" + or journal.get("result_kind") != "wait" + or journal.get("host_attempt_count") != 1 + or as_mapping(journal.get("host_result")).get("classification") != "no_typed_host_result" + ): + return None + events = host.store.events_after(str(actor["session_id"]), str(original["turn_id"]), None) + stopped_event = any( + row.get("kind") == "native_loopx.result" + and isinstance(row.get("payload"), Mapping) + and as_mapping(row["payload"]).get("resume_turn_key") == key + and as_mapping(row["payload"]).get("status") == "stopped" + and as_mapping(row["payload"]).get("result_kind") == "wait" + for row in events + ) + if not stopped_event: + return None + parsed = _find_matching_editorial_candidate(events, expected_digest=request_digest) + if parsed is None: + return None + proof: dict[str, object] = { + "turn_key": key, + "result_kind": "wait", + "classification": "no_typed_host_result", + "host_attempt_count": 1, + "generation_verified": True, + "saved_candidate_verified": True, + } + return proof, dict(parsed) + + +def has_recoverable_stopped_report( + host: StewardTurnHostProtocol, + actor: Mapping[str, object], + window: Mapping[str, object], + todo: Mapping[str, object], + *, + report_turn_fn: Callable[[StewardStoreProtocol, Mapping[str, object], Mapping[str, object]], dict[str, object] | None], +) -> bool: + """Read-only gate check before acquiring the recovery fence.""" + if todo.get("status") != "open": + return False + original = report_turn_fn(host.store, actor, window) + if not original: + return False + if any( + row.get("kind") == "native_loopx.result" and as_mapping(row.get("payload")).get("status") == "committed" + for row in host.store.events_after(str(actor["session_id"]), str(original["turn_id"]), None) + ): + return False + request = as_mapping(original.get("loopx_request")) + turn_instance_id = request.get("turn_instance_id") + if not isinstance(turn_instance_id, str) or not turn_instance_id: + return False + from ...control_plane.turn_driver.journal_store import find_loopx_turn_key_by_settlement_identity + from ..periodic_report.private_generation import attempt_directory + from .steward_reports import report_service + + reports, _ = report_service(host.controller, dict(actor)) + folder = attempt_directory(reports.root, dict(window)) + goal_id = str(actor["goal_id"]) + agent_id = str(actor["agent_id"]) + todo_id = str(todo["todo_id"]) + saved_key = find_loopx_turn_key_by_settlement_identity( + reports.root, + goal_id=goal_id, + agent_id=agent_id, + todo_id=todo_id, + turn_instance_id=turn_instance_id + ".saved-candidate", + ) + if saved_key is not None and (folder / "private-generation.json").exists(): + return True + key = find_loopx_turn_key_by_settlement_identity( + reports.root, + goal_id=goal_id, + agent_id=agent_id, + todo_id=todo_id, + turn_instance_id=turn_instance_id, + ) + return bool( + key is not None + and host._stopped_report_candidate_recovery( + actor, + window, + original, + key=str(key), + folder=folder, + root=reports.root, + ) + is not None + ) + + +def build_replay_runner( + normalized_candidate: Mapping[str, object], +) -> Callable[[Mapping[str, object], object], dict[str, object]]: + """Build a once-only host callback replaying an already-frozen report candidate.""" + from ...control_plane.turn_driver.host_candidate import build_result + + replayed = False + + def replay_frozen_candidate(native_request: Mapping[str, object], _launch_scope: object) -> dict[str, object]: + nonlocal replayed + if replayed: + raise ValueError("frozen report candidate replay may execute at most once") + replayed = True + built = build_result(native_request, dict(normalized_candidate), host_name="Codex app-server", allow_completion=True) + return as_dict(built) + + return replay_frozen_candidate + + +def settle_stopped_report_candidate( + host: StewardTurnHostProtocol, + *, + actor: Mapping[str, object], + window: Mapping[str, object], + todo: Mapping[str, object], + original: Mapping[str, object], + request: dict[str, object], + observed: dict[str, object] | None, + reports: object, + owner_key: str, + folder: Path, + original_key: str, + stopped_proof: dict[str, object], + raw_candidate: dict[str, object], + normalize_report_candidate: Callable[[Mapping[str, object]], dict[str, object]], +) -> dict[str, object]: + """Freeze and settle an already-generated stopped report candidate without invoking a model.""" + from ...cli_runtime import _build_selected_parser + from ...cli_commands.turn import handle_turn_command + from ...control_plane.turn_driver import inspect_loopx_turn_journal + from ..periodic_report.private_generation import validate_private_generation + + typed_reports = cast(_ReportServiceProtocol, reports) + goal_id = str(actor["goal_id"]) + agent_id = str(actor["agent_id"]) + inspection = as_dict( + inspect_loopx_turn_journal( + typed_reports.root, + goal_id=goal_id, + agent_id=agent_id, + turn_key=original_key, + retry_failed=True, + ) + ) + admitted = host._admit( + request, + observed=observed, + settlement_recovery=inspection, + frozen_contract_recovery=stopped_proof, + ) + if not (folder / "private-generation.json").exists(): + typed_reports.freeze(request, dict(raw_candidate)) + generation = as_mapping(validate_private_generation(folder)) + if as_mapping(raw_candidate.get("editorial_response")).get("request_digest") != generation.get("request_digest"): + raise ValueError("the recovered candidate digest does not match the frozen report") + if not typed_reports.delivery_current(owner_key, window): + raise ValueError("the original report authorization changed before settlement recovery") + saved_instance_id = str(request["turn_instance_id"]) + ".saved-candidate" + argv = [ + "turn", + "run-once", + "--goal-id", + goal_id, + "--agent-id", + agent_id, + "--project", + str(admitted["workspace_path"]), + "--host", + "generic-cli", + "--turn-instance-id", + saved_instance_id, + "--todo-id", + str(todo["todo_id"]), + "--execute", + ] + if request.get("validation_command") is not None: + argv += ["--validation-command-json", json.dumps(request["validation_command"])] + args = _build_selected_parser("turn").parse_args(argv) + args.host, args.session_scope = "codex-app-server", "agent" + result: dict[str, object] = {} + host_runner = host._build_replay_runner(normalize_report_candidate(raw_candidate)) + with host._task_execution_lease(request, str(original["turn_id"]), recovery=True) as lease: + handle_turn_command( + args, + registry_path=cast(Path, host.controller.registry_path), + runtime_root_arg=str(typed_reports.root), + output_format=lambda *_a, **_kw: "json", + print_payload=lambda value, *_a: result.update(as_mapping(value)), + native_host_runner=host_runner, + native_session_binding_resolver=lambda _envelope: { + "schema_version": "loopx_turn_session_binding_v0", + "goal_id": goal_id, + "agent_id": agent_id, + }, + native_task_validator=host._report_validator(request), + native_completion_lease_resolver=lambda: host._task_lease_proof(request, lease), + ) + return result + + +def recover_report_settlement( + host: StewardTurnHostProtocol, + actor: dict[str, object], + window: dict[str, object], + todo: dict[str, object], + *, + report_turn_fn: Callable[[StewardStoreProtocol, Mapping[str, object], Mapping[str, object]], dict[str, object] | None], +) -> None: + """Resume only cached, validated native effects of the original report.""" + from ...cli_runtime import _build_selected_parser + from ...cli_commands.turn import handle_turn_command + from ...control_plane.turn_driver import inspect_loopx_turn_journal + from ...control_plane.turn_driver.journal_store import find_loopx_turn_key_by_settlement_identity + from ..periodic_report.private_generation import attempt_directory, validate_private_generation + from .steward_reports import report_service + + observed = host._observe(actor) + session_id = str(actor["session_id"]) + goal_id = str(actor["goal_id"]) + agent_id = str(actor["agent_id"]) + with host.controller.lock, host._report_fence({"actor": actor}): + original = report_turn_fn(host.store, actor, window) + if not original: + return + original_turn_id = str(original["turn_id"]) + request = as_dict(original.get("loopx_request")) + if ( + request.get("actor") != actor + or request.get("report_window_id") != window["window_id"] + or request.get("todo_id") != todo["todo_id"] + ): + raise ValueError("the original report settlement identity changed") + if any( + row.get("kind") == "native_loopx.result" and as_mapping(row.get("payload")).get("status") == "committed" + for row in host.store.events_after(session_id, original_turn_id, None) + ): + return + reports, owner_key = report_service(host.controller, actor) + folder = attempt_directory(reports.root, window) + turn_instance_id = str(request["turn_instance_id"]) + saved_key = find_loopx_turn_key_by_settlement_identity( + reports.root, + goal_id=goal_id, + agent_id=agent_id, + todo_id=str(todo["todo_id"]), + turn_instance_id=turn_instance_id + ".saved-candidate", + ) + key = saved_key or find_loopx_turn_key_by_settlement_identity( + reports.root, + goal_id=goal_id, + agent_id=agent_id, + todo_id=str(todo["todo_id"]), + turn_instance_id=turn_instance_id, + ) + if key is None: + return + if saved_key is None: + stopped_recovery = host._stopped_report_candidate_recovery( + actor, + window, + original, + key=str(key), + folder=folder, + root=reports.root, + ) + if stopped_recovery is not None: + stopped_result = host._settle_stopped_report_candidate( + actor=actor, + window=window, + todo=todo, + original=original, + request=request, + observed=observed, + reports=reports, + owner_key=str(owner_key), + folder=folder, + original_key=str(key), + stopped_proof=stopped_recovery[0], + raw_candidate=stopped_recovery[1], + ) + host.store.append_event(session_id, original_turn_id, kind="native_loopx.result", payload=stopped_result) + return + generation = as_mapping(validate_private_generation(folder)) + if not reports.delivery_current(owner_key, window): + raise ValueError("the original report authorization changed before settlement recovery") + inspection = as_dict( + inspect_loopx_turn_journal(reports.root, goal_id=goal_id, agent_id=agent_id, turn_key=str(key), retry_failed=True) + ) + contract_recovery = ( + host._frozen_report_contract_recovery( + actor, + window, + original, + key=str(key), + generation=generation, + root=reports.root, + ) + if as_mapping(inspection.get("recovery_decision")).get("reinvoke_host") is True + else None + ) + admitted = host._admit( + request, + observed=observed, + settlement_recovery=inspection, + frozen_contract_recovery=contract_recovery[0] if contract_recovery else None, + ) + + def no_model(*_args: object) -> dict[str, object]: + raise ValueError("report settlement recovery must never invoke a model") + + host_runner: Callable[[Mapping[str, object], object], dict[str, object]] = ( + host._build_replay_runner(contract_recovery[1]) if contract_recovery is not None else no_model + ) + args = _build_selected_parser("turn").parse_args( + [ + "turn", + "run-once", + "--goal-id", + goal_id, + "--agent-id", + agent_id, + "--project", + str(admitted["workspace_path"]), + "--host", + "generic-cli", + "--resume-turn-key", + str(key), + "--retry-failed-turn", + "--execute", + ] + ) + args.host, args.session_scope = "codex-app-server", "agent" + result: dict[str, object] = {} + with ( + host._task_execution_lease(request, original_turn_id, recovery=True) + if todo.get("status") == "open" + else nullcontext(None) + ) as lease: + handle_turn_command( + args, + registry_path=cast(Path, host.controller.registry_path), + runtime_root_arg=str(reports.root), + output_format=lambda *_a, **_kw: "json", + print_payload=lambda value, *_a: result.update(as_mapping(value)), + native_host_runner=host_runner, + native_session_binding_resolver=lambda _envelope: { + "schema_version": "loopx_turn_session_binding_v0", + "goal_id": goal_id, + "agent_id": agent_id, + }, + native_task_validator=host._report_validator(request), + native_completion_lease_resolver=( + (lambda: host._task_lease_proof(request, lease)) if lease else None + ), + ) + # Retain the historical outer failure. The actual native owner + # supplies the new event; no status or publication proof is forged. + host.store.append_event(session_id, original_turn_id, kind="native_loopx.result", payload=result) diff --git a/loopx/extensions/lark/steward_reports.py b/loopx/extensions/lark/steward_reports.py index 41218b9504..e4795357b3 100644 --- a/loopx/extensions/lark/steward_reports.py +++ b/loopx/extensions/lark/steward_reports.py @@ -5,47 +5,120 @@ """ from __future__ import annotations +from collections.abc import Callable, Mapping from copy import deepcopy from datetime import datetime, timezone import hashlib import json from pathlib import Path -from typing import Any +from typing import Protocol -from ...chat_store import _read_json -from ...file_lock import try_exclusive_file_lock -from ...file_lock import exclusive_file_lock +from ...control_plane.collaboration.source_chat_observation import _read_json +from ...file_lock import exclusive_file_lock, try_exclusive_file_lock from ...registry import atomic_write_json from ...capabilities.native_chat.steward_monitor import steward_monitor_delivery_dir from ...capabilities.native_chat.steward_reports import StewardReports from ...capabilities.native_chat.steward_turn import report_turn +from ...capabilities.native_chat.steward_turn_common import ( + StewardBindingsProtocol, + StewardControllerProtocol, + as_dict, + as_dict_list, + as_mapping, + as_optional_dict, +) from ...capabilities.periodic_report.cadence_journal import read_cadence_journal -from ...capabilities.periodic_report.private_generation import attempt_directory, validate_private_generation from ...capabilities.periodic_report.incremental import commit_periodic_report_publication_cursor +from ...capabilities.periodic_report.private_generation import attempt_directory, validate_private_generation + + +class _LarkOwnerAttentionProtocol(Protocol): + def _route( + self, + binding: dict[str, object], + saved: dict[str, object] | None = None, + *, + session_id: str | None = None, + source_ref: str | None = None, + ) -> dict[str, object]: ... + + +class _LarkCoreProtocol(Protocol): + @property + def controller(self) -> StewardControllerProtocol: ... + + def read_request(self, request_ref: str) -> dict[str, object]: ... + + +class _LarkTransportProtocol(Protocol): + @property + def root(self) -> Path: ... + + @property + def core(self) -> _LarkCoreProtocol: ... + + @property + def bindings(self) -> StewardBindingsProtocol: ... + + @property + def owner_attention(self) -> _LarkOwnerAttentionProtocol: ... + + def _inbox(self, record: dict[str, object]) -> Path: ... + + def _deliver( + self, + path: Path, + record: dict[str, object], + phase: str, + text: str, + *, + inbox: Callable[[], Path], + authorization_check: Callable[[], bool] | None = None, + reply_placement: str | None = None, + finalize_source: bool = True, + ) -> bool: ... class LarkStewardReports: - def __init__(self, transport: Any) -> None: - self.transport = transport - self.controller = transport.core.controller - self.reports = StewardReports(self.controller) - - def _original_route(self, binding: dict[str, Any], actor: dict[str, Any], - saved: dict[str, Any] | None = None) -> dict[str, Any]: - route = self.transport.owner_attention._route(binding, saved, - session_id=actor["session_id"], source_ref=actor["source_ref"]) - native = self.transport.core.read_request(route["request_ref"]) - if native.get("session_id") != actor["session_id"] or route["source"]["source_ref"] != actor["source_ref"]: + def __init__(self, transport: _LarkTransportProtocol) -> None: + self.transport: _LarkTransportProtocol = transport + self.controller: StewardControllerProtocol = transport.core.controller + self.reports: StewardReports = StewardReports(self.controller) + + def _original_route( + self, + binding: Mapping[str, object], + actor: Mapping[str, object], + saved: object = None, + ) -> dict[str, object]: + saved_dict = as_dict(saved) if saved is not None else None + route = as_dict( + self.transport.owner_attention._route( + as_dict(binding), + saved_dict, + session_id=str(actor["session_id"]), + source_ref=str(actor["source_ref"]), + ) + ) + native = as_mapping(self.transport.core.read_request(str(route["request_ref"]))) + if ( + native.get("session_id") != actor["session_id"] + or as_mapping(route.get("source")).get("source_ref") != actor["source_ref"] + ): raise ValueError("the private source does not belong to the original reporting steward") return route - def route_proof(self, binding: dict[str, Any], actor: dict[str, Any]) -> dict[str, Any]: + def route_proof(self, binding: Mapping[str, object], actor: Mapping[str, object]) -> dict[str, object]: self._original_route(binding, actor) - return {"binding_id": binding["binding_id"], "source_ref": actor["source_ref"], - "session_id": actor["session_id"], "provider_ref": binding["provider_ref"], - "operator_ref": binding["operator_ref"]} + return { + "binding_id": binding["binding_id"], + "source_ref": actor["source_ref"], + "session_id": actor["session_id"], + "provider_ref": binding["provider_ref"], + "operator_ref": binding["operator_ref"], + } - def _pending_monitor_report_paths(self, actor: dict[str, Any]) -> list[Path]: + def _pending_monitor_report_paths(self, actor: Mapping[str, object]) -> list[Path]: goal_id = str(actor.get("goal_id") or "").strip() if not goal_id: return [] @@ -61,88 +134,104 @@ def _pending_monitor_report_paths(self, actor: dict[str, Any]) -> list[Path]: item = _read_json(path) except (OSError, ValueError): continue - if (isinstance(item, dict) - and item.get("schema_version") == "steward_monitor_report_delivery_v0" - and item.get("goal_id") == goal_id - and item.get("agent_id") == actor.get("agent_id") - and item.get("session_id") == actor.get("session_id") - and item.get("delivery_status") in {"pending", "unconfirmed"} - and str(item.get("markdown") or "").strip()): + if ( + isinstance(item, dict) + and item.get("schema_version") == "steward_monitor_report_delivery_v0" + and item.get("goal_id") == goal_id + and item.get("agent_id") == actor.get("agent_id") + and item.get("session_id") == actor.get("session_id") + and item.get("delivery_status") in {"pending", "unconfirmed"} + and str(item.get("markdown") or "").strip() + ): pending.append(path) return pending def pending(self) -> bool: return any( - row.get("managed_actor") and ( - self.reports.health(row["binding_id"]).get("enabled") - or self._pending_monitor_report_paths(row["managed_actor"]) + row.get("managed_actor") + and ( + self.reports.health(str(row["binding_id"])).get("enabled") + or self._pending_monitor_report_paths(as_mapping(row["managed_actor"])) ) - for row in self.transport.bindings.read()["bindings"] + for row in as_dict_list(self.transport.bindings.read().get("bindings")) ) - def _committed_turn(self, actor: dict[str, Any], window: dict[str, Any]) -> dict[str, Any] | None: + def _committed_turn(self, actor: Mapping[str, object], window: Mapping[str, object]) -> dict[str, object] | None: # Same stable client identity as the original native host. Reading a # retained completion/event never replays an unknown or failed Turn. turn = report_turn(self.controller.store, actor, window) if not turn: return None - request = turn.get("loopx_request") or {} - if (request.get("work_kind") != "report" or request.get("actor") != actor - or request.get("report_window_id") != window["window_id"] - or request.get("report_subscription_revision") != window["subscription_revision"]): + request = as_mapping(turn.get("loopx_request")) + if ( + request.get("work_kind") != "report" + or request.get("actor") != actor + or request.get("report_window_id") != window["window_id"] + or request.get("report_subscription_revision") != window["subscription_revision"] + ): raise ValueError("the original report Turn changed identity") - native = (turn.get("response") or {}).get("native_loopx") or {} + native = as_mapping(as_mapping(turn.get("response")).get("native_loopx")) if native.get("status") == "committed": return turn # A host response can be lost after native settlement. The original # immutable result event is also sufficient; no second model is run. - events = self.controller.store.events_after(actor["session_id"], turn["turn_id"], None) - if any(row.get("kind") == "native_loopx.result" and (row.get("payload") or {}).get("status") == "committed" - for row in events): + events = self.controller.store.events_after(str(actor["session_id"]), str(turn["turn_id"]), None) + if any( + row.get("kind") == "native_loopx.result" and as_mapping(row.get("payload")).get("status") == "committed" + for row in events + ): return turn return None - def _reconcile_monitor_reports(self, binding: dict[str, Any], actor: dict[str, Any]) -> int: + def _reconcile_monitor_reports(self, binding: Mapping[str, object], actor: dict[str, object]) -> int: verified = 0 + session_id = str(actor["session_id"]) + binding_id = str(binding["binding_id"]) for path in self._pending_monitor_report_paths(actor): try: with try_exclusive_file_lock(path.with_suffix(".lock"), operation="return_steward_monitor_report") as acquired: if not acquired or not path.exists(): continue item = _read_json(path) - if (not isinstance(item, dict) - or item.get("delivery_status") not in {"pending", "unconfirmed"} - or item.get("goal_id") != actor.get("goal_id") - or item.get("agent_id") != actor.get("agent_id") - or item.get("session_id") != actor.get("session_id") - or not str(item.get("markdown") or "").strip()): + if ( + not isinstance(item, dict) + or item.get("delivery_status") not in {"pending", "unconfirmed"} + or item.get("goal_id") != actor.get("goal_id") + or item.get("agent_id") != actor.get("agent_id") + or item.get("session_id") != session_id + or not str(item.get("markdown") or "").strip() + ): continue turn_id = str(item.get("turn_id") or "").strip() if not turn_id: continue - turn = self.controller.store.load_turn(actor["session_id"], turn_id) + turn = self.controller.store.load_turn(session_id, turn_id) if not turn: continue - req = turn.get("loopx_request") or {} - if (turn.get("origin") != "native_loopx" - or turn.get("loopx_execution") is not True - or req.get("actor") != actor): + req = as_mapping(turn.get("loopx_request")) + if ( + turn.get("origin") != "native_loopx" + or turn.get("loopx_execution") is not True + or req.get("actor") != actor + ): raise ValueError("the monitor report Turn changed identity") - native = (turn.get("response") or {}).get("native_loopx") or {} + native = as_mapping(as_mapping(turn.get("response")).get("native_loopx")) committed = native.get("status") == "committed" or any( row.get("kind") == "native_loopx.result" and isinstance(row.get("payload"), dict) - and row["payload"].get("status") == "committed" - for row in self.controller.store.events_after(actor["session_id"], turn_id, None) + and as_mapping(row.get("payload")).get("status") == "committed" + for row in self.controller.store.events_after(session_id, turn_id, None) ) if not committed: continue - def current() -> bool: + + def current(b_id: str = binding_id, expected_actor: dict[str, object] = actor) -> bool: try: - selected = self.reports.selected(binding["binding_id"]) + selected = self.reports.selected(b_id) except (OSError, ValueError, KeyError, TypeError): return False - return bool(selected["binding"].get("enabled") is True and selected["actor"] == actor) + return bool(as_mapping(selected.get("binding")).get("enabled") is True and selected.get("actor") == expected_actor) + if not current(): continue saved_route = item.get("original_route") @@ -150,22 +239,29 @@ def current() -> bool: if saved_route is not None and saved_route != route: raise ValueError("the frozen monitor report changed its original audience") if "source" not in item or "event" not in item or "original_route" not in item: - original = _read_json(self.transport.root / (route["request_ref"] + ".json")) - base = {k: deepcopy(v) for k, v in original.items() - if k not in {"deliveries", "stream", "recovery_streams", "context_recovery"}} - record = {**base, **item} - record["deliveries"] = dict(item.get("deliveries") or {}) + original = _read_json(self.transport.root / (str(route["request_ref"]) + ".json")) + base = { + k: deepcopy(v) + for k, v in original.items() + if k not in {"deliveries", "stream", "recovery_streams", "context_recovery"} + } + record: dict[str, object] = {**base, **item} + record["deliveries"] = dict(as_mapping(item.get("deliveries"))) record["original_route"] = route atomic_write_json(path, record) else: record = item phase = f"steward_monitor_report.{turn_id}" + + def make_inbox(rec: dict[str, object] = record) -> Path: + return self.transport._inbox(rec) + delivered = self.transport._deliver( path, record, phase, str(record["markdown"]), - inbox=lambda r=record: self.transport._inbox(r), + inbox=make_inbox, authorization_check=current, reply_placement="chat_root", finalize_source=False, @@ -174,7 +270,7 @@ def current() -> bool: atomic_write_json(path, record) if not delivered or not current(): continue - proof = (record.get("deliveries") or {}).get(phase) or {} + proof = as_mapping(as_mapping(record.get("deliveries")).get(phase)) if proof.get("verified") is not True: raise ValueError("the monitor report reply has no verified provider receipt") verified += 1 @@ -184,19 +280,21 @@ def current() -> bool: def reconcile(self) -> int: verified = 0 - for binding in self.transport.bindings.read()["bindings"]: - actor = binding.get("managed_actor") + for binding in as_dict_list(self.transport.bindings.read().get("bindings")): + actor = as_optional_dict(binding.get("managed_actor")) if not actor: continue verified += self._reconcile_monitor_reports(binding, actor) try: - subscription = self.reports.subscription(binding["binding_id"]) + binding_id = str(binding["binding_id"]) + subscription = self.reports.subscription(binding_id) if subscription is None: continue - journal = read_cadence_journal(runtime_root=self.reports.root, goal_id=actor["goal_id"]) - if not journal or journal["publication"]: + journal = as_optional_dict(read_cadence_journal(runtime_root=self.reports.root, goal_id=str(actor["goal_id"]))) + if not journal or journal.get("publication"): continue - window = journal["window"] + window = as_dict(journal["window"]) + window_id = str(window["window_id"]) folder = attempt_directory(self.reports.root, window) if not (folder / "private-generation.json").exists(): continue @@ -206,60 +304,93 @@ def reconcile(self) -> int: continue if not self._committed_turn(actor, window): continue - generation = validate_private_generation(folder) - def current(): - return self.reports.delivery_current(binding["binding_id"], window) + generation = as_mapping(validate_private_generation(folder)) + + def current(b_id: str = binding_id, win: dict[str, object] = window) -> bool: + return bool(self.reports.delivery_current(b_id, win)) + if not current(): continue if path.exists(): - record = _read_json(path) + record: dict[str, object] = _read_json(path) if record.get("publication_cursor"): continue route = self._original_route(binding, actor, record["original_route"]) else: route = self._original_route(binding, actor) - original = _read_json(self.transport.root / (route["request_ref"] + ".json")) + original = _read_json(self.transport.root / (str(route["request_ref"]) + ".json")) # Preserve the original Core correlation and provider # source; only this report's reply receipt is separate. - record = {k: deepcopy(v) for k, v in original.items() - if k not in {"deliveries", "stream", "recovery_streams", "context_recovery"}} - record.update(deliveries={}, original_route=route, report_window_id=window["window_id"], - report_generation_id=generation["generation_id"], delivery_status="pending", - reply_placement="chat_root") + record = { + k: deepcopy(v) + for k, v in original.items() + if k not in {"deliveries", "stream", "recovery_streams", "context_recovery"} + } + record.update( + deliveries={}, + original_route=route, + report_window_id=window_id, + report_generation_id=generation["generation_id"], + delivery_status="pending", + reply_placement="chat_root", + ) atomic_write_json(path, record) - if (record["report_window_id"] != window["window_id"] - or record["report_generation_id"] != generation["generation_id"] - or record["original_route"] != route): + if ( + record["report_window_id"] != window_id + or record["report_generation_id"] != generation["generation_id"] + or record["original_route"] != route + ): raise ValueError("the frozen report return changed its original audience") body = (folder / "report.md").read_text(encoding="utf-8") # A route's captured message proves the original audience; # it is not the parent of a newly scheduled result. Missing # placement denotes a retained pre-upgrade delivery intent. - placement = record.get("reply_placement") - if placement not in (None, "chat_root"): + placement_raw = record.get("reply_placement") + if placement_raw not in (None, "chat_root"): raise ValueError("the frozen private report placement changed") - phase = "periodic_report." + window["window_id"] - delivered = self.transport._deliver(path, record, phase, body, - inbox=lambda: self.transport._inbox(record), authorization_check=current, - reply_placement=placement) + placement = str(placement_raw) if placement_raw is not None else None + phase = "periodic_report." + window_id + + def make_inbox(rec: dict[str, object] = record) -> Path: + return self.transport._inbox(rec) + + delivered = self.transport._deliver( + path, + record, + phase, + body, + inbox=make_inbox, + authorization_check=current, + reply_placement=placement, + ) record["delivery_status"] = "delivered" if delivered else "unconfirmed" atomic_write_json(path, record) if not delivered or not current(): continue - proof = record["deliveries"][phase] + proof = as_mapping(as_mapping(record.get("deliveries")).get(phase)) if proof.get("verified") is not True: raise ValueError("the complete report reply has no verified provider receipt") - publication_id = "private-report-" + hashlib.sha256(json.dumps( - [window["window_id"], generation["generation_id"], proof], - sort_keys=True, ensure_ascii=False).encode()).hexdigest() + publication_id = "private-report-" + hashlib.sha256( + json.dumps( + [window_id, generation["generation_id"], proof], + sort_keys=True, + ensure_ascii=False, + ).encode() + ).hexdigest() candidate = _read_json(folder / "publication-candidate.json") - with self.controller.lock, exclusive_file_lock(self.transport.bindings.path, - operation="commit_original_report_publication"): + with self.controller.lock, exclusive_file_lock( + self.transport.bindings.path, + operation="commit_original_report_publication", + ): if not current(): continue - cursor = commit_periodic_report_publication_cursor(runtime_root=self.reports.root, - candidate=candidate, publication_id=publication_id, - delivered_at=datetime.now(timezone.utc).isoformat(), covered_until=window["due_at"]) + cursor = commit_periodic_report_publication_cursor( + runtime_root=self.reports.root, + candidate=candidate, + publication_id=publication_id, + delivered_at=datetime.now(timezone.utc).isoformat(), + covered_until=str(window["due_at"]), + ) record.update(publication_cursor=cursor, delivery_status="delivered") atomic_write_json(path, record) verified += 1 diff --git a/packages/loopx-core/prepare.py b/packages/loopx-core/prepare.py index 1b51573201..ecb83fa916 100644 --- a/packages/loopx-core/prepare.py +++ b/packages/loopx-core/prepare.py @@ -25,6 +25,10 @@ "loopx/capabilities/native_chat/steward_monitor.py", "loopx/capabilities/native_chat/steward_reports.py", "loopx/capabilities/native_chat/steward_turn.py", + "loopx/capabilities/native_chat/steward_turn_common.py", + "loopx/capabilities/native_chat/steward_turn_context.py", + "loopx/capabilities/native_chat/steward_turn_execution.py", + "loopx/capabilities/native_chat/steward_turn_recovery.py", "loopx/dashboard_launcher.py", "loopx/cli_commands/support_control_chat.py", "loopx/cli_commands/support_control_chat_endpoint.py", diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index c2c4144012..aa0bc225a9 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -67,6 +67,14 @@ def test_core_staging_excludes_workspace_and_reuses_kernel_bytes(tmp_path): assert not list((package / "cli_commands").glob("benchmark_*.py")) assert not (package / "presentation/research_analysis_api.py").exists() assert not (package / "presentation/runtime_workspace.py").exists() + for name in ( + "steward_turn.py", + "steward_turn_common.py", + "steward_turn_context.py", + "steward_turn_execution.py", + "steward_turn_recovery.py", + ): + assert not (package / "capabilities/native_chat" / name).exists() for name in ("entrypoint.py", "chat_action_store.py", "control_plane/turn_driver/executor.py", "control_plane/coordination/sqlite_authority_store.ts", "extensions/lark/extension.toml"): diff --git a/tests/test_core_workspace_distribution.py b/tests/test_core_workspace_distribution.py index 55971901b8..235694c7cf 100644 --- a/tests/test_core_workspace_distribution.py +++ b/tests/test_core_workspace_distribution.py @@ -61,6 +61,10 @@ def test_workspace_wheel_owns_the_complete_bundle_without_core_files(wheels): assert "loopx/dashboard_launcher.py" in workspace_zip.namelist() assert { "loopx/capabilities/native_chat/steward_turn.py", + "loopx/capabilities/native_chat/steward_turn_common.py", + "loopx/capabilities/native_chat/steward_turn_context.py", + "loopx/capabilities/native_chat/steward_turn_execution.py", + "loopx/capabilities/native_chat/steward_turn_recovery.py", "loopx/capabilities/native_chat/steward_managed_mode.py", "loopx/capabilities/native_chat/steward_monitor.py", "loopx/capabilities/native_chat/steward_reports.py", diff --git a/tests/test_steward_turn_controller_contract.py b/tests/test_steward_turn_controller_contract.py new file mode 100644 index 0000000000..9c7d4e12f7 --- /dev/null +++ b/tests/test_steward_turn_controller_contract.py @@ -0,0 +1,449 @@ +"""Contract tests binding StewardTurnHost and LarkStewardReports protocols to real runtime hosts.""" +from __future__ import annotations + +from collections.abc import Mapping, Sequence +import importlib.util +import inspect +import os +from pathlib import Path +import re +import subprocess +import sys +import sysconfig + +import pytest + +from loopx.capabilities.native_chat.conversation_bindings import ChatConversationBindings +from loopx.capabilities.native_chat.external_conversations import ChatExternalConversations +from loopx.capabilities.native_chat.session_calendar_tasks import SessionCalendarTasks +from loopx.capabilities.native_chat.steward_reports import ManagedSessionReports, StewardReports +from loopx.capabilities.native_chat.steward_turn import StewardTurnHost, report_turn +from loopx.capabilities.native_chat.steward_turn_common import ( + StewardBindingsProtocol, + StewardControllerProtocol, + StewardStoreProtocol, +) +from loopx.capabilities.native_chat.steward_turn_context import build_steward_turn_prompt +from loopx.chat_runtime import ChatRuntimeController +from loopx.chat_store import ChatSessionStore +from loopx.extensions.lark.owner_attention import LarkOwnerAttention +from loopx.extensions.lark.private_conversations import LarkPrivateConversations +from loopx.extensions.lark.steward_reports import ( + LarkStewardReports, + _LarkCoreProtocol, + _LarkOwnerAttentionProtocol, + _LarkTransportProtocol, +) + +_REPO_ROOT = Path(__file__).resolve().parents[1] +_MYPY_SUCCESS_RE = re.compile(r"^Success: no issues found in (\d+) source files?\s*$", re.MULTILINE) +_MYPY_FOUND_RE = re.compile( + r"^Found (\d+) errors? in (\d+) files? \(checked (\d+) source files?\)\s*$", + re.MULTILINE, +) + + +def _collect_mypy_contract_errors( + proc: subprocess.CompletedProcess[str], + *, + probe: Path, + callers: Sequence[str], +) -> tuple[list[str], dict[str, list[str]]]: + expected_files = 1 + len(callers) + details = f"rc={proc.returncode}\nSTDOUT:\n{proc.stdout.strip()}\nSTDERR:\n{proc.stderr.strip()}" + if proc.returncode not in (0, 1): + raise AssertionError(f"mypy exited unexpectedly:\n{details}") + if proc.stderr.strip(): + raise AssertionError(f"mypy reported errors on stderr:\n{details}") + if proc.returncode == 0: + success_match = _MYPY_SUCCESS_RE.search(proc.stdout) + if success_match is None or int(success_match.group(1)) != expected_files: + raise AssertionError(f"mypy did not report checking all {expected_files} files:\n{details}") + else: + found_match = _MYPY_FOUND_RE.search(proc.stdout) + if found_match is None or int(found_match.group(3)) != expected_files: + raise AssertionError(f"mypy aborted before checking all {expected_files} files:\n{details}") + if int(found_match.group(1)) <= 0: + raise AssertionError(f"mypy returned 1 without reporting error diagnostics:\n{details}") + + probe_errors: list[str] = [] + caller_errors: dict[str, list[str]] = {path: [] for path in callers} + probe_prefix = f"{probe}:" + for line in proc.stdout.splitlines(): + if ": error:" not in line: + continue + if line.startswith(probe_prefix): + probe_errors.append(line) + continue + for caller in callers: + if line.startswith(f"{caller}:"): + caller_errors[caller].append(line) + break + return probe_errors, caller_errors + + +def _run_mypy_contract_probe( + tmp_path: Path, + *, + probe_name: str, + probe_lines: Sequence[str], + callers: Sequence[str], + follow_imports_silent: bool = False, + extra_env: Mapping[str, str] | None = None, +) -> tuple[list[str], dict[str, list[str]]]: + if importlib.util.find_spec("mypy") is None: + pytest.skip("mypy optional test dependency is unavailable") + + probe = tmp_path / probe_name + probe.write_text("\n".join([*probe_lines, ""]), encoding="utf-8") + cmd = [ + sys.executable, + "-m", + "mypy", + "--config-file", + str(_REPO_ROOT / "pyproject.toml"), + *(["--follow-imports=silent"] if follow_imports_silent else []), + "--cache-dir", + str(tmp_path / ".mypy_cache"), + "--show-error-codes", + str(probe), + *callers, + ] + env = {**os.environ, **extra_env} if extra_env is not None else None + proc = subprocess.run(cmd, cwd=_REPO_ROOT, env=env, capture_output=True, text=True, check=False) + return _collect_mypy_contract_errors(proc, probe=probe, callers=callers) + + +def test_real_controller_constructs_host_and_matches_protocol_signatures(tmp_path: Path) -> None: + store = ChatSessionStore(tmp_path / "chat") + controller = ChatRuntimeController(store=store, codex_bin="codex") + controller.project_contexts.conversation_bindings = ChatConversationBindings( + root=store.root, + project_contexts=controller.project_contexts, + observe=lambda _profile: {}, + ) + + host = StewardTurnHost(controller) + reports = StewardReports(controller) + managed_reports = ManagedSessionReports(controller) + calendar_tasks = SessionCalendarTasks(controller) + transport = LarkPrivateConversations( + controller=controller, + runtime_root=tmp_path, + runner=lambda *_args, **_kwargs: {}, + cli_bin="lark-cli", + ) + lark_reports = LarkStewardReports(transport) + + assert host.controller is controller + assert host.store is store + assert reports.controller is controller + assert managed_reports.controller is controller + assert calendar_tasks.controller is controller + assert lark_reports.controller is controller + assert lark_reports.transport is transport + assert callable(report_turn) + + protocol_methods = ( + (StewardControllerProtocol, ChatRuntimeController, "_ensure_adapter_locked"), + (StewardControllerProtocol, ChatRuntimeController, "_start_accepted_turn_worker"), + (StewardControllerProtocol, ChatRuntimeController, "_fail_queue_preparation"), + (StewardStoreProtocol, ChatSessionStore, "events_after"), + (StewardStoreProtocol, ChatSessionStore, "messages"), + (StewardStoreProtocol, ChatSessionStore, "append_event"), + (StewardStoreProtocol, ChatSessionStore, "update_session"), + (StewardStoreProtocol, ChatSessionStore, "accept_managed_turn"), + (StewardBindingsProtocol, ChatConversationBindings, "resolve"), + (StewardBindingsProtocol, ChatConversationBindings, "_resolve_observed"), + (_LarkTransportProtocol, LarkPrivateConversations, "_inbox"), + (_LarkTransportProtocol, LarkPrivateConversations, "_deliver"), + (_LarkCoreProtocol, ChatExternalConversations, "read_request"), + (_LarkOwnerAttentionProtocol, LarkOwnerAttention, "_route"), + ) + for proto_cls, real_cls, method_name in protocol_methods: + proto_params = list(inspect.signature(getattr(proto_cls, method_name)).parameters.items())[1:] + real_params = inspect.signature(getattr(real_cls, method_name)).parameters + for name, proto_param in proto_params: + if proto_param.kind is inspect.Parameter.VAR_KEYWORD: + assert any(p.kind is inspect.Parameter.VAR_KEYWORD for p in real_params.values()), ( + f"{real_cls.__name__}.{method_name} missing **kwargs" + ) + continue + assert name in real_params, f"{real_cls.__name__}.{method_name} missing parameter {name!r}" + + +def test_real_controller_protocol_and_four_callers_mypy_contract(tmp_path: Path) -> None: + callers = [ + "loopx/chat_runtime.py", + "loopx/capabilities/native_chat/steward_managed_mode.py", + "loopx/capabilities/native_chat/steward_reports.py", + "loopx/capabilities/native_chat/session_calendar_tasks.py", + "loopx/extensions/lark/steward_reports.py", + ] + probe_errors, caller_errors = _run_mypy_contract_probe( + tmp_path, + probe_name="controller_contract_probe.py", + probe_lines=[ + "from loopx.capabilities.native_chat.conversation_bindings import ChatConversationBindings", + "from loopx.capabilities.native_chat.session_calendar_tasks import SessionCalendarTasks", + "from loopx.capabilities.native_chat.steward_reports import ManagedSessionReports, StewardReports", + "from loopx.capabilities.native_chat.steward_turn import StewardTurnHost", + "from loopx.capabilities.native_chat.steward_turn_common import (", + " StewardBindingsProtocol,", + " StewardControllerProtocol,", + " StewardStoreProtocol,", + ")", + "from loopx.chat_runtime import ChatRuntimeController", + "from loopx.chat_store import ChatSessionStore", + "", + "def bind_host(ctrl: ChatRuntimeController) -> StewardTurnHost:", + " return StewardTurnHost(ctrl)", + "", + "def bind_ctrl(ctrl: ChatRuntimeController) -> StewardControllerProtocol:", + " return ctrl", + "", + "def bind_store(store: ChatSessionStore) -> StewardStoreProtocol:", + " return store", + "", + "def bind_bindings(bindings: ChatConversationBindings) -> StewardBindingsProtocol:", + " return bindings", + "", + "def bind_reports(ctrl: ChatRuntimeController) -> tuple[StewardReports, ManagedSessionReports, SessionCalendarTasks]:", + " return StewardReports(ctrl), ManagedSessionReports(ctrl), SessionCalendarTasks(ctrl)", + ], + callers=callers, + ) + assert not probe_errors, f"Real controller/protocol contract errors: {probe_errors}" + + assert not any( + 'Argument 1 to "StewardTurnHost"' in err or "StewardControllerProtocol" in err + for err in caller_errors["loopx/chat_runtime.py"] + ), caller_errors["loopx/chat_runtime.py"] + assert len(caller_errors["loopx/chat_runtime.py"]) <= 27, caller_errors["loopx/chat_runtime.py"] + assert len(caller_errors["loopx/capabilities/native_chat/steward_managed_mode.py"]) <= 13, ( + caller_errors["loopx/capabilities/native_chat/steward_managed_mode.py"] + ) + assert caller_errors["loopx/capabilities/native_chat/steward_reports.py"] == [] + assert caller_errors["loopx/capabilities/native_chat/session_calendar_tasks.py"] == [] + assert caller_errors["loopx/extensions/lark/steward_reports.py"] == [] + assert sum(len(lines) for lines in caller_errors.values()) <= 40 + + +def test_real_lark_transport_protocol_and_callers_mypy_contract(tmp_path: Path) -> None: + callers = [ + "loopx/extensions/lark/private_conversations.py", + "loopx/extensions/lark/owner_attention.py", + ] + probe_errors, caller_errors = _run_mypy_contract_probe( + tmp_path, + probe_name="lark_transport_contract_probe.py", + probe_lines=[ + "from loopx.capabilities.native_chat.external_conversations import ChatExternalConversations", + "from loopx.extensions.lark.owner_attention import LarkOwnerAttention", + "from loopx.extensions.lark.private_conversations import LarkPrivateConversations", + "from loopx.extensions.lark.steward_reports import (", + " LarkStewardReports,", + " _LarkCoreProtocol,", + " _LarkOwnerAttentionProtocol,", + " _LarkTransportProtocol,", + ")", + "", + "def bind_transport(transport: LarkPrivateConversations) -> _LarkTransportProtocol:", + " return transport", + "", + "def bind_lark_reports(transport: LarkPrivateConversations) -> LarkStewardReports:", + " return LarkStewardReports(transport)", + "", + "def bind_core(core: ChatExternalConversations) -> _LarkCoreProtocol:", + " return core", + "", + "def bind_owner_attention(attention: LarkOwnerAttention) -> _LarkOwnerAttentionProtocol:", + " return attention", + ], + callers=callers, + follow_imports_silent=True, + ) + assert not probe_errors, f"Real Lark transport/protocol contract errors: {probe_errors}" + + private_errors = caller_errors["loopx/extensions/lark/private_conversations.py"] + assert not any( + 'Argument 1 to "LarkStewardReports"' in err + or "_LarkTransportProtocol" in err + for err in private_errors + ), private_errors + assert len(private_errors) <= 19, private_errors + owner_errors = caller_errors["loopx/extensions/lark/owner_attention.py"] + assert not any( + 'Argument 1 to "LarkStewardReports"' in err + or "_LarkOwnerAttentionProtocol" in err + or "_LarkTransportProtocol" in err + for err in owner_errors + ), owner_errors + owner_non_reexport_errors = [ + err + for err in owner_errors + if 'Module "loopx.chat_store" does not explicitly export' not in err + ] + assert len(owner_non_reexport_errors) <= 3, owner_errors + assert len(private_errors) + len(owner_non_reexport_errors) <= 22 + + +def test_mypy_contract_probe_rejects_early_exit_or_aborted_run(tmp_path: Path) -> None: + probe = tmp_path / "dummy_probe.py" + with pytest.raises(AssertionError, match="MYPYPATH"): + _collect_mypy_contract_errors( + subprocess.CompletedProcess( + args=["mypy"], + returncode=1, + stdout="", + stderr="site-packages is in the MYPYPATH. Please remove it.\n", + ), + probe=probe, + callers=["loopx/chat_runtime.py"], + ) + + with pytest.raises(AssertionError, match="checking all 2 files"): + _collect_mypy_contract_errors( + subprocess.CompletedProcess( + args=["mypy"], + returncode=0, + stdout="Success: no issues found in 1 source file\n", + stderr="", + ), + probe=probe, + callers=["loopx/chat_runtime.py"], + ) + + with pytest.raises(AssertionError, match="exited unexpectedly"): + _collect_mypy_contract_errors( + subprocess.CompletedProcess(args=["mypy"], returncode=2, stdout="", stderr="fatal error"), + probe=probe, + callers=[], + ) + + purelib = sysconfig.get_path("purelib") + assert purelib + with pytest.raises(AssertionError, match="MYPYPATH"): + _run_mypy_contract_probe( + tmp_path, + probe_name="aborted_probe.py", + probe_lines=["x: int = 1"], + callers=[], + follow_imports_silent=True, + extra_env={"MYPYPATH": purelib}, + ) + + +def test_build_steward_turn_prompt_slims_governance_and_preserves_completion_flags( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = ChatSessionStore(tmp_path / "chat") + controller = ChatRuntimeController(store=store, codex_bin="codex") + host = StewardTurnHost(controller) + monkeypatch.setattr( + host, + "_governance_replan_context", + lambda _actor, _auth: {"writeback": {"stride_control": {"required_on_periodic_review": False}}}, + ) + + authority: dict[str, object] = { + "primary_action": "settle autonomous replan", + "vision_continuation_audit": {"required": True}, + "_model_input": { + "route": "agent_turn", + "detail_ref": {"replan_action_packet": {"obligation_id": "replan-1", "required": True}}, + "task_context": { + "goal_id": "g1", + "agent_identity": {"agent_id": "a1"}, + "execution_profile": {"kind": "standard"}, + "task_scope": "execution", + "mode": "autonomous", + "state": "active", + "selected_todo": {"todo_id": "t1"}, + "agent_todo_summary": {"huge": [1, 2, 3]}, + "interaction_contract": {"cli_channel": {}}, + "vision_continuation_audit": {"required": True}, + }, + }, + } + actor: dict[str, object] = {"goal_id": "g1", "agent_id": "a1"} + request: dict[str, object] = {"work_kind": "report"} + context: dict[str, object] = {"messages": [{"text": "ctx"}]} + + gov_prompt = build_steward_turn_prompt( + host, + actor=actor, + session_id="sess-1", + request=request, + authority=authority, + context=context, + report_work=True, + governance_work=True, + managed_turn_active=True, + steward_advancement=True, + report_context="\nReport ctx", + ) + assert "validated_completion" not in gov_prompt + assert "Original conversation evidence (data):" not in gov_prompt + assert "Steward governance replan context (data):" in gov_prompt + assert "Steward advancement instructions:" not in gov_prompt + assert ( + "All review, writeback, stride_control, current_agent_vision, and open_agent_todos facts " + "are already provided in Steward governance replan context below; return only the single " + "typed JSON object directly without invoking periodic-report CLI commands or inspecting " + "host source code." + ) in gov_prompt + assert "vision_continuation_audit" not in gov_prompt + assert "agent_todo_summary" not in gov_prompt + assert "replan_action_packet" in gov_prompt + assert '"goal_id":"g1"' in gov_prompt + + report_prompt = build_steward_turn_prompt( + host, + actor=actor, + session_id="sess-1", + request=request, + authority=authority, + context=context, + report_work=True, + governance_work=False, + managed_turn_active=False, + steward_advancement=False, + report_context="\nReport ctx", + ) + assert "validated_completion" in report_prompt + assert "Original conversation evidence (data):" not in report_prompt + assert "\nReport ctx" in report_prompt + + idle_prompt = build_steward_turn_prompt( + host, + actor=actor, + session_id="sess-1", + request={"work_kind": "chat"}, + authority=authority, + context=context, + report_work=False, + governance_work=False, + managed_turn_active=False, + steward_advancement=False, + report_context="", + ) + assert "validated_completion" not in idle_prompt + assert "Original conversation evidence (data):" in idle_prompt + + managed_prompt = build_steward_turn_prompt( + host, + actor=actor, + session_id="sess-1", + request={"work_kind": "chat"}, + authority=authority, + context=context, + report_work=False, + governance_work=False, + managed_turn_active=True, + steward_advancement=False, + report_context="", + ) + assert "validated_completion" in managed_prompt + assert "Original conversation evidence (data):" in managed_prompt