diff --git a/loopx/capabilities/native_chat/external_conversations.py b/loopx/capabilities/native_chat/external_conversations.py index 6edf7085fd..e21170023d 100644 --- a/loopx/capabilities/native_chat/external_conversations.py +++ b/loopx/capabilities/native_chat/external_conversations.py @@ -43,6 +43,7 @@ QuotaBacklogObservationCache, _DeferredBacklogRequest, _RecoveryDiscoveryReads, + _iso_datetime, _preparation_image_identity, _project_source_request_digest, _project_user_message_hint, @@ -242,7 +243,7 @@ def _context_recovery_plan(self, row: dict[str, Any], *, "failure_notice_receipt_unknown": bool(failure_notice_receipt_unknown), "later_source_input_present": any(item.get("binding_id") == row["binding_id"] and item.get("source") == row["source"] and item.get("command") is None - and datetime.fromisoformat(item["created_at"]) > datetime.fromisoformat(row["created_at"]) + and _iso_datetime(item["created_at"]) > datetime.fromisoformat(row["created_at"]) for item in read_source_controls()) if turn.get("error_code") == "antigravity_step_error" else None, "native_input": anchors[0] if len(anchors) == 1 else None, **({"retained_result_review": retained_review} if retained_review is not None else {}), diff --git a/loopx/capabilities/native_chat/file_discovery.py b/loopx/capabilities/native_chat/file_discovery.py index 28d143bcb3..1893a8fd54 100644 --- a/loopx/capabilities/native_chat/file_discovery.py +++ b/loopx/capabilities/native_chat/file_discovery.py @@ -1,18 +1,40 @@ -"""File-backed Chat journal discovery and bounded reply image artifacts.""" +"""File-backed Chat journal discovery, fingerprints, and bounded reply image facade.""" from __future__ import annotations from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from copy import deepcopy from datetime import datetime -import base64 import hashlib import json from pathlib import Path -import re import sys -from urllib.parse import unquote from threading import Lock -from typing import Any +from typing import TypeVar, cast + +from .file_discovery_backlog import ( + QuotaBacklogObservationCache as QuotaBacklogObservationCache, + _DeferredBacklogRequest as _DeferredBacklogRequest, + _RecoveryDiscoveryReads as _RecoveryDiscoveryReads, + _iso_datetime as _iso_datetime, + _same_store_method as _same_store_method, + _set_bounded_cache as _set_bounded_cache, + _summarize_turn_events as _summarize_turn_events, + observe_quota_backlog_batch as observe_quota_backlog_batch, + observed_turn_event_summary as observed_turn_event_summary, + observed_turn_interrupt as observed_turn_interrupt, +) +from .file_discovery_media import ( + REPLY_IMAGE_NAME_PATTERN as REPLY_IMAGE_NAME_PATTERN, + _REPLY_IMAGE_SIGNATURES as _REPLY_IMAGE_SIGNATURES, + _REPLY_IMAGE_TYPES as _REPLY_IMAGE_TYPES, + _check_reply_image as _check_reply_image, + _preparation_image_identity as _preparation_image_identity, + capture_reply_image_plan as capture_reply_image_plan, + read_reply_image as read_reply_image, + reply_image_attachment as reply_image_attachment, + reply_image_directory as reply_image_directory, + reply_image_workspace as reply_image_workspace, +) def external_source_route_path(root: Path, binding_id: str, source_ref: str) -> Path: @@ -20,21 +42,28 @@ def external_source_route_path(root: Path, binding_id: str, source_ref: str) -> return root / "source-fences" / f"{binding_id}.{source_ref}.json" -def _ordinary_request_text_digest(row: dict[str, Any]) -> str | None: +def _ordinary_request_text_digest(row: Mapping[str, object]) -> str | None: """Match ordinary private text without retaining its body in discovery.""" message = row.get("message") source = row.get("source") status = row.get("status") - if (status not in ("accepted", "prepared") or row.get("command") is not None - or row.get("capture_origin") is not None or row.get("agent_target") is not None - or row.get("attachments") not in (None, []) or not isinstance(message, str) or not message - or not row.get("session_id") - or not isinstance(source, dict) or source.get("private_human_message") is not True): + if ( + status not in ("accepted", "prepared") + or row.get("command") is not None + or row.get("capture_origin") is not None + or row.get("agent_target") is not None + or row.get("attachments") not in (None, []) + or not isinstance(message, str) + or not message + or not row.get("session_id") + or not isinstance(source, dict) + or source.get("private_human_message") is not True + ): return None return hashlib.sha256(message.encode("utf-8", errors="surrogatepass")).hexdigest() -_RECOVERY_JOURNAL_FIELDS = ( +_RECOVERY_JOURNAL_FIELDS: tuple[str, ...] = ( "request_ref", "status", "delivery_verified", @@ -51,37 +80,44 @@ def _ordinary_request_text_digest(row: dict[str, Any]) -> str | None: ) -def recovery_journal_fields(_path: Path, row: dict[str, Any]) -> dict[str, Any] | None: +def recovery_journal_fields(_path: Path, row: Mapping[str, object]) -> dict[str, object] | None: """Keep only bounded recovery/commission metadata in the long-lived file cache.""" if not isinstance(row, dict) or "request_ref" not in row or "status" not in row: return None return {key: row[key] for key in _RECOVERY_JOURNAL_FIELDS if key in row} -def source_control_fields(path: Path, row: dict[str, Any]) -> dict[str, Any] | None: +def source_control_fields(path: Path, row: Mapping[str, object]) -> dict[str, object] | None: """Keep exact source controls and the metadata needed to prove admission.""" fields = ("binding_id", "source", "command", "created_at") # A tolerant reader can return an incomplete journal after a transient # failure. Do not cache that read as an unchanged-file observation. if not all(key in row for key in fields): return None - result = {key: row[key] for key in fields} + result: dict[str, object] = {key: row[key] for key in fields} digest = _ordinary_request_text_digest(row) if digest is None: return result if row["status"] == "accepted" and row.get("turn_id"): result.update(text_sha256=digest, session_id=row["session_id"]) - elif (row["status"] == "prepared" and row.get("turn_id") is None - and row.get("request_ref") == path.stem): - result.update(text_sha256=digest, session_id=row["session_id"], - prepared_client_turn_id=f"external-{path.stem}", origin=row.get("origin", "lark")) + elif ( + row["status"] == "prepared" + and row.get("turn_id") is None + and row.get("request_ref") == path.stem + ): + result.update( + text_sha256=digest, + session_id=row["session_id"], + prepared_client_turn_id=f"external-{path.stem}", + origin=row.get("origin", "lark"), + ) return result def later_equivalent_source_input( - row: dict[str, Any], - read_controls: Callable[[], list[dict[str, Any]]], - read_turn_for_client: Callable[[str, str], dict[str, Any] | None], + row: Mapping[str, object], + read_controls: Callable[[], Sequence[Mapping[str, object]]], + read_turn_for_client: Callable[[str, str], Mapping[str, object] | None], ) -> bool | None: """Check canonical acceptance in the same source and Session, even before dispatch.""" if row.get("status") != "accepted" or not row.get("turn_id"): @@ -89,22 +125,32 @@ def later_equivalent_source_input( digest = _ordinary_request_text_digest(row) if digest is None: return None - created = datetime.fromisoformat(row["created_at"]) + created: datetime = _iso_datetime(row["created_at"]) for item in read_controls(): - if (item.get("text_sha256") != digest or item["binding_id"] != row["binding_id"] - or item["source"] != row["source"] or item["session_id"] != row["session_id"] - or datetime.fromisoformat(item["created_at"]) <= created): + if ( + item.get("text_sha256") != digest + or item["binding_id"] != row["binding_id"] + or item["source"] != row["source"] + or item["session_id"] != row["session_id"] + or _iso_datetime(item["created_at"]) <= created + ): continue client_turn_id = item.get("prepared_client_turn_id") if client_turn_id is None: return True + if not isinstance(client_turn_id, str) or not isinstance(item["session_id"], str): + continue # Core owns the durable queue receipt even if the outer journal has # not finished its write. Never treat preparation alone as admission. turn = read_turn_for_client(item["session_id"], client_turn_id) - if (turn is not None and turn.get("origin") == item["origin"] - and turn.get("_queue_original_message", turn.get("message")) == row["message"] - and turn.get("attachments") in (None, []) - and turn.get("external_agent_target") is None and turn.get("collaboration_request") is None): + if ( + turn is not None + and turn.get("origin") == item["origin"] + and turn.get("_queue_original_message", turn.get("message")) == row["message"] + and turn.get("attachments") in (None, []) + and turn.get("external_agent_target") is None + and turn.get("collaboration_request") is None + ): return True return False @@ -132,288 +178,7 @@ def optional_file_fingerprint(path: Path) -> tuple[int, ...] | None: return None -def _set_bounded_cache(cache_map: dict[Any, Any], key: Any, value: Any, max_entries: int) -> None: - if key in cache_map: - del cache_map[key] - elif len(cache_map) >= max_entries: - del cache_map[next(iter(cache_map))] - cache_map[key] = value - - -class QuotaBacklogObservationCache: - """Revision-bound cache for read-only quota backlog health classification. - - Stores only pure boolean verdicts and Turn status labels keyed by file - fingerprints, Session status, and evaluator identity. Never retains Turn - bodies or request attachments. - """ - - def __init__(self, *, max_entries: int = 8192) -> None: - self._lock = Lock() - self._max_entries = max(1, max_entries) - self._base: dict[str, tuple[tuple[Any, ...], tuple[bool, str | None]]] = {} - self._stopped: dict[str, tuple[tuple[Any, ...], bool]] = {} - self._event_summaries: dict[tuple[str, str], tuple[tuple[int, ...], tuple[dict[str, Any] | None, bool, bool]]] = {} - - def get_base(self, request_ref: str, key: tuple[Any, ...]) -> tuple[bool, str | None] | None: - with self._lock: - entry = self._base.get(request_ref) - return entry[1] if entry is not None and entry[0] == key else None - - def has_base_prefix(self, request_ref: str, key_prefix: tuple[Any, ...]) -> bool: - with self._lock: - entry = self._base.get(request_ref) - return entry is not None and entry[0][:-1] == key_prefix - - def put_base(self, request_ref: str, key: tuple[Any, ...], pending: bool, turn_status: str | None) -> None: - with self._lock: - _set_bounded_cache(self._base, request_ref, (key, (pending, turn_status)), self._max_entries) - stopped = self._stopped.get(request_ref) - if stopped is not None and stopped[0] != key: - self._stopped.pop(request_ref, None) - - def get_stopped(self, request_ref: str, key: tuple[Any, ...]) -> bool | None: - with self._lock: - entry = self._stopped.get(request_ref) - return entry[1] if entry is not None and entry[0] == key else None - - def put_stopped(self, request_ref: str, key: tuple[Any, ...], pending: bool) -> None: - with self._lock: - _set_bounded_cache(self._stopped, request_ref, (key, pending), self._max_entries) - - def drop_request(self, request_ref: str) -> None: - with self._lock: - self._base.pop(request_ref, None) - self._stopped.pop(request_ref, None) - - @staticmethod - def build_key_prefix( - root: Path, store: Any, row: dict[str, Any], evaluator_id: int, - *, req_fp_override: tuple[int, ...] | None = None, - ) -> tuple[Any, Path | None, Path | None, tuple[int, ...] | None, tuple[int, ...] | None]: - try: - req_path = root / f"{row['request_ref']}.json" - turn_path = store._turn_path(row["session_id"], row["turn_id"]) - req_fp = req_fp_override if isinstance(req_fp_override, tuple) else optional_file_fingerprint(req_path) - turn_fp = optional_file_fingerprint(turn_path) - except (OSError, ValueError): - return None, None, None, None, None - if req_fp is None or turn_fp is None: - return None, req_path, turn_path, req_fp, turn_fp - prefix = (req_fp, turn_fp, row["session_id"], row["turn_id"], - row.get("status"), row.get("command"), evaluator_id) - return prefix, req_path, turn_path, req_fp, turn_fp - - def commit(self, request_ref: str, meta_entry: tuple[Any, ...], pending: bool, *, - turn_status: str | None = None, stopped: bool = False) -> None: - key, req_path, turn_path, req_fp, turn_fp = meta_entry - if key is None or req_path is None or turn_path is None: - return - if (optional_file_fingerprint(req_path), optional_file_fingerprint(turn_path)) != (req_fp, turn_fp): - self.drop_request(request_ref) - return - if stopped: - self.put_stopped(request_ref, key, pending) - else: - self.put_base(request_ref, key, pending, turn_status) - - def get_event_summary( - self, session_id: str, turn_id: str, events_fp: tuple[int, ...], - ) -> tuple[dict[str, Any] | None, bool, bool] | None: - with self._lock: - entry = self._event_summaries.get((session_id, turn_id)) - if entry is None or entry[0] != events_fp: - return None - anchor, steering, interrupted = entry[1] - return (deepcopy(anchor) if anchor is not None else None), steering, interrupted - - def put_event_summary( - self, session_id: str, turn_id: str, events_fp: tuple[int, ...], - summary: tuple[dict[str, Any] | None, bool, bool], - ) -> None: - anchor, steering, interrupted = summary - stored = (deepcopy(anchor) if anchor is not None else None), steering, interrupted - with self._lock: - _set_bounded_cache(self._event_summaries, (session_id, turn_id), (events_fp, stored), self._max_entries) - - def drop_event_summary(self, session_id: str, turn_id: str) -> None: - with self._lock: - self._event_summaries.pop((session_id, turn_id), None) - - def get_interrupt(self, session_id: str, turn_id: str, events_fp: tuple[int, ...]) -> bool | None: - summary = self.get_event_summary(session_id, turn_id, events_fp) - return summary[2] if summary is not None else None - - def put_interrupt(self, session_id: str, turn_id: str, events_fp: tuple[int, ...], observed: bool) -> None: - self.put_event_summary(session_id, turn_id, events_fp, (None, False, observed)) - - def drop_interrupt(self, session_id: str, turn_id: str) -> None: - self.drop_event_summary(session_id, turn_id) - - -def _summarize_turn_events(events: Sequence[dict[str, Any]]) -> tuple[dict[str, Any] | None, bool, bool]: - anchors = [ - item["payload"]["native_input"] - for item in events - if item.get("kind") == "turn.started" and item.get("payload", {}).get("native_input") - ] - single_anchor = deepcopy(anchors[0]) if len(anchors) == 1 else None - steering = any(e.get("kind") == "turn.steered" for e in events) - interrupted = any(e.get("kind") in {"turn.interrupt_requested", "turn.interrupted"} for e in events) - return single_anchor, steering, interrupted - - -def observed_turn_event_summary( - store: Any, - session_id: str, - turn_id: str, - cache_store: QuotaBacklogObservationCache | None, - *, - real_events: bool, -) -> tuple[dict[str, Any] | None, bool, bool]: - """Read compact Turn event summary with fingerprint/pending-buffer guard on real stores.""" - if not real_events or cache_store is None: - return _summarize_turn_events(store.events_after(session_id, turn_id, None)) - key = (session_id, turn_id) - try: - event_path = store._event_path(session_id, turn_id) - except ValueError: - return _summarize_turn_events(store.events_after(session_id, turn_id, None)) - flush_lock = store._event_flush_lock(key) - fp_before: tuple[int, ...] | None = None - if flush_lock.acquire(blocking=False): - try: - with store._event_lock: - has_pending = bool(store._event_pending.get(key)) - if not has_pending: - fp_before = optional_file_fingerprint(event_path) - if fp_before is not None: - cached = cache_store.get_event_summary(session_id, turn_id, fp_before) - if cached is not None: - return cached - finally: - flush_lock.release() - summary = _summarize_turn_events(store.events_after(session_id, turn_id, None)) - if fp_before is not None and flush_lock.acquire(blocking=False): - try: - with store._event_lock: - has_pending_after = bool(store._event_pending.get(key)) - fp_after = None if has_pending_after else optional_file_fingerprint(event_path) - if fp_after == fp_before: - cache_store.put_event_summary(session_id, turn_id, fp_after, summary) - else: - cache_store.drop_event_summary(session_id, turn_id) - finally: - flush_lock.release() - return summary - - -def observed_turn_interrupt( - store: Any, - session_id: str, - turn_id: str, - cache_store: QuotaBacklogObservationCache | None, - *, - real_events: bool, -) -> bool: - """Check Turn interrupt events with fingerprint/pending-buffer guard on real stores.""" - return observed_turn_event_summary( - store, session_id, turn_id, cache_store, real_events=real_events, - )[2] - - -def _same_store_method(store: Any, name: str, expected_cls: type[Any]) -> bool: - return isinstance(store, expected_cls) and getattr(getattr(store, name, None), "__func__", None) is getattr(expected_cls, name) - - -def observe_quota_backlog_batch( - *, - root: Path, - store: Any, - rows: Sequence[dict[str, Any]], - build_inputs: Callable[[dict[str, Any]], dict[str, Any]], - eval_flags: Callable[[Sequence[dict[str, Any]]], list[bool]], - stop_controls: Callable[[], tuple[tuple[Any, Any, datetime], ...]], - evaluator_id: int, - cache_store: QuotaBacklogObservationCache | None, -) -> list[bool]: - """Evaluate backlog pending flags with optional revision-bound caching.""" - from ...chat_store import ChatSessionStore - - real_load_turn = cache_store is not None and _same_store_method(store, "load_turn", ChatSessionStore) - real_events = cache_store is not None and _same_store_method(store, "events_after", ChatSessionStore) - flags: list[bool] = [False] * len(rows) - turn_statuses: list[str | None] = [None] * len(rows) - params: list[dict[str, Any] | None] = [None] * len(rows) - meta: list[tuple[Any, ...]] = [(None, None, None, None, None)] * len(rows) - for index, row in enumerate(rows): - entry = (cache_store.build_key_prefix(root, store, row, evaluator_id, req_fp_override=getattr(row, "req_fp", None)) - if real_load_turn and cache_store is not None else (None, None, None, None, None)) - meta[index] = entry - if entry[0] is not None and cache_store is not None and cache_store.has_base_prefix(row["request_ref"], entry[0]): - continue - params[index] = build_inputs(row) - load_session = store.load_session - sessions: dict[str, dict[str, Any] | None] = {} - for session_id in dict.fromkeys(row["session_id"] for row in rows): - # A transient read failure must not mask a closed Session. - session = load_session(session_id) or load_session(session_id) - sessions[session_id] = ( - {key: session[key] for key in ("session_id", "status") if key in session} - if session is not None else None - ) - misses: list[tuple[int, dict[str, Any]]] = [] - for index, row in enumerate(rows): - session_row = sessions[row["session_id"]] - prefix, req_path, turn_path, req_fp, turn_fp = meta[index] - if prefix is not None and cache_store is not None: - session_status = session_row.get("status") if session_row is not None else None - full_key = (*prefix, session_status) - meta[index] = (full_key, req_path, turn_path, req_fp, turn_fp) - cached = cache_store.get_base(row["request_ref"], full_key) - if cached is not None: - flags[index], turn_statuses[index] = cached - continue - values = params[index] if params[index] is not None else build_inputs(row) - values["current_session"] = session_row - params[index] = values - misses.append((index, values)) - if misses: - for (index, values), pending in zip(misses, eval_flags([v for _, v in misses]), strict=True): - turn_dict = values["pending_observation"]["turn"] - turn_status = turn_dict.get("status") if isinstance(turn_dict, dict) else None - flags[index], turn_statuses[index] = pending, turn_status - if cache_store is not None: - cache_store.commit(rows[index]["request_ref"], meta[index], pending, turn_status=turn_status) - stopped_misses: list[tuple[int, dict[str, Any]]] = [] - for index, (row, pending) in enumerate(zip(rows, flags, strict=True)): - if not pending: - continue - if not observed_turn_interrupt(store, row["session_id"], row["turn_id"], cache_store, real_events=real_events): - if turn_statuses[index] not in {"failed", "completed"}: - continue - row_created = datetime.fromisoformat(row["created_at"]) - if not any(b == row["binding_id"] and s == row["source"] and c >= row_created - for b, s, c in stop_controls()): - continue - cache_key = meta[index][0] - if cache_store is not None and cache_key is not None: - cached_stop = cache_store.get_stopped(row["request_ref"], cache_key) - if cached_stop is not None: - flags[index] = cached_stop - continue - values = params[index] - if values is None: - values = build_inputs(row) - values["current_session"] = sessions[row["session_id"]] - values["pending_observation"]["stop_observed"] = True - stopped_misses.append((index, values)) - if stopped_misses: - for (index, _), pending in zip(stopped_misses, eval_flags([v for _, v in stopped_misses]), strict=True): - flags[index] = pending - if cache_store is not None: - cache_store.commit(rows[index]["request_ref"], meta[index], pending, stopped=True) - return flags +_RowDictT = TypeVar("_RowDictT", bound=dict[str, object]) class FileChatDiscovery: @@ -426,18 +191,18 @@ class FileChatDiscovery: def __init__(self) -> None: self._lock = Lock() - self._directories: dict[Path, dict[Path, tuple[tuple[int, ...], dict[str, Any]]]] = {} + self._directories: dict[Path, dict[Path, tuple[tuple[int, ...], dict[str, object]]]] = {} def rows_with_fingerprints( self, directory: Path, paths: Iterable[Path], *, - read: Callable[[Path], dict[str, Any]], - project: Callable[[Path, dict[str, Any]], dict[str, Any] | None], + read: Callable[[Path], _RowDictT], + project: Callable[[Path, _RowDictT], _RowDictT | None], known_fingerprints: Mapping[Path, tuple[int, ...]] | None = None, - ) -> Iterator[tuple[Path, dict[str, Any], tuple[int, ...] | None]]: - seen = set() + ) -> Iterator[tuple[Path, _RowDictT, tuple[int, ...] | None]]: + seen: set[Path] = set() with self._lock: entries = self._directories.setdefault(directory, {}) for path in paths: @@ -454,7 +219,7 @@ def rows_with_fingerprints( entries.pop(path, None) saved = None if saved is not None: - yield path, deepcopy(saved[1]), before + yield path, cast(_RowDictT, deepcopy(saved[1])), before continue # Preserve the owning reader's missing/unreadable/strict behavior. value = read(path) @@ -472,134 +237,19 @@ def rows_with_fingerprints( for path in entries.keys() - seen: del entries[path] - def rows(self, directory: Path, paths: Iterable[Path], *, - read: Callable[[Path], dict[str, Any]], - project: Callable[[Path, dict[str, Any]], dict[str, Any] | None], - ) -> Iterator[tuple[Path, dict[str, Any]]]: - for path, view, _ in self.rows_with_fingerprints(directory, paths, read=read, project=project): - yield path, view - - -_REPLY_IMAGE_TYPES = { - ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", - ".gif": "image/gif", ".webp": "image/webp", -} -_REPLY_IMAGE_SIGNATURES = {"image/png": b"\x89PNG\r\n\x1a\n", "image/jpeg": b"\xff\xd8\xff", "image/gif": b"GIF8"} -REPLY_IMAGE_NAME_PATTERN = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9_.-]{0,119}") - - -def reply_image_directory(turn_id: str) -> Path: - """Return the sole workspace output directory for this exact Core Turn.""" - if not re.fullmatch(r"[a-f0-9]{32}", turn_id): - raise ValueError("invalid reply image Turn") - return Path(".local/loopx-reply-images") / turn_id - - -def reply_image_workspace(session: dict[str, Any], turn: dict[str, Any]) -> Path | None: - """Local image output belongs to an ordinary, bound-owner Lark project Turn.""" - context = session.get("project_context") or {} - if (turn.get("origin") != "lark" or session.get("session_mode") != "managed_runtime" - or session.get("agent_id") != "codex" or context.get("audience") != "bound_owner" - or context.get("grant") != "workspace_write" or not context.get("workspace_path") - or session.get("steward_context")): - return None - return Path(context["workspace_path"]).resolve() - - -def _check_reply_image(data: bytes, mime: str) -> None: - from ...chat.attachments import CHAT_IMAGE_MAX_BYTES - - if not data or len(data) > CHAT_IMAGE_MAX_BYTES: - raise ValueError("reply image is empty or exceeds its size bound") - if not ((mime in _REPLY_IMAGE_SIGNATURES and data.startswith(_REPLY_IMAGE_SIGNATURES[mime])) - or (mime == "image/webp" and data[:4] == b"RIFF" and data[8:12] == b"WEBP")): - raise ValueError("unsupported reply image bytes") - - -def reply_image_attachment(data: bytes, mime: str, index: int) -> dict[str, Any]: - _check_reply_image(data, mime) - return {"id": f"reply-image-{index}", "name": f"original-{index}.{mime.split('/')[1]}", - "mime_type": mime, "size": len(data), - "data_url": f"data:{mime};base64," + base64.b64encode(data).decode("ascii")} - - -def read_reply_image(workspace: Path, turn_id: str, name: str) -> tuple[str, bytes]: - from ...control_plane.collaboration.result_files import _workspace_file - - if not REPLY_IMAGE_NAME_PATTERN.fullmatch(name): - raise ValueError("invalid reply image name") - mime = _REPLY_IMAGE_TYPES.get(Path(name).suffix.lower()) - if mime is None: - raise ValueError("unsupported reply image type") - ref = reply_image_directory(turn_id) / name - data = _workspace_file(workspace, ref) - _check_reply_image(data, mime) - return mime, data - - -def capture_reply_image_plan(workspace: Path, turn_id: str, targets: list[str]) -> list[str | dict[str, Any] | None]: - """Pin exact local bytes without keeping host paths in Chat responses.""" - from ...chat.attachments import CHAT_IMAGE_MAX_COUNT, CHAT_IMAGE_MAX_TOTAL_BYTES - - if all(target.startswith("https://") for target in targets): - return [] # The original remote-image path remains authoritative. - if len(targets) > CHAT_IMAGE_MAX_COUNT: - return [None] - output_dir = workspace / reply_image_directory(turn_id) - result: list[str | dict[str, Any] | None] = [] - total = 0 - for target in targets: - if target.startswith("https://"): - result.append(target) - continue - try: - path = Path(unquote(target)) - if path.parent != output_dir or ".." in path.parts: - raise ValueError("reply image is outside the current Turn's output directory") - _, data = read_reply_image(workspace, turn_id, path.name) - total += len(data) - if total > CHAT_IMAGE_MAX_TOTAL_BYTES: - raise ValueError("reply images exceed their aggregate size bound") - result.append({"name": path.name, "sha256": hashlib.sha256(data).hexdigest()}) - except (OSError, ValueError): - result.append(None) - return result - - -class _DeferredBacklogRequest(dict[str, Any]): - """Bounded backlog request view carrying its observed file fingerprint.""" - - __slots__ = ("req_fp", "needs_full_read") - - def __init__( + def rows( self, - data: Mapping[str, Any], + directory: Path, + paths: Iterable[Path], *, - req_fp: tuple[int, ...] | None, - needs_full_read: bool, - ) -> None: - super().__init__(data) - self.req_fp = req_fp - self.needs_full_read = needs_full_read - - -def _preparation_image_identity(value: Any) -> dict[str, Any] | None: - """Fingerprint already normalized Core images without exporting their bytes.""" - from ...chat.attachments import normalize_chat_image_attachments - - if not isinstance(value, list) or not value: - return None - try: - images = normalize_chat_image_attachments(value) - if images != value: - return None - encoded = json.dumps(images, sort_keys=True, separators=(",", ":")).encode() - return {"count": len(images), "sha256": hashlib.sha256(encoded).hexdigest()} - except (ValueError, TypeError, OverflowError): - return None + read: Callable[[Path], _RowDictT], + project: Callable[[Path, _RowDictT], _RowDictT | None], + ) -> Iterator[tuple[Path, _RowDictT]]: + for path, view, _ in self.rows_with_fingerprints(directory, paths, read=read, project=project): + yield path, view -def _project_source_request_digest(_path: Path, item: dict[str, Any]) -> dict[str, Any]: +def _project_source_request_digest(_path: Path, item: Mapping[str, object]) -> dict[str, object]: canonical = json.dumps(item, sort_keys=True, ensure_ascii=False, separators=(",", ":")) return { "request_ref": item.get("request_ref"), @@ -609,48 +259,9 @@ def _project_source_request_digest(_path: Path, item: dict[str, Any]) -> dict[st } -def _project_user_message_hint(message: Mapping[str, Any]) -> dict[str, Any]: +def _project_user_message_hint(message: Mapping[str, object]) -> dict[str, object]: return { key: message[key] for key in ("role", "turn_id", "text", "origin", "created_at") if key in message } - - -class _RecoveryDiscoveryReads: - """Lazy facts for one queue-discovery pass, never recovery admission. - - Historical requests share Session history. Retain queue/control/history - hints, never provider identity or a recovery decision. A new - pass builds new observations; normal admission never receives this object. - """ - - def __init__(self, core: Any) -> None: - self.core = core - self.queues: dict[str, bool] = {} - self.histories: dict[str, list[dict[str, Any]]] = {} - self.message_indexes: dict[str, dict[str, list[dict[str, Any]]]] = {} - self.controls: list[dict[str, Any]] | None = None - - def queued(self, session_id: str) -> bool: - if session_id not in self.queues: - self.queues[session_id] = bool(self.core.controller.store.queued_turns(session_id)) - return self.queues[session_id] - - def user_messages(self, session_id: str) -> list[dict[str, Any]]: - if session_id not in self.histories: - self.histories[session_id] = list(self.core._cached_user_messages(session_id)) - return self.histories[session_id] - - def source_controls(self) -> list[dict[str, Any]]: - if self.controls is None: - self.controls = self.core.source_controls() - return self.controls - - def matching_user_messages(self, session_id: str, text: str) -> list[dict[str, Any]]: - if session_id not in self.message_indexes: - index: dict[str, list[dict[str, Any]]] = {} - for row in self.user_messages(session_id): - index.setdefault(row.get("text", ""), []).append(row) - self.message_indexes[session_id] = index - return self.message_indexes[session_id].get(text, []) diff --git a/loopx/capabilities/native_chat/file_discovery_backlog.py b/loopx/capabilities/native_chat/file_discovery_backlog.py new file mode 100644 index 0000000000..dc0673c5fa --- /dev/null +++ b/loopx/capabilities/native_chat/file_discovery_backlog.py @@ -0,0 +1,510 @@ +"""Revision-bound quota backlog observation cache, turn-event summaries, and recovery reads.""" +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from contextlib import AbstractContextManager +from copy import deepcopy +from datetime import datetime +from pathlib import Path +from threading import Lock +from typing import Literal, Protocol, TypeVar, overload, runtime_checkable + + +_CacheKeyT = TypeVar("_CacheKeyT") +_CacheValT = TypeVar("_CacheValT") +_RowT = TypeVar("_RowT", bound=Mapping[str, object]) + +_MetaKey = tuple[object, ...] +_ObservationMetaEntry = tuple[ + _MetaKey | None, + Path | None, + Path | None, + tuple[int, ...] | None, + tuple[int, ...] | None, +] +_EventSummary = tuple[dict[str, object] | None, bool, bool] + + +@runtime_checkable +class _TurnPathStoreProtocol(Protocol): + def _turn_path(self, session_id: str, turn_id: str) -> Path: ... + + +class _EventStoreProtocol(Protocol): + def events_after(self, session_id: str, turn_id: str, event_id: str | None) -> Sequence[Mapping[str, object]]: ... + + +class _FlushLockProtocol(Protocol): + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + + +@runtime_checkable +class _BufferedEventStoreProtocol(_EventStoreProtocol, Protocol): + _event_lock: AbstractContextManager[object] + _event_pending: Mapping[tuple[str, str], object] + + def _event_path(self, session_id: str, turn_id: str) -> Path: ... + def _event_flush_lock(self, key: tuple[str, str]) -> _FlushLockProtocol: ... + + +class _BacklogStoreProtocol(_EventStoreProtocol, Protocol): + def load_session(self, session_id: str) -> Mapping[str, object] | None: ... + + +class _RecoveryStoreProtocol(Protocol): + def queued_turns(self, session_id: str) -> Sequence[object]: ... + + +class _RecoveryControllerProtocol(Protocol): + @property + def store(self) -> _RecoveryStoreProtocol: ... + + +class _RecoveryCoreProtocol(Protocol): + @property + def controller(self) -> _RecoveryControllerProtocol: ... + def _cached_user_messages(self, session_id: str) -> Sequence[Mapping[str, object]]: ... + def source_controls(self) -> Sequence[Mapping[str, object]]: ... + + +class _DiscoveryRowDict(dict[str, object]): + """Read-only dict view carrying known ISO-timestamp key types.""" + + @overload + def __getitem__(self, key: Literal["created_at"]) -> str: ... + + @overload + def __getitem__(self, key: str) -> object: ... + + def __getitem__(self, key: str) -> object: + return super().__getitem__(key) + + +def _optional_fp(path: Path) -> tuple[int, ...] | None: + # Look up through the facade module so platform/monkeypatch test overrides apply uniformly. + from . import file_discovery + + return file_discovery.optional_file_fingerprint(path) + + +def _require_str(mapping: Mapping[str, object], key: str) -> str: + value = mapping[key] + if not isinstance(value, str): + raise TypeError(f"{key} must be a str") + return value + + +def _iso_datetime(value: object) -> datetime: + if not isinstance(value, str): + raise TypeError(f"fromisoformat: argument must be str, not {type(value).__name__}") + return datetime.fromisoformat(value) + + +def _set_bounded_cache( + cache_map: dict[_CacheKeyT, _CacheValT], + key: _CacheKeyT, + value: _CacheValT, + max_entries: int, +) -> None: + if key in cache_map: + del cache_map[key] + elif len(cache_map) >= max_entries: + del cache_map[next(iter(cache_map))] + cache_map[key] = value + + +class QuotaBacklogObservationCache: + """Revision-bound cache for read-only quota backlog health classification. + + Stores only pure boolean verdicts and Turn status labels keyed by file + fingerprints, Session status, and evaluator identity. Never retains Turn + bodies or request attachments. + """ + + def __init__(self, *, max_entries: int = 8192) -> None: + self._lock = Lock() + self._max_entries = max(1, max_entries) + self._base: dict[str, tuple[_MetaKey, tuple[bool, str | None]]] = {} + self._stopped: dict[str, tuple[_MetaKey, bool]] = {} + self._event_summaries: dict[tuple[str, str], tuple[tuple[int, ...], _EventSummary]] = {} + + def get_base(self, request_ref: str, key: _MetaKey) -> tuple[bool, str | None] | None: + with self._lock: + entry = self._base.get(request_ref) + return entry[1] if entry is not None and entry[0] == key else None + + def has_base_prefix(self, request_ref: str, key_prefix: _MetaKey) -> bool: + with self._lock: + entry = self._base.get(request_ref) + return entry is not None and entry[0][:-1] == key_prefix + + def put_base(self, request_ref: str, key: _MetaKey, pending: bool, turn_status: str | None) -> None: + with self._lock: + _set_bounded_cache(self._base, request_ref, (key, (pending, turn_status)), self._max_entries) + stopped = self._stopped.get(request_ref) + if stopped is not None and stopped[0] != key: + self._stopped.pop(request_ref, None) + + def get_stopped(self, request_ref: str, key: _MetaKey) -> bool | None: + with self._lock: + entry = self._stopped.get(request_ref) + return entry[1] if entry is not None and entry[0] == key else None + + def put_stopped(self, request_ref: str, key: _MetaKey, pending: bool) -> None: + with self._lock: + _set_bounded_cache(self._stopped, request_ref, (key, pending), self._max_entries) + + def drop_request(self, request_ref: str) -> None: + with self._lock: + self._base.pop(request_ref, None) + self._stopped.pop(request_ref, None) + + @staticmethod + def build_key_prefix( + root: Path, + store: _TurnPathStoreProtocol, + row: Mapping[str, object], + evaluator_id: int, + *, + req_fp_override: tuple[int, ...] | None = None, + ) -> _ObservationMetaEntry: + try: + request_ref = _require_str(row, "request_ref") + session_id = _require_str(row, "session_id") + turn_id = _require_str(row, "turn_id") + req_path = root / f"{request_ref}.json" + turn_path = store._turn_path(session_id, turn_id) + req_fp = req_fp_override if isinstance(req_fp_override, tuple) else _optional_fp(req_path) + turn_fp = _optional_fp(turn_path) + except (OSError, TypeError, ValueError): + return None, None, None, None, None + if req_fp is None or turn_fp is None: + return None, req_path, turn_path, req_fp, turn_fp + prefix: _MetaKey = ( + req_fp, + turn_fp, + session_id, + turn_id, + row.get("status"), + row.get("command"), + evaluator_id, + ) + return prefix, req_path, turn_path, req_fp, turn_fp + + def commit( + self, + request_ref: str, + meta_entry: _ObservationMetaEntry, + pending: bool, + *, + turn_status: str | None = None, + stopped: bool = False, + ) -> None: + key, req_path, turn_path, req_fp, turn_fp = meta_entry + if key is None or req_path is None or turn_path is None: + return + if (_optional_fp(req_path), _optional_fp(turn_path)) != (req_fp, turn_fp): + self.drop_request(request_ref) + return + if stopped: + self.put_stopped(request_ref, key, pending) + else: + self.put_base(request_ref, key, pending, turn_status) + + def get_event_summary( + self, session_id: str, turn_id: str, events_fp: tuple[int, ...], + ) -> _EventSummary | None: + with self._lock: + entry = self._event_summaries.get((session_id, turn_id)) + if entry is None or entry[0] != events_fp: + return None + anchor, steering, interrupted = entry[1] + return (deepcopy(anchor) if anchor is not None else None), steering, interrupted + + def put_event_summary( + self, session_id: str, turn_id: str, events_fp: tuple[int, ...], summary: _EventSummary, + ) -> None: + anchor, steering, interrupted = summary + stored: _EventSummary = (deepcopy(anchor) if anchor is not None else None), steering, interrupted + with self._lock: + _set_bounded_cache(self._event_summaries, (session_id, turn_id), (events_fp, stored), self._max_entries) + + def drop_event_summary(self, session_id: str, turn_id: str) -> None: + with self._lock: + self._event_summaries.pop((session_id, turn_id), None) + + def get_interrupt(self, session_id: str, turn_id: str, events_fp: tuple[int, ...]) -> bool | None: + summary = self.get_event_summary(session_id, turn_id, events_fp) + return summary[2] if summary is not None else None + + def put_interrupt(self, session_id: str, turn_id: str, events_fp: tuple[int, ...], observed: bool) -> None: + self.put_event_summary(session_id, turn_id, events_fp, (None, False, observed)) + + def drop_interrupt(self, session_id: str, turn_id: str) -> None: + self.drop_event_summary(session_id, turn_id) + + +def _summarize_turn_events(events: Sequence[Mapping[str, object]]) -> _EventSummary: + anchor: dict[str, object] | None = None + anchor_count = 0 + steering = False + interrupted = False + for item in events: + if not isinstance(item, Mapping): + anchor_count += 1 + anchor = None + continue + kind = item.get("kind") + if kind == "turn.started": + payload = item.get("payload", {}) + if isinstance(payload, Mapping): + native_input = payload.get("native_input") + if native_input: + anchor_count += 1 + anchor = native_input if anchor_count == 1 and isinstance(native_input, dict) else None + else: + anchor_count += 1 + anchor = None + elif kind == "turn.steered": + steering = True + elif kind in {"turn.interrupt_requested", "turn.interrupted"}: + interrupted = True + single_anchor = deepcopy(anchor) if anchor_count == 1 and anchor is not None else None + return single_anchor, steering, interrupted + + +def observed_turn_event_summary( + store: _EventStoreProtocol, + session_id: str, + turn_id: str, + cache_store: QuotaBacklogObservationCache | None, + *, + real_events: bool, +) -> _EventSummary: + """Read compact Turn event summary with fingerprint/pending-buffer guard on real stores.""" + if not real_events or cache_store is None or not isinstance(store, _BufferedEventStoreProtocol): + return _summarize_turn_events(store.events_after(session_id, turn_id, None)) + key = (session_id, turn_id) + try: + event_path = store._event_path(session_id, turn_id) + except ValueError: + return _summarize_turn_events(store.events_after(session_id, turn_id, None)) + flush_lock = store._event_flush_lock(key) + fp_before: tuple[int, ...] | None = None + if flush_lock.acquire(blocking=False): + try: + with store._event_lock: + has_pending = bool(store._event_pending.get(key)) + if not has_pending: + fp_before = _optional_fp(event_path) + if fp_before is not None: + cached = cache_store.get_event_summary(session_id, turn_id, fp_before) + if cached is not None: + return cached + finally: + flush_lock.release() + summary = _summarize_turn_events(store.events_after(session_id, turn_id, None)) + if fp_before is not None and flush_lock.acquire(blocking=False): + try: + with store._event_lock: + has_pending_after = bool(store._event_pending.get(key)) + fp_after = None if has_pending_after else _optional_fp(event_path) + if fp_after is not None and fp_after == fp_before: + cache_store.put_event_summary(session_id, turn_id, fp_after, summary) + else: + cache_store.drop_event_summary(session_id, turn_id) + finally: + flush_lock.release() + return summary + + +def observed_turn_interrupt( + store: _EventStoreProtocol, + session_id: str, + turn_id: str, + cache_store: QuotaBacklogObservationCache | None, + *, + real_events: bool, +) -> bool: + """Check Turn interrupt events with fingerprint/pending-buffer guard on real stores.""" + return observed_turn_event_summary( + store, session_id, turn_id, cache_store, real_events=real_events, + )[2] + + +def _same_store_method(store: object, name: str, expected_cls: type[object]) -> bool: + return ( + isinstance(store, expected_cls) + and getattr(getattr(store, name, None), "__func__", None) is getattr(expected_cls, name) + ) + + +def observe_quota_backlog_batch( + *, + root: Path, + store: _BacklogStoreProtocol, + rows: Sequence[_RowT], + build_inputs: Callable[[_RowT], dict[str, object]], + eval_flags: Callable[[Sequence[dict[str, object]]], list[bool]], + stop_controls: Callable[[], tuple[tuple[object, object, datetime], ...]], + evaluator_id: int, + cache_store: QuotaBacklogObservationCache | None, +) -> list[bool]: + """Evaluate backlog pending flags with optional revision-bound caching.""" + from ...chat_store import ChatSessionStore + + real_load_turn = ( + cache_store is not None + and _same_store_method(store, "load_turn", ChatSessionStore) + and isinstance(store, _TurnPathStoreProtocol) + ) + real_events = cache_store is not None and _same_store_method(store, "events_after", ChatSessionStore) + flags: list[bool] = [False] * len(rows) + turn_statuses: list[str | None] = [None] * len(rows) + params: list[dict[str, object] | None] = [None] * len(rows) + meta: list[_ObservationMetaEntry] = [(None, None, None, None, None)] * len(rows) + for index, row in enumerate(rows): + if real_load_turn and cache_store is not None and isinstance(store, _TurnPathStoreProtocol): + req_fp_raw = row.req_fp if isinstance(row, _DeferredBacklogRequest) else getattr(row, "req_fp", None) + req_fp_override = req_fp_raw if isinstance(req_fp_raw, tuple) else None + entry = cache_store.build_key_prefix(root, store, row, evaluator_id, req_fp_override=req_fp_override) + else: + entry = (None, None, None, None, None) + meta[index] = entry + if entry[0] is not None and cache_store is not None and cache_store.has_base_prefix(_require_str(row, "request_ref"), entry[0]): + continue + params[index] = build_inputs(row) + load_session = store.load_session + sessions: dict[str, dict[str, object] | None] = {} + for session_id in dict.fromkeys(_require_str(row, "session_id") for row in rows): + # A transient read failure must not mask a closed Session. + session = load_session(session_id) or load_session(session_id) + sessions[session_id] = ( + {key: session[key] for key in ("session_id", "status") if key in session} + if session is not None + else None + ) + misses: list[tuple[int, dict[str, object]]] = [] + for index, row in enumerate(rows): + session_row = sessions[_require_str(row, "session_id")] + prefix, req_path, turn_path, req_fp, turn_fp = meta[index] + if prefix is not None and cache_store is not None: + session_status = session_row.get("status") if session_row is not None else None + full_key: _MetaKey = (*prefix, session_status) + meta[index] = (full_key, req_path, turn_path, req_fp, turn_fp) + cached = cache_store.get_base(_require_str(row, "request_ref"), full_key) + if cached is not None: + flags[index], turn_statuses[index] = cached + continue + existing_params = params[index] + miss_values = existing_params if existing_params is not None else build_inputs(row) + miss_values["current_session"] = session_row + params[index] = miss_values + misses.append((index, miss_values)) + if misses: + for (index, values), pending in zip(misses, eval_flags([v for _, v in misses]), strict=True): + pending_obs = values["pending_observation"] + turn_dict = pending_obs.get("turn") if isinstance(pending_obs, Mapping) else None + turn_status_raw = turn_dict.get("status") if isinstance(turn_dict, Mapping) else None + turn_status = turn_status_raw if isinstance(turn_status_raw, str) else None + flags[index], turn_statuses[index] = pending, turn_status + if cache_store is not None: + cache_store.commit(_require_str(rows[index], "request_ref"), meta[index], pending, turn_status=turn_status) + stopped_misses: list[tuple[int, dict[str, object]]] = [] + controls_cache: tuple[tuple[object, object, datetime], ...] | None = None + for index, (row, pending) in enumerate(zip(rows, flags, strict=True)): + if not pending: + continue + session_id = _require_str(row, "session_id") + turn_id = _require_str(row, "turn_id") + if not observed_turn_interrupt(store, session_id, turn_id, cache_store, real_events=real_events): + if turn_statuses[index] not in {"failed", "completed"}: + continue + row_created = _iso_datetime(row["created_at"]) + if controls_cache is None: + controls_cache = stop_controls() + if not any( + b == row["binding_id"] and s == row["source"] and c >= row_created + for b, s, c in controls_cache + ): + continue + cache_key = meta[index][0] + if cache_store is not None and cache_key is not None: + cached_stop = cache_store.get_stopped(_require_str(row, "request_ref"), cache_key) + if cached_stop is not None: + flags[index] = cached_stop + continue + stop_values = params[index] + if stop_values is None: + stop_values = build_inputs(row) + stop_values["current_session"] = sessions[session_id] + pending_obs = stop_values["pending_observation"] + if not isinstance(pending_obs, dict): + raise TypeError("pending_observation must be a dict") + pending_obs["stop_observed"] = True + stopped_misses.append((index, stop_values)) + if stopped_misses: + for (index, _), pending in zip(stopped_misses, eval_flags([v for _, v in stopped_misses]), strict=True): + flags[index] = pending + if cache_store is not None: + cache_store.commit(_require_str(rows[index], "request_ref"), meta[index], pending, stopped=True) + return flags + + +class _DeferredBacklogRequest(dict[str, object]): + """Bounded backlog request view carrying its observed file fingerprint.""" + + __slots__ = ("req_fp", "needs_full_read") + + def __init__( + self, + data: Mapping[str, object], + *, + req_fp: tuple[int, ...] | None, + needs_full_read: bool, + ) -> None: + super().__init__(data) + self.req_fp = req_fp + self.needs_full_read = needs_full_read + + +class _RecoveryDiscoveryReads: + """Lazy facts for one queue-discovery pass, never recovery admission. + + Historical requests share Session history. Retain queue/control/history + hints, never provider identity or a recovery decision. A new + pass builds new observations; normal admission never receives this object. + """ + + def __init__(self, core: _RecoveryCoreProtocol) -> None: + self.core = core + self.queues: dict[str, bool] = {} + self.histories: dict[str, list[_DiscoveryRowDict]] = {} + self.message_indexes: dict[str, dict[str, list[_DiscoveryRowDict]]] = {} + self.controls: list[dict[str, object]] | None = None + + def queued(self, session_id: str) -> bool: + if session_id not in self.queues: + self.queues[session_id] = bool(self.core.controller.store.queued_turns(session_id)) + return self.queues[session_id] + + def user_messages(self, session_id: str) -> list[_DiscoveryRowDict]: + if session_id not in self.histories: + self.histories[session_id] = [_DiscoveryRowDict(row) for row in self.core._cached_user_messages(session_id)] + return self.histories[session_id] + + def source_controls(self) -> list[dict[str, object]]: + if self.controls is None: + self.controls = [dict(row) for row in self.core.source_controls()] + return self.controls + + def matching_user_messages(self, session_id: str, text: str) -> list[_DiscoveryRowDict]: + if session_id not in self.message_indexes: + index: dict[str, list[_DiscoveryRowDict]] = {} + for row in self.user_messages(session_id): + msg_text = row.get("text", "") + key = msg_text if isinstance(msg_text, str) else "" + index.setdefault(key, []).append(row) + self.message_indexes[session_id] = index + return self.message_indexes[session_id].get(text, []) diff --git a/loopx/capabilities/native_chat/file_discovery_media.py b/loopx/capabilities/native_chat/file_discovery_media.py new file mode 100644 index 0000000000..f1d25bd04c --- /dev/null +++ b/loopx/capabilities/native_chat/file_discovery_media.py @@ -0,0 +1,141 @@ +"""Workspace reply-image verification, attachment encoding, and capture plans.""" +from __future__ import annotations + +import base64 +from collections.abc import Mapping, Sequence +import hashlib +import json +from pathlib import Path +import re +from urllib.parse import unquote + + +_REPLY_IMAGE_TYPES: dict[str, str] = { + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".webp": "image/webp", +} +_REPLY_IMAGE_SIGNATURES: dict[str, bytes] = { + "image/png": b"\x89PNG\r\n\x1a\n", + "image/jpeg": b"\xff\xd8\xff", + "image/gif": b"GIF8", +} +REPLY_IMAGE_NAME_PATTERN = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9_.-]{0,119}") + + +def reply_image_directory(turn_id: str) -> Path: + """Return the sole workspace output directory for this exact Core Turn.""" + if not re.fullmatch(r"[a-f0-9]{32}", turn_id): + raise ValueError("invalid reply image Turn") + return Path(".local/loopx-reply-images") / turn_id + + +def reply_image_workspace(session: Mapping[str, object], turn: Mapping[str, object]) -> Path | None: + """Local image output belongs to an ordinary, bound-owner Lark project Turn.""" + context_raw = session.get("project_context") + context: Mapping[str, object] = context_raw if isinstance(context_raw, Mapping) else {} + workspace_path = context.get("workspace_path") + if ( + turn.get("origin") != "lark" + or session.get("session_mode") != "managed_runtime" + or session.get("agent_id") != "codex" + or context.get("audience") != "bound_owner" + or context.get("grant") != "workspace_write" + or not isinstance(workspace_path, str) + or not workspace_path + or session.get("steward_context") + ): + return None + return Path(workspace_path).resolve() + + +def _check_reply_image(data: bytes, mime: str) -> None: + from ...chat.attachments import CHAT_IMAGE_MAX_BYTES + + if not data or len(data) > CHAT_IMAGE_MAX_BYTES: + raise ValueError("reply image is empty or exceeds its size bound") + sig = _REPLY_IMAGE_SIGNATURES.get(mime) + valid_sig = (sig is not None and data.startswith(sig)) or ( + mime == "image/webp" and data[:4] == b"RIFF" and data[8:12] == b"WEBP" + ) + if not valid_sig: + raise ValueError("unsupported reply image bytes") + + +def reply_image_attachment(data: bytes, mime: str, index: int) -> dict[str, object]: + """Validate and encode one captured reply image as a bounded Chat attachment.""" + _check_reply_image(data, mime) + return { + "id": f"reply-image-{index}", + "name": f"original-{index}.{mime.split('/')[1]}", + "mime_type": mime, + "size": len(data), + "data_url": f"data:{mime};base64," + base64.b64encode(data).decode("ascii"), + } + + +def read_reply_image(workspace: Path, turn_id: str, name: str) -> tuple[str, bytes]: + """Read and validate one workspace reply image inside the Turn directory.""" + from ...control_plane.collaboration import result_files + + if not REPLY_IMAGE_NAME_PATTERN.fullmatch(name): + raise ValueError("invalid reply image name") + mime = _REPLY_IMAGE_TYPES.get(Path(name).suffix.lower()) + if mime is None: + raise ValueError("unsupported reply image type") + ref = reply_image_directory(turn_id) / name + workspace_file = getattr(result_files, "_workspace_file") + data = workspace_file(workspace, ref) + if not isinstance(data, bytes): + raise ValueError("reply image payload must be bytes") + _check_reply_image(data, mime) + return mime, data + + +def capture_reply_image_plan( + workspace: Path, turn_id: str, targets: Sequence[str], +) -> list[str | dict[str, object] | None]: + """Pin exact local bytes without keeping host paths in Chat responses.""" + from ...chat.attachments import CHAT_IMAGE_MAX_COUNT, CHAT_IMAGE_MAX_TOTAL_BYTES + + if all(target.startswith("https://") for target in targets): + return [] # The original remote-image path remains authoritative. + if len(targets) > CHAT_IMAGE_MAX_COUNT: + return [None] + output_dir = workspace / reply_image_directory(turn_id) + result: list[str | dict[str, object] | None] = [] + total = 0 + for target in targets: + if target.startswith("https://"): + result.append(target) + continue + try: + path = Path(unquote(target)) + if path.parent != output_dir or ".." in path.parts: + raise ValueError("reply image is outside the current Turn's output directory") + _, data = read_reply_image(workspace, turn_id, path.name) + total += len(data) + if total > CHAT_IMAGE_MAX_TOTAL_BYTES: + raise ValueError("reply images exceed their aggregate size bound") + result.append({"name": path.name, "sha256": hashlib.sha256(data).hexdigest()}) + except (OSError, ValueError): + result.append(None) + return result + + +def _preparation_image_identity(value: object) -> dict[str, object] | None: + """Fingerprint already normalized Core images without exporting their bytes.""" + from ...chat.attachments import normalize_chat_image_attachments + + if not isinstance(value, list) or not value: + return None + try: + images = normalize_chat_image_attachments(value) + if images != value: + return None + encoded = json.dumps(images, sort_keys=True, separators=(",", ":")).encode() + return {"count": len(images), "sha256": hashlib.sha256(encoded).hexdigest()} + except (ValueError, TypeError, OverflowError): + return None diff --git a/tests/capabilities/test_file_discovery_contract.py b/tests/capabilities/test_file_discovery_contract.py new file mode 100644 index 0000000000..0a3b5cb435 --- /dev/null +++ b/tests/capabilities/test_file_discovery_contract.py @@ -0,0 +1,542 @@ +"""Contract, edge-case, and origin/main parity tests for native_chat file_discovery.""" +from __future__ import annotations + +import ast +import base64 +from collections.abc import Mapping, Sequence +from datetime import datetime, timezone +import json +from pathlib import Path +import re +import subprocess +import types +from types import SimpleNamespace + +import pytest + +from loopx.capabilities.native_chat import ( + file_discovery as fd, + file_discovery_backlog as fd_backlog, + file_discovery_media as fd_media, +) +from loopx.chat_store import ChatSessionStore, _atomic_write_json + +_PNG_1X1 = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" +) +_TURN_HEX = "a" * 32 +_REQ_HEX = "b" * 24 + + +def _load_baseline_file_discovery() -> types.ModuleType | None: + repo_root = Path(__file__).resolve().parents[2] + proc = subprocess.run( + ["git", "show", "origin/main:loopx/capabilities/native_chat/file_discovery.py"], + cwd=repo_root, + capture_output=True, + text=True, + check=False, + ) + if proc.returncode != 0 or not proc.stdout: + return None + mod = types.ModuleType("_baseline_file_discovery") + mod.__package__ = "loopx.capabilities.native_chat" + mod.__file__ = str(repo_root / "loopx/capabilities/native_chat/file_discovery.py") + exec(compile(proc.stdout, mod.__file__, "exec"), mod.__dict__) + return mod + + +def test_file_discovery_modules_strict_zero_any_and_size_bounds() -> None: + root = Path(__file__).resolve().parents[2] + paths = [ + root / "loopx/capabilities/native_chat/file_discovery.py", + root / "loopx/capabilities/native_chat/file_discovery_backlog.py", + root / "loopx/capabilities/native_chat/file_discovery_media.py", + Path(__file__).resolve(), + ] + for path in paths: + source = path.read_text(encoding="utf-8") + assert len(source.splitlines()) <= 550, f"{path} exceeded 550 LOC" + assert re.search(r"#\s*type:\s*ignore\b", source) is None, f"{path} contains type ignore" + tree = ast.parse(source) + any_refs = sum( + 1 + for node in ast.walk(tree) + if (isinstance(node, ast.Name) and node.id == "Any") + or (isinstance(node, ast.Attribute) and node.attr == "Any") + or (isinstance(node, ast.alias) and node.name == "Any") + ) + assert any_refs == 0, f"{path} has {any_refs} Any references" + + +def test_facade_preserves_expected_exports() -> None: + expected = ( + "external_source_route_path", + "_ordinary_request_text_digest", + "_RECOVERY_JOURNAL_FIELDS", + "recovery_journal_fields", + "source_control_fields", + "later_equivalent_source_input", + "_MISSING_FILE_FP", + "file_change_fingerprint", + "optional_file_fingerprint", + "_set_bounded_cache", + "QuotaBacklogObservationCache", + "_summarize_turn_events", + "observed_turn_event_summary", + "observed_turn_interrupt", + "_same_store_method", + "observe_quota_backlog_batch", + "FileChatDiscovery", + "_REPLY_IMAGE_TYPES", + "_REPLY_IMAGE_SIGNATURES", + "REPLY_IMAGE_NAME_PATTERN", + "reply_image_directory", + "reply_image_workspace", + "_check_reply_image", + "reply_image_attachment", + "read_reply_image", + "capture_reply_image_plan", + "_DeferredBacklogRequest", + "_preparation_image_identity", + "_project_source_request_digest", + "_project_user_message_hint", + "_RecoveryDiscoveryReads", + ) + for name in expected: + assert hasattr(fd, name), f"missing export {name}" + assert fd.QuotaBacklogObservationCache is fd_backlog.QuotaBacklogObservationCache + assert fd.capture_reply_image_plan is fd_media.capture_reply_image_plan + + +def test_journal_and_source_control_key_presence_vs_none(tmp_path: Path) -> None: + req_path = tmp_path / f"{_REQ_HEX}.json" + assert fd.recovery_journal_fields(req_path, {"request_ref": None, "status": None}) == { + "request_ref": None, + "status": None, + } + assert fd.recovery_journal_fields(req_path, {"request_ref": _REQ_HEX}) is None + assert fd.source_control_fields(req_path, {"binding_id": "b", "source": {}, "command": None}) is None + + prepared_none_origin = fd.source_control_fields( + req_path, + { + "request_ref": _REQ_HEX, + "status": "prepared", + "turn_id": None, + "binding_id": "b", + "session_id": "s1", + "source": {"private_human_message": True}, + "command": None, + "created_at": "2026-01-01T00:00:00+00:00", + "message": "hello", + "origin": None, + }, + ) + assert prepared_none_origin is not None + assert prepared_none_origin["origin"] is None + assert prepared_none_origin["prepared_client_turn_id"] == f"external-{_REQ_HEX}" + + accepted_empty_turn = fd.source_control_fields( + req_path, + { + "request_ref": _REQ_HEX, + "status": "accepted", + "turn_id": "", + "binding_id": "b", + "session_id": "s1", + "source": {"private_human_message": True}, + "command": None, + "created_at": "2026-01-01T00:00:00+00:00", + "message": "hello", + }, + ) + assert accepted_empty_turn is not None + assert "text_sha256" not in accepted_empty_turn + + +def test_later_equivalent_source_input_and_malformed_timestamps() -> None: + base_row: dict[str, object] = { + "status": "accepted", + "turn_id": "t1", + "binding_id": "b1", + "session_id": "s1", + "source": {"source_ref": "sr", "private_human_message": True}, + "command": None, + "created_at": "2026-01-01T00:00:00+00:00", + "message": "ping", + } + digest = fd._ordinary_request_text_digest(base_row) + assert digest is not None + + with pytest.raises(TypeError): + fd.later_equivalent_source_input( + {**base_row, "created_at": 12345}, + lambda: [], + lambda _sid, _cid: None, + ) + + assert ( + fd.later_equivalent_source_input( + base_row, + lambda: [ + { + "binding_id": "b1", + "source": {"source_ref": "sr", "private_human_message": True}, + "session_id": "s1", + "created_at": "2026-01-01T00:01:00+00:00", + "text_sha256": digest, + "prepared_client_turn_id": "external-next", + "origin": "lark", + } + ], + lambda _sid, _cid: { + "origin": "lark", + "message": "rewritten", + "_queue_original_message": "ping", + "attachments": [], + "external_agent_target": None, + "collaboration_request": None, + }, + ) + is True + ) + + +def test_summarize_turn_events_single_pass_and_isolation() -> None: + anchor_payload = {"thread_id": "th-1", "nested": {"x": 1}} + single, steered, interrupted = fd._summarize_turn_events( + [ + {"kind": "turn.started"}, + {"kind": "turn.started", "payload": {}}, + {"kind": "turn.started", "payload": {"native_input": anchor_payload}}, + {"kind": "turn.steered"}, + {"kind": "turn.interrupt_requested"}, + ] + ) + assert single == {"thread_id": "th-1", "nested": {"x": 1}} + assert single is not anchor_payload + assert steered is True + assert interrupted is True + + valid_ev: dict[str, object] = {"kind": "turn.started", "payload": {"native_input": {"thread_id": "1"}}} + assert fd._summarize_turn_events([{"kind": "turn.started", "payload": {"native_input": "corrupt"}}])[0] is None + for bad in ( + {"kind": "turn.started", "payload": {"native_input": "corrupt"}}, + {"kind": "turn.started", "payload": None}, + {"kind": "turn.started", "payload": "corrupt-payload"}, + {"kind": "turn.started", "payload": {"native_input": {"thread_id": "2"}}}, + ): + assert fd._summarize_turn_events([valid_ev, bad]) == (None, False, False) + assert fd._summarize_turn_events([{"kind": "turn.started", "payload": {"native_input": ["corrupt"]}}, valid_ev]) == (None, False, False) + + +def test_cache_and_discovery_bounds_and_monkeypatch_seams( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + cache = fd.QuotaBacklogObservationCache(max_entries=2) + fp = (1, 2, 3, 4, 5) + for idx in ("r1", "r2", "r3"): + cache.put_base(idx, (idx,), True, "running") + assert cache.get_base("r1", ("r1",)) is None + assert cache.get_base("r3", ("r3",)) == (True, "running") + + # Monkeypatching optional_file_fingerprint on facade must govern commit invalidation. + req = tmp_path / "req.json" + trn = tmp_path / "trn.json" + req.write_text("{}") + trn.write_text("{}") + meta: fd_backlog._ObservationMetaEntry = (("k",), req, trn, fp, fp) + monkeypatch.setattr(fd, "optional_file_fingerprint", lambda _p: fp) + cache.commit("rx", meta, True, turn_status="running") + assert cache.get_base("rx", ("k",)) == (True, "running") + monkeypatch.setattr(fd, "optional_file_fingerprint", lambda _p: (9, 9)) + cache.commit("rx", meta, False, turn_status="completed") + assert cache.get_base("rx", ("k",)) is None + + # FileChatDiscovery drops stale keys and passes raw values when project returns None. + p1 = tmp_path / "one.json" + p2 = tmp_path / "two.json" + p1.write_text('{"v": 1}') + p2.write_text('{"v": 2}') + discovery = fd.FileChatDiscovery() + out1 = list( + discovery.rows( + tmp_path, + [p1, p2], + read=lambda p: json.loads(p.read_text()), + project=lambda _p, row: None if row["v"] == 2 else {"keep": row["v"]}, + ) + ) + assert out1 == [(p1, {"keep": 1}), (p2, {"v": 2})] + assert set(discovery._directories[tmp_path]) == {p1} + + +def test_reply_image_validation_and_malformed_inputs(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="invalid reply image Turn"): + fd.reply_image_directory("not-32-hex") + + assert fd.reply_image_workspace({"project_context": "bad"}, {"origin": "lark"}) is None + assert ( + fd.reply_image_workspace( + { + "session_mode": "managed_runtime", + "agent_id": "codex", + "project_context": { + "audience": "bound_owner", + "grant": "workspace_write", + "workspace_path": str(tmp_path), + }, + }, + {"origin": "lark"}, + ) + == tmp_path.resolve() + ) + + # WebP header verification & invalid RIFF payload rejection + valid_webp = b"RIFF1234WEBP" + b"\x00" * 10 + att = fd.reply_image_attachment(valid_webp, "image/webp", 0) + assert att["mime_type"] == "image/webp" + with pytest.raises(ValueError, match="unsupported reply image bytes"): + fd.reply_image_attachment(b"RIFF1234XXXX" + b"\x00" * 10, "image/webp", 0) + + out_dir = tmp_path / fd.reply_image_directory(_TURN_HEX) + out_dir.mkdir(parents=True) + ok_img = out_dir / "chart.png" + bad_img = out_dir / "corrupt.png" + ok_img.write_bytes(_PNG_1X1) + bad_img.write_bytes(b"not-a-png") + outside = tmp_path / "escape.png" + outside.write_bytes(_PNG_1X1) + + assert fd.capture_reply_image_plan(tmp_path, _TURN_HEX, []) == [] + assert fd.capture_reply_image_plan(tmp_path, _TURN_HEX, ["https://x.test/a.png"]) == [] + assert fd.capture_reply_image_plan(tmp_path, _TURN_HEX, [str(ok_img)] * 5) == [None] + + plan = fd.capture_reply_image_plan( + tmp_path, + _TURN_HEX, + [str(ok_img), str(bad_img), str(outside), "https://x.test/keep.png"], + ) + assert isinstance(plan[0], dict) and plan[0]["name"] == "chart.png" + assert plan[1] is None + assert plan[2] is None + assert plan[3] == "https://x.test/keep.png" + + assert fd._preparation_image_identity([]) is None + assert fd._preparation_image_identity("bad") is None + + +def test_paired_origin_main_behavioral_parity(tmp_path: Path) -> None: + baseline = _load_baseline_file_discovery() + if baseline is None: + pytest.skip("git origin/main unavailable in this checkout") + + # 1. Batch quota backlog + deferred requests + real ChatSessionStore parity + store_head = ChatSessionStore(tmp_path / "head", startup_maintenance=False) + store_base = ChatSessionStore(tmp_path / "base", startup_maintenance=False) + for st in (store_head, store_base): + sess = st.create_session(goal_id="g1", agent_id="codex", adapter_kind="codex", upstream_thread_id="th-1") + sid = sess["session_id"] + turn, _ = st.create_turn(sid, client_turn_id=f"external-{_REQ_HEX}", message="hi") + tid = turn["turn_id"] + st.update_turn(sid, tid, status="failed") + st.append_event(sid, tid, kind="turn.started", payload={"native_input": {"thread_id": "t0"}}) + st.append_event(sid, tid, kind="turn.interrupted", payload={}) + + s_head = next(iter(store_head.sessions_root.iterdir())).name + s_base = next(iter(store_base.sessions_root.iterdir())).name + t_head = next(iter((store_head.sessions_root / s_head / "turns").glob("*.json"))).stem + t_base = next(iter((store_base.sessions_root / s_base / "turns").glob("*.json"))).stem + + for mod, st, sid, tid, tag in [ + (fd, store_head, s_head, t_head, "head"), + (baseline, store_base, s_base, t_base, "base"), + ]: + root = tmp_path / tag / "ext" + root.mkdir(parents=True) + req_file = root / f"{_REQ_HEX}.json" + payload = { + "request_ref": _REQ_HEX, + "binding_id": "b1", + "session_id": sid, + "turn_id": tid, + "status": "accepted", + "command": None, + "source": {"source_ref": "sr", "private_human_message": True}, + "created_at": datetime.now(timezone.utc).isoformat(), + "message": "hi", + } + _atomic_write_json(req_file, payload) + cache_store = mod.QuotaBacklogObservationCache() + deferred = mod._DeferredBacklogRequest(payload, req_fp=mod.optional_file_fingerprint(req_file), needs_full_read=False) + + def _build_inputs(r: Mapping[str, object], _st: ChatSessionStore = st) -> dict[str, object]: + t = _st.load_turn(str(r["session_id"]), str(r["turn_id"])) + return {"request": dict(r), "pending_observation": {"turn": t, "stop_observed": False}} + + def _eval(params: Sequence[Mapping[str, object]]) -> list[bool]: + out: list[bool] = [] + for p in params: + obs = p.get("pending_observation") + stop_observed = obs.get("stop_observed") if isinstance(obs, Mapping) else False + out.append(not bool(stop_observed)) + return out + + flags = mod.observe_quota_backlog_batch( + root=root, + store=st, + rows=[deferred], + build_inputs=_build_inputs, + eval_flags=_eval, + stop_controls=lambda: (), + evaluator_id=1, + cache_store=cache_store, + ) + assert flags == [False], f"{tag} expected False after interrupt" + # Warm cache hit must return identical result + flags_warm = mod.observe_quota_backlog_batch( + root=root, + store=st, + rows=[deferred], + build_inputs=_build_inputs, + eval_flags=lambda _p: (_ for _ in ()).throw(AssertionError("cache miss")), + stop_controls=lambda: (), + evaluator_id=1, + cache_store=cache_store, + ) + assert flags_warm == flags + + # 2. Recovery discovery hints + image identity + workspace checks parity + fake_core = SimpleNamespace( + controller=SimpleNamespace(store=store_head), + _cached_user_messages=lambda _sid: [ + fd._project_user_message_hint({"role": "user", "turn_id": t_head, "text": "hi", "created_at": "2026-01-01T00:00:00+00:00"}) + ], + source_controls=lambda: [], + ) + r_head = fd._RecoveryDiscoveryReads(fake_core) + r_base = baseline._RecoveryDiscoveryReads(fake_core) + assert r_head.user_messages(s_head) == r_base.user_messages(s_head) + assert r_head.matching_user_messages(s_head, "hi") == r_base.matching_user_messages(s_head, "hi") + + ws_sess = { + "session_mode": "managed_runtime", + "agent_id": "codex", + "project_context": {"audience": "bound_owner", "grant": "workspace_write", "workspace_path": str(tmp_path)}, + } + ws_turn = {"origin": "lark"} + assert fd.reply_image_workspace(ws_sess, ws_turn) == baseline.reply_image_workspace(ws_sess, ws_turn) + assert fd.reply_image_attachment(_PNG_1X1, "image/png", 1) == baseline.reply_image_attachment(_PNG_1X1, "image/png", 1) + assert fd._preparation_image_identity([fd.reply_image_attachment(_PNG_1X1, "image/png", 1)]) == baseline._preparation_image_identity( + [baseline.reply_image_attachment(_PNG_1X1, "image/png", 1)] + ) + + # 3. Journal/source projections, FileChatDiscovery, and reply-image plans parity + ctl_path = tmp_path / f"{_REQ_HEX}.json" + ctl_row = { + "request_ref": _REQ_HEX, + "binding_id": "b1", + "session_id": s_head, + "status": "prepared", + "turn_id": None, + "command": None, + "source": {"private_human_message": True}, + "created_at": "2026-01-01T00:00:00+00:00", + "message": "ping", + } + _atomic_write_json(ctl_path, ctl_row) + assert fd.recovery_journal_fields(ctl_path, ctl_row) == baseline.recovery_journal_fields(ctl_path, ctl_row) + assert fd.source_control_fields(ctl_path, ctl_row) == baseline.source_control_fields(ctl_path, ctl_row) + disc_head = fd.FileChatDiscovery() + disc_base = baseline.FileChatDiscovery() + assert list(disc_head.rows_with_fingerprints(tmp_path, [ctl_path], read=lambda p: json.loads(p.read_text()), project=fd.source_control_fields)) == list( + disc_base.rows_with_fingerprints(tmp_path, [ctl_path], read=lambda p: json.loads(p.read_text()), project=baseline.source_control_fields) + ) + img_dir = tmp_path / fd.reply_image_directory(_TURN_HEX) + img_dir.mkdir(parents=True, exist_ok=True) + img_file = img_dir / "parity.png" + img_file.write_bytes(_PNG_1X1) + assert fd.read_reply_image(tmp_path, _TURN_HEX, "parity.png") == baseline.read_reply_image(tmp_path, _TURN_HEX, "parity.png") + assert fd.capture_reply_image_plan(tmp_path, _TURN_HEX, [str(img_file), "https://x.test/ok.png"]) == baseline.capture_reply_image_plan( + tmp_path, _TURN_HEX, [str(img_file), "https://x.test/ok.png"] + ) + + +def test_real_discovery_preserves_malformed_start_ambiguity(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + import threading + from loopx.capabilities.native_chat import external_conversations as ext_mod + from loopx.chat_manager import MANAGER_CONTEXT_VERSION + from loopx.chat_store import CHAT_TURN_SCHEMA_VERSION + from loopx.extensions.lark.private_conversations import LarkPrivateConversations + + baseline = _load_baseline_file_discovery() + binding_id, prov_id, op_id, proj_id, src_id = ("b" * 24, "a" * 24, "e" * 24, "f" * 24, "c" * 24) + binding = { + "schema_version": "loopx_chat_conversation_binding_v0", "binding_id": binding_id, "enabled": True, + "transport_ref": "steward-app", "context_kind": "steward", "goal_ids": [], "grant": "portfolio_read", + "provider_ref": prov_id, "operator_ref": op_id, "project_ref": proj_id, "executor_endpoint_id": "antigravity", + } + store = ChatSessionStore(tmp_path, startup_maintenance=False) + bindings = SimpleNamespace(controller=None, read=lambda: {"bindings": [binding]}, resolve=lambda **_: {"binding": binding}) + ctrl = SimpleNamespace( + store=store, project_contexts=SimpleNamespace(conversation_bindings=bindings), + lock=threading.Lock(), adapters={}, codex_home=tmp_path, registry_path=None, coordination_runtime_root=tmp_path, + ) + lp = LarkPrivateConversations(controller=ctrl, runtime_root=tmp_path, runner=object(), cli_bin="echo") + lp.root.mkdir(parents=True, exist_ok=True) + core = lp.core + core.root.mkdir(parents=True, exist_ok=True) + anchor: dict[str, object] = {"thread_id": "cas-1", "start_step_index": 0, "input_sha256": "a" * 64} + cases: list[tuple[str, list[tuple[str, dict[str, object]]], dict[str, object] | None, bool, bool]] = [ + ("clean", [("turn.started", {"native_input": anchor})], None, True, True), + ("missing_payload", [("turn.started", {"native_input": anchor})], {"kind": "turn.started"}, True, True), + ("explicit_none_payload", [("turn.started", {"native_input": anchor})], {"kind": "turn.started", "payload": None}, False, False), + ("malformed_second_str", [("turn.started", {"native_input": anchor}), ("turn.started", {"native_input": "corrupt"})], None, False, True), + ("malformed_first_list", [("turn.started", {"native_input": ["corrupt"]}), ("turn.started", {"native_input": anchor})], None, False, True), + ("single_malformed", [("turn.started", {"native_input": "corrupt-only"})], None, False, False), + ("corrupt_second_payload", [("turn.started", {"native_input": anchor})], {"kind": "turn.started", "payload": "corrupt-payload"}, False, False), + ] + for idx, (_label, evs, extra_raw, expected, check_baseline) in enumerate(cases): + sid, tid, req = f"{3000 + idx:032x}", f"{4000 + idx:032x}", f"{5000 + idx:024x}" + store.create_session( + goal_id="loopx-manager", agent_id="antigravity", adapter_kind="antigravity", upstream_thread_id="cas-1", + upstream_mode="default", session_id=sid, channel_id=f"manager.external.native.{binding_id}.{src_id}", + steward_context={"kind": "bound_steward", "binding_id": binding_id, "audience": "bound_owner", "grant": "portfolio_read", + "goal_ids": [], "provider_ref": prov_id, "operator_ref": op_id, "project_ref": proj_id, "source_ref": src_id, "workspace_path": str(tmp_path)}, + ) + loaded_session = store.load_session(sid) + assert loaded_session is not None + _atomic_write_json(store._session_path(sid), {**loaded_session, "session_mode": "managed_runtime", "executor_endpoint_id": "antigravity", "manager_context_version": MANAGER_CONTEXT_VERSION}) + _atomic_write_json(store._turn_path(sid, tid), {"schema_version": CHAT_TURN_SCHEMA_VERSION, "session_id": sid, "turn_id": tid, + "client_turn_id": f"external-{req}", "message": "q", "origin": "lark", "status": "failed", "error_code": "antigravity_step_error", + "delta_count": 0, "upstream_turn_id": "up-1", "created_at": "2026-01-01T00:00:00+00:00", "completed_at": "2026-01-01T00:01:00+00:00", "response": None}) + for kind, payload in evs: + store.append_event(sid, tid, kind=kind, payload=dict(payload), buffered=False) + if extra_raw is not None: + store.append_event(sid, tid, kind="turn.started", payload={}, buffered=False) + ev_path = store._event_path(sid, tid) + lines = ev_path.read_text(encoding="utf-8").splitlines() + ev_obj = json.loads(lines[-1]) + ev_obj.pop("payload", None) + lines[-1] = json.dumps({**ev_obj, **extra_raw}) + ev_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + row: dict[str, object] = {"request_ref": req, "binding_id": binding_id, "source": {"source_ref": src_id, "sender_ref": op_id, "private_human_message": True}, + "session_id": sid, "turn_id": tid, "command": None, "origin": "lark", "status": "accepted", "delivery_verified": True, + "message": "q", "created_at": "2026-01-01T00:00:00+00:00"} + _atomic_write_json(core.root / f"{req}.json", row) + _atomic_write_json(lp.root / f"{req}.json", { + "schema_version": "lark_private_delivery_v0", "request_ref": req, "binding_id": binding_id, "session_id": sid, "turn_id": tid, + "status": "delivered", "source": {"source_ref": src_id, "sender_ref": op_id, "private_human_message": True}, + "deliveries": {"terminal": {"status": "delivered"}}, + }) + assert core.context_recovery_candidate(req) is expected + assert core.context_recovery_candidate(req) is expected + if check_baseline: + assert (core._context_recovery_plan(row, discovery_only=False).get("recovery_candidate") is True) is expected + if baseline is not None: + with monkeypatch.context() as mp: + mp.setattr(ext_mod, "observed_turn_event_summary", baseline.observed_turn_event_summary) + core._quota_backlog_cache.drop_event_summary(sid, tid) + assert core.context_recovery_candidate(req) is expected + assert {p.stem for p in lp.pending_delivery_paths()} == {f"{5000 + i:024x}" for i, item in enumerate(cases) if item[3]}