From 9da61581eae0e7de26a4ad5974aae1797c9a02ce Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:59:27 +0800 Subject: [PATCH 1/2] feat(steward,manager-context): isolate background monitor session and cache turn context by authority revision Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../templates/FOLLOWTHROUGH.md | 8 + .../manager_context/turn_context_cache.py | 481 ++++++++++++++++++ .../native_chat/steward_monitor.py | 228 +++++++-- .../capabilities/native_chat/steward_turn.py | 93 +++- loopx/chat_lark_api.py | 14 + loopx/chat_manager_context.py | 173 ++++++- .../collaboration/steward_managed_mode.ts | 83 ++- .../steward_background_session.test.ts | 393 ++++++++++++++ tests/test_manager_turn_context_cache.py | 423 +++++++++++++++ ...st_steward_background_monitor_isolation.py | 299 +++++++++++ 10 files changed, 2116 insertions(+), 79 deletions(-) create mode 100644 loopx/capabilities/manager_context/turn_context_cache.py create mode 100644 tests/control_plane_ts/steward_background_session.test.ts create mode 100644 tests/test_manager_turn_context_cache.py create mode 100644 tests/test_steward_background_monitor_isolation.py diff --git a/loopx/capabilities/manager_context/templates/FOLLOWTHROUGH.md b/loopx/capabilities/manager_context/templates/FOLLOWTHROUGH.md index 74cd580cf1..662404a699 100644 --- a/loopx/capabilities/manager_context/templates/FOLLOWTHROUGH.md +++ b/loopx/capabilities/manager_context/templates/FOLLOWTHROUGH.md @@ -69,6 +69,14 @@ the manager workspace without granting new execution, audience or state permissi - Compare candidates by the importance and dependencies of their current commitments, reusable context, switching cost and independent-review boundaries—neither being online nor having fewer Todos is sufficient by itself. +- Keep foreground Steward reception responsive (fast/slow lane separation): when + a request requires a multi-minute repository implementation, verification or PR + delivery loop and `view=agent_route` or `resolve-peer-route` verifies a + qualified authorized Goal worker with an active usable host route, delegate + that execution via `context_handoff` with `original_conversation` return + instead of running long coding loops inline on a shared foreground reception + queue. Keep concise status checks, triage, routing and quick explanations + inline. ## Deliver the owed handoff before separate self-repair diff --git a/loopx/capabilities/manager_context/turn_context_cache.py b/loopx/capabilities/manager_context/turn_context_cache.py new file mode 100644 index 0000000000..9694519211 --- /dev/null +++ b/loopx/capabilities/manager_context/turn_context_cache.py @@ -0,0 +1,481 @@ +"""Bounded authority-revision hot snapshot cache for manager turn context. + +Reuses a verified local ``manager_turn_context`` snapshot only while every +underlying authority store, Goal runtime projection, declared state file, +delivery directory, and machine/policy configuration remains unchanged. +""" + +from __future__ import annotations + +from collections import OrderedDict +from collections.abc import Callable, Mapping +import copy +from dataclasses import dataclass +import hashlib +import json +import os +from pathlib import Path +import sqlite3 +import threading +import time +from typing import Any, cast + +from . import _root +from .ssh_evidence import grants as _raw_ssh_grants, registered_evidence_hosts +from ...goal_portfolio import registry_semantic_revision +from ...history import decode_registry_snapshot +from ...paths import resolve_runtime_root + +DEFAULT_MAX_AGE_SECONDS = 30.0 +MAX_CACHE_ENTRIES = 16 +MANAGER_CONTEXT_CACHE_ENV_VAR = "LOOPX_MANAGER_CONTEXT_CACHE" +_SQLITE_SUFFIXES = (".sqlite", ".db", ".sqlite3") +_ssh_grants = cast(Callable[[Path, str], Mapping[str, Any]], _raw_ssh_grants) + + +@dataclass(frozen=True) +class _CacheEntry: + stored_at_monotonic: float + payload: dict[str, Any] + + +_CACHE_LOCK = threading.Lock() +_CACHE: OrderedDict[str, _CacheEntry] = OrderedDict() + + +def clear_manager_turn_context_cache() -> None: + """Clear all in-memory cached manager turn context snapshots.""" + with _CACHE_LOCK: + _CACHE.clear() + + +def is_manager_turn_context_cache_enabled( + *, + registry_path: Path | None, + session: Mapping[str, Any], + runtime_root: Path, + scope_kind: str, + owner_scope: bool, + include_details: bool, + include_stopped: bool, + read_goal_status: bool, + remote_evidence: bool, + remote_runner: Any = None, +) -> bool: + """Return False whenever the caller requires an uncached fresh read.""" + del include_details # part of cache key; both True and False may cache + if os.environ.get(MANAGER_CONTEXT_CACHE_ENV_VAR, "").strip().lower() == "off": + return False + if registry_path is None: + return False + if include_stopped is True: + return False + if read_goal_status is False: + return False + if remote_runner is not None: + return False + channel_id = str(session.get("channel_id") or "") + if _ssh_grants(runtime_root, channel_id): + return False + if ( + owner_scope + and scope_kind != "owner_goal" + and remote_evidence + and registered_evidence_hosts(runtime_root) + ): + return False + return True + + +def _stat_signature(path: Path) -> tuple[int, int, int, int] | None: + try: + st = path.stat() + except OSError: + return None + return (st.st_dev, st.st_ino, st.st_mtime_ns, st.st_size) + + +def _head_bytes_digest(path: Path, max_bytes: int) -> str | None: + fd = None + try: + fd = os.open(path, os.O_RDONLY) + chunk = os.read(fd, max_bytes) + except OSError: + return None + finally: + if fd is not None: + try: + os.close(fd) + except OSError: + pass + return hashlib.sha256(chunk).hexdigest()[:24] + + +def _sqlite_pragma_data_version(db_path: Path) -> int | None: + try: + uri = f"{db_path.resolve().as_uri()}?mode=ro" + except (OSError, ValueError): + return None + conn: sqlite3.Connection | None = None + try: + conn = sqlite3.connect(uri, uri=True, timeout=0.05) + row = conn.execute("PRAGMA data_version").fetchone() + return int(row[0]) if row and row[0] is not None else None + except (sqlite3.Error, OSError, ValueError, TypeError): + return None + finally: + if conn is not None: + try: + conn.close() + except sqlite3.Error: + pass + + +def _sqlite_bundle_signature(db_path: Path) -> dict[str, Any] | None: + wal_path = Path(f"{db_path}-wal") + shm_path = Path(f"{db_path}-shm") + db_stat = _stat_signature(db_path) + wal_stat = _stat_signature(wal_path) + shm_stat = _stat_signature(shm_path) + if db_stat is None and wal_stat is None and shm_stat is None: + return None + return { + "db": db_stat, + "wal": wal_stat, + "shm": shm_stat, + "data_version": _sqlite_pragma_data_version(db_path) if db_stat is not None else None, + "db_hdr": _head_bytes_digest(db_path, 100) if db_stat is not None else None, + "wal_hdr": _head_bytes_digest(wal_path, 64) if wal_stat is not None else None, + "shm_hdr": _head_bytes_digest(shm_path, 136) if shm_stat is not None else None, + } + + +def _deliveries_dir_signature(deliveries_dir: Path) -> dict[str, Any] | None: + dir_stat = _stat_signature(deliveries_dir) + if dir_stat is None: + return None + count = 0 + latest: tuple[int, str, int] | None = None + try: + with os.scandir(deliveries_dir) as it: + for entry in it: + try: + st = entry.stat() + except OSError: + continue + count += 1 + candidate = (st.st_mtime_ns, entry.name, st.st_size) + if latest is None or candidate > latest: + latest = candidate + except OSError: + return {"dir": dir_stat, "scan_error": True} + return {"dir": dir_stat, "count": count, "latest": latest} + + +def _direct_sqlite_files(directory: Path) -> list[Path]: + found: list[Path] = [] + try: + with os.scandir(directory) as it: + for entry in it: + name = entry.name + if name.endswith(_SQLITE_SUFFIXES): + found.append(Path(entry.path)) + except OSError: + return [] + found.sort(key=lambda item: item.name) + return found + + +def _declared_goal_storage_paths(goal: Mapping[str, Any], base_dir: Path) -> list[Path]: + raw_storage = goal.get("storage") + candidates: list[str] = [] + if isinstance(raw_storage, str) and raw_storage.strip(): + candidates.append(raw_storage.strip()) + elif isinstance(raw_storage, Mapping): + for key, value in raw_storage.items(): + if isinstance(value, str) and value.strip() and ( + key in {"path", "root", "directory", "runtime_root", "db_path", "sqlite_path", "file"} + or key.endswith(("_path", "_dir", "_root", "_file")) + ): + candidates.append(value.strip()) + resolved: list[Path] = [] + for raw in candidates: + path = Path(raw).expanduser() + if not path.is_absolute(): + path = base_dir / path + try: + norm = path.resolve() + except OSError: + norm = path + if norm not in resolved: + resolved.append(norm) + return resolved + + +def _dedupe_paths(paths: list[Path]) -> list[Path]: + unique: list[Path] = [] + seen: set[str] = set() + for path in paths: + try: + norm = path.expanduser().resolve() + except OSError: + norm = path.expanduser() + key = str(norm) + if key not in seen: + seen.add(key) + unique.append(norm) + return unique + + +def _goal_local_fingerprint( + goal: Mapping[str, Any], + *, + registry_path: Path, + base_roots: list[Path], +) -> dict[str, Any]: + goal_id = str(goal.get("id") or "") + goal_sha = hashlib.sha256(goal_id.encode("utf-8")).hexdigest() + goal_sha16 = goal_sha[:16] + candidate_roots = list(base_roots) + + source_reg_sig = None + raw_source_reg = str(goal.get("source_registry") or "").strip() + if raw_source_reg: + source_reg_path = Path(raw_source_reg).expanduser() + if not source_reg_path.is_absolute(): + source_reg_path = registry_path.parent / source_reg_path + source_reg_sig = _stat_signature(source_reg_path) + try: + source_raw = source_reg_path.read_bytes() + source_decoded = decode_registry_snapshot(source_reg_path, source_raw) + source_root = resolve_runtime_root( + source_decoded, None, registry_path=source_reg_path, + ) + candidate_roots.append(source_root) + except (OSError, ValueError, TypeError, KeyError): + pass + + roots = _dedupe_paths(candidate_roots) + per_root: list[dict[str, Any]] = [] + for root in roots: + goal_dir = root / "goals" / goal_id + goal_dir_stat = _stat_signature(goal_dir) + extra_dbs = ( + { + db_file.name: _sqlite_bundle_signature(db_file) + for db_file in _direct_sqlite_files(goal_dir) + } + if goal_dir_stat is not None + else {} + ) + per_root.append( + { + "root": str(root), + "provider_marker": _stat_signature( + root / "authority" / f"provider-{goal_sha}.json" + ), + "file_authority": _stat_signature( + root / "authority" / "file-v0" / f"authority-store-{goal_sha16}.json" + ), + "file_identity": _stat_signature( + root / "authority" / "file-v0" / "store-identity" + ), + "sqlite_authority": _sqlite_bundle_signature( + root / "authority" / "sqlite-v0" / f"authority-{goal_sha}.sqlite" + ), + "goal_dir": goal_dir_stat, + "goal_sqlite": extra_dbs, + "todos_json": _stat_signature(goal_dir / "todos.json"), + "runs_index": _stat_signature(goal_dir / "runs" / "index.jsonl"), + "rollout_events": _stat_signature(goal_dir / "rollout-event-log.jsonl"), + "state_json": _stat_signature(goal_dir / "state.json"), + "acceptance_json": _stat_signature(goal_dir / "acceptance.json"), + "deliveries": _deliveries_dir_signature(goal_dir / "deliveries"), + } + ) + + storage_sigs: list[dict[str, Any]] = [] + for storage_path in _declared_goal_storage_paths(goal, registry_path.parent): + if storage_path.name.endswith(_SQLITE_SUFFIXES): + storage_sigs.append( + {"path": str(storage_path), "sqlite": _sqlite_bundle_signature(storage_path)} + ) + else: + st = _stat_signature(storage_path) + sub_dbs = { + db_file.name: _sqlite_bundle_signature(db_file) + for db_file in _direct_sqlite_files(storage_path) + } if st is not None else {} + storage_sigs.append( + { + "path": str(storage_path), + "stat": st, + "sqlite_files": sub_dbs, + "todos_json": _stat_signature(storage_path / "todos.json"), + "deliveries": _deliveries_dir_signature(storage_path / "deliveries"), + } + ) + + declared_state_sig = None + repo_registry_sig = None + raw_repo = str(goal.get("repo") or "").strip() + if raw_repo: + repo_path = Path(raw_repo).expanduser() + raw_state_file = str(goal.get("state_file") or "").strip() + if raw_state_file: + declared_state_sig = _stat_signature(repo_path / raw_state_file) + repo_registry_sig = _stat_signature(repo_path / ".loopx" / "registry.json") + + return { + "goal_id": goal_id, + "source_registry": source_reg_sig, + "declared_state": declared_state_sig, + "repo_registry": repo_registry_sig, + "roots": per_root, + "storage": storage_sigs, + } + + +def compute_manager_turn_context_fingerprint( + *, + registry_path: Path | None, + session: Mapping[str, Any], + runtime_root: Path, + scope_kind: str, + authorized_goal_ids: list[str] | None, + bound_steward: bool, + include_details: bool, + include_stopped: bool, + read_goal_status: bool, + remote_evidence: bool, +) -> str | None: + """Compute a fast zero-subprocess digest over all local authority inputs.""" + if registry_path is None: + return None + try: + resolved_registry_path = registry_path.expanduser().resolve() + raw = resolved_registry_path.read_bytes() + registry = decode_registry_snapshot(resolved_registry_path, raw) + except (OSError, ValueError, TypeError, KeyError): + return None + raw_goals = registry.get("goals") + if not isinstance(raw_goals, list): + return None + if bound_steward: + registry_rev = registry_semantic_revision(resolved_registry_path, raw) + if registry_rev is None: + return None + else: + registry_rev = "sha256:" + hashlib.sha256(raw).hexdigest() + + try: + resolved_reg_root = resolve_runtime_root( + registry, str(runtime_root), registry_path=resolved_registry_path, + ) + except (OSError, ValueError, TypeError): + resolved_reg_root = runtime_root + base_roots = _dedupe_paths([runtime_root, resolved_reg_root]) + + allowed_ids = set(authorized_goal_ids) if authorized_goal_ids is not None else None + target_goals = [ + goal + for goal in raw_goals + if isinstance(goal, Mapping) + and isinstance(goal.get("id"), str) + and goal["id"] + and (allowed_ids is None or goal["id"] in allowed_ids) + ] + target_goals.sort(key=lambda item: str(item.get("id") or "")) + + machine_configs = [ + { + "root": str(root), + "machine_configuration": _stat_signature( + root / "machine" / "configuration.json" + ), + "manager_policy": _stat_signature(_root(root) / "policy.json"), + } + for root in base_roots + ] + + basis = { + "schema_version": "manager_turn_context_cache_key_v1", + "registry_path": str(resolved_registry_path), + "registry_revision": registry_rev, + "params": [ + scope_kind, + sorted(allowed_ids) if allowed_ids is not None else None, + str(session.get("channel_id") or ""), + bool(bound_steward), + bool(include_details), + bool(include_stopped), + bool(read_goal_status), + bool(remote_evidence), + str(os.environ.get("LOOPX_MANAGER_EVIDENCE_WINDOW_DAYS", "") or ""), + ], + "machine_configs": machine_configs, + "goals": [ + _goal_local_fingerprint( + goal, + registry_path=resolved_registry_path, + base_roots=base_roots, + ) + for goal in target_goals + ], + } + encoded = json.dumps(basis, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8") + return "sha256:" + hashlib.sha256(encoded).hexdigest() + + +def _evict_expired_locked(now_mono: float, max_age_seconds: float) -> None: + expired = [ + key + for key, entry in _CACHE.items() + if now_mono - entry.stored_at_monotonic > max_age_seconds + ] + for key in expired: + _CACHE.pop(key, None) + + +def get_cached_manager_turn_context( + fingerprint: str, + *, + max_age_seconds: float = DEFAULT_MAX_AGE_SECONDS, + now_monotonic: float | None = None, +) -> dict[str, Any] | None: + """Return a deep-copied cached context snapshot if present and within TTL.""" + now_mono = time.monotonic() if now_monotonic is None else now_monotonic + with _CACHE_LOCK: + _evict_expired_locked(now_mono, max_age_seconds) + entry = _CACHE.get(fingerprint) + if entry is None: + return None + _CACHE.move_to_end(fingerprint) + return copy.deepcopy(entry.payload) + + +def put_cached_manager_turn_context( + fingerprint: str, + context: Mapping[str, Any], + *, + max_age_seconds: float = DEFAULT_MAX_AGE_SECONDS, + now_monotonic: float | None = None, +) -> bool: + """Cache a complete, warning-free context snapshot with deep-copy isolation.""" + if context.get("warnings"): + return False + coverage = context.get("coverage") + if not isinstance(coverage, Mapping) or coverage.get("complete") is not True: + return False + snapshot = copy.deepcopy(dict(context)) + now_mono = time.monotonic() if now_monotonic is None else now_monotonic + with _CACHE_LOCK: + _evict_expired_locked(now_mono, max_age_seconds) + _CACHE[fingerprint] = _CacheEntry( + stored_at_monotonic=now_mono, + payload=snapshot, + ) + _CACHE.move_to_end(fingerprint) + while len(_CACHE) > MAX_CACHE_ENTRIES: + _CACHE.popitem(last=False) + return True diff --git a/loopx/capabilities/native_chat/steward_monitor.py b/loopx/capabilities/native_chat/steward_monitor.py index 1df0861845..16b74ba26e 100644 --- a/loopx/capabilities/native_chat/steward_monitor.py +++ b/loopx/capabilities/native_chat/steward_monitor.py @@ -34,12 +34,101 @@ TARGET = "steward-portfolio-watch" FOLLOWUP_TARGET_PREFIX = "steward-monitor-followup:" +STEWARD_BACKGROUND_SESSION_PREFIX = "steward.background." +STEWARD_BACKGROUND_CHANNEL_PREFIX = "manager.external.steward.background." ADVANCEMENT_PRECOMMIT_RETRY_COOLDOWN_SECONDS = 60 ADVANCEMENT_ADMISSION_RETRY_SUFFIX = ".admission-retry" ADVANCEMENT_PRECOMMIT_RETRY_SUFFIX = ".precommit-retry" _LOG = logging.getLogger(__name__) +def steward_background_session_id(binding_id: str) -> str: + return f"{STEWARD_BACKGROUND_SESSION_PREFIX}{binding_id}" + + +def steward_background_channel_id(binding_id: str) -> str: + return f"{STEWARD_BACKGROUND_CHANNEL_PREFIX}{binding_id}" + + +def actor_steward_binding_id(actor: Mapping[str, Any]) -> str | None: + if actor.get("schema_version") != "loopx_steward_managed_actor_v0": + return None + goal_id = str(actor.get("goal_id") or "") + if not goal_id.startswith("steward-agent-"): + return None + return goal_id.removeprefix("steward-agent-") or None + + +def lookup_steward_monitor_turn( + store: Any, binding_id: str | None, fallback_session_id: str, client_id: str, +) -> dict[str, Any] | None: + if binding_id is not None: + bg_sid = steward_background_session_id(binding_id) + if store.load_session(bg_sid) is not None: + found = store.turn_for_client(bg_sid, client_id) + if found is not None: + return found + return store.turn_for_client(fallback_session_id, client_id) + + +def load_steward_monitor_turn_by_id( + store: Any, actor: Mapping[str, Any], turn_id: str, +) -> dict[str, Any] | None: + binding_id = actor_steward_binding_id(actor) + if binding_id is not None: + bg_sid = steward_background_session_id(binding_id) + if store.load_session(bg_sid) is not None: + found = store.load_turn(bg_sid, turn_id) + if found is not None: + return found + return store.load_turn(actor["session_id"], turn_id) + + +def ensure_steward_background_session( + store: Any, binding_id: str, parent_session: Mapping[str, Any], +) -> dict[str, Any]: + from ...chat_store import utc_now + + saved = parent_session.get("steward_context") + if not isinstance(saved, Mapping): + raise ValueError("the original steward Session is unavailable") + bg_sid = steward_background_session_id(binding_id) + if store.load_session(bg_sid) is None: + try: + store.create_session( + session_id=bg_sid, + goal_id="loopx-manager", + agent_id=str(parent_session["agent_id"]), + adapter_kind=str(parent_session["adapter_kind"]), + upstream_thread_id=f"steward-watch-{binding_id}", + channel_id=steward_background_channel_id(binding_id), + executor_endpoint_id=parent_session.get("executor_endpoint_id"), + steward_context=None, + ) + except FileExistsError: + pass + parent_scope_id = parent_session.get("manager_authorization_scope_id") + expected_bg_context = dict(saved) + with store._locked_session_path(bg_sid, "ensure_steward_background_session") as path: + carrier = store.load_session(bg_sid) + if carrier is None or carrier.get("status") == "closed": + raise ValueError("the steward background watch Session is unavailable") + dirty = False + if carrier.get("steward_background_context") != expected_bg_context: + carrier["steward_background_context"] = expected_bg_context + dirty = True + if isinstance(parent_scope_id, str) and parent_scope_id and carrier.get("manager_authorization_scope_id") != parent_scope_id: + carrier["manager_authorization_scope_id"] = parent_scope_id + dirty = True + elif parent_scope_id is None and "manager_authorization_scope_id" in carrier: + carrier.pop("manager_authorization_scope_id", None) + dirty = True + if dirty: + carrier["updated_at"] = utc_now() + _atomic_write_json(path, carrier, preserve_mode=True) + return carrier + + class StewardObservationAdapter: """A watch reads native state, never an old model context or a new thread.""" observation_only = True @@ -649,6 +738,9 @@ def pump_steward_monitors(controller: Any, *, cancelled=lambda: False) -> list[d cache = getattr(controller, "_steward_monitor_next_check", None) if cache is None: cache = controller._steward_monitor_next_check = {} + fg_checked = getattr(controller, "_steward_monitor_fg_idle_checked", None) + if fg_checked is None: + fg_checked = controller._steward_monitor_fg_idle_checked = {} for binding in bindings.read()["bindings"] if bindings is not None else []: if cancelled(): break @@ -656,65 +748,107 @@ def pump_steward_monitors(controller: Any, *, cancelled=lambda: False) -> list[d if binding.get("enabled") is not True or not actor: continue try: - session = controller.store.load_session(actor["session_id"]) - if not session or session.get("active_turn_id") or controller.store.queued_turns(actor["session_id"]): + parent_session = controller.store.load_session(actor["session_id"]) + if not parent_session or parent_session.get("status") == "closed": continue - if cache.get(binding["binding_id"], 0) > time.monotonic(): + human_idle = ( + not parent_session.get("active_turn_id") + and not controller.store.queued_turns(actor["session_id"]) + ) + binding_id = binding["binding_id"] + bg_session_id = StewardTurnHost.background_session_id(binding_id) + bg_session = controller.store.load_session(bg_session_id) + if ( + bg_session is not None + and bg_session.get("active_turn_id") + and callable(getattr(controller, "recover_exited_turn", None)) + ): + controller.recover_exited_turn(bg_session_id) + bg_session = controller.store.load_session(bg_session_id) + if bg_session is not None and bg_session.get("status") == "closed": + bg_idle = False + else: + bg_idle = ( + bg_session is None + or ( + not bg_session.get("active_turn_id") + and not controller.store.queued_turns(bg_session_id) + ) + ) + if not human_idle and not bg_idle: + continue + now_mono = time.monotonic() + bypass_fg_throttle = ( + human_idle + and binding_id in cache + and fg_checked.get(binding_id) is False + ) + if not bypass_fg_throttle and cache.get(binding_id, 0) > now_mono: continue # An ephemeral wake hint only, never authority. Configuration clears # it immediately; external edits are observed within a minute. Every # actual dispatch rechecks native state, original grant and provider. - cache[binding["binding_id"]] = time.monotonic() + 60 + cache[binding_id] = now_mono + 60 + fg_checked[binding_id] = human_idle # The existing pump also observes the optional report frontier. # No second consumer/timer is installed. Closed/not-due calendars # never invoke a model, and original user work wins the idle check. - goal = load_goal_from_registry(controller.registry_path, actor["goal_id"]) - report_config = (goal or {}).get("control_plane", {}).get("periodic_report", {}) - if report_config.get("enabled") is True and report_config.get("profile_preset") == "portfolio-progress": - from .steward_reports import StewardReports - try: - accepted, created = StewardReports(controller).frontier(binding) - if created: - changed.append(accepted) - continue - except (OSError, ValueError, KeyError, TypeError, RuntimeError): - _LOG.warning("An original steward report is unavailable; its window and other work are retained") - due = service.due_monitors(actor) - if due: - dispatched = False - for todo in due: + if human_idle: + goal = load_goal_from_registry(controller.registry_path, actor["goal_id"]) + report_config = (goal or {}).get("control_plane", {}).get("periodic_report", {}) + if report_config.get("enabled") is True and report_config.get("profile_preset") == "portfolio-progress": + from .steward_reports import StewardReports try: - accepted, created = StewardTurnHost(controller).submit( - binding["binding_id"], - turn_instance_id=monitor_turn_id(todo), - todo_id=todo["todo_id"], - work_kind="monitor", - monitor_deadline=todo["next_due_at"], - ) + accepted, created = StewardReports(controller).frontier(binding) + if created: + changed.append(accepted) + if bg_idle: + cache.pop(binding_id, None) + continue except (OSError, ValueError, KeyError, TypeError, RuntimeError): - _LOG.warning( - "A native steward monitor is unavailable; original work retained" - ) + _LOG.warning("An original steward report is unavailable; its window and other work are retained") + if bg_idle: + due = service.due_monitors(actor) + if due: + dispatched = False + for todo in due: + try: + accepted, created = StewardTurnHost(controller).submit( + binding_id, + turn_instance_id=monitor_turn_id(todo), + todo_id=todo["todo_id"], + work_kind="monitor", + monitor_deadline=todo["next_due_at"], + ) + except (OSError, ValueError, KeyError, TypeError, RuntimeError): + _LOG.warning( + "A native steward monitor is unavailable; original work retained" + ) + continue + if created: + changed.append(accepted) + dispatched = True + break + if isinstance(accepted, dict) and accepted.get("status") in {"queued", "running"}: + dispatched = True + break + if dispatched: + if human_idle: + fg_checked[binding_id] = False continue + advancement_dispatched = False + if human_idle: + for adv in service.runnable_advancement_todos(actor): + turn_id_token = resolve_advancement_turn_id(controller.store, actor, adv) + if turn_id_token is None: + continue + accepted, created = StewardTurnHost(controller).submit(binding_id, + turn_instance_id=turn_id_token, todo_id=adv["todo_id"], work_kind="native_turn") if created: changed.append(accepted) - dispatched = True - break - if isinstance(accepted, dict) and accepted.get("status") in {"queued", "running"}: - dispatched = True - break - if dispatched: - continue - for adv in service.runnable_advancement_todos(actor): - turn_id_token = resolve_advancement_turn_id(controller.store, actor, adv) - if turn_id_token is None: - continue - accepted, created = StewardTurnHost(controller).submit(binding["binding_id"], - turn_instance_id=turn_id_token, todo_id=adv["todo_id"], work_kind="native_turn") - if created: - changed.append(accepted) - break - else: + advancement_dispatched = True + break + if not advancement_dispatched: all_monitors = [row for row in service.todos(actor) if row.get("task_class") == "continuous_monitor" and row.get("status") == "open" and isinstance(row.get("target_key"), str) @@ -726,7 +860,7 @@ def pump_steward_monitors(controller: Any, *, cancelled=lambda: False) -> list[d due_dt = datetime.fromisoformat(soonest["next_due_at"].replace("Z", "+00:00")) remaining = (due_dt - datetime.now(timezone.utc)).total_seconds() if remaining > 0: - cache[binding["binding_id"]] = time.monotonic() + min(60, remaining) + cache[binding_id] = time.monotonic() + min(60, remaining) except (OSError, ValueError, KeyError, TypeError, RuntimeError): # One unreadable conversation or unavailable provider must not starve # other native monitors; retain its original data and deadline. diff --git a/loopx/capabilities/native_chat/steward_turn.py b/loopx/capabilities/native_chat/steward_turn.py index 23afc6c2b3..3e0d4d9bbb 100644 --- a/loopx/capabilities/native_chat/steward_turn.py +++ b/loopx/capabilities/native_chat/steward_turn.py @@ -30,6 +30,16 @@ verify_report_window_failure, ) from .steward_managed_mode import ManagedSessionTurn, ManagedTaskValidationUnavailable, 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, +) MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS = 300 _WORKER_EXITED_ERROR = ( @@ -240,6 +250,20 @@ def __init__(self, controller: Any) -> None: self.bindings = controller.project_contexts.conversation_bindings self.managed = StewardManagedMode(controller, self.bindings) + @staticmethod + def background_session_id(binding_id: str) -> str: + return 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 @@ -267,7 +291,7 @@ def _observe(self, actor: Mapping[str, Any]) -> dict[str, Any] | None: 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, + 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, @@ -304,6 +328,16 @@ def _admit(self, request: dict[str, Any], *, turn: dict[str, Any] | None = None, 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) + if request.get("work_kind") == "monitor" and carrier_session is None: + bg_sid = self.background_session_id(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: + raise ValueError("the steward background watch Session is unavailable") + elif turn is 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 = {} if request.get("work_kind") == "report": from .steward_reports import StewardReports @@ -311,23 +345,28 @@ def _admit(self, request: dict[str, Any], *, turn: dict[str, Any] | None = None, 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 = None + scope, observed_scope_id = 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): + 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=session["channel_id"]) + 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 {}), @@ -336,9 +375,11 @@ def scope_id(ids): **self.report_timeout_basis(request), **self.monitor_restart_basis(request), **({"preparing_model_context": True} if prepare_context else {}), **report}) - if admitted["refresh_original_scope"]: + if admitted["refresh_original_scope"] and scope is not None: self.store.update_session(session["session_id"], manager_authorization_scope_id=scope["current"]) - return {**admitted, "observed_scope_id": scope["current"] if scope else None} + 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) + 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. @@ -353,15 +394,16 @@ def monitor_restart_basis(self, request: Mapping[str, Any]) -> dict[str, Any]: 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 = self.store.load_turn(actor["session_id"], recovery["original_turn_id"]) + 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(actor["session_id"], original["turn_id"]), + 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(actor["session_id"], original["turn_id"]), + 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) @@ -417,9 +459,11 @@ def monitor_restart_carrier(self, original: dict[str, Any], client_id: str) -> d 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 := self.store.turn_for_client(original["session_id"], next_client_id)) is not None: + 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") @@ -1057,7 +1101,11 @@ def _prepare_submission(self, binding: dict[str, Any] | None, *, turn_instance_i 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.store.turn_for_client(actor["session_id"], client_id) + existing = ( + self._lookup_monitor_turn(binding["binding_id"], actor, client_id) + if work_kind == "monitor" + else self.store.turn_for_client(actor["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") @@ -1114,7 +1162,11 @@ def _prepare_submission(self, binding: dict[str, Any] | None, *, turn_instance_i # 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.store.turn_for_client(actor["session_id"], client_id) + retry = ( + self._lookup_monitor_turn(binding["binding_id"], actor, client_id) + if work_kind == "monitor" + else self.store.turn_for_client(actor["session_id"], client_id) + ) if retry is not None: if work_kind != "report": return {"turn": retry} @@ -1188,13 +1240,18 @@ def inspect_submission(quota_observation: dict[str, Any] | None = None) -> dict[ 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"]) + 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, + admitted = self._admit(request, observed=observed, carrier_session=carrier, launch_recovery=current["launch_recovery"], selection_recovery=current["selection_recovery"]) - session = self.store.load_session(actor["session_id"]) - accepted = self.store.accept_managed_turn(actor["session_id"], client_turn_id=client_id, + 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, message="Advance the currently admitted native LoopX work.", display_message="检查授权工作状态。" if work_kind == "monitor" else "生成本期授权项目日报。" if work_kind == "report" else "推进管家的 LoopX 任务。", origin="native_loopx", @@ -1213,17 +1270,17 @@ def inspect_submission(quota_observation: dict[str, Any] | None = None) -> dict[ origin="native_loopx") if admitted["observation_only"]: from .steward_monitor import StewardObservationAdapter - adapter = StewardObservationAdapter(session.get("upstream_thread_id")) + adapter = StewardObservationAdapter(target_session.get("upstream_thread_id")) else: adapter = controller._ensure_adapter_locked(session, work_dir=Path(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=actor["session_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) except Exception as exc: - controller._fail_queue_preparation(actor["session_id"], accepted.turn["turn_id"], exc) + controller._fail_queue_preparation(target_session_id, accepted.turn["turn_id"], exc) raise return accepted.turn, accepted.created diff --git a/loopx/chat_lark_api.py b/loopx/chat_lark_api.py index 1fa689ac0b..e56e104bdc 100644 --- a/loopx/chat_lark_api.py +++ b/loopx/chat_lark_api.py @@ -59,6 +59,20 @@ def read(session): if bindings is None: raise ValueError("Steward conversation bindings are unavailable") return bindings.steward_scope(session) + if isinstance(session.get("steward_background_context"), dict) and session.get("steward_context") is None: + bindings = controller.project_contexts.conversation_bindings + if bindings is None: + raise ValueError("Steward conversation bindings are unavailable") + bg_context = session["steward_background_context"] + binding_id = str(bg_context.get("binding_id") or "") + if ( + session.get("goal_id") != "loopx-manager" + or session.get("project_context") is not None + or session.get("session_id") != f"steward.background.{binding_id}" + or session.get("channel_id") != f"manager.external.steward.background.{binding_id}" + ): + raise ValueError("bound steward background audience changed") + return list(bindings.session_context(bg_context)["context"]["goal_ids"]) return authorized_manager_goal_ids( build_lark_goal_topic_runtime_snapshot( registry_path=server.registry_path, runtime_root_override=server.runtime_root_override, diff --git a/loopx/chat_manager_context.py b/loopx/chat_manager_context.py index 9e7586b942..c7ef016c5b 100644 --- a/loopx/chat_manager_context.py +++ b/loopx/chat_manager_context.py @@ -15,6 +15,13 @@ from .chat.manager_details import read_manager_goal_details from .chat.manager_history import read_manager_delivery_history from .capabilities.manager_context.inspection import agent_work_summary +from .capabilities.manager_context.turn_context_cache import ( + clear_manager_turn_context_cache as clear_manager_turn_context_cache, + compute_manager_turn_context_fingerprint, + get_cached_manager_turn_context, + is_manager_turn_context_cache_enabled, + put_cached_manager_turn_context, +) from .history import decode_registry_snapshot from .goal_portfolio import ( build_goal_portfolio, @@ -516,6 +523,29 @@ def manager_authorization_scope_is_current( ) +def _is_steward_background_carrier(session: Mapping[str, Any]) -> bool: + bg_ctx = session.get("steward_background_context") + if ( + session.get("goal_id") == "loopx-manager" + and session.get("steward_context") is None + and session.get("project_context") is None + and isinstance(bg_ctx, Mapping) + ): + binding_id = str(bg_ctx.get("binding_id") or "") + return ( + bool(binding_id) + and session.get("session_id") == f"steward.background.{binding_id}" + and session.get("channel_id") == f"manager.external.steward.background.{binding_id}" + ) + return False + + +def _is_bound_steward_session( + session: Mapping[str, Any], conversation: Mapping[str, Any], +) -> bool: + return conversation.get("bound_steward") is True or _is_steward_background_carrier(session) + + def manager_turn_context( registry_path: Path | None, session: dict[str, Any], @@ -563,7 +593,8 @@ def manager_turn_context( } owner_scope = conversation["private_conversation"] scope = conversation["goal_ids"] if owner_scope else authorized_goal_ids - if not owner_scope and not scope and not (conversation.get("bound_steward") is True and scope == []): + bound_steward_carrier = _is_bound_steward_session(session, conversation) + if not owner_scope and not scope and not (bound_steward_carrier and scope == []): return unavailable_manager_context( "external_authorization_unavailable", evidence_window=_evidence_window( @@ -786,8 +817,43 @@ def collect_manager_turn_context( remote_evidence: bool = False, remote_runner=None, ) -> dict[str, Any]: - if conversation_scope(session)["private_conversation"]: - return manager_turn_context( + conv = conversation_scope(session) + if conv["private_conversation"]: + scope_kind = str(conv["kind"]) + private_goals = list(conv["goal_ids"]) if isinstance(conv["goal_ids"], list) else None + cache_enabled = is_manager_turn_context_cache_enabled( + registry_path=registry_path, + session=session, + runtime_root=runtime_root, + scope_kind=scope_kind, + owner_scope=True, + include_details=include_details, + include_stopped=include_stopped, + read_goal_status=read_goal_status, + remote_evidence=remote_evidence, + remote_runner=remote_runner, + ) + before_fp = ( + compute_manager_turn_context_fingerprint( + registry_path=registry_path, + session=session, + runtime_root=runtime_root, + scope_kind=scope_kind, + authorized_goal_ids=private_goals, + bound_steward=False, + include_details=include_details, + include_stopped=include_stopped, + read_goal_status=read_goal_status, + remote_evidence=remote_evidence, + ) + if cache_enabled + else None + ) + if before_fp is not None: + cached = get_cached_manager_turn_context(before_fp) + if cached is not None: + return cached + context = manager_turn_context( registry_path, session, runtime_root, @@ -797,10 +863,42 @@ def collect_manager_turn_context( remote_evidence=remote_evidence, remote_runner=remote_runner, ) + if cache_enabled and before_fp is not None: + after_fp = compute_manager_turn_context_fingerprint( + registry_path=registry_path, + session=session, + runtime_root=runtime_root, + scope_kind=scope_kind, + authorized_goal_ids=private_goals, + bound_steward=False, + include_details=include_details, + include_stopped=include_stopped, + read_goal_status=read_goal_status, + remote_evidence=remote_evidence, + ) + if after_fp == before_fp: + put_cached_manager_turn_context(before_fp, context) + return context def resolve() -> list[str] | None: try: scope = scope_resolver(session) if scope_resolver else None + if ( + scope is None + and scope_resolver is not None + and _is_steward_background_carrier(session) + ): + bg_ctx = session["steward_background_context"] + binding_id = str(bg_ctx.get("binding_id") or "") + source_ref = str(bg_ctx.get("source_ref") or "") + if binding_id and source_ref: + scope = scope_resolver( + { + **session, + "steward_context": bg_ctx, + "channel_id": f"manager.external.native.{binding_id}.{source_ref}", + } + ) if not isinstance(scope, list) or any( not isinstance(g, str) for g in scope ): @@ -845,9 +943,61 @@ def scope_unchanged() -> bool: remote_evidence and grants(runtime_root, str(session.get("channel_id") or "")) ) - bound_steward = conversation_scope(session).get("bound_steward") is True + bound_steward = _is_bound_steward_session(session, conv) + scope_kind = str(conv["kind"]) + cache_enabled = is_manager_turn_context_cache_enabled( + registry_path=registry_path, + session=session, + runtime_root=runtime_root, + scope_kind=scope_kind, + owner_scope=False, + include_details=include_details, + include_stopped=include_stopped, + read_goal_status=read_goal_status, + remote_evidence=remote_evidence, + remote_runner=remote_runner, + ) + if ( + cache_enabled + and before is not None + and (bool(before) or bound_steward) + and before_scope_id is not None + ): + before_fp = compute_manager_turn_context_fingerprint( + registry_path=registry_path, + session=session, + runtime_root=runtime_root, + scope_kind=scope_kind, + authorized_goal_ids=before, + bound_steward=bound_steward, + include_details=include_details, + include_stopped=include_stopped, + read_goal_status=read_goal_status, + remote_evidence=remote_evidence, + ) + if before_fp is not None: + cached = get_cached_manager_turn_context(before_fp) + if cached is not None and cached.get("authorization_scope_id") == before_scope_id: + return cached + attempt_fp: str | None = None for attempt in range(2): + attempt_fp = ( + compute_manager_turn_context_fingerprint( + registry_path=registry_path, + session=session, + runtime_root=runtime_root, + scope_kind=scope_kind, + authorized_goal_ids=before, + bound_steward=bound_steward, + include_details=include_details, + include_stopped=include_stopped, + read_goal_status=read_goal_status, + remote_evidence=remote_evidence, + ) + if cache_enabled and before is not None and (bool(before) or bound_steward) + else None + ) kwargs: dict[str, Any] = { "authorized_goal_ids": before, "include_details": include_details, @@ -905,4 +1055,19 @@ def scope_unchanged() -> bool: and context.get("warnings") == ["external_authorization_changed"]): continue break + if cache_enabled and attempt_fp is not None: + post_fp = compute_manager_turn_context_fingerprint( + registry_path=registry_path, + session=session, + runtime_root=runtime_root, + scope_kind=scope_kind, + authorized_goal_ids=before, + bound_steward=bound_steward, + include_details=include_details, + include_stopped=include_stopped, + read_goal_status=read_goal_status, + remote_evidence=remote_evidence, + ) + if post_fp == attempt_fp: + put_cached_manager_turn_context(attempt_fp, context) return context diff --git a/loopx/control_plane/collaboration/steward_managed_mode.ts b/loopx/control_plane/collaboration/steward_managed_mode.ts index 18c5b509f3..3e7bdf0224 100644 --- a/loopx/control_plane/collaboration/steward_managed_mode.ts +++ b/loopx/control_plane/collaboration/steward_managed_mode.ts @@ -68,7 +68,13 @@ function hasSingleManagerContextEvidence(basis: JsonObject, prior: JsonObject, e return requireJsonObject(basis.contexts[0], "watch context").schema_version === "manager_turn_context_v1"; } -function admitMonitorRestartRecovery(params: JsonObject, request: JsonObject, session: JsonObject): void { +function admitMonitorRestartRecovery( + params: JsonObject, + request: JsonObject, + session: JsonObject, + legacySessionId?: string, + queuedTurnCount?: unknown, +): void { if (request.monitor_restart_recovery === undefined) { if (params.monitor_restart_basis != null) throw new EffectRuntimeRequestError("watch recovery lacks its original request"); return; @@ -128,9 +134,12 @@ function admitMonitorRestartRecovery(params: JsonObject, request: JsonObject, se const chainedPostContextWatchRecoverable = postContextWatchRecoverable && Number.isFinite(completedAtMs) && Number.isFinite(observedAtMs) && observedAtMs - completedAtMs >= MONITOR_RECOVERY_RETRY_COOLDOWN_MS; + const effectiveQueuedCount = queuedTurnCount !== undefined ? queuedTurnCount : params.queued_turn_count; + const originalSessionMatches = original.session_id === session.session_id + || (legacySessionId !== undefined && original.session_id === legacySessionId); if (Object.keys(recovery).join() !== "original_turn_id" || recovery.original_turn_id !== original.turn_id || typeof original.turn_id !== "string" - || !/^[a-f0-9]{32}$/.test(original.turn_id) || original.session_id !== session.session_id + || !/^[a-f0-9]{32}$/.test(original.turn_id) || !originalSessionMatches || original.status !== "failed" || !(original.error_code === "server_restarted" || scopeRefused || identityRefused || postContextWatchRecoverable) || original.origin !== "native_loopx" || original.loopx_execution !== true @@ -145,7 +154,7 @@ function admitMonitorRestartRecovery(params: JsonObject, request: JsonObject, se || events.some(kind => !["turn.queued", "agent.phase", "manager.context", "turn.failed"].includes(String(kind))) || priorKeys.length !== keys.length || keys.some(key => key !== "monitor_lease_version" && JSON.stringify(request[key]) !== JSON.stringify(prior[key])) - || Number(params.queued_turn_count) !== 0) { + || Number(effectiveQueuedCount) !== 0) { throw new EffectRuntimeRequestError("watch restart requires independent proof before any native observation"); } } @@ -612,6 +621,8 @@ function reportSettlementOnly(params: JsonObject, request: JsonObject, todo: Jso } export const STEWARD_MANAGED_ACTOR_SCHEMA = "loopx_steward_managed_actor_v0"; +export const STEWARD_BACKGROUND_SESSION_PREFIX = "steward.background."; +export const STEWARD_BACKGROUND_CHANNEL_PREFIX = "manager.external.steward.background."; const AGENT_ID = "steward"; function text(value: unknown, name: string, expression?: RegExp): string { @@ -622,6 +633,35 @@ function text(value: unknown, name: string, expression?: RegExp): string { return result; } +export function stewardBackgroundSessionId(bindingId: string): string { + const id = text(bindingId, "binding identity", /^[a-f0-9]{24}$/); + return `${STEWARD_BACKGROUND_SESSION_PREFIX}${id}`; +} + +function validateStewardBackgroundCarrier(carrierRaw: unknown, bindingId: string, parentContext: JsonObject): JsonObject { + const carrier = requireJsonObject(carrierRaw, "steward background carrier Session"); + const bgContext = requireJsonObject(carrier.steward_background_context, "steward background carrier authority"); + if (carrier.session_id !== stewardBackgroundSessionId(bindingId) + || carrier.channel_id !== `${STEWARD_BACKGROUND_CHANNEL_PREFIX}${bindingId}` + || carrier.goal_id !== "loopx-manager" + || carrier.session_mode !== "managed_runtime" + || carrier.status === "closed" + || carrier.project_context != null + || carrier.steward_context != null + || carrier.managed_agent_id != null + || bgContext.kind !== "bound_steward" + || bgContext.audience !== "bound_owner" + || bgContext.grant !== "portfolio_read" + || (parentContext.kind !== undefined && bgContext.kind !== parentContext.kind) + || (parentContext.audience !== undefined && bgContext.audience !== parentContext.audience) + || (parentContext.grant !== undefined && bgContext.grant !== parentContext.grant) + || ["binding_id", "source_ref", "provider_ref", "operator_ref", "project_ref"].some( + key => bgContext[key] !== parentContext[key])) { + throw new EffectRuntimeRequestError("the steward background watch carrier Session is invalid"); + } + return carrier; +} + export function normalizeStewardManagedActor(value: unknown): JsonObject { const row = requireJsonObject(value, "managed steward identity"); const fields = ["schema_version", "goal_id", "goal_instance_id", "agent_id", "session_id", "source_ref", "creation_operation_id"]; @@ -656,12 +696,17 @@ export function stewardManagedBasis(params: JsonObject, executing = false) { const observation = requireJsonObject(params.observation, "current provider observation"); const id = text(binding.binding_id, "binding identity", /^[a-f0-9]{24}$/); const source = text(context.source_ref, "steward source", /^[a-f0-9]{24}$/); + const hasCarrier = params.carrier_session != null; + if (hasCarrier && jsonObject(params.request)?.work_kind !== "monitor") { + throw new EffectRuntimeRequestError("steward background carrier is reserved for observation-only monitor work"); + } + const carrier = hasCarrier ? validateStewardBackgroundCarrier(params.carrier_session, id, context) : null; if (binding.context_kind !== "steward" || binding.grant !== "portfolio_read" || binding.enabled !== true || binding.audience === "group" || observeStewardNativeExecutor(params).execution_available !== true || session.goal_id !== "loopx-manager" || session.session_mode === "attached_host" || session.status === "closed" || session.channel_id !== `manager.external.native.${id}.${source}` - || !executing && (session.active_turn_id || params.queued_turn_count !== 0)) { + || !executing && !hasCarrier && (session.active_turn_id || params.queued_turn_count !== 0)) { throw new EffectRuntimeRequestError("prepare the original idle private steward, retaining its current work"); } for (const key of ["binding_id", "provider_ref", "operator_ref", "project_ref"]) { @@ -685,7 +730,7 @@ export function stewardManagedBasis(params: JsonObject, executing = false) { || !Array.isArray(goal.registered_agents) || !goal.registered_agents.includes(AGENT_ID))) { throw new EffectRuntimeRequestError("the prepared steward identity or its original Goal lifetime is unavailable"); } - return {binding, session, id, source, workspace, sessionId, goalId, creation, goal, actor}; + return {binding, session, id, source, workspace, sessionId, goalId, creation, goal, actor, carrier}; } /** Bind an internal host dispatch to the prepared actor and original Core Turn. @@ -717,11 +762,29 @@ export function admitStewardManagedTurn(params: JsonObject): JsonObject { admitReportSelectionRecovery(params, request, current.sessionId); admitReportQuotaRecovery(params, request, current.session); admitReportTimeoutRecovery(params, request, current.session); - admitMonitorRestartRecovery(params, request, current.session); - if (turn && (turn.session_id !== current.sessionId || turn.turn_id !== current.session.active_turn_id - || !["starting", "running"].includes(String(turn.status)) || turn.origin !== "native_loopx" - || turn.loopx_execution !== true || JSON.stringify(turn.loopx_request) !== JSON.stringify(request))) { - throw new EffectRuntimeRequestError("the original native Chat Turn no longer owns execution"); + if (current.carrier !== null) { + const rawCarrierQueued = params.carrier_queued_turn_count ?? 0; + if (!Number.isSafeInteger(rawCarrierQueued) || Number(rawCarrierQueued) < 0) { + throw new EffectRuntimeRequestError("invalid steward background carrier queue count"); + } + const carrierQueuedCount = Number(rawCarrierQueued); + admitMonitorRestartRecovery(params, request, current.carrier, current.sessionId, carrierQueuedCount); + if (turn === null) { + if (current.carrier.active_turn_id || carrierQueuedCount !== 0) { + throw new EffectRuntimeRequestError("the steward background watch carrier is busy; retain its current observation"); + } + } else if (turn.session_id !== current.carrier.session_id || turn.turn_id !== current.carrier.active_turn_id + || !["starting", "running"].includes(String(turn.status)) || turn.origin !== "native_loopx" + || turn.loopx_execution !== true || JSON.stringify(turn.loopx_request) !== JSON.stringify(request)) { + throw new EffectRuntimeRequestError("the original native Chat Turn no longer owns execution"); + } + } else { + admitMonitorRestartRecovery(params, request, current.session); + if (turn && (turn.session_id !== current.sessionId || turn.turn_id !== current.session.active_turn_id + || !["starting", "running"].includes(String(turn.status)) || turn.origin !== "native_loopx" + || turn.loopx_execution !== true || JSON.stringify(turn.loopx_request) !== JSON.stringify(request))) { + throw new EffectRuntimeRequestError("the original native Chat Turn no longer owns execution"); + } } const monitor = params.monitor_todo == null ? null : requireJsonObject(params.monitor_todo, "native monitor"); const observationOnly = request.work_kind === "monitor"; diff --git a/tests/control_plane_ts/steward_background_session.test.ts b/tests/control_plane_ts/steward_background_session.test.ts new file mode 100644 index 0000000000..75b75d3bc6 --- /dev/null +++ b/tests/control_plane_ts/steward_background_session.test.ts @@ -0,0 +1,393 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + STEWARD_BACKGROUND_CHANNEL_PREFIX, + STEWARD_BACKGROUND_SESSION_PREFIX, + admitStewardManagedTurn, + bindStewardManagedActor, + stewardBackgroundSessionId, + stewardManagedBasis, +} from "../../loopx/control_plane/collaboration/steward_managed_mode.ts"; +import {listLocalBoundSessions} from "../../loopx/control_plane/collaboration/conversation_binding.ts"; +import {resolveConversationScope} from "../../loopx/control_plane/collaboration/conversation_scope.ts"; + +function buildFixture() { + const binding = { + schema_version: "loopx_chat_conversation_binding_v0", + binding_id: "b".repeat(24), + transport_ref: "steward-app", + provider_ref: "c".repeat(24), + operator_ref: "d".repeat(24), + project_ref: "a".repeat(24), + context_kind: "steward", + grant: "portfolio_read", + executor_endpoint_id: "codex", + enabled: true, + goal_scope: "all_registered", + goal_ids: [], + }; + const source = "e".repeat(24); + const stewardContext = { + kind: "bound_steward", + audience: "bound_owner", + grant: "portfolio_read", + binding_id: binding.binding_id, + provider_ref: binding.provider_ref, + operator_ref: binding.operator_ref, + project_ref: binding.project_ref, + source_ref: source, + workspace_path: "/runtime/chat/manager-workspaces/original", + goal_ids: [], + }; + const session = { + session_id: "f".repeat(32), + agent_id: "codex", + executor_endpoint_id: "codex", + goal_id: "loopx-manager", + session_mode: "managed_runtime", + status: "ready", + active_turn_id: null, + upstream_thread_id: "original-thread", + channel_id: `manager.external.native.${binding.binding_id}.${source}`, + steward_context: stewardContext, + }; + const carrier = { + session_id: stewardBackgroundSessionId(binding.binding_id), + agent_id: "codex", + executor_endpoint_id: "codex", + goal_id: "loopx-manager", + session_mode: "managed_runtime", + status: "ready", + active_turn_id: null, + upstream_thread_id: `steward-watch-${binding.binding_id}`, + channel_id: `${STEWARD_BACKGROUND_CHANNEL_PREFIX}${binding.binding_id}`, + project_context: null, + steward_context: null, + steward_background_context: {...stewardContext}, + }; + const observation = { + transport_ref: binding.transport_ref, + provider_ref: binding.provider_ref, + operator_ref: binding.operator_ref, + verified: true, + }; + const workspacePath = "/runtime/chat/manager-workspaces/original"; + const goal = { + goal_id: `steward-agent-${binding.binding_id}`, + goal_instance_id: "original-goal-lifetime", + workspace_path: workspacePath, + registered_agents: ["steward"], + creation_operation_id: `steward-managed:${binding.binding_id}:${source}`, + }; + const actor = bindStewardManagedActor({ + binding, + session, + observation, + workspace_path: workspacePath, + queued_turn_count: 0, + goal, + }); + const preparedBinding = {...binding, managed_actor: actor}; + const monitorTodo = { + todo_id: "todo_watch", + task_class: "continuous_monitor", + target_key: "steward-portfolio-watch", + watch_only: true, + claimed_by: "steward", + status: "open", + next_due_at: "2026-11-23T12:00:00Z", + }; + const monitorRequest = { + operation: "native_turn", + host: "codex-app-server", + actor, + work_kind: "monitor", + turn_instance_id: "monitor.bg.1", + todo_id: monitorTodo.todo_id, + validation_command: null, + monitor_deadline: monitorTodo.next_due_at, + monitor_lease_version: 0, + }; + return { + binding: preparedBinding, + source, + stewardContext, + session, + carrier, + observation, + workspacePath, + goal, + actor, + monitorTodo, + monitorRequest, + }; +} + +test("background carrier Session uses external_audience scope and stays invisible to bound human session discovery", () => { + const f = buildFixture(); + assert.equal(f.carrier.session_id, `${STEWARD_BACKGROUND_SESSION_PREFIX}${f.binding.binding_id}`); + assert.equal(f.carrier.channel_id, `${STEWARD_BACKGROUND_CHANNEL_PREFIX}${f.binding.binding_id}`); + + const scope = resolveConversationScope(f.carrier); + assert.deepEqual(scope, { + kind: "external_audience", + goal_ids: [], + private_conversation: false, + }); + assert.equal(scope.bound_steward, undefined); + + const state = { + schema_version: "loopx_chat_conversation_bindings_v0", + revision: 1, + bindings: [f.binding], + }; + const listed = listLocalBoundSessions({ + current: state, + binding_id: f.binding.binding_id, + observation: f.observation, + available_projects: [{ + kind: "project_workspace", + project_ref: f.binding.project_ref, + workspace_path: f.workspacePath, + audience: "local_owner", + grant: "workspace_read", + }], + available_goal_ids: [f.goal.goal_id], + sessions: [f.session, f.carrier], + }); + assert.deepEqual(listed.session_ids, [f.session.session_id]); +}); + +test("background monitor turns admit and execute while the foreground human Steward Session is busy and queued", () => { + const f = buildFixture(); + const busyHumanSession = { + ...f.session, + status: "busy", + active_turn_id: "human-turn-in-progress", + }; + const baseParams = { + binding: f.binding, + session: busyHumanSession, + carrier_session: f.carrier, + carrier_queued_turn_count: 0, + observation: f.observation, + workspace_path: f.workspacePath, + queued_turn_count: 3, + goal: f.goal, + goal_active: true, + request: f.monitorRequest, + monitor_todo: f.monitorTodo, + }; + + // Pre-acceptance admission succeeds despite busy human session + 3 queued human turns. + const admitted = admitStewardManagedTurn(baseParams); + assert.equal(admitted.observation_only, true); + assert.deepEqual(admitted.actor, f.actor); + + // Without carrier_session, legacy admission still blocks on busy human session. + assert.throws(() => admitStewardManagedTurn({ + ...baseParams, + carrier_session: undefined, + carrier_queued_turn_count: undefined, + })); + + // Active execution on carrier validates turn against carrier, not human session. + const runningCarrier = {...f.carrier, status: "busy", active_turn_id: "bg-turn-1"}; + const runningTurn = { + session_id: runningCarrier.session_id, + turn_id: "bg-turn-1", + status: "running", + origin: "native_loopx", + loopx_execution: true, + loopx_request: f.monitorRequest, + }; + const activeAdmitted = admitStewardManagedTurn({ + ...baseParams, + carrier_session: runningCarrier, + turn: runningTurn, + scope: {current: "scope-hash-1", without_actor: "scope-hash-0"}, + }); + assert.equal(activeAdmitted.observation_only, true); + + // Busy or queued carrier blocks a second concurrent monitor turn. + assert.throws(() => admitStewardManagedTurn({ + ...baseParams, + carrier_session: runningCarrier, + })); + assert.throws(() => admitStewardManagedTurn({ + ...baseParams, + carrier_queued_turn_count: 1, + })); + + // Turn bound to the wrong session or wrong active_turn_id is rejected. + assert.throws(() => admitStewardManagedTurn({ + ...baseParams, + carrier_session: runningCarrier, + turn: {...runningTurn, session_id: f.session.session_id}, + scope: {current: "scope-hash-1", without_actor: "scope-hash-0"}, + })); + assert.throws(() => admitStewardManagedTurn({ + ...baseParams, + carrier_session: runningCarrier, + turn: {...runningTurn, turn_id: "other-turn"}, + scope: {current: "scope-hash-1", without_actor: "scope-hash-0"}, + })); +}); + +test("background carrier rejects non-monitor work and any tampered carrier identity or authority", () => { + const f = buildFixture(); + const baseParams = { + binding: f.binding, + session: f.session, + carrier_session: f.carrier, + carrier_queued_turn_count: 0, + observation: f.observation, + workspace_path: f.workspacePath, + queued_turn_count: 0, + goal: f.goal, + goal_active: true, + request: f.monitorRequest, + monitor_todo: f.monitorTodo, + }; + + // Non-monitor work cannot use carrier_session to bypass foreground queue fencing. + assert.throws(() => stewardManagedBasis({ + ...baseParams, + request: {...f.monitorRequest, work_kind: "native_turn"}, + })); + assert.throws(() => admitStewardManagedTurn({ + ...baseParams, + monitor_todo: undefined, + request: { + operation: "native_turn", + host: "codex-app-server", + actor: f.actor, + work_kind: "native_turn", + turn_instance_id: "advancement.1", + todo_id: "todo_adv", + validation_command: null, + }, + })); + + for (const invalidCarrier of [ + {...f.carrier, session_id: "0".repeat(32)}, + {...f.carrier, channel_id: f.session.channel_id}, + {...f.carrier, channel_id: "manager.external.steward.background." + "0".repeat(24)}, + {...f.carrier, goal_id: f.goal.goal_id}, + {...f.carrier, session_mode: "attached_host"}, + {...f.carrier, status: "closed"}, + {...f.carrier, project_context: {kind: "project_workspace"}}, + {...f.carrier, steward_context: f.stewardContext}, + {...f.carrier, managed_agent_id: "steward"}, + {...f.carrier, steward_background_context: null}, + {...f.carrier, steward_background_context: {...f.stewardContext, kind: "project_workspace"}}, + {...f.carrier, steward_background_context: {...f.stewardContext, audience: "bound_group"}}, + {...f.carrier, steward_background_context: {...f.stewardContext, grant: "workspace_write"}}, + {...f.carrier, steward_background_context: {...f.stewardContext, binding_id: "0".repeat(24)}}, + {...f.carrier, steward_background_context: {...f.stewardContext, source_ref: "0".repeat(24)}}, + {...f.carrier, steward_background_context: {...f.stewardContext, provider_ref: "0".repeat(24)}}, + {...f.carrier, steward_background_context: {...f.stewardContext, operator_ref: "0".repeat(24)}}, + {...f.carrier, steward_background_context: {...f.stewardContext, project_ref: "0".repeat(24)}}, + ]) { + assert.throws(() => admitStewardManagedTurn({ + ...baseParams, + carrier_session: invalidCarrier, + })); + } +}); + +test("monitor restart recovery on background carrier accepts both carrier and legacy pre-upgrade original turns", () => { + const f = buildFixture(); + const busyHumanSession = { + ...f.session, + status: "busy", + active_turn_id: "human-active-turn", + }; + for (const originalSessionId of [f.carrier.session_id, f.session.session_id]) { + const original = { + turn_id: "1".repeat(32), + session_id: originalSessionId, + status: "failed", + error_code: "server_restarted", + error: "The original host stopped before observation.", + origin: "native_loopx", + loopx_execution: true, + upstream_turn_id: null, + response: null, + delta_count: 0, + loopx_request: f.monitorRequest, + }; + const basis = { + original, + contexts: [], + phases: [], + event_kinds: ["turn.queued", "turn.failed"], + poll_absent: true, + old_worker_excluded: true, + lease_available: true, + }; + const recoveryParams = { + binding: f.binding, + session: busyHumanSession, + carrier_session: f.carrier, + carrier_queued_turn_count: 0, + observation: f.observation, + workspace_path: f.workspacePath, + queued_turn_count: 2, // Foreground human queue is non-empty! + goal: f.goal, + goal_active: true, + request: { + ...f.monitorRequest, + monitor_restart_recovery: {original_turn_id: original.turn_id}, + }, + monitor_todo: f.monitorTodo, + monitor_restart_basis: basis, + }; + assert.equal(admitStewardManagedTurn(recoveryParams).observation_only, true); + + // Non-empty carrier queue must still block recovery. + assert.throws(() => admitStewardManagedTurn({ + ...recoveryParams, + carrier_queued_turn_count: 1, + })); + } + + // Foreign session_id on original stopped turn is rejected. + const foreignOriginal = { + turn_id: "2".repeat(32), + session_id: "9".repeat(32), + status: "failed", + error_code: "server_restarted", + origin: "native_loopx", + loopx_execution: true, + upstream_turn_id: null, + response: null, + delta_count: 0, + loopx_request: f.monitorRequest, + }; + assert.throws(() => admitStewardManagedTurn({ + binding: f.binding, + session: busyHumanSession, + carrier_session: f.carrier, + carrier_queued_turn_count: 0, + observation: f.observation, + workspace_path: f.workspacePath, + queued_turn_count: 0, + goal: f.goal, + goal_active: true, + request: { + ...f.monitorRequest, + monitor_restart_recovery: {original_turn_id: foreignOriginal.turn_id}, + }, + monitor_todo: f.monitorTodo, + monitor_restart_basis: { + original: foreignOriginal, + contexts: [], + phases: [], + event_kinds: ["turn.queued", "turn.failed"], + poll_absent: true, + old_worker_excluded: true, + lease_available: true, + }, + })); +}); diff --git a/tests/test_manager_turn_context_cache.py b/tests/test_manager_turn_context_cache.py new file mode 100644 index 0000000000..43d859a962 --- /dev/null +++ b/tests/test_manager_turn_context_cache.py @@ -0,0 +1,423 @@ +"""Unit and integration tests for authority-revision manager turn context hot cache.""" + +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone +import json +from pathlib import Path +import sqlite3 + +import pytest + +import loopx.chat_manager_context as manager_ctx +from loopx.capabilities.manager_context import POLICY_SCHEMA, _root, _write +from loopx.capabilities.manager_context.turn_context_cache import ( + DEFAULT_MAX_AGE_SECONDS, + MAX_CACHE_ENTRIES, + clear_manager_turn_context_cache, + compute_manager_turn_context_fingerprint, + get_cached_manager_turn_context, + put_cached_manager_turn_context, +) +from loopx.chat_manager import MANAGED_FOLLOWTHROUGH_CURRENT_MARKER, manager_followthrough_text + + +@pytest.fixture(autouse=True) +def _clean_turn_context_cache(): + clear_manager_turn_context_cache() + yield + clear_manager_turn_context_cache() + + +def _setup_registry_and_goal(tmp_path: Path, goal_id: str = "alpha") -> tuple[Path, Path, Path]: + runtime_root = tmp_path / "runtime" + repo_dir = tmp_path / "repos" / goal_id + repo_dir.mkdir(parents=True, exist_ok=True) + state_file = repo_dir / "STATE.md" + state_file.write_text("# Initial state\n", encoding="utf-8") + + goal_dir = runtime_root / "goals" / goal_id + (goal_dir / "runs").mkdir(parents=True, exist_ok=True) + (goal_dir / "deliveries").mkdir(parents=True, exist_ok=True) + (goal_dir / "todos.json").write_text( + json.dumps({"todos": [{"todo_id": "todo_1", "status": "open", "text": "Ship slice"}]}), + encoding="utf-8", + ) + (goal_dir / "runs" / "index.jsonl").write_text( + json.dumps({ + "run_id": "run_1", + "goal_id": goal_id, + "agent_id": "worker", + "generated_at": datetime.now(timezone.utc).isoformat(), + "classification": "advancement", + "delivery_outcome": "outcome_progress", + }) + "\n", + encoding="utf-8", + ) + + registry_path = tmp_path / "registry.json" + registry_path.write_text( + json.dumps({ + "schema_version": "0.1", + "updated_at": "2026-11-23T10:00:00Z", + "runtime_root": str(runtime_root), + "goals": [ + { + "id": goal_id, + "repo": str(repo_dir), + "state_file": "STATE.md", + "status": "active", + "synced_at": "2026-11-23T10:00:00Z", + "coordination": {"registered_agents": ["worker"]}, + } + ], + }), + encoding="utf-8", + ) + return registry_path, runtime_root, repo_dir + + +def _bound_steward_session(tmp_path: Path) -> dict: + binding_id = "b" * 24 + source_ref = "e" * 24 + return { + "session_id": "f" * 32, + "goal_id": "loopx-manager", + "session_mode": "managed_runtime", + "channel_id": f"manager.external.native.{binding_id}.{source_ref}", + "steward_context": { + "kind": "bound_steward", + "project_ref": "a" * 24, + "workspace_path": str(tmp_path), + "audience": "bound_owner", + "grant": "portfolio_read", + "binding_id": binding_id, + "provider_ref": "c" * 24, + "operator_ref": "d" * 24, + "source_ref": source_ref, + "goal_ids": ["alpha"], + }, + } + + +def _stub_fast_portfolio(monkeypatch) -> list[dict]: + calls: list[dict] = [] + + def fake_build_goal_portfolio(**kwargs): + calls.append(dict(kwargs)) + now_iso = datetime.now(timezone.utc).isoformat() + return { + "ok": True, + "schema_version": "goal_portfolio_v0", + "snapshot_id": f"sha256:{len(calls):064x}", + "inventory_revision": "sha256:" + __import__("hashlib").sha256( + Path(kwargs["registry_path"]).read_bytes() + ).hexdigest(), + "inventory_semantic_revision": manager_ctx.registry_semantic_revision( + Path(kwargs["registry_path"]), + Path(kwargs["registry_path"]).read_bytes(), + ), + "collected_at": now_iso, + "collection_completed_at": now_iso, + "coverage": {"discovered": 1, "verified": 1, "complete": True}, + "warnings": [], + "limitations": [], + "goals": [ + { + "goal_id": "alpha", + "activation_state": "active", + "quality": "verified", + "progress": "recorded_delivery_available", + "attention": {"status": "read", "items": []}, + "goal_lifecycle": { + "schema_version": "goal_lifecycle_readback_v0", + "goal_id": "alpha", + "status": "unavailable", + "reason": "projection_not_derived", + }, + "agents": [], + "deliveries": [], + "warnings": [], + } + ], + } + + monkeypatch.setattr(manager_ctx, "build_goal_portfolio", fake_build_goal_portfolio) + return calls + + +def test_bound_steward_cache_hits_across_sync_timestamp_churn_and_isolates_caller_mutations( + tmp_path: Path, monkeypatch, +) -> None: + registry_path, runtime_root, _ = _setup_registry_and_goal(tmp_path) + calls = _stub_fast_portfolio(monkeypatch) + session = _bound_steward_session(tmp_path) + + first = manager_ctx.collect_manager_turn_context( + registry_path, + session, + runtime_root, + scope_resolver=lambda _s: ["alpha"], + include_details=False, + ) + assert len(calls) == 1 + original_snapshot_id = first["snapshot_id"] + + # Mutate returned payload the same way coordination.py does; cached entry must stay pristine. + first["bound_steward"]["executions"] = [{"turn_id": "mutated"}] + first["context_delegation"] = {"targets": [{"goal_id": "alpha", "agent_id": "worker"}]} + first["goals"][0]["progress"] = "mutated_in_place" + + # Churn benign updated_at / synced_at timestamps in registry.json. + reg_payload = json.loads(registry_path.read_text(encoding="utf-8")) + reg_payload["updated_at"] = "2026-11-23T10:05:00Z" + reg_payload["goals"][0]["synced_at"] = "2026-11-23T10:05:00Z" + registry_path.write_text(json.dumps(reg_payload), encoding="utf-8") + + second = manager_ctx.collect_manager_turn_context( + registry_path, + session, + runtime_root, + scope_resolver=lambda _s: ["alpha"], + include_details=False, + ) + assert len(calls) == 1 # Hit hot cache despite sync timestamp churn! + assert second["snapshot_id"] == original_snapshot_id + assert "executions" not in second["bound_steward"] + assert "context_delegation" not in second + assert second["goals"][0]["progress"] == "recorded_delivery_available" + + +def test_cache_immediately_invalidates_on_every_local_authority_and_storage_mutation( + tmp_path: Path, monkeypatch, +) -> None: + registry_path, runtime_root, repo_dir = _setup_registry_and_goal(tmp_path) + calls = _stub_fast_portfolio(monkeypatch) + owner_session = {"session_id": "a" * 32, "goal_id": "loopx-manager", "channel_id": "manager"} + + manager_ctx.collect_manager_turn_context( + registry_path, owner_session, runtime_root, include_details=False, + ) + assert len(calls) == 1 + + # Repeat without changes -> cache hit. + manager_ctx.collect_manager_turn_context( + registry_path, owner_session, runtime_root, include_details=False, + ) + assert len(calls) == 1 + + # 1. SQLite authority DB creation & WAL write invalidates immediately. + goal_sha = __import__("hashlib").sha256(b"alpha").hexdigest() + sqlite_dir = runtime_root / "authority" / "sqlite-v0" + sqlite_dir.mkdir(parents=True, exist_ok=True) + db_path = sqlite_dir / f"authority-{goal_sha}.sqlite" + conn = sqlite3.connect(db_path) + try: + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, val TEXT)") + conn.execute("INSERT INTO items (val) VALUES ('v1')") + conn.commit() + finally: + conn.close() + + manager_ctx.collect_manager_turn_context( + registry_path, owner_session, runtime_root, include_details=False, + ) + assert len(calls) == 2 + + # Second SQLite commit updates WAL/header and invalidates again. + conn = sqlite3.connect(db_path) + try: + conn.execute("INSERT INTO items (val) VALUES ('v2')") + conn.commit() + finally: + conn.close() + + manager_ctx.collect_manager_turn_context( + registry_path, owner_session, runtime_root, include_details=False, + ) + assert len(calls) == 3 + + # 2. todos.json mutation invalidates immediately. + (runtime_root / "goals" / "alpha" / "todos.json").write_text( + json.dumps({"todos": [{"todo_id": "todo_2", "status": "open", "text": "Updated"}]}), + encoding="utf-8", + ) + manager_ctx.collect_manager_turn_context( + registry_path, owner_session, runtime_root, include_details=False, + ) + assert len(calls) == 4 + + # 3. Declared repo/state_file mutation invalidates immediately. + (repo_dir / "STATE.md").write_text("# Updated state v2\n", encoding="utf-8") + manager_ctx.collect_manager_turn_context( + registry_path, owner_session, runtime_root, include_details=False, + ) + assert len(calls) == 5 + + # 4. runs/index.jsonl append invalidates immediately. + with (runtime_root / "goals" / "alpha" / "runs" / "index.jsonl").open("a", encoding="utf-8") as fh: + fh.write(json.dumps({"run_id": "run_2", "goal_id": "alpha"}) + "\n") + manager_ctx.collect_manager_turn_context( + registry_path, owner_session, runtime_root, include_details=False, + ) + assert len(calls) == 6 + + # 5. deliveries directory new entry invalidates immediately. + (runtime_root / "goals" / "alpha" / "deliveries" / "receipt_1.json").write_text( + '{"ok":true}', encoding="utf-8", + ) + manager_ctx.collect_manager_turn_context( + registry_path, owner_session, runtime_root, include_details=False, + ) + assert len(calls) == 7 + + # 6. machine/configuration.json mutation invalidates immediately. + machine_cfg = runtime_root / "machine" / "configuration.json" + machine_cfg.parent.mkdir(parents=True, exist_ok=True) + machine_cfg.write_text('{"schema_version":"machine_configuration_v0","namespaces":{}}', encoding="utf-8") + manager_ctx.collect_manager_turn_context( + registry_path, owner_session, runtime_root, include_details=False, + ) + assert len(calls) == 8 + + +def test_cache_bypasses_stopped_status_off_ssh_grants_env_off_and_incomplete_results( + tmp_path: Path, monkeypatch, +) -> None: + registry_path, runtime_root, _ = _setup_registry_and_goal(tmp_path) + calls = _stub_fast_portfolio(monkeypatch) + session = _bound_steward_session(tmp_path) + + # 1. include_stopped=True (observation_only watch turns) ALWAYS bypasses cache. + manager_ctx.collect_manager_turn_context( + registry_path, session, runtime_root, scope_resolver=lambda _s: ["alpha"], + include_details=False, include_stopped=True, + ) + manager_ctx.collect_manager_turn_context( + registry_path, session, runtime_root, scope_resolver=lambda _s: ["alpha"], + include_details=False, include_stopped=True, + ) + assert len(calls) == 2 + + # 2. read_goal_status=False bypasses cache. + manager_ctx.collect_manager_turn_context( + registry_path, session, runtime_root, scope_resolver=lambda _s: ["alpha"], + include_details=False, read_goal_status=False, + ) + manager_ctx.collect_manager_turn_context( + registry_path, session, runtime_root, scope_resolver=lambda _s: ["alpha"], + include_details=False, read_goal_status=False, + ) + assert len(calls) == 4 + + # 3. LOOPX_MANAGER_CONTEXT_CACHE=off bypasses cache. + with monkeypatch.context() as env: + env.setenv("LOOPX_MANAGER_CONTEXT_CACHE", "off") + manager_ctx.collect_manager_turn_context( + registry_path, session, runtime_root, scope_resolver=lambda _s: ["alpha"], + include_details=False, + ) + manager_ctx.collect_manager_turn_context( + registry_path, session, runtime_root, scope_resolver=lambda _s: ["alpha"], + include_details=False, + ) + assert len(calls) == 6 + + # 4. Non-empty SSH grants on channel bypasses cache. + _write( + _root(runtime_root) / "policy.json", + { + "schema_version": POLICY_SCHEMA, + "sources": { + session["channel_id"]: { + "evidence_ssh_hosts": {"gpu-box": ["remote-goal"]}, + } + }, + }, + ) + manager_ctx.collect_manager_turn_context( + registry_path, session, runtime_root, scope_resolver=lambda _s: ["alpha"], + include_details=False, + ) + manager_ctx.collect_manager_turn_context( + registry_path, session, runtime_root, scope_resolver=lambda _s: ["alpha"], + include_details=False, + ) + assert len(calls) == 8 + + # 5. Incomplete coverage or non-empty warnings are never stored. + assert put_cached_manager_turn_context( + "sha256:warn", + {"warnings": ["registry_unreadable"], "coverage": {"complete": True}}, + ) is False + assert put_cached_manager_turn_context( + "sha256:incomplete", + {"warnings": [], "coverage": {"complete": False}}, + ) is False + assert get_cached_manager_turn_context("sha256:warn") is None + assert get_cached_manager_turn_context("sha256:incomplete") is None + + +def test_cache_ttl_lru_eviction_thread_safety_and_followthrough_fast_slow_lane_guidance( + tmp_path: Path, +) -> None: + registry_path, runtime_root, _ = _setup_registry_and_goal(tmp_path) + fp = compute_manager_turn_context_fingerprint( + registry_path=registry_path, + session={"channel_id": "manager"}, + runtime_root=runtime_root, + scope_kind="owner_portfolio", + authorized_goal_ids=None, + bound_steward=False, + include_details=False, + include_stopped=False, + read_goal_status=True, + remote_evidence=False, + ) + assert fp is not None and fp.startswith("sha256:") + + # TTL expiry check. + sample = {"warnings": [], "coverage": {"complete": True}, "goals": [{"goal_id": "alpha"}]} + assert put_cached_manager_turn_context(fp, sample, now_monotonic=100.0) is True + assert get_cached_manager_turn_context(fp, now_monotonic=100.0 + DEFAULT_MAX_AGE_SECONDS - 0.1) is not None + assert get_cached_manager_turn_context(fp, now_monotonic=100.0 + DEFAULT_MAX_AGE_SECONDS + 0.1) is None + + # Bounded LRU eviction check (MAX_CACHE_ENTRIES = 16). + for idx in range(MAX_CACHE_ENTRIES + 4): + assert put_cached_manager_turn_context( + f"sha256:key_{idx}", + {"warnings": [], "coverage": {"complete": True}, "idx": idx}, + now_monotonic=200.0 + idx * 0.01, + ) is True + for evicted_idx in range(4): + assert get_cached_manager_turn_context(f"sha256:key_{evicted_idx}", now_monotonic=201.0) is None + for retained_idx in range(4, MAX_CACHE_ENTRIES + 4): + hit = get_cached_manager_turn_context(f"sha256:key_{retained_idx}", now_monotonic=201.0) + assert hit is not None and hit["idx"] == retained_idx + + # Concurrent read/write thread safety. + def worker(n: int) -> bool: + key = f"sha256:concurrent_{n % 8}" + put_cached_manager_turn_context( + key, + {"warnings": [], "coverage": {"complete": True}, "n": n}, + ) + got = get_cached_manager_turn_context(key) + return got is None or isinstance(got.get("n"), int) + + with ThreadPoolExecutor(max_workers=8) as pool: + results = list(pool.map(worker, range(64))) + assert all(results) + + clear_manager_turn_context_cache() + assert get_cached_manager_turn_context("sha256:concurrent_0") is None + + # Verify FOLLOWTHROUGH.md fast/slow lane guidance and marker invariants. + followthrough = manager_followthrough_text() + assert followthrough.startswith(MANAGED_FOLLOWTHROUGH_CURRENT_MARKER) + assert "fast/slow lane separation" in followthrough + assert "resolve-peer-route" in followthrough + assert "original_conversation" in followthrough + assert len(followthrough.encode("utf-8")) <= 24_000 diff --git a/tests/test_steward_background_monitor_isolation.py b/tests/test_steward_background_monitor_isolation.py new file mode 100644 index 0000000000..c3a47a6b8b --- /dev/null +++ b/tests/test_steward_background_monitor_isolation.py @@ -0,0 +1,299 @@ +"""Background Steward monitor carrier isolation and legacy recovery tests.""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from loopx.capabilities.native_chat.steward_monitor import ( + FOLLOWUP_TARGET_PREFIX, + StewardMonitor, + monitor_turn_id, + pump_steward_monitors, +) +from loopx.capabilities.native_chat.steward_turn import ( + StewardTurnHost, + native_steward_client_id, +) +from loopx.chat_lark_api import manager_source_scope_resolver +from loopx.control_plane.collaboration import conversation_scope +from test_native_steward_managed_mode import original, storage +from test_native_steward_monitor import edit_local_watch, local_watch_row +from test_native_steward_private import finish, steward as steward_fixture +from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + +steward = steward_fixture + + +def _prepare_steward_monitor(steward_env, tmp_path: Path, monkeypatch) -> tuple[str, dict, StewardMonitor, str]: + isolate_sqlite_runtime(tmp_path, monkeypatch) + store, runtime, _, transport, binding, _, workspace = steward_env + payload = json.loads(runtime.registry_path.read_text(encoding="utf-8")) + payload["goals"] = [ + *list(payload.get("goals") or []), + { + "id": "peer-goal", + "repo": str(workspace), + "coordination": {"registered_agents": ["peer-worker"]}, + }, + ] + runtime.registry_path.write_text(json.dumps(payload), encoding="utf-8") + + sid, managed = original(steward_env) + storage(runtime, "sqlite") + plan = managed.prepare(binding["binding_id"], session_id=sid)["plan"] + actor = managed.prepare( + binding["binding_id"], + session_id=sid, + expected_plan_id=plan["plan_id"], + execute=True, + )["actor"] + transport.reconcile() + monitor = StewardMonitor(runtime) + enable_plan = monitor.configure(binding["binding_id"], operation="enable")["plan"] + enabled = monitor.configure( + binding["binding_id"], + operation="enable", + expected_plan_id=enable_plan["plan_id"], + execute=True, + ) + return sid, actor, monitor, enabled["monitor"]["todo_id"] + + +def test_due_monitor_runs_in_background_session_while_human_session_is_busy_and_queued( + steward, tmp_path, monkeypatch, +) -> None: + store, runtime, provider, transport, binding, capture, _ = steward + sid, actor, monitor, todo_id = _prepare_steward_monitor(steward, tmp_path, monkeypatch) + binding_id = binding["binding_id"] + bg_sid = StewardTurnHost.background_session_id(binding_id) + + # Wire the production HTTP server scope resolver so background carrier scope resolution is exercised end-to-end. + fake_server = SimpleNamespace( + runtime_controller=runtime, + registry_path=runtime.registry_path, + runtime_root_override=str(runtime.coordination_runtime_root), + ) + runtime.manager_scope_resolver = manager_source_scope_resolver( + fake_server, + registry_path=runtime.registry_path, + executor_runtime_root=runtime.coordination_runtime_root, + ) + + # Simulate an active long-running turn + queued human follow-up on the foreground Steward session. + store.update_session(sid, status="busy", active_turn_id="foreground-active-turn") + queued_human, _ = store.create_queued_turn( + sid, + client_turn_id="foreground-queued-user-msg", + message="请帮我跟进线上状态。", + origin="lark", + ) + human_messages_before = store.messages(sid) + calls_before = capture.read_bytes() + writes_before = list(provider.writes) + + getattr(runtime, "_steward_monitor_next_check", {}).clear() + dispatched = pump_steward_monitors(runtime) + assert len(dispatched) == 1 + bg_turn = dispatched[0] + assert bg_turn["session_id"] == bg_sid + assert bg_turn["session_id"] != sid + + completed = finish(runtime, bg_turn) + assert completed["status"] == "completed", completed + native = completed["response"]["native_loopx"] + assert native["ok"] is True + assert native["status"] == "observed" + assert native["model_invoked"] is False + assert native["quota_spent"] is False + + # Carrier session invariants: external_audience, steward_context=None, steward_background_context populated. + carrier = store.load_session(bg_sid) + parent = store.load_session(sid) + assert carrier is not None and parent is not None + assert carrier["channel_id"] == f"manager.external.steward.background.{binding_id}" + assert carrier.get("steward_context") is None + assert carrier.get("project_context") is None + assert carrier["steward_background_context"] == parent["steward_context"] + assert conversation_scope(carrier) == { + "kind": "external_audience", + "goal_ids": [], + "private_conversation": False, + } + + # Tampered background session metadata is rejected by manager_source_scope_resolver. + with pytest.raises(ValueError, match="bound steward background audience changed"): + runtime.manager_scope_resolver({**carrier, "channel_id": "manager.external.other"}) + with pytest.raises(ValueError, match="bound steward background audience changed"): + runtime.manager_scope_resolver({**carrier, "session_id": "a" * 32}) + + # Human session discovery & transcript remain 100% isolated from the background carrier. + assert [row["session_id"] for row in transport.bindings.local_sessions(binding_id)] == [sid] + assert store.messages(sid) == human_messages_before + assert store.load_session(sid)["active_turn_id"] == "foreground-active-turn" + assert [row["turn_id"] for row in store.queued_turns(sid)] == [queued_human["turn_id"]] + assert capture.read_bytes() == calls_before + assert provider.writes == writes_before + assert local_watch_row(runtime, actor, todo_id).get("result_hash") == native["monitor"]["result_hash"] + + +def test_advancement_followup_waits_for_human_idle_then_dispatches_without_throttle_delay( + steward, tmp_path, monkeypatch, +) -> None: + from loopx.capabilities.native_chat.steward_commands import native_command + + store, runtime, _, _, binding, _, _ = steward + sid, actor, _, todo_id = _prepare_steward_monitor(steward, tmp_path, monkeypatch) + + # Create a runnable Steward monitor follow-up advancement Todo. + adv = native_command( + runtime, + [ + "todo", + "add", + "--goal-id", + actor["goal_id"], + "--role", + "agent", + "--task-class", + "advancement_task", + "--action-kind", + "triage", + "--continuation-policy", + "same_agent_non_delivery", + "--claimed-by", + actor["agent_id"], + "--target-key", + f"{FOLLOWUP_TARGET_PREFIX}{todo_id}", + "--text", + "[steward-portfolio-watch] 信号变更跟进:检查新信号", + "--operation-id", + "test-adv-followup-1", + "--execute", + ], + ) + adv_todo_id = adv["todo_id"] + + # Make the watch due while human session is busy. + edit_local_watch( + runtime, + actor, + todo_id, + "--next-due-at", + (datetime.now(timezone.utc) - timedelta(seconds=2)).isoformat(), + ) + store.update_session(sid, status="busy", active_turn_id="busy-human-turn") + getattr(runtime, "_steward_monitor_next_check", {}).clear() + + # Pump 1 while human is busy: dispatches ONLY the background watch, NOT the advancement task. + first_batch = pump_steward_monitors(runtime) + assert len(first_batch) == 1 + assert first_batch[0]["loopx_request"]["work_kind"] == "monitor" + assert first_batch[0]["session_id"] == StewardTurnHost.background_session_id(binding["binding_id"]) + assert finish(runtime, first_batch[0])["status"] == "completed" + + # Pump 2 while human is still busy: advancement task remains gated on human_idle. + getattr(runtime, "_steward_monitor_next_check", {}).clear() + assert pump_steward_monitors(runtime) == [] + + # Release human session without clearing _steward_monitor_next_check: + # foreground idle transition must immediately dispatch the advancement task without a 60s delay! + store.update_session(sid, status="ready", active_turn_id=None) + with monkeypatch.context() as hold_worker: + hold_worker.setattr(runtime, "_start_accepted_turn_worker", lambda **_kw: None) + second_batch = pump_steward_monitors(runtime) + assert len(second_batch) == 1 + assert second_batch[0]["session_id"] == sid + assert second_batch[0]["loopx_request"]["work_kind"] == "native_turn" + assert second_batch[0]["loopx_request"]["todo_id"] == adv_todo_id + + +@pytest.mark.parametrize("legacy_pre_upgrade", [False, True]) +def test_monitor_restart_recovery_recovers_background_and_legacy_watches_while_human_busy( + steward, tmp_path, monkeypatch, legacy_pre_upgrade: bool, +) -> None: + store, runtime, _, _, binding, _, _ = steward + sid, actor, monitor, todo_id = _prepare_steward_monitor(steward, tmp_path, monkeypatch) + binding_id = binding["binding_id"] + bg_sid = StewardTurnHost.background_session_id(binding_id) + todo = local_watch_row(runtime, actor, todo_id) + turn_instance = monitor_turn_id(todo) + client_id = native_steward_client_id(actor, turn_instance) + + if legacy_pre_upgrade: + # Simulate a pre-upgrade stopped monitor turn recorded on actor["session_id"]. + request = { + "operation": "native_turn", + "host": "codex-app-server", + "actor": actor, + "turn_instance_id": turn_instance, + "todo_id": todo_id, + "work_kind": "monitor", + "validation_command": None, + "monitor_deadline": todo["next_due_at"], + "monitor_lease_version": 0, + } + accepted = store.accept_managed_turn( + sid, + client_turn_id=client_id, + message="Advance the currently admitted native LoopX work.", + display_message="检查授权工作状态。", + origin="native_loopx", + loopx_execution=True, + loopx_request=request, + ) + original_turn = accepted.turn + original_sid = sid + else: + getattr(runtime, "_steward_monitor_next_check", {}).clear() + with monkeypatch.context() as stopped_worker: + stopped_worker.setattr(runtime, "_start_accepted_turn_worker", lambda **_kw: None) + original_turn = pump_steward_monitors(runtime)[0] + original_sid = bg_sid + assert original_turn["session_id"] == bg_sid + + # Mark the unstarted watch as failed due to server_restarted. + store.update_turn( + original_sid, + original_turn["turn_id"], + status="failed", + error_code="server_restarted", + error="The original host stopped before observation.", + response=None, + upstream_turn_id=None, + ) + store.append_event( + original_sid, + original_turn["turn_id"], + kind="turn.failed", + payload={"error_code": "server_restarted"}, + ) + store.update_session(original_sid, active_turn_id=None, status="ready") + + # Make the foreground human session busy AND queued during restart recovery! + store.update_session(sid, status="busy", active_turn_id="foreground-human-turn") + store.create_queued_turn( + sid, + client_turn_id="foreground-queued-during-recovery", + message="继续讨论当前方案。", + origin="lark", + ) + + getattr(runtime, "_steward_monitor_next_check", {}).clear() + recovered = pump_steward_monitors(runtime) + assert len(recovered) == 1 + assert recovered[0]["session_id"] == bg_sid + assert recovered[0]["loopx_request"]["monitor_restart_recovery"] == { + "original_turn_id": original_turn["turn_id"], + } + done = finish(runtime, recovered[0]) + assert done["status"] == "completed", done + assert done["response"]["native_loopx"]["status"] == "observed" + + # Subsequent pump sees the completed recovery on bg_sid and does not re-dispatch! + getattr(runtime, "_steward_monitor_next_check", {}).clear() + assert pump_steward_monitors(runtime) == [] From 324f55ce78cfa041d5f3c9f6a861cd0a90d21533 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:30:35 +0800 Subject: [PATCH 2/2] fix(manager-context): ignore WAL -shm reader churn and cache clean stale/stopped portfolios Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../manager_context/turn_context_cache.py | 39 ++++-- tests/test_manager_turn_context_cache.py | 122 +++++++++++++++++- 2 files changed, 150 insertions(+), 11 deletions(-) diff --git a/loopx/capabilities/manager_context/turn_context_cache.py b/loopx/capabilities/manager_context/turn_context_cache.py index 9694519211..a1e4cb348c 100644 --- a/loopx/capabilities/manager_context/turn_context_cache.py +++ b/loopx/capabilities/manager_context/turn_context_cache.py @@ -133,20 +133,19 @@ def _sqlite_pragma_data_version(db_path: Path) -> int | None: def _sqlite_bundle_signature(db_path: Path) -> dict[str, Any] | None: wal_path = Path(f"{db_path}-wal") - shm_path = Path(f"{db_path}-shm") db_stat = _stat_signature(db_path) wal_stat = _stat_signature(wal_path) - shm_stat = _stat_signature(shm_path) - if db_stat is None and wal_stat is None and shm_stat is None: + if db_stat is None and wal_stat is None: return None + # SQLite WAL-index (-shm) mtime and reader-mark bytes mutate on read-only + # connections (including PRAGMA data_version); committed writes always advance + # either the main database file/header or the -wal file/header + data_version. return { "db": db_stat, "wal": wal_stat, - "shm": shm_stat, "data_version": _sqlite_pragma_data_version(db_path) if db_stat is not None else None, "db_hdr": _head_bytes_digest(db_path, 100) if db_stat is not None else None, "wal_hdr": _head_bytes_digest(wal_path, 64) if wal_stat is not None else None, - "shm_hdr": _head_bytes_digest(shm_path, 136) if shm_stat is not None else None, } @@ -454,6 +453,29 @@ def get_cached_manager_turn_context( return copy.deepcopy(entry.payload) +def _is_cacheable_coverage(context: Mapping[str, Any]) -> bool: + if context.get("status") == "unavailable" or context.get("warnings"): + return False + coverage = context.get("coverage") + if not isinstance(coverage, Mapping): + return False + if any( + int(coverage.get(field) or 0) != 0 + for field in ("conflicting", "unreadable", "partial", "invalid_registry_entries") + ): + return False + if coverage.get("complete") is True: + return True + discovered = int(coverage.get("discovered") or 0) + verified = int(coverage.get("verified") or 0) + stale = int(coverage.get("stale") or 0) + stopped_excluded = int(coverage.get("stopped_excluded") or 0) + if discovered > 0 and verified + stale + stopped_excluded == discovered: + return True + bound = context.get("bound_steward") + return discovered == 0 and isinstance(bound, Mapping) and bound.get("empty") is True + + def put_cached_manager_turn_context( fingerprint: str, context: Mapping[str, Any], @@ -461,11 +483,8 @@ def put_cached_manager_turn_context( max_age_seconds: float = DEFAULT_MAX_AGE_SECONDS, now_monotonic: float | None = None, ) -> bool: - """Cache a complete, warning-free context snapshot with deep-copy isolation.""" - if context.get("warnings"): - return False - coverage = context.get("coverage") - if not isinstance(coverage, Mapping) or coverage.get("complete") is not True: + """Cache a clean, warning-free context snapshot with deep-copy isolation.""" + if not _is_cacheable_coverage(context): return False snapshot = copy.deepcopy(dict(context)) now_mono = time.monotonic() if now_monotonic is None else now_monotonic diff --git a/tests/test_manager_turn_context_cache.py b/tests/test_manager_turn_context_cache.py index 43d859a962..f2767e0a82 100644 --- a/tests/test_manager_turn_context_cache.py +++ b/tests/test_manager_turn_context_cache.py @@ -347,7 +347,8 @@ def test_cache_bypasses_stopped_status_off_ssh_grants_env_off_and_incomplete_res ) assert len(calls) == 8 - # 5. Incomplete coverage or non-empty warnings are never stored. + # 5. Incomplete/unreadable coverage or non-empty warnings are never stored, + # while clean portfolios with idle (stale) or stopped_excluded Goals cache. assert put_cached_manager_turn_context( "sha256:warn", {"warnings": ["registry_unreadable"], "coverage": {"complete": True}}, @@ -356,8 +357,127 @@ def test_cache_bypasses_stopped_status_off_ssh_grants_env_off_and_incomplete_res "sha256:incomplete", {"warnings": [], "coverage": {"complete": False}}, ) is False + assert put_cached_manager_turn_context( + "sha256:unreadable_goal", + { + "warnings": [], + "coverage": { + "discovered": 2, + "verified": 1, + "stale": 1, + "stopped_excluded": 0, + "unreadable": 1, + "complete": False, + }, + }, + ) is False + assert put_cached_manager_turn_context( + "sha256:clean_with_stale_and_stopped", + { + "warnings": [], + "coverage": { + "discovered": 7, + "attempted": 6, + "stopped_excluded": 1, + "verified": 4, + "stale": 2, + "conflicting": 0, + "unreadable": 0, + "partial": 0, + "omitted": 1, + "invalid_registry_entries": 0, + "complete": False, + }, + }, + ) is True assert get_cached_manager_turn_context("sha256:warn") is None assert get_cached_manager_turn_context("sha256:incomplete") is None + assert get_cached_manager_turn_context("sha256:unreadable_goal") is None + assert get_cached_manager_turn_context("sha256:clean_with_stale_and_stopped") is not None + + +def test_wal_sqlite_shm_reader_churn_does_not_prevent_cache_population( + tmp_path: Path, monkeypatch, +) -> None: + registry_path, runtime_root, _ = _setup_registry_and_goal(tmp_path) + goal_sha = __import__("hashlib").sha256(b"alpha").hexdigest() + sqlite_dir = runtime_root / "authority" / "sqlite-v0" + sqlite_dir.mkdir(parents=True, exist_ok=True) + db_path = sqlite_dir / f"authority-{goal_sha}.sqlite" + + writer = sqlite3.connect(db_path) + writer.execute("PRAGMA journal_mode=WAL") + writer.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, val TEXT)") + writer.execute("INSERT INTO items (val) VALUES ('v1')") + writer.commit() + + shm_path = Path(f"{db_path}-shm") + calls: list[int] = [] + + def fake_portfolio_reading_wal(**kwargs): + calls.append(1) + # Simulate SQLite WAL reader connection touching -shm mtime/reader-marks during collection. + ro = sqlite3.connect(f"{db_path.resolve().as_uri()}?mode=ro", uri=True) + ro.execute("SELECT COUNT(*) FROM items").fetchone() + ro.close() + if shm_path.exists(): + import os + st = shm_path.stat() + os.utime(shm_path, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000)) + now_iso = datetime.now(timezone.utc).isoformat() + raw = Path(kwargs["registry_path"]).read_bytes() + return { + "ok": True, + "schema_version": "goal_portfolio_v0", + "snapshot_id": f"sha256:{len(calls):064x}", + "inventory_revision": "sha256:" + __import__("hashlib").sha256(raw).hexdigest(), + "inventory_semantic_revision": manager_ctx.registry_semantic_revision( + Path(kwargs["registry_path"]), raw, + ), + "collected_at": now_iso, + "collection_completed_at": now_iso, + "coverage": { + "discovered": 2, + "attempted": 1, + "stopped_excluded": 1, + "verified": 0, + "stale": 1, + "conflicting": 0, + "unreadable": 0, + "partial": 0, + "omitted": 1, + "invalid_registry_entries": 0, + "complete": False, + }, + "warnings": [], + "limitations": [], + "goals": [{"goal_id": "alpha", "quality": "stale", "progress": "idle", "deliveries": []}], + } + + monkeypatch.setattr(manager_ctx, "build_goal_portfolio", fake_portfolio_reading_wal) + session = _bound_steward_session(tmp_path) + + first = manager_ctx.collect_manager_turn_context( + registry_path, session, runtime_root, scope_resolver=lambda _s: ["alpha"], + include_details=False, + ) + second = manager_ctx.collect_manager_turn_context( + registry_path, session, runtime_root, scope_resolver=lambda _s: ["alpha"], + include_details=False, + ) + assert len(calls) == 1 + assert second["snapshot_id"] == first["snapshot_id"] + + # Real committed WAL write must still immediately invalidate the cache. + writer.execute("INSERT INTO items (val) VALUES ('v2')") + writer.commit() + third = manager_ctx.collect_manager_turn_context( + registry_path, session, runtime_root, scope_resolver=lambda _s: ["alpha"], + include_details=False, + ) + assert len(calls) == 2 + assert third["snapshot_id"] != first["snapshot_id"] + writer.close() def test_cache_ttl_lru_eviction_thread_safety_and_followthrough_fast_slow_lane_guidance(