diff --git a/examples/session_runtime/session-runtime-readonly-projection-smoke.py b/examples/session_runtime/session-runtime-readonly-projection-smoke.py index 3b83482bd5..71182ad601 100644 --- a/examples/session_runtime/session-runtime-readonly-projection-smoke.py +++ b/examples/session_runtime/session-runtime-readonly-projection-smoke.py @@ -3,6 +3,7 @@ from __future__ import annotations +from collections.abc import Mapping import json import sys import tempfile @@ -27,7 +28,7 @@ LOCAL_PATH_FIXTURE = "/" + "private" + "/tmp/raw-run.log" -def assert_no_raw_values(payload: dict[str, object]) -> None: +def assert_no_raw_values(payload: Mapping[str, object]) -> None: text = json.dumps(payload, sort_keys=True) forbidden_values = ( LOCAL_PATH_FIXTURE, diff --git a/loopx/session_runtime.py b/loopx/session_runtime.py index 285ae88be9..b777c88e53 100644 --- a/loopx/session_runtime.py +++ b/loopx/session_runtime.py @@ -13,15 +13,15 @@ from __future__ import annotations -import re -from collections.abc import Mapping, Sequence +from collections.abc import Iterable, Mapping, Sequence from enum import Enum -from typing import Any, NamedTuple +from itertools import chain +import re +from typing import NamedTuple, TypedDict SESSION_RUNTIME_READONLY_PROJECTION_SCHEMA_VERSION = ( "session_runtime_readonly_projection_v0" ) - UNCLASSIFIED_KEY_LIMIT = 24 @@ -44,31 +44,88 @@ class KeyClassification(NamedTuple): category: RawMaterialCategory | None = None +class SourceRefs(TypedDict): + sessions: list[dict[str, str]] + events: list[dict[str, str]] + outcomes: list[dict[str, str]] + gates: list[dict[str, str]] + artifacts: list[dict[str, str]] + decision_results: list[dict[str, str]] + + +class SessionRuntimeSource(TypedDict): + host_kind: str + source_refs: SourceRefs + latest_fact_at: str | None + + +class SessionRuntimeBoundary(TypedDict): + raw_transcript_copied: bool + raw_logs_copied: bool + credentials_copied: bool + runtime_writeback_allowed: bool + runtime_mutation_allowed: bool + raw_material_detected: bool + raw_material_key_names: list[str] + raw_material_categories: list[str] + unclassified_key_names: list[str] + + +class SessionRuntimeFirstScreen(TypedDict): + waiting_on: str + user_action_required: bool + agent_can_continue: bool + first_user_todo: str | None + first_agent_todo: str | None + latest_validation: str | None + latest_blocker: str | None + gate_state: str + recommended_action: str | None + + +class SessionRuntimeWorkLaneContract(TypedDict): + lane: str + must_attempt_work: bool + user_gate_blocks_delivery: bool + monitor_only: bool + + +class SessionRuntimeAttentionItem(TypedDict): + kind: str + priority: str + title: str | None + waiting_on: str + evidence_refs: SourceRefs + + +class SessionRuntimeReconcileRule(TypedDict): + raw_fact_source: str + compact_projection_source: str + conflict_policy: str + + +class SessionRuntimeReadonlyProjection(TypedDict): + schema_version: str + goal_id: str + mode: str + source: SessionRuntimeSource + boundary: SessionRuntimeBoundary + first_screen: SessionRuntimeFirstScreen + work_lane_contract: SessionRuntimeWorkLaneContract + attention_item: SessionRuntimeAttentionItem + reconcile_rule: SessionRuntimeReconcileRule + + SOURCE_ID_KEYS = ( - "session_id", - "event_id", - "outcome_id", - "gate_id", - "approval_id", - "artifact_id", - "tool_call_id", - "run_id", - "ref_id", + "session_id", "event_id", "outcome_id", "gate_id", "approval_id", + "artifact_id", "tool_call_id", "run_id", "ref_id", ) - TIMESTAMP_KEYS = ("created_at", "event_at", "updated_at", "timestamp") # Public-safe pointers and aggregate counters whose leading word otherwise # carries raw-material meaning. Keep these exceptions explicit and reviewable. EXPLICIT_COMPACT_COLLISION_KEYS = frozenset( - { - "conversation_id", - "log_count", - "message_id", - "prompt_token_count", - "prompt_tokens", - "trace_id", - } + {"conversation_id", "log_count", "message_id", "prompt_token_count", "prompt_tokens", "trace_id"} ) # Exact keys the projection itself reads, plus its input booleans. @@ -77,30 +134,11 @@ class KeyClassification(NamedTuple): *SOURCE_ID_KEYS, *TIMESTAMP_KEYS, *EXPLICIT_COMPACT_COLLISION_KEYS, - "kind", - "type", - "status", - "state", - "actor", - "required_actor", - "decision_actor", - "channel", - "requires_human_decision", - "action_required", - "advisory", - "blocking", - "question", - "requested_decision", - "title", - "summary", - "next_action", - "recommended_action", - "agent_next_action", - "handoff", - "validation_summary", - "validated", - "result", - "blocker", + "kind", "type", "status", "state", "actor", "required_actor", + "decision_actor", "channel", "requires_human_decision", "action_required", + "advisory", "blocking", "question", "requested_decision", "title", + "summary", "next_action", "recommended_action", "agent_next_action", + "handoff", "validation_summary", "validated", "result", "blocker", "blocker_summary", } ) @@ -114,56 +152,32 @@ class KeyClassification(NamedTuple): # Exact keys that are raw material even though their words are individually # ambiguous (``key``, ``token``, ``content``, ``output``). RAW_MATERIAL_KEYS: Mapping[str, RawMaterialCategory] = { - "token": RawMaterialCategory.CREDENTIAL, - "access_token": RawMaterialCategory.CREDENTIAL, - "auth_token": RawMaterialCategory.CREDENTIAL, - "api_token": RawMaterialCategory.CREDENTIAL, - "bearer_token": RawMaterialCategory.CREDENTIAL, - "refresh_token": RawMaterialCategory.CREDENTIAL, - "id_token": RawMaterialCategory.CREDENTIAL, - "session_token": RawMaterialCategory.CREDENTIAL, - "api_key": RawMaterialCategory.CREDENTIAL, - "apikey": RawMaterialCategory.CREDENTIAL, - "private_key": RawMaterialCategory.CREDENTIAL, - "secret_key": RawMaterialCategory.CREDENTIAL, - "access_key": RawMaterialCategory.CREDENTIAL, - "authorization": RawMaterialCategory.CREDENTIAL, - "cookie": RawMaterialCategory.CREDENTIAL, - "cookies": RawMaterialCategory.CREDENTIAL, - "content": RawMaterialCategory.TRANSCRIPT, - "body": RawMaterialCategory.TRANSCRIPT, - "request_body": RawMaterialCategory.TRANSCRIPT, - "response_body": RawMaterialCategory.TRANSCRIPT, - "message": RawMaterialCategory.TRANSCRIPT, - "output": RawMaterialCategory.RAW_OUTPUT, - "output_text": RawMaterialCategory.RAW_OUTPUT, - "tool_output": RawMaterialCategory.RAW_OUTPUT, - "tool_result": RawMaterialCategory.RAW_OUTPUT, -} - -# Whole words that mark raw material in any position. Category precedence is -# the tuple order, so ``raw_transcript`` is a transcript and ``raw_log`` a log. -RAW_MATERIAL_WORDS: tuple[tuple[RawMaterialCategory, frozenset[str]], ...] = ( - ( + **dict.fromkeys( + ( + "token", "access_token", "auth_token", "api_token", "bearer_token", + "refresh_token", "id_token", "session_token", "api_key", "apikey", + "private_key", "secret_key", "access_key", "authorization", "cookie", "cookies", + ), RawMaterialCategory.CREDENTIAL, - frozenset({"credential", "credentials", "secret", "secrets", "password", "passwd", "passphrase"}), ), - ( + **dict.fromkeys( + ("content", "body", "request_body", "response_body", "message"), RawMaterialCategory.TRANSCRIPT, - frozenset({"transcript", "transcripts", "messages", "prompt", "prompts", "conversation"}), - ), - ( - RawMaterialCategory.LOG, - frozenset({"log", "logs", "trace", "traces", "stacktrace", "traceback"}), - ), - ( - RawMaterialCategory.LOCAL_PATH, - frozenset({"path", "paths", "cwd", "workdir", "filename", "filepath"}), ), - ( + **dict.fromkeys( + ("output", "output_text", "tool_output", "tool_result"), RawMaterialCategory.RAW_OUTPUT, - frozenset({"raw", "stdout", "stderr", "diff", "patch", "dump"}), ), +} + +# Whole words that mark raw material in any position. Category precedence is +# the tuple order, so ``raw_transcript`` is a transcript and ``raw_log`` a log. +RAW_MATERIAL_WORDS: tuple[tuple[RawMaterialCategory, frozenset[str]], ...] = ( + (RawMaterialCategory.CREDENTIAL, frozenset({"credential", "credentials", "secret", "secrets", "password", "passwd", "passphrase"})), + (RawMaterialCategory.TRANSCRIPT, frozenset({"transcript", "transcripts", "messages", "prompt", "prompts", "conversation"})), + (RawMaterialCategory.LOG, frozenset({"log", "logs", "trace", "traces", "stacktrace", "traceback"})), + (RawMaterialCategory.LOCAL_PATH, frozenset({"path", "paths", "cwd", "workdir", "filename", "filepath"})), + (RawMaterialCategory.RAW_OUTPUT, frozenset({"raw", "stdout", "stderr", "diff", "patch", "dump"})), ) # Multi-word exact raw keys also remain raw when embedded in a larger key. This @@ -182,30 +196,31 @@ class KeyClassification(NamedTuple): _WORD_SEPARATOR = re.compile(r"[^a-z0-9]+") OPEN_GATE_STATUSES = { - "blocked", - "needs_decision", - "open", - "pending", - "requested", - "requires_decision", - "waiting", + "blocked", "needs_decision", "open", "pending", + "requested", "requires_decision", "waiting", } - HUMAN_GATE_ACTORS = {"controller", "human", "operator", "owner", "user"} BLOCKED_STATUSES = {"blocked", "error", "failed", "timed_out"} VALIDATED_STATUSES = {"ok", "passed", "success", "validated"} -def _as_mappings(values: Sequence[Mapping[str, Any]] | None) -> list[dict[str, Any]]: +def _as_mappings(values: Sequence[Mapping[str, object]] | None) -> tuple[Mapping[str, object], ...]: if not values: - return [] - return [dict(item) for item in values if isinstance(item, Mapping)] + return () + # Exact builtin dicts cannot compute or cache missing keys on lookup; other + # Mappings are snapshotted from their enumerated keys to stay read-only. + return tuple( + item if type(item) is dict else dict(item) + for item in values + if isinstance(item, Mapping) + ) -def _text(value: Any, *, limit: int = 180) -> str | None: +def _text(value: object, *, limit: int = 180) -> str | None: if value is None: return None - text = " ".join(str(value).split()) + raw = value if isinstance(value, str) else str(value) + text = " ".join(raw.split()) if not text: return None if len(text) <= limit: @@ -213,7 +228,7 @@ def _text(value: Any, *, limit: int = 180) -> str | None: return text[: max(0, limit - 1)].rstrip() + "..." -def _first_text(item: Mapping[str, Any], keys: Sequence[str]) -> str | None: +def _first_text(item: Mapping[str, object], keys: Sequence[str]) -> str | None: for key in keys: text = _text(item.get(key)) if text: @@ -221,11 +236,15 @@ def _first_text(item: Mapping[str, Any], keys: Sequence[str]) -> str | None: return None -def _status(item: Mapping[str, Any]) -> str: +def _status(item: Mapping[str, object]) -> str: return str(item.get("status") or item.get("state") or "").strip().lower() -def _actor(item: Mapping[str, Any]) -> str: +def _kind(item: Mapping[str, object]) -> str: + return str(item.get("kind") or item.get("type") or "").strip().lower() + + +def _actor(item: Mapping[str, object]) -> str: return str( item.get("actor") or item.get("required_actor") @@ -235,54 +254,40 @@ def _actor(item: Mapping[str, Any]) -> str: ).strip().lower() -def _is_human_gate(item: Mapping[str, Any]) -> bool: - status = _status(item) - actor = _actor(item) - return status in OPEN_GATE_STATUSES and ( - actor in HUMAN_GATE_ACTORS - or bool(item.get("requires_human_decision")) - or bool(item.get("action_required")) +def _event_timestamp(item: Mapping[str, object]) -> object: + return ( + item.get("created_at") + or item.get("event_at") + or item.get("updated_at") + or item.get("timestamp") ) -def _is_blocking_gate(item: Mapping[str, Any]) -> bool: - if not _is_human_gate(item): +def _is_blocking_gate(item: Mapping[str, object]) -> bool: + if _status(item) not in OPEN_GATE_STATUSES: return False - if item.get("advisory") is True: - return False - return item.get("blocking", True) is not False + human_targeted = ( + _actor(item) in HUMAN_GATE_ACTORS + or bool(item.get("requires_human_decision")) + or bool(item.get("action_required")) + ) + return human_targeted and item.get("advisory") is not True and item.get("blocking", True) is not False -def _is_blocker(item: Mapping[str, Any]) -> bool: - kind = str(item.get("kind") or item.get("type") or "").strip().lower() - return kind == "blocker" or _status(item) in BLOCKED_STATUSES +def _is_blocker(item: Mapping[str, object]) -> bool: + return _kind(item) == "blocker" or _status(item) in BLOCKED_STATUSES -def _is_validation(item: Mapping[str, Any]) -> bool: - kind = str(item.get("kind") or item.get("type") or "").strip().lower() - return kind in {"validation", "outcome"} and _status(item) in VALIDATED_STATUSES +def _is_validation(item: Mapping[str, object]) -> bool: + return _kind(item) in {"validation", "outcome"} and _status(item) in VALIDATED_STATUSES -def _latest(items: Sequence[Mapping[str, Any]]) -> dict[str, Any] | None: - if not items: - return None - return max( - (dict(item) for item in items), - key=lambda item: str( - item.get("created_at") - or item.get("event_at") - or item.get("updated_at") - or item.get("timestamp") - or "" - ), - ) +def _latest(items: Iterable[Mapping[str, object]]) -> Mapping[str, object] | None: + return max(items, key=lambda item: str(_event_timestamp(item) or ""), default=None) -def _source_ref(item: Mapping[str, Any], *, default_kind: str) -> dict[str, Any]: - ref: dict[str, Any] = { - "kind": _text(item.get("kind") or item.get("type") or default_kind, limit=60) - or default_kind - } +def _source_ref(item: Mapping[str, object], *, default_kind: str) -> dict[str, str]: + ref = {"kind": _text(item.get("kind") or item.get("type") or default_kind, limit=60) or default_kind} for key in SOURCE_ID_KEYS: value = _text(item.get(key), limit=120) if value: @@ -292,23 +297,20 @@ def _source_ref(item: Mapping[str, Any], *, default_kind: str) -> dict[str, Any] def _source_refs( *, - sessions: Sequence[Mapping[str, Any]], - events: Sequence[Mapping[str, Any]], - outcomes: Sequence[Mapping[str, Any]], - gates: Sequence[Mapping[str, Any]], - artifacts: Sequence[Mapping[str, Any]], - decision_results: Sequence[Mapping[str, Any]], -) -> dict[str, list[dict[str, Any]]]: + sessions: Sequence[Mapping[str, object]], + events: Sequence[Mapping[str, object]], + outcomes: Sequence[Mapping[str, object]], + gates: Sequence[Mapping[str, object]], + artifacts: Sequence[Mapping[str, object]], + decision_results: Sequence[Mapping[str, object]], +) -> SourceRefs: return { "sessions": [_source_ref(item, default_kind="session") for item in sessions], "events": [_source_ref(item, default_kind="event") for item in events], "outcomes": [_source_ref(item, default_kind="outcome") for item in outcomes], "gates": [_source_ref(item, default_kind="gate") for item in gates], "artifacts": [_source_ref(item, default_kind="artifact") for item in artifacts], - "decision_results": [ - _source_ref(item, default_kind="decision_result") - for item in decision_results - ], + "decision_results": [_source_ref(item, default_kind="decision_result") for item in decision_results], } @@ -319,10 +321,7 @@ def _key_words(key: str) -> list[str]: def _contains_word_sequence(words: Sequence[str], phrase: tuple[str, ...]) -> bool: width = len(phrase) - return any( - tuple(words[index : index + width]) == phrase - for index in range(len(words) - width + 1) - ) + return any(tuple(words[index : index + width]) == phrase for index in range(len(words) - width + 1)) def classify_session_runtime_key(key: str) -> KeyClassification: @@ -331,7 +330,12 @@ def classify_session_runtime_key(key: str) -> KeyClassification: Matching is exact-key, whole-word, or exact word-sequence only; substrings never match. Raw evidence outranks generic pointer and metric shortcuts. """ - + if isinstance(key, str): + if key in COMPACT_KEYS: + return KeyClassification(KeyState.COMPACT) + exact_category = RAW_MATERIAL_KEYS.get(key) + if exact_category is not None: + return KeyClassification(KeyState.RAW_MATERIAL, exact_category) words = _key_words(key) if not words: return KeyClassification(KeyState.UNCLASSIFIED) @@ -343,155 +347,113 @@ def classify_session_runtime_key(key: str) -> KeyClassification: return KeyClassification(KeyState.RAW_MATERIAL, category) for category, raw_words in RAW_MATERIAL_WORDS: if raw_words.intersection(words) or any( - _contains_word_sequence(words, phrase) - for phrase in RAW_MATERIAL_KEY_PHRASES[category] + _contains_word_sequence(words, phrase) for phrase in RAW_MATERIAL_KEY_PHRASES[category] ): return KeyClassification(KeyState.RAW_MATERIAL, category) - if words[-1] in COMPACT_SUFFIX_WORDS: - return KeyClassification(KeyState.COMPACT) - if COMPACT_METRIC_WORDS.intersection(words): + if words[-1] in COMPACT_SUFFIX_WORDS or COMPACT_METRIC_WORDS.intersection(words): return KeyClassification(KeyState.COMPACT) return KeyClassification(KeyState.UNCLASSIFIED) -def _classify_keys( - *groups: Sequence[Mapping[str, Any]], -) -> tuple[list[str], list[str], list[str]]: +def _classify_keys(*groups: Sequence[Mapping[str, object]]) -> tuple[list[str], list[str], list[str]]: """Return sorted raw-material key names, their categories, and unclassified names.""" - raw_keys: set[str] = set() categories: set[str] = set() unclassified: set[str] = set() + seen: set[str] = set() for group in groups: for item in group: for key in item: - classification = classify_session_runtime_key(str(key)) + key_name = key if isinstance(key, str) else str(key) + if key_name in seen: + continue + seen.add(key_name) + classification = classify_session_runtime_key(key_name) if classification.state is KeyState.RAW_MATERIAL: - raw_keys.add(str(key)) + raw_keys.add(key_name) if classification.category is not None: categories.add(classification.category.value) elif classification.state is KeyState.UNCLASSIFIED: - unclassified.add(str(key)) + unclassified.add(key_name) return sorted(raw_keys), sorted(categories), sorted(unclassified)[:UNCLASSIFIED_KEY_LIMIT] -def _first_user_todo(gate: Mapping[str, Any] | None) -> str | None: +def _first_user_todo(gate: Mapping[str, object] | None) -> str | None: if gate is None: return None - return _first_text( - gate, - ( - "question", - "requested_decision", - "title", - "summary", - "next_action", - ), - ) + return _first_text(gate, ("question", "requested_decision", "title", "summary", "next_action")) def _first_agent_todo( *, - decision_results: Sequence[Mapping[str, Any]], - sessions: Sequence[Mapping[str, Any]], - events: Sequence[Mapping[str, Any]], - outcomes: Sequence[Mapping[str, Any]], + decision_results: Sequence[Mapping[str, object]], + sessions: Sequence[Mapping[str, object]], + events: Sequence[Mapping[str, object]], + outcomes: Sequence[Mapping[str, object]], ) -> str | None: + todo_keys = ("recommended_action", "agent_next_action", "next_action", "handoff", "summary") for group in (decision_results, sessions, events, outcomes): for item in group: - text = _first_text( - item, - ( - "recommended_action", - "agent_next_action", - "next_action", - "handoff", - "summary", - ), - ) + text = _first_text(item, todo_keys) if text: return text return None def _latest_validation( - outcomes: Sequence[Mapping[str, Any]], events: Sequence[Mapping[str, Any]] + outcomes: Sequence[Mapping[str, object]], events: Sequence[Mapping[str, object]] ) -> str | None: - candidates = [ + latest = _latest( item - for item in [*outcomes, *events] - if _is_validation(item) - or _first_text(item, ("validation_summary", "validated", "result")) - ] - latest = _latest(candidates) + for item in chain(outcomes, events) + if _is_validation(item) or _first_text(item, ("validation_summary", "validated", "result")) + ) if latest is None: return None - return _first_text( - latest, - ("validation_summary", "validated", "result", "summary"), - ) + return _first_text(latest, ("validation_summary", "validated", "result", "summary")) def _latest_blocker( - gates: Sequence[Mapping[str, Any]], - outcomes: Sequence[Mapping[str, Any]], - events: Sequence[Mapping[str, Any]], + gates: Sequence[Mapping[str, object]], + outcomes: Sequence[Mapping[str, object]], + events: Sequence[Mapping[str, object]], ) -> str | None: - candidates = [ + latest = _latest( item - for item in [*gates, *outcomes, *events] + for item in chain(gates, outcomes, events) if _is_blocker(item) or _first_text(item, ("blocker", "blocker_summary")) - ] - latest = _latest(candidates) + ) if latest is None: return None - return _first_text( - latest, - ("blocker", "blocker_summary", "summary", "title"), - ) + return _first_text(latest, ("blocker", "blocker_summary", "summary", "title")) -def _waiting_on( +def _waiting_and_lane( *, - blocking_gate: Mapping[str, Any] | None, + blocking_gate: Mapping[str, object] | None, blocker: str | None, first_agent_todo: str | None, -) -> str: +) -> tuple[str, str]: if blocking_gate is not None: actor = _actor(blocking_gate) - return actor if actor in HUMAN_GATE_ACTORS else "operator" - if blocker and not first_agent_todo: - return "runtime" - if first_agent_todo: - return "agent" - return "none" - - -def _lane( - *, - blocking_gate: Mapping[str, Any] | None, - blocker: str | None, - first_agent_todo: str | None, -) -> str: - if blocking_gate is not None: - return "user_gate" + return (actor if actor in HUMAN_GATE_ACTORS else "operator"), "user_gate" if blocker and not first_agent_todo: - return "blocker" + return "runtime", "blocker" if first_agent_todo: - return "advancement_task" - return "monitor" + return "agent", "advancement_task" + return "none", "monitor" def build_session_runtime_readonly_projection( *, goal_id: str, - sessions: Sequence[Mapping[str, Any]] | None = None, - events: Sequence[Mapping[str, Any]] | None = None, - outcomes: Sequence[Mapping[str, Any]] | None = None, - gates: Sequence[Mapping[str, Any]] | None = None, - artifacts: Sequence[Mapping[str, Any]] | None = None, - decision_results: Sequence[Mapping[str, Any]] | None = None, -) -> dict[str, Any]: + sessions: Sequence[Mapping[str, object]] | None = None, + events: Sequence[Mapping[str, object]] | None = None, + outcomes: Sequence[Mapping[str, object]] | None = None, + gates: Sequence[Mapping[str, object]] | None = None, + artifacts: Sequence[Mapping[str, object]] | None = None, + decision_results: Sequence[Mapping[str, object]] | None = None, +) -> SessionRuntimeReadonlyProjection: """Project compact session-runtime facts into a LoopX first screen. This adapter is intentionally read-only. It consumes only compact summaries @@ -499,7 +461,6 @@ def build_session_runtime_readonly_projection( paths. Known raw-material keys are recorded as a boundary violation without copying their values; unrecognized keys are reported but do not block. """ - session_items = _as_mappings(sessions) event_items = _as_mappings(events) outcome_items = _as_mappings(outcomes) @@ -510,39 +471,20 @@ def build_session_runtime_readonly_projection( blocking_gate = next((gate for gate in gate_items if _is_blocking_gate(gate)), None) user_todo = _first_user_todo(blocking_gate) agent_todo = _first_agent_todo( - decision_results=decision_items, - sessions=session_items, - events=event_items, - outcomes=outcome_items, + decision_results=decision_items, sessions=session_items, events=event_items, outcomes=outcome_items ) validation = _latest_validation(outcome_items, event_items) blocker = _latest_blocker(gate_items, outcome_items, event_items) - waiting = _waiting_on( - blocking_gate=blocking_gate, - blocker=blocker, - first_agent_todo=agent_todo, - ) - lane = _lane( - blocking_gate=blocking_gate, - blocker=blocker, - first_agent_todo=agent_todo, + waiting, lane = _waiting_and_lane( + blocking_gate=blocking_gate, blocker=blocker, first_agent_todo=agent_todo ) raw_keys, raw_categories, unclassified_keys = _classify_keys( - session_items, - event_items, - outcome_items, - gate_items, - artifact_items, - decision_items, + session_items, event_items, outcome_items, gate_items, artifact_items, decision_items ) - latest_event = _latest([*session_items, *event_items, *outcome_items]) + latest_event = _latest(chain(session_items, event_items, outcome_items)) source_refs = _source_refs( - sessions=session_items, - events=event_items, - outcomes=outcome_items, - gates=gate_items, - artifacts=artifact_items, - decision_results=decision_items, + sessions=session_items, events=event_items, outcomes=outcome_items, + gates=gate_items, artifacts=artifact_items, decision_results=decision_items, ) can_continue = bool(agent_todo and blocking_gate is None and not raw_keys) @@ -555,30 +497,16 @@ def build_session_runtime_readonly_projection( if agent_todo else "monitor for a material transition" ) + latest_fact_at = _text(_event_timestamp(latest_event), limit=80) if latest_event else None return { "schema_version": SESSION_RUNTIME_READONLY_PROJECTION_SCHEMA_VERSION, "goal_id": str(goal_id), "mode": "read_only", - "source": { - "host_kind": "session_runtime", - "source_refs": source_refs, - "latest_fact_at": _text( - latest_event.get("created_at") - or latest_event.get("event_at") - or latest_event.get("updated_at") - or latest_event.get("timestamp"), - limit=80, - ) - if latest_event - else None, - }, + "source": {"host_kind": "session_runtime", "source_refs": source_refs, "latest_fact_at": latest_fact_at}, "boundary": { - "raw_transcript_copied": False, - "raw_logs_copied": False, - "credentials_copied": False, - "runtime_writeback_allowed": False, - "runtime_mutation_allowed": False, + "raw_transcript_copied": False, "raw_logs_copied": False, "credentials_copied": False, + "runtime_writeback_allowed": False, "runtime_mutation_allowed": False, "raw_material_detected": bool(raw_keys), "raw_material_key_names": raw_keys, "raw_material_categories": raw_categories, @@ -596,17 +524,12 @@ def build_session_runtime_readonly_projection( "recommended_action": recommended_action, }, "work_lane_contract": { - "lane": lane, - "must_attempt_work": can_continue, - "user_gate_blocks_delivery": blocking_gate is not None, - "monitor_only": lane == "monitor", + "lane": lane, "must_attempt_work": can_continue, + "user_gate_blocks_delivery": blocking_gate is not None, "monitor_only": lane == "monitor", }, "attention_item": { - "kind": lane, - "priority": "P0" if lane in {"user_gate", "blocker"} else "P1", - "title": recommended_action, - "waiting_on": waiting, - "evidence_refs": source_refs, + "kind": lane, "priority": "P0" if lane in {"user_gate", "blocker"} else "P1", + "title": recommended_action, "waiting_on": waiting, "evidence_refs": source_refs, }, "reconcile_rule": { "raw_fact_source": "host_session_log", diff --git a/tests/control_plane/test_goal_artifact_work_observation.py b/tests/control_plane/test_goal_artifact_work_observation.py index deadd8093f..27f65751d7 100644 --- a/tests/control_plane/test_goal_artifact_work_observation.py +++ b/tests/control_plane/test_goal_artifact_work_observation.py @@ -147,8 +147,10 @@ def test_persisted_work_observation_coverage_before_display_trimming( def test_work_observation_rejects_foreign_or_untyped_projection(field, value): from loopx.control_plane.runtime.session_runtime import session_runtime_work_observation - projection = build_session_runtime_readonly_projection( - goal_id="demo", decision_results=[{"recommended_action": "Continue verification"}], + projection: dict[str, object] = dict( + build_session_runtime_readonly_projection( + goal_id="demo", decision_results=[{"recommended_action": "Continue verification"}], + ) ) projection[field] = value before = copy.deepcopy(projection) diff --git a/tests/test_session_runtime_key_classification.py b/tests/test_session_runtime_key_classification.py index 9cca200973..5955840806 100644 --- a/tests/test_session_runtime_key_classification.py +++ b/tests/test_session_runtime_key_classification.py @@ -2,14 +2,31 @@ from __future__ import annotations +import ast +from collections import defaultdict +from collections.abc import Iterator, Mapping +import io +from pathlib import Path +import tokenize +from types import MappingProxyType +from typing import cast + import pytest +from loopx.canary.maintainability_ratchet import ( + DECISION_POINT_LIMIT, + DECISION_STATEMENT_LIMIT, + _FunctionMetrics, + _iter_functions, +) from loopx.control_plane.runtime.session_runtime import ( compact_session_runtime_readonly_projection, ) from loopx.session_runtime import ( + KeyClassification, KeyState, RawMaterialCategory, + SOURCE_ID_KEYS, build_session_runtime_readonly_projection, classify_session_runtime_key, ) @@ -224,3 +241,201 @@ def test_compaction_keeps_typed_boundary_fields_bounded() -> None: assert boundary["raw_material_key_names"] == ["api_key", "raw_transcript"] assert boundary["raw_material_categories"] == ["credential", "transcript"] assert len(boundary["unclassified_key_names"]) == 8 + + +def _ast_any_count(source: str) -> int: + tree = ast.parse(source) + return 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.ImportFrom) + and any(alias.name == "Any" for alias in node.names) + ) + ) + + +def _comment_ignore_or_noqa_count(source: str) -> int: + tokens = tokenize.generate_tokens(io.StringIO(source).readline) + return sum( + 1 + for tok in tokens + if tok.type == tokenize.COMMENT + and ("type: ignore" in tok.string or "noqa" in tok.string) + ) + + +def test_session_runtime_zero_any_size_and_complexity_contract() -> None: + repo_root = Path(__file__).resolve().parents[1] + sr_path = repo_root / "loopx" / "session_runtime.py" + for path in (sr_path, Path(__file__)): + source = path.read_text(encoding="utf-8") + assert _ast_any_count(source) == 0, path + assert _comment_ignore_or_noqa_count(source) == 0, path + + lines = sr_path.read_text(encoding="utf-8").splitlines() + assert len(lines) <= 550 + assert "session_id" in SOURCE_ID_KEYS + assert classify_session_runtime_key("status") == KeyClassification(KeyState.COMPACT) + + tree = ast.parse(sr_path.read_text(encoding="utf-8")) + for qname, fn in _iter_functions(tree.body): + metrics = _FunctionMetrics(fn) + metrics.visit(fn) + assert metrics.statement_count <= DECISION_STATEMENT_LIMIT, qname + assert metrics.decision_points <= DECISION_POINT_LIMIT, qname + + +def test_projection_filters_non_mappings_reads_mappingproxy_and_dedups_repeated_keys() -> None: + proxy_session = MappingProxyType( + { + "session_id": "s1", + "created_at": "2026-01-01T00:00:00Z", + "next_action": "advance step", + "opaque_extra": "v1", + } + ) + proxy_event_a = MappingProxyType( + { + "event_id": "e1", + "event_at": "2026-01-01T00:01:00Z", + "opaque_extra": "v2", + } + ) + proxy_event_b = MappingProxyType( + { + "event_id": "e2", + "updated_at": "2026-01-01T00:02:00Z", + "opaque_extra": "v3", + } + ) + payload = build_session_runtime_readonly_projection( + goal_id="g-proxy", + sessions=[cast(Mapping[str, object], "malformed-entry"), proxy_session], + ) + assert payload["source"]["source_refs"]["sessions"] == [ + {"kind": "session", "session_id": "s1"} + ] + assert payload["boundary"]["unclassified_key_names"] == ["opaque_extra"] + assert payload["first_screen"]["agent_can_continue"] is True + + repeated = build_session_runtime_readonly_projection( + goal_id="g-repeat", + sessions=[proxy_session], + events=[proxy_event_a, proxy_event_b], + ) + assert repeated["source"]["latest_fact_at"] == "2026-01-01T00:02:00Z" + assert repeated["boundary"]["unclassified_key_names"] == ["opaque_extra"] + + +def test_gate_blocker_validation_and_empty_text_precedence() -> None: + blocked_without_todo = build_session_runtime_readonly_projection( + goal_id="g-blocker", + gates=[ + {"gate_id": "g-adv", "status": "open", "actor": "human", "advisory": True}, + {"gate_id": "g-nonblock", "status": "pending", "actor": "user", "blocking": False}, + {"gate_id": "g-blocker", "kind": "blocker", "status": "failed", "blocker": "disk full"}, + ], + ) + assert blocked_without_todo["first_screen"]["waiting_on"] == "runtime" + assert blocked_without_todo["first_screen"]["user_action_required"] is False + assert blocked_without_todo["first_screen"]["latest_blocker"] == "disk full" + assert blocked_without_todo["work_lane_contract"]["lane"] == "blocker" + assert blocked_without_todo["attention_item"]["priority"] == "P0" + + empty_text_gate = build_session_runtime_readonly_projection( + goal_id="g-empty-gate", + gates=[ + { + "gate_id": "g-open", + "status": "pending", + "requires_human_decision": True, + "actor": "bot_router", + } + ], + decision_results=[{"recommended_action": "continue"}], + ) + assert empty_text_gate["first_screen"]["waiting_on"] == "operator" + assert empty_text_gate["first_screen"]["user_action_required"] is True + assert empty_text_gate["first_screen"]["first_user_todo"] is None + assert empty_text_gate["first_screen"]["first_agent_todo"] is None + assert empty_text_gate["first_screen"]["recommended_action"] is None + assert empty_text_gate["attention_item"]["title"] is None + assert empty_text_gate["work_lane_contract"]["lane"] == "user_gate" + + +class _LazyCachingSessionMapping(Mapping[str, object]): + """Test Mapping that materializes missing action keys on lookup if probed directly.""" + + def __init__(self, initial: Mapping[str, object]) -> None: + self._data: dict[str, object] = dict(initial) + self.probed_keys: list[str] = [] + + def __getitem__(self, key: str) -> object: + self.probed_keys.append(key) + if key not in self._data and key in ("recommended_action", "agent_next_action", "next_action", "handoff", "summary"): + self._data[key] = f"synthesized:{key}" + return self._data[key] + + def __iter__(self) -> Iterator[str]: + return iter(tuple(self._data)) + + def __len__(self) -> int: + return len(self._data) + + +class _LazyGetDict(dict[str, object]): + """Test dict subclass whose .get() lazily caches recommended_action if called.""" + + def get(self, key: str, default: object = None) -> object: + if key not in self and key == "recommended_action": + self[key] = "synthesized:get" + return super().get(key, default) + + +def test_lazy_mapping_preserves_enumerated_key_snapshot_and_input_invariance() -> None: + base_record: dict[str, object] = {"session_id": "s-idle"} + lazy_session = _LazyCachingSessionMapping(base_record) + lazy_proxy = MappingProxyType(_LazyCachingSessionMapping(base_record)) + lazy_subdict: defaultdict[str, object] = defaultdict(lambda: "synthesized", base_record) + lazy_get_dict = _LazyGetDict(base_record) + lazy_decision = _LazyCachingSessionMapping({"ref_id": "d-idle"}) + static_proxy = MappingProxyType({"session_id": "s-idle"}) + static_decision_proxy = MappingProxyType({"ref_id": "d-idle"}) + + expected = build_session_runtime_readonly_projection( + goal_id="g-lazy", + sessions=[static_proxy], + ) + assert expected["first_screen"]["recommended_action"] == "monitor for a material transition" + assert expected["first_screen"]["agent_can_continue"] is False + assert expected["work_lane_contract"]["lane"] == "monitor" + assert expected["work_lane_contract"]["must_attempt_work"] is False + + for candidate in (base_record, lazy_session, lazy_proxy, lazy_subdict, lazy_get_dict): + projected = build_session_runtime_readonly_projection( + goal_id="g-lazy", + sessions=[candidate], + ) + assert projected == expected + + multi_group_expected = build_session_runtime_readonly_projection( + goal_id="g-lazy", + sessions=[static_proxy], + decision_results=[static_decision_proxy], + ) + multi_group_actual = build_session_runtime_readonly_projection( + goal_id="g-lazy", + sessions=[_LazyCachingSessionMapping(base_record)], + decision_results=[lazy_decision], + ) + assert multi_group_actual == multi_group_expected + assert lazy_session.probed_keys == ["session_id"] + assert lazy_decision.probed_keys == ["ref_id"] + assert dict(lazy_session) == {"session_id": "s-idle"} + assert dict(lazy_decision) == {"ref_id": "d-idle"} + assert dict(lazy_subdict) == {"session_id": "s-idle"} + assert dict(lazy_get_dict) == {"session_id": "s-idle"} + assert list(lazy_proxy.keys()) == ["session_id"]