diff --git a/loopx/chat/lark_api.py b/loopx/chat/lark_api.py index fada4e57ea..032604f417 100644 --- a/loopx/chat/lark_api.py +++ b/loopx/chat/lark_api.py @@ -358,8 +358,8 @@ def session_matches( "executor_endpoint_source": executor_endpoint_source, "manager_channel_id": expected_channel, **( - {"connector": dict(binding["connector"])} - if isinstance(binding.get("connector"), Mapping) + {"connector": dict(connector)} + if isinstance((connector := binding.get("connector")), Mapping) else {} ), } @@ -690,7 +690,8 @@ def _lark_connect(self) -> None: if connection_id else None ) - stored_routing = (stored or {}).get("routing") or {} + raw_stored_routing = (stored or {}).get("routing") + stored_routing = raw_stored_routing if isinstance(raw_stored_routing, Mapping) else {} conversation_kind = ( _compact_text(body.get("conversation_kind"), limit=40) or stored_routing.get("conversation_kind") diff --git a/loopx/extensions/lark/goal_channel_contracts.py b/loopx/extensions/lark/goal_channel_contracts.py index e560c2a659..022c572240 100644 --- a/loopx/extensions/lark/goal_channel_contracts.py +++ b/loopx/extensions/lark/goal_channel_contracts.py @@ -1,34 +1,58 @@ +"""Binding persistence, routing enums, and public packet helpers for Lark Goal Channel.""" + from __future__ import annotations import hashlib import inspect import json -from collections.abc import Mapping +from collections.abc import Callable, Mapping from contextlib import nullcontext from datetime import datetime, timezone from enum import Enum from functools import wraps from pathlib import Path -from typing import Any, Callable, ParamSpec, TypeVar +from typing import ParamSpec, TypeVar, cast from ...control_plane.runtime.public_safety import public_safe_compact_text -from ...registry import registry_goals from ...file_lock import exclusive_file_lock +from ...registry import registry_goals +from .goal_channel_gate_contracts import ( + BLOCKED_NOTICE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION as BLOCKED_NOTICE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION, + BLOCKED_NOTICE_AUTO_NOTIFY_SETTING as BLOCKED_NOTICE_AUTO_NOTIFY_SETTING, + BLOCKED_NOTICE_RETIRED_STATES as BLOCKED_NOTICE_RETIRED_STATES, + DEFAULT_GATE_COOLDOWN_SECONDS as DEFAULT_GATE_COOLDOWN_SECONDS, + HUMAN_GATE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION as HUMAN_GATE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION, + HUMAN_GATE_AUTO_NOTIFY_SETTING as HUMAN_GATE_AUTO_NOTIFY_SETTING, + BlockedNoticeReceiptState as BlockedNoticeReceiptState, + _gate_notice_projection as _gate_notice_projection, + _quota_human_gate_items as _quota_human_gate_items, + blocked_notice_auto_notify_enabled as blocked_notice_auto_notify_enabled, + blocked_notice_auto_notify_marker_enabled as blocked_notice_auto_notify_marker_enabled, + blocked_notice_auto_notify_marker_path as blocked_notice_auto_notify_marker_path, + blocked_notice_receipt_matches_target as blocked_notice_receipt_matches_target, + clear_blocked_notice_auto_notify_marker as clear_blocked_notice_auto_notify_marker, + clear_human_gate_auto_notify_marker as clear_human_gate_auto_notify_marker, + human_gate_auto_notify_enabled as human_gate_auto_notify_enabled, + human_gate_auto_notify_marker_enabled as human_gate_auto_notify_marker_enabled, + human_gate_auto_notify_marker_path as human_gate_auto_notify_marker_path, + notification_request_snapshot as notification_request_snapshot, + quota_human_gate_identity as quota_human_gate_identity, + quota_human_gate_notification_suppressed as quota_human_gate_notification_suppressed, + quota_human_gate_reminder_generation as quota_human_gate_reminder_generation, + quota_human_gate_state_generation as quota_human_gate_state_generation, + quota_selects_human_gate as quota_selects_human_gate, + semantic_key as semantic_key, + write_blocked_notice_auto_notify_marker as write_blocked_notice_auto_notify_marker, + write_human_gate_auto_notify_marker as write_human_gate_auto_notify_marker, +) from .private_json import write_private_json_atomic +Payload = dict[str, object] +PayloadView = Mapping[str, object] GOAL_CHANNEL_BINDING_SCHEMA_VERSION = "loopx_goal_channel_lark_binding_v0" GOAL_CHANNEL_OPERATION_SCHEMA_VERSION = "loopx_goal_channel_operation_v0" GOAL_CHANNEL_CONNECTION_SET_SCHEMA_VERSION = "loopx_goal_channel_connection_set_v0" -# Compatibility export for older callers. Scheduler-projected reminder windows -# now own repeat-notification timing. -DEFAULT_GATE_COOLDOWN_SECONDS = 3600 -HUMAN_GATE_AUTO_NOTIFY_SETTING = "human_gate_auto_notify_enabled" -BLOCKED_NOTICE_AUTO_NOTIFY_SETTING = "blocked_notice_auto_notify_enabled" -BLOCKED_NOTICE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION = "loopx_goal_channel_blocked_notice_marker_v0" -HUMAN_GATE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION = ( - "loopx_goal_channel_auto_notify_marker_v0" -) PRIVATE_PACKET_KEYS = { "base_token", "chat_id", @@ -41,40 +65,6 @@ } - -class BlockedNoticeReceiptState(str, Enum): - """Provider delivery lifecycle; it does not mutate canonical Todo state.""" - - PENDING = "pending" - SENT_UNVERIFIED = "sent_unverified" - DELIVERED = "delivered" - RESUMED = "resumed" - RESOLVED = "resolved" - SUPERSEDED = "superseded" - - -BLOCKED_NOTICE_RETIRED_STATES = frozenset({ - BlockedNoticeReceiptState.RESUMED, - BlockedNoticeReceiptState.RESOLVED, - BlockedNoticeReceiptState.SUPERSEDED, -}) - - -def blocked_notice_receipt_matches_target( - key: str, receipt: Mapping[str, Any], *, goal_id: str, chat_id: str, -) -> bool: - if not chat_id or receipt.get("kind") != "blocked_notice": - return False - if receipt.get("chat_id"): - return receipt["chat_id"] == chat_id - # Older initial receipts encode the destination in their semantic key. - # An unbound historical/reopened receipt cannot prove this target's delivery. - return key == semantic_key( - goal_id, "lark", "blocked_notice", str(receipt.get("blocker_identity") or ""), - str(receipt.get("blocker_revision") or ""), chat_id, - ) - - class LarkTopicEventDecisionReason(str, Enum): """Typed, content-free outcome of Goal Topic routing.""" @@ -99,7 +89,7 @@ class LarkTopicEventDecisionReason(str, Enum): } -def normalize_lark_topic_event_rejection_reason(value: Any) -> str | None: +def normalize_lark_topic_event_rejection_reason(value: object) -> str | None: normalized = str(value or "").strip() return normalized if normalized in LARK_TOPIC_EVENT_REJECTION_REASONS else None @@ -138,51 +128,33 @@ def serialized(*args: _P.args, **kwargs: _P.kwargs) -> _R: def default_goal_channel_binding_path(registry_path: Path) -> Path: expanded = registry_path.expanduser().resolve() if expanded.parent.name != ".loopx": - raise ValueError( - "Goal Channel default binding requires a project source registry" - ) + raise ValueError("Goal Channel default binding requires a project source registry") return expanded.parent / "goal-channel.json" -def read_goal_channel_binding(path: Path) -> dict[str, Any]: +def read_goal_channel_binding(path: Path) -> Payload: binding_path = path.expanduser() if not binding_path.exists(): - return { - "schema_version": GOAL_CHANNEL_BINDING_SCHEMA_VERSION, - "bindings": {}, - } + return {"schema_version": GOAL_CHANNEL_BINDING_SCHEMA_VERSION, "bindings": {}} payload = json.loads(binding_path.read_text(encoding="utf-8")) if not isinstance(payload, dict): raise ValueError("Goal Channel binding root must be a JSON object") if payload.get("schema_version") != GOAL_CHANNEL_BINDING_SCHEMA_VERSION: - raise ValueError( - f"Goal Channel binding must use {GOAL_CHANNEL_BINDING_SCHEMA_VERSION}" - ) - bindings = payload.get("bindings") - if not isinstance(bindings, dict): + raise ValueError(f"Goal Channel binding must use {GOAL_CHANNEL_BINDING_SCHEMA_VERSION}") + if not isinstance(payload.get("bindings"), dict): raise ValueError("Goal Channel binding requires an object `bindings`") - return payload + return cast(Payload, payload) -def write_goal_channel_binding( - path: Path, - payload: Mapping[str, Any], -) -> None: - binding_path = path.expanduser() - write_private_json_atomic(binding_path, payload) +def write_goal_channel_binding(path: Path, payload: PayloadView) -> None: + write_private_json_atomic(path.expanduser(), dict(payload) if not isinstance(payload, dict) else payload) -def goal_from_registry( - registry: Mapping[str, Any], - goal_id: str, -) -> dict[str, Any]: +def goal_from_registry(registry: PayloadView, goal_id: str) -> Payload: safe_goal_id = str(goal_id or "").strip() + registry_dict = cast(Payload, registry) if isinstance(registry, dict) else dict(registry) match = next( - ( - dict(goal) - for goal in registry_goals(dict(registry)) - if str(goal.get("id") or "") == safe_goal_id - ), + (dict(goal) for goal in registry_goals(registry_dict) if str(goal.get("id") or "") == safe_goal_id), None, ) if match is None: @@ -197,24 +169,56 @@ def goal_channel_connection_id(goal_id: str, agent_id: str | None) -> str: return f"lark_{digest}" +def _stored_goal_entry(payload: PayloadView, goal_id: str) -> PayloadView | None: + bindings = payload.get("bindings") + stored = bindings.get(goal_id) if isinstance(bindings, Mapping) else None + return cast(PayloadView, stored) if isinstance(stored, Mapping) else None + + +def _resolve_goal_binding( + binding: PayloadView, + *, + provider_target: PayloadView | None, + copy: bool = True, +) -> Payload: + resolved = dict(binding) if copy or not isinstance(binding, dict) else cast(Payload, binding) + target_ref = str(resolved.get("target_ref") or "") + if not target_ref or provider_target is None: + return resolved + if str(provider_target.get("name") or "") != target_ref: + raise ValueError("Goal Channel provider target does not match target_ref") + if str(provider_target.get("provider") or "") != str(resolved.get("provider") or ""): + raise ValueError("Goal Channel provider target does not match provider") + target_channel = provider_target.get("channel") + target_identity = provider_target.get("identity") + if not isinstance(target_channel, Mapping) or not isinstance(target_identity, Mapping): + raise ValueError("Goal Channel provider target is incomplete") + raw_channel = resolved.get("channel") + binding_channel = raw_channel if isinstance(raw_channel, Mapping) else {} + pinned_id = binding_channel.get("pinned_message_id") + resolved["channel"] = { + **dict(cast(PayloadView, target_channel)), + **({"pinned_message_id": pinned_id} if pinned_id else {}), + } + resolved["identity"] = dict(cast(PayloadView, target_identity)) + return resolved + + def bindings_for_goal( - payload: Mapping[str, Any], + payload: PayloadView, goal_id: str, *, - provider_target: Mapping[str, Any] | None = None, -) -> list[dict[str, Any]]: - bindings = payload.get("bindings") - stored = bindings.get(goal_id) if isinstance(bindings, Mapping) else None - if not isinstance(stored, Mapping): + provider_target: PayloadView | None = None, +) -> list[Payload]: + stored = _stored_goal_entry(payload, goal_id) + if stored is None: return [] raw_connections = stored.get("connections") - if stored.get( - "schema_version" - ) == GOAL_CHANNEL_CONNECTION_SET_SCHEMA_VERSION and isinstance( + if stored.get("schema_version") == GOAL_CHANNEL_CONNECTION_SET_SCHEMA_VERSION and isinstance( raw_connections, Mapping ): candidates = [ - {**dict(item), "connection_id": str(connection_id)} + {**dict(cast(PayloadView, item)), "connection_id": str(connection_id)} for connection_id, item in raw_connections.items() if isinstance(item, Mapping) ] @@ -227,386 +231,81 @@ def bindings_for_goal( ), } ] - return [ - _resolve_goal_binding(candidate, provider_target=provider_target) - for candidate in candidates - ] + return [_resolve_goal_binding(candidate, provider_target=provider_target, copy=False) for candidate in candidates] -def _resolve_goal_binding( - binding: Mapping[str, Any], +def _select_connection_set_binding( + stored: PayloadView, + raw_connections: Mapping[object, object], *, - provider_target: Mapping[str, Any] | None, -) -> dict[str, Any]: - resolved = dict(binding) - target_ref = str(resolved.get("target_ref") or "") - if not target_ref or provider_target is None: - return resolved - if str(provider_target.get("name") or "") != target_ref: - raise ValueError("Goal Channel provider target does not match target_ref") - if str(provider_target.get("provider") or "") != str( - resolved.get("provider") or "" - ): - raise ValueError("Goal Channel provider target does not match provider") - target_channel = provider_target.get("channel") - target_identity = provider_target.get("identity") - if not isinstance(target_channel, Mapping) or not isinstance( - target_identity, Mapping - ): - raise ValueError("Goal Channel provider target is incomplete") - binding_channel = resolved.get("channel") - binding_channel = ( - dict(binding_channel) if isinstance(binding_channel, Mapping) else {} - ) - resolved["channel"] = { - **dict(target_channel), - **( - {"pinned_message_id": binding_channel["pinned_message_id"]} - if binding_channel.get("pinned_message_id") - else {} - ), - } - resolved["identity"] = dict(target_identity) - return resolved + agent_id: str | None, + connection_id: str | None, +) -> Payload | None: + if connection_id: + item = raw_connections.get(connection_id) + if not isinstance(item, Mapping): + return None + return {**dict(cast(PayloadView, item)), "connection_id": str(connection_id)} + if agent_id is not None: + for cid, item in raw_connections.items(): + if isinstance(item, Mapping) and item.get("agent_id") == agent_id: + return {**dict(cast(PayloadView, item)), "connection_id": str(cid)} + return None + default_id = str(stored.get("default_connection_id") or "") + if default_id: + default_item = raw_connections.get(default_id) + if isinstance(default_item, Mapping): + return {**dict(cast(PayloadView, default_item)), "connection_id": default_id} + best_cid: str | None = None + best_item: PayloadView | None = None + for cid, item in raw_connections.items(): + if not isinstance(item, Mapping): + continue + cid_text = str(cid) + if best_cid is None or cid_text < best_cid: + best_cid = cid_text + best_item = cast(PayloadView, item) + return {**dict(best_item), "connection_id": best_cid} if best_item is not None and best_cid is not None else None def binding_for_goal( - payload: Mapping[str, Any], + payload: PayloadView, goal_id: str, *, - provider_target: Mapping[str, Any] | None = None, + provider_target: PayloadView | None = None, agent_id: str | None = None, connection_id: str | None = None, -) -> dict[str, Any] | None: +) -> Payload | None: # Select one raw connection before resolving its provider target. A target # belongs to one connection; applying it to every sibling lets an unrelated # Agent's target invalidate the requested Agent's otherwise valid binding. - candidates = bindings_for_goal(payload, goal_id) - selected: dict[str, Any] | None = None - if connection_id: - selected = next( - (item for item in candidates if item.get("connection_id") == connection_id), - None, - ) - elif agent_id is not None: - selected = next( - (item for item in candidates if item.get("agent_id") == agent_id), - None, - ) - else: - bindings = payload.get("bindings") - stored = bindings.get(goal_id) if isinstance(bindings, Mapping) else None - default_id = ( - str(stored.get("default_connection_id") or "") - if isinstance(stored, Mapping) - else "" - ) - if default_id: - selected = next( - ( - item - for item in candidates - if item.get("connection_id") == default_id - ), - None, - ) - if selected is None and candidates: - # Keep the invalid-default fallback aligned with the writer in - # _without_goal_topic_connection, which promotes min(connection_id). - selected = min( - candidates, - key=lambda item: str(item.get("connection_id") or ""), - ) - return ( - _resolve_goal_binding(selected, provider_target=provider_target) - if selected is not None - else None - ) - - -def human_gate_auto_notify_enabled(binding: Mapping[str, Any] | None) -> bool: - automation = ( - binding.get("automation") - if isinstance(binding, Mapping) - and isinstance(binding.get("automation"), Mapping) - else {} - ) - return automation.get(HUMAN_GATE_AUTO_NOTIFY_SETTING) is True - - -def blocked_notice_auto_notify_enabled(binding: Mapping[str, Any] | None) -> bool: - automation = ( - binding.get("automation") - if isinstance(binding, Mapping) - and isinstance(binding.get("automation"), Mapping) - else {} - ) - return automation.get(BLOCKED_NOTICE_AUTO_NOTIFY_SETTING) is True - - -def human_gate_auto_notify_marker_path( - binding_path: Path, - goal_id: str, -) -> Path: - safe_goal_id = str(goal_id or "").strip() - if ( - not safe_goal_id - or safe_goal_id in {".", ".."} - or "/" in safe_goal_id - or "\\" in safe_goal_id - ): - raise ValueError("Goal Channel goal id must be a single path segment") - return binding_path.with_name( - f"{binding_path.stem}.{safe_goal_id}.human-gate-auto-notify.json" - ) - - -def human_gate_auto_notify_marker_enabled(path: Path) -> bool: - marker_path = path.expanduser() - if not marker_path.exists(): - return False - try: - payload = json.loads(marker_path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return True - return bool( - isinstance(payload, Mapping) - and payload.get("schema_version") - == HUMAN_GATE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION - and payload.get("enabled") is True - ) - - -def write_human_gate_auto_notify_marker(path: Path) -> None: - write_private_json_atomic( - path, - { - "schema_version": HUMAN_GATE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION, - "enabled": True, - }, - ) - - -def clear_human_gate_auto_notify_marker(path: Path) -> None: - path.expanduser().unlink(missing_ok=True) - - -def blocked_notice_auto_notify_marker_path(binding_path: Path, goal_id: str) -> Path: - human_marker = human_gate_auto_notify_marker_path(binding_path, goal_id) - return human_marker.with_name( - human_marker.name.replace( - ".human-gate-auto-notify.json", ".blocked-notice-auto-notify.json" - ) - ) - - -def blocked_notice_auto_notify_marker_enabled(path: Path) -> bool: - marker_path = path.expanduser() - if not marker_path.exists(): - return False - try: - payload = json.loads(marker_path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - # A damaged enabled marker must leave the sink visibly failed. - return True - return bool( - isinstance(payload, Mapping) - and payload.get("schema_version") - == BLOCKED_NOTICE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION - and payload.get("enabled") is True - ) - - -def write_blocked_notice_auto_notify_marker(path: Path) -> None: - write_private_json_atomic( - path, - { - "schema_version": BLOCKED_NOTICE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION, - "enabled": True, - }, - ) - - -def clear_blocked_notice_auto_notify_marker(path: Path) -> None: - path.expanduser().unlink(missing_ok=True) - - -def quota_human_gate_identity(quota_packet: Mapping[str, Any]) -> str: - summary = quota_packet.get("user_todo_summary") - summary = summary if isinstance(summary, Mapping) else {} - for key in ("gate_open_items", "first_open_items"): - items = summary.get(key) - if not isinstance(items, list): - continue - for item in items: - if not isinstance(item, Mapping): - continue - identity = str(item.get("todo_id") or item.get("gate_id") or "").strip() - if identity: - return identity - return str( - quota_packet.get("gate_id") - or quota_packet.get("operator_gate_id") - or "unidentified_gate" - ).strip() - - -def _quota_human_gate_items( - quota_packet: Mapping[str, Any], -) -> list[dict[str, Any]]: - summary = quota_packet.get("user_todo_summary") - summary = summary if isinstance(summary, Mapping) else {} - for key in ("gate_open_items", "first_open_items"): - raw_items = summary.get(key) - if not isinstance(raw_items, list): - continue - items = [dict(item) for item in raw_items if isinstance(item, Mapping)] - if items: - return items[:3] - return [] - - -def notification_request_snapshot(status: Mapping[str, Any], goal_id: str) -> dict[str, Any]: - """Adapt the existing complete same-read Goal Todo projection for transport. - - This never admits requests: the shared TS owner joins only already selected - quota IDs and verifies their version/lifecycle before taking display fields. - """ - queue = status.get("attention_queue") or {} - rows = [row for row in queue.get("items", []) - if isinstance(row, Mapping) and row.get("goal_id") == goal_id] - summary = (rows[0].get("user_todos") or {}) if len(rows) == 1 else {} - return {"goal_id": goal_id, "items": summary.get("items", [])} - - -def quota_human_gate_state_generation( - quota_packet: Mapping[str, Any], -) -> str: - """Fingerprint the material state of the currently projected human gate.""" - - material_items = [] - for item in _quota_human_gate_items(quota_packet): - material_items.append( - { - key: item.get(key) - for key in ( - "todo_id", - "gate_id", - "status", - "task_class", - "updated_at", - "material_change_generation", - "decision_scope", - "decision_outcome", - "blocks_agent", - "global_gate", - "unblocks_todo_id", - ) - if item.get(key) is not None - } - ) - text = public_safe_compact_text( - item.get("text") or item.get("title"), - limit=300, - ) - if text: - material_items[-1]["text"] = text - material: dict[str, Any] = { - "gate_identity": quota_human_gate_identity(quota_packet), - "items": material_items, - } - if "request_snapshot" in quota_packet: - # Delivery idempotency must cover the complete selected display body, - # not only the first 180/300 characters of a scheduling label. - material["request_content"] = _gate_notice_projection( - quota_packet=quota_packet, goal_id=str(quota_packet.get("goal_id") or ""), - ) - if not material_items: - material["state"] = str(quota_packet.get("state") or "") - material["question"] = public_safe_compact_text( - quota_packet.get("gate_prompt") - or quota_packet.get("operator_question") - or quota_packet.get("reason"), - limit=900, - ) - return semantic_key( - "human_gate_state_v0", - json.dumps( - material, - ensure_ascii=False, - sort_keys=True, - separators=(",", ":"), - ), - ) - - -def quota_human_gate_reminder_generation( - quota_packet: Mapping[str, Any], -) -> str | None: - cooldown = quota_packet.get("user_gate_notification_cooldown") - if ( - not isinstance(cooldown, Mapping) - or cooldown.get("notification_due") is not True - ): + stored = _stored_goal_entry(payload, goal_id) + if stored is None: return None - reminder_identity = { - key: cooldown.get(key) - for key in ( - "policy", - "failed_at", - "next_reminder_at", - "cooldown_minutes", - "reminder_window_minutes", + raw_connections = stored.get("connections") + if stored.get("schema_version") == GOAL_CHANNEL_CONNECTION_SET_SCHEMA_VERSION and isinstance( + raw_connections, Mapping + ): + selected = _select_connection_set_binding( + stored, raw_connections, agent_id=agent_id, connection_id=connection_id ) - if cooldown.get(key) is not None - } - return semantic_key( - "human_gate_reminder_v0", - json.dumps( - reminder_identity, - ensure_ascii=False, - sort_keys=True, - separators=(",", ":"), - ), - ) - - -def quota_human_gate_notification_suppressed( - quota_packet: Mapping[str, Any], -) -> bool: - cooldown = quota_packet.get("user_gate_notification_cooldown") - return bool( - isinstance(cooldown, Mapping) - and cooldown.get("notification_suppressed") is True - ) - - -def quota_selects_human_gate(quota_packet: Mapping[str, Any]) -> bool: - if quota_human_gate_notification_suppressed(quota_packet): - return False - interaction = quota_packet.get("interaction_contract") - if isinstance(interaction, Mapping): - user_channel = interaction.get("user_channel") - if isinstance(user_channel, Mapping): - if user_channel.get("notify") != "NOTIFY": - return False - if user_channel.get("action_required") is True or bool( - user_channel.get("actions") - ): - return True - return bool( - quota_packet.get("state") == "operator_gate" - or quota_packet.get("notify_user_on_gate") is True - or quota_packet.get("notify_user_on_open_todo") is True - ) + else: + cid = goal_channel_connection_id(goal_id, str(stored.get("agent_id") or "") or None) + if connection_id and cid != connection_id: + selected = None + elif connection_id is None and agent_id is not None and stored.get("agent_id") != agent_id: + selected = None + else: + selected = {**dict(stored), "connection_id": cid} + return _resolve_goal_binding(selected, provider_target=provider_target, copy=False) if selected is not None else None def save_goal_binding( *, binding_path: Path, - payload: Mapping[str, Any], + payload: PayloadView, goal_id: str, - binding: Mapping[str, Any], + binding: PayloadView, ) -> None: """Compatibility writer for the Goal's explicit default connection. @@ -614,73 +313,55 @@ def save_goal_binding( route. Preserve peer Agent routes when the Goal has migrated to a connection set instead of collapsing the set back to v0. """ - bindings = payload.get("bindings") - stored = bindings.get(goal_id) if isinstance(bindings, Mapping) else None - if ( - isinstance(stored, Mapping) - and stored.get("schema_version") == GOAL_CHANNEL_CONNECTION_SET_SCHEMA_VERSION - ): + stored = _stored_goal_entry(payload, goal_id) + if stored is not None and stored.get("schema_version") == GOAL_CHANNEL_CONNECTION_SET_SCHEMA_VERSION: save_goal_connection( binding_path=binding_path, payload=payload, goal_id=goal_id, - binding={ - **dict(binding), - "connection_id": str(stored.get("default_connection_id") or ""), - }, + binding={**dict(binding), "connection_id": str(stored.get("default_connection_id") or "")}, make_default=True, ) return - mutable_bindings = dict(bindings) if isinstance(bindings, Mapping) else {} + raw_bindings = payload.get("bindings") + mutable_bindings: Payload = dict(cast(PayloadView, raw_bindings)) if isinstance(raw_bindings, Mapping) else {} mutable_bindings[goal_id] = dict(binding) write_goal_channel_binding( binding_path, - { - "schema_version": GOAL_CHANNEL_BINDING_SCHEMA_VERSION, - "bindings": mutable_bindings, - }, + {"schema_version": GOAL_CHANNEL_BINDING_SCHEMA_VERSION, "bindings": mutable_bindings}, ) def save_goal_connection( *, binding_path: Path, - payload: Mapping[str, Any], + payload: PayloadView, goal_id: str, - binding: Mapping[str, Any], + binding: PayloadView, make_default: bool = False, ) -> str: """Upsert one Agent route while retaining v0 single-binding read compatibility.""" - connection_id = str( - binding.get("connection_id") or "" - ) or goal_channel_connection_id( - goal_id, - str(binding.get("agent_id") or "") or None, + connection_id = str(binding.get("connection_id") or "") or goal_channel_connection_id( + goal_id, str(binding.get("agent_id") or "") or None ) all_bindings = payload.get("bindings") - mutable_bindings = dict(all_bindings) if isinstance(all_bindings, Mapping) else {} + mutable_bindings: Payload = dict(cast(PayloadView, all_bindings)) if isinstance(all_bindings, Mapping) else {} stored = mutable_bindings.get(goal_id) if ( isinstance(stored, Mapping) and stored.get("schema_version") == GOAL_CHANNEL_CONNECTION_SET_SCHEMA_VERSION and isinstance(stored.get("connections"), Mapping) ): - connections = dict(stored["connections"]) + connections: Payload = dict(cast(PayloadView, stored["connections"])) default_id = str(stored.get("default_connection_id") or "") else: connections = {} default_id = "" if isinstance(stored, Mapping): - legacy_id = goal_channel_connection_id( - goal_id, - str(stored.get("agent_id") or "") or None, - ) - connections[legacy_id] = dict(stored) + legacy_id = goal_channel_connection_id(goal_id, str(stored.get("agent_id") or "") or None) + connections[legacy_id] = dict(cast(PayloadView, stored)) default_id = legacy_id - connections[connection_id] = { - **dict(binding), - "connection_id": connection_id, - } + connections[connection_id] = {**dict(binding), "connection_id": connection_id} if make_default or not default_id: default_id = connection_id mutable_bindings[goal_id] = { @@ -690,21 +371,11 @@ def save_goal_connection( } write_goal_channel_binding( binding_path, - { - "schema_version": GOAL_CHANNEL_BINDING_SCHEMA_VERSION, - "bindings": mutable_bindings, - }, + {"schema_version": GOAL_CHANNEL_BINDING_SCHEMA_VERSION, "bindings": mutable_bindings}, ) return connection_id -def semantic_key(*parts: str) -> str: - digest = hashlib.sha256( - json.dumps(parts, ensure_ascii=False, separators=(",", ":")).encode("utf-8") - ).hexdigest() - return f"sha256:{digest}" - - def provider_idempotency_key(receipt: str) -> str: return f"loopx-{receipt.removeprefix('sha256:')[:32]}" @@ -713,7 +384,7 @@ def now_iso() -> str: return datetime.now(timezone.utc).isoformat() -def parse_time(value: Any) -> datetime | None: +def parse_time(value: object) -> datetime | None: try: parsed = datetime.fromisoformat(str(value or "")) except ValueError: @@ -734,9 +405,9 @@ def operation_packet( idempotency_key: str | None = None, receipt_id: str | None = None, blocker: str | None = None, - details: Mapping[str, Any] | None = None, -) -> dict[str, Any]: - packet: dict[str, Any] = { + details: PayloadView | None = None, +) -> Payload: + packet: Payload = { "schema_version": GOAL_CHANNEL_OPERATION_SCHEMA_VERSION, "ok": ok, "goal_id": goal_id, @@ -759,42 +430,36 @@ def operation_packet( return packet -def assert_public_packet(packet: Mapping[str, Any]) -> None: - from .goal_channel_transport import CHAT_ID_PATTERN, MESSAGE_ID_PATTERN +def assert_public_packet(packet: PayloadView) -> None: + from .identity_shapes import LARK_CHAT_ID_SEARCH, LARK_MESSAGE_ID_SEARCH - def visit(value: Any) -> None: + def visit(value: object) -> None: if isinstance(value, Mapping): for key, child in value.items(): if key in PRIVATE_PACKET_KEYS: - raise ValueError( - f"public Goal Channel packet contains private key `{key}`" - ) + raise ValueError(f"public Goal Channel packet contains private key `{key}`") visit(child) elif isinstance(value, list): for child in value: visit(child) elif isinstance(value, str): - if CHAT_ID_PATTERN.search(value) or MESSAGE_ID_PATTERN.search(value): - raise ValueError( - "public Goal Channel packet contains a private provider id" - ) + if LARK_CHAT_ID_SEARCH.search(value) or LARK_MESSAGE_ID_SEARCH.search(value): + raise ValueError("public Goal Channel packet contains a private provider id") visit(packet) -def goal_objective(goal: Mapping[str, Any]) -> str: - return public_safe_compact_text( - goal.get("objective") or goal.get("description") or goal.get("id"), - limit=300, +def goal_objective(goal: PayloadView) -> str: + return cast( + str, + public_safe_compact_text( + cast(str | None, goal.get("objective") or goal.get("description") or goal.get("id")), + limit=300, + ), ) -def control_message( - *, - goal_id: str, - objective: str, - kanban_url: str, -) -> str: +def control_message(*, goal_id: str, objective: str, kanban_url: str) -> str: lines = [ f"LoopX Goal: {goal_id}", f"Objective: {objective}", @@ -805,37 +470,12 @@ def control_message( return "\n".join(lines) -def _gate_notice_projection( - *, goal_id: str, quota_packet: Mapping[str, Any], -) -> dict[str, Any]: - # Scheduling labels cannot substitute for a decision request body. - from ...control_plane.effect_runtime import effect_runtime_result - - from ...capabilities.manager_context.goal_attention import notice_request_fields - - requests = [] - for item in _quota_human_gate_items(quota_packet): - fields = notice_request_fields(item) - fields["request_id"] = public_safe_compact_text(item.get("todo_id") or item.get("gate_id"), limit=120) - fields["reason"] = fields["note"] - requests.append(fields) - notice_input: dict[str, Any] = {"goal_id": goal_id, "requests": requests} - if "request_snapshot" in quota_packet: - snapshot = quota_packet.get("request_snapshot") or {} - notice_input["request_snapshot"] = { - "goal_id": snapshot.get("goal_id"), - "items": [notice_request_fields(item) for item in snapshot.get("items", []) - if isinstance(item, Mapping)], - } - return dict(effect_runtime_result("presentation.decision_notice.project", notice_input)) - - def reusable_goal_topic_root( - payload: Mapping[str, Any], + payload: PayloadView, goal_id: str, *, connection_id: str, - provider_target: Mapping[str, Any] | None, + provider_target: PayloadView | None, chat_id: str, ) -> str: """Return the established topic root when reconnect may adopt it. @@ -846,35 +486,26 @@ def reusable_goal_topic_root( reader), and its stored root is a well-formed message id for this chat. Anything else returns "" so the caller sends a new topic. """ - - from .goal_channel_transport import MESSAGE_ID_PATTERN + from .identity_shapes import LARK_MESSAGE_ID_PATTERN try: existing = binding_for_goal( payload, goal_id, connection_id=connection_id, + provider_target=provider_target, ) - if existing is not None: - existing = _resolve_goal_binding(existing, provider_target=provider_target) except ValueError: return "" if not existing or existing.get("enabled") is not True: return "" - prior_topic = ( - existing.get("topic") if isinstance(existing.get("topic"), Mapping) else {} - ) - prior_channel = ( - existing.get("channel") if isinstance(existing.get("channel"), Mapping) else {} - ) + raw_topic = existing.get("topic") + prior_topic = raw_topic if isinstance(raw_topic, Mapping) else {} + raw_channel = existing.get("channel") + prior_channel = raw_channel if isinstance(raw_channel, Mapping) else {} candidate_root = str( - prior_topic.get("root_message_id") - or prior_channel.get("pinned_message_id") - or "" + prior_topic.get("root_message_id") or prior_channel.get("pinned_message_id") or "" ) - if ( - MESSAGE_ID_PATTERN.fullmatch(candidate_root) - and str(prior_channel.get("chat_id") or "") == chat_id - ): + if LARK_MESSAGE_ID_PATTERN.fullmatch(candidate_root) and str(prior_channel.get("chat_id") or "") == chat_id: return candidate_root return "" diff --git a/loopx/extensions/lark/goal_channel_gate_contracts.py b/loopx/extensions/lark/goal_channel_gate_contracts.py new file mode 100644 index 0000000000..e111808c83 --- /dev/null +++ b/loopx/extensions/lark/goal_channel_gate_contracts.py @@ -0,0 +1,365 @@ +"""Human-gate, blocked-notice, and quota projection contracts for Lark Goal Channel.""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping +from enum import Enum +from pathlib import Path +from typing import TypedDict, cast + +from ...control_plane.runtime.public_safety import public_safe_compact_text +from .private_json import write_private_json_atomic + +Payload = dict[str, object] +PayloadView = Mapping[str, object] + + +class GateNoticeProjection(TypedDict, total=False): + goal_id: str + items: list[Payload] + requests: list[Payload] + +# Compatibility export for older callers. Scheduler-projected reminder windows +# now own repeat-notification timing. +DEFAULT_GATE_COOLDOWN_SECONDS = 3600 +HUMAN_GATE_AUTO_NOTIFY_SETTING = "human_gate_auto_notify_enabled" +BLOCKED_NOTICE_AUTO_NOTIFY_SETTING = "blocked_notice_auto_notify_enabled" +BLOCKED_NOTICE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION = ( + "loopx_goal_channel_blocked_notice_marker_v0" +) +HUMAN_GATE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION = "loopx_goal_channel_auto_notify_marker_v0" + +_MATERIAL_ITEM_KEYS: tuple[str, ...] = ( + "todo_id", + "gate_id", + "status", + "task_class", + "updated_at", + "material_change_generation", + "decision_scope", + "decision_outcome", + "blocks_agent", + "global_gate", + "unblocks_todo_id", +) +_REMINDER_IDENTITY_KEYS: tuple[str, ...] = ( + "policy", + "failed_at", + "next_reminder_at", + "cooldown_minutes", + "reminder_window_minutes", +) + + +class BlockedNoticeReceiptState(str, Enum): + """Provider delivery lifecycle; it does not mutate canonical Todo state.""" + + PENDING = "pending" + SENT_UNVERIFIED = "sent_unverified" + DELIVERED = "delivered" + RESUMED = "resumed" + RESOLVED = "resolved" + SUPERSEDED = "superseded" + + +BLOCKED_NOTICE_RETIRED_STATES = frozenset( + { + BlockedNoticeReceiptState.RESUMED, + BlockedNoticeReceiptState.RESOLVED, + BlockedNoticeReceiptState.SUPERSEDED, + } +) + + +def semantic_key(*parts: str) -> str: + digest = hashlib.sha256( + json.dumps(parts, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + ).hexdigest() + return f"sha256:{digest}" + + +def blocked_notice_receipt_matches_target( + key: str, + receipt: PayloadView, + *, + goal_id: str, + chat_id: str, +) -> bool: + if not chat_id or receipt.get("kind") != "blocked_notice": + return False + if receipt.get("chat_id"): + return receipt["chat_id"] == chat_id + # Older initial receipts encode the destination in their semantic key. + # An unbound historical/reopened receipt cannot prove this target's delivery. + return key == semantic_key( + goal_id, + "lark", + "blocked_notice", + str(receipt.get("blocker_identity") or ""), + str(receipt.get("blocker_revision") or ""), + chat_id, + ) + + +def _automation_flag(binding: PayloadView | None, setting: str) -> bool: + automation = ( + binding.get("automation") + if isinstance(binding, Mapping) and isinstance(binding.get("automation"), Mapping) + else None + ) + return isinstance(automation, Mapping) and automation.get(setting) is True + + +def human_gate_auto_notify_enabled(binding: PayloadView | None) -> bool: + return _automation_flag(binding, HUMAN_GATE_AUTO_NOTIFY_SETTING) + + +def blocked_notice_auto_notify_enabled(binding: PayloadView | None) -> bool: + return _automation_flag(binding, BLOCKED_NOTICE_AUTO_NOTIFY_SETTING) + + +def human_gate_auto_notify_marker_path(binding_path: Path, goal_id: str) -> Path: + safe_goal_id = str(goal_id or "").strip() + if ( + not safe_goal_id + or safe_goal_id in {".", ".."} + or "/" in safe_goal_id + or "\\" in safe_goal_id + ): + raise ValueError("Goal Channel goal id must be a single path segment") + return binding_path.with_name(f"{binding_path.stem}.{safe_goal_id}.human-gate-auto-notify.json") + + +def _marker_enabled(path: Path, schema_version: str) -> bool: + marker_path = path.expanduser() + if not marker_path.exists(): + return False + try: + payload = json.loads(marker_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + # A damaged enabled marker must leave the sink visibly failed. + return True + return bool( + isinstance(payload, Mapping) + and payload.get("schema_version") == schema_version + and payload.get("enabled") is True + ) + + +def _write_marker(path: Path, schema_version: str) -> None: + write_private_json_atomic(path, {"schema_version": schema_version, "enabled": True}) + + +def human_gate_auto_notify_marker_enabled(path: Path) -> bool: + return _marker_enabled(path, HUMAN_GATE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION) + + +def write_human_gate_auto_notify_marker(path: Path) -> None: + _write_marker(path, HUMAN_GATE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION) + + +def clear_human_gate_auto_notify_marker(path: Path) -> None: + path.expanduser().unlink(missing_ok=True) + + +def blocked_notice_auto_notify_marker_path(binding_path: Path, goal_id: str) -> Path: + human_marker = human_gate_auto_notify_marker_path(binding_path, goal_id) + return human_marker.with_name( + human_marker.name.replace(".human-gate-auto-notify.json", ".blocked-notice-auto-notify.json") + ) + + +def blocked_notice_auto_notify_marker_enabled(path: Path) -> bool: + return _marker_enabled(path, BLOCKED_NOTICE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION) + + +def write_blocked_notice_auto_notify_marker(path: Path) -> None: + _write_marker(path, BLOCKED_NOTICE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION) + + +def clear_blocked_notice_auto_notify_marker(path: Path) -> None: + path.expanduser().unlink(missing_ok=True) + + +def _summary_gate_items(quota_packet: PayloadView) -> list[PayloadView]: + raw_summary = quota_packet.get("user_todo_summary") + summary = raw_summary if isinstance(raw_summary, Mapping) else None + if summary is None: + return [] + for key in ("gate_open_items", "first_open_items"): + raw_items = summary.get(key) + if not isinstance(raw_items, list): + continue + items = [cast(PayloadView, item) for item in raw_items if isinstance(item, Mapping)] + if items: + return items + return [] + + +def _gate_identity_from_items(quota_packet: PayloadView, items: list[PayloadView]) -> str: + for item in items: + identity = str(item.get("todo_id") or item.get("gate_id") or "").strip() + if identity: + return identity + return str( + quota_packet.get("gate_id") + or quota_packet.get("operator_gate_id") + or "unidentified_gate" + ).strip() + + +def quota_human_gate_identity(quota_packet: PayloadView) -> str: + return _gate_identity_from_items(quota_packet, _summary_gate_items(quota_packet)) + + +def _quota_human_gate_items(quota_packet: PayloadView) -> list[Payload]: + return [dict(item) for item in _summary_gate_items(quota_packet)[:3]] + + +def notification_request_snapshot(status: PayloadView, goal_id: str) -> Payload: + """Adapt the existing complete same-read Goal Todo projection for transport. + + This never admits requests: the shared TS owner joins only already selected + quota IDs and verifies their version/lifecycle before taking display fields. + """ + raw_queue = status.get("attention_queue") + queue = raw_queue if isinstance(raw_queue, Mapping) else {} + raw_items = queue.get("items") + rows = ( + [ + item + for item in raw_items + if isinstance(item, Mapping) and item.get("goal_id") == goal_id + ] + if isinstance(raw_items, list) + else [] + ) + raw_summary = rows[0].get("user_todos") if len(rows) == 1 else None + summary = raw_summary if isinstance(raw_summary, Mapping) else {} + summary_items = summary.get("items", []) + return {"goal_id": goal_id, "items": summary_items} + + +def _gate_notice_projection(*, goal_id: str, quota_packet: PayloadView) -> GateNoticeProjection: + # Scheduling labels cannot substitute for a decision request body. + from ...capabilities.manager_context.goal_attention import notice_request_fields + from ...control_plane.effect_runtime import effect_runtime_result + + requests: list[Payload] = [] + for item in _summary_gate_items(quota_packet)[:3]: + fields = cast(Payload, notice_request_fields(item)) + fields["request_id"] = public_safe_compact_text( + cast(str | None, item.get("todo_id") or item.get("gate_id")), + limit=120, + ) + fields["reason"] = fields["note"] + requests.append(fields) + notice_input: Payload = {"goal_id": goal_id, "requests": requests} + if "request_snapshot" in quota_packet: + raw_snapshot = quota_packet.get("request_snapshot") + snapshot = raw_snapshot if isinstance(raw_snapshot, Mapping) else {} + raw_snapshot_items = snapshot.get("items", []) + snapshot_items = ( + [ + notice_request_fields(item) + for item in raw_snapshot_items + if isinstance(item, Mapping) + ] + if isinstance(raw_snapshot_items, list) + else [] + ) + notice_input["request_snapshot"] = { + "goal_id": snapshot.get("goal_id"), + "items": snapshot_items, + } + return cast( + GateNoticeProjection, + dict( + cast(PayloadView, effect_runtime_result("presentation.decision_notice.project", notice_input)) + ), + ) + + +def quota_human_gate_state_generation(quota_packet: PayloadView) -> str: + """Fingerprint the material state of the currently projected human gate.""" + raw_items = _summary_gate_items(quota_packet) + material_items: list[Payload] = [] + for item in raw_items[:3]: + row: Payload = { + key: item.get(key) + for key in _MATERIAL_ITEM_KEYS + if item.get(key) is not None + } + text = public_safe_compact_text( + cast(str | None, item.get("text") or item.get("title")), + limit=300, + ) + if text: + row["text"] = text + material_items.append(row) + material: Payload = { + "gate_identity": _gate_identity_from_items(quota_packet, raw_items), + "items": material_items, + } + if "request_snapshot" in quota_packet: + # Delivery idempotency must cover the complete selected display body, + # not only the first 180/300 characters of a scheduling label. + material["request_content"] = _gate_notice_projection( + quota_packet=quota_packet, + goal_id=str(quota_packet.get("goal_id") or ""), + ) + if not material_items: + material["state"] = str(quota_packet.get("state") or "") + material["question"] = public_safe_compact_text( + cast( + str | None, + quota_packet.get("gate_prompt") + or quota_packet.get("operator_question") + or quota_packet.get("reason"), + ), + limit=900, + ) + return semantic_key( + "human_gate_state_v0", + json.dumps(material, ensure_ascii=False, sort_keys=True, separators=(",", ":")), + ) + + +def quota_human_gate_reminder_generation(quota_packet: PayloadView) -> str | None: + cooldown = quota_packet.get("user_gate_notification_cooldown") + if not isinstance(cooldown, Mapping) or cooldown.get("notification_due") is not True: + return None + reminder_identity = { + key: cooldown.get(key) + for key in _REMINDER_IDENTITY_KEYS + if cooldown.get(key) is not None + } + return semantic_key( + "human_gate_reminder_v0", + json.dumps(reminder_identity, ensure_ascii=False, sort_keys=True, separators=(",", ":")), + ) + + +def quota_human_gate_notification_suppressed(quota_packet: PayloadView) -> bool: + cooldown = quota_packet.get("user_gate_notification_cooldown") + return bool(isinstance(cooldown, Mapping) and cooldown.get("notification_suppressed") is True) + + +def quota_selects_human_gate(quota_packet: PayloadView) -> bool: + if quota_human_gate_notification_suppressed(quota_packet): + return False + interaction = quota_packet.get("interaction_contract") + if isinstance(interaction, Mapping): + user_channel = interaction.get("user_channel") + if isinstance(user_channel, Mapping): + if user_channel.get("notify") != "NOTIFY": + return False + if user_channel.get("action_required") is True or bool(user_channel.get("actions")): + return True + return bool( + quota_packet.get("state") == "operator_gate" + or quota_packet.get("notify_user_on_gate") is True + or quota_packet.get("notify_user_on_open_todo") is True + ) diff --git a/loopx/extensions/lark/goal_channel_notice.py b/loopx/extensions/lark/goal_channel_notice.py index a20f750fcd..1a22cbcab6 100644 --- a/loopx/extensions/lark/goal_channel_notice.py +++ b/loopx/extensions/lark/goal_channel_notice.py @@ -27,7 +27,7 @@ def render_channel_notice( def scope_valid() -> bool: payload = read_goal_channel_binding(binding_path) raw = binding_for_goal(payload, goal_id) - target_ref = (raw or {}).get("target_ref") + target_ref = str((raw or {}).get("target_ref") or "") current_target = goal_channel_target_for_name( read_goal_channel_targets(default_goal_channel_target_path(runtime_root)), target_ref, ) if target_ref else None @@ -35,8 +35,9 @@ def scope_valid() -> bool: return False binding = binding_for_goal(read_goal_channel_binding(binding_path), goal_id, provider_target=current_target) + raw_channel = binding.get("channel") if isinstance(binding, Mapping) else None return bool(binding and binding.get("enabled") is True - and (binding.get("channel") or {}).get("chat_id") == chat_id) + and isinstance(raw_channel, Mapping) and raw_channel.get("chat_id") == chat_id) if cached_text: current_notice_revision(registry_path=registry_path, runtime_root=runtime_root, diff --git a/loopx/extensions/lark/goal_topic_batch.py b/loopx/extensions/lark/goal_topic_batch.py index c1e3f7d0c7..4156a885cd 100644 --- a/loopx/extensions/lark/goal_topic_batch.py +++ b/loopx/extensions/lark/goal_topic_batch.py @@ -205,9 +205,9 @@ def upgrade_lark_goal_topics( if connection.get("provider") != "lark" or not connection.get("enabled"): continue ref = str(connection["connection_id"]) - if (connection.get("routing") or {}).get( - "ingress_mode", "direct_session" - ) != "direct_session": + raw_routing = connection.get("routing") + routing = raw_routing if isinstance(raw_routing, Mapping) else {} + if routing.get("ingress_mode", "direct_session") != "direct_session": results.append( {"connection_id": ref, "status": "already_current", "ok": True} ) diff --git a/loopx/extensions/lark/goal_topic_connections.py b/loopx/extensions/lark/goal_topic_connections.py index f55f394174..0d6229f070 100644 --- a/loopx/extensions/lark/goal_topic_connections.py +++ b/loopx/extensions/lark/goal_topic_connections.py @@ -821,7 +821,14 @@ def connect_lark_goal_topic( payload = read_goal_channel_binding(binding_path) existing = binding_for_goal(payload, goal_id, connection_id=connection_id) or {} - receipts = dict(existing.get("receipts") or {}) + raw_receipts = existing.get("receipts") + receipts = dict(raw_receipts) if isinstance(raw_receipts, Mapping) else {} + raw_channel = existing.get("channel") + existing_channel = dict(raw_channel) if isinstance(raw_channel, Mapping) else {} + raw_topic = existing.get("topic") + existing_topic = dict(raw_topic) if isinstance(raw_topic, Mapping) else {} + raw_automation = existing.get("automation") + existing_automation = dict(raw_automation) if isinstance(raw_automation, Mapping) else {} receipts[semantic_key(goal_id, "lark", "goal_topic_receipt", root_message_id)] = { "kind": "goal_topic", "message_id": root_message_id, @@ -842,12 +849,12 @@ def connect_lark_goal_topic( "enabled": True, "target_ref": target_name, "channel": { - **dict(existing.get("channel") or {}), + **existing_channel, "pinned_message_id": root_message_id, }, "topic": { - **dict(existing.get("topic") or {}), - "name": (existing.get("topic") or {}).get("name", topic_name) + **existing_topic, + "name": existing_topic.get("name", topic_name) if editing else topic_name, "root_message_id": root_message_id, @@ -871,7 +878,7 @@ def connect_lark_goal_topic( **({"inbox_config_ref": inbox_config_ref} if inbox_config_ref else {}), }, **({"connector": connector_binding} if connector_binding else {}), - "automation": dict(existing.get("automation") or {}), + "automation": existing_automation, "receipts": receipts, }, ) @@ -1075,11 +1082,8 @@ def list_lark_connections( history_permission_guidance = bot_group_history_permission_guidance( str(identity.get("bot_app_id") or "") ) - topic = ( - binding.get("topic") - if isinstance(binding.get("topic"), Mapping) - else {} - ) + raw_topic = binding.get("topic") + topic = raw_topic if isinstance(raw_topic, Mapping) else {} raw_routing = binding.get("routing") routing = raw_routing if isinstance(raw_routing, Mapping) else {} connector_status: dict[str, Any] | None = None @@ -1105,9 +1109,10 @@ def list_lark_connections( reply_mode = ReplyMode.TOPIC_REPLY.value reply_ready = False health_error_code = "invalid_routing_state" + raw_legacy_channel = binding.get("channel") legacy_root = ( - binding.get("channel", {}).get("pinned_message_id") - if isinstance(binding.get("channel"), Mapping) + raw_legacy_channel.get("pinned_message_id") + if isinstance(raw_legacy_channel, Mapping) else None ) rows.append( @@ -1223,16 +1228,10 @@ def decide_lark_topic_event( if isinstance(target.get("identity"), Mapping) else {} ) - topic = ( - binding.get("topic") - if isinstance(binding.get("topic"), Mapping) - else {} - ) - binding_channel = ( - binding.get("channel") - if isinstance(binding.get("channel"), Mapping) - else {} - ) + raw_topic = binding.get("topic") + topic = raw_topic if isinstance(raw_topic, Mapping) else {} + raw_binding_channel = binding.get("channel") + binding_channel = raw_binding_channel if isinstance(raw_binding_channel, Mapping) else {} topic_root = str( topic.get("root_message_id") or binding_channel.get("pinned_message_id") diff --git a/loopx/extensions/lark/goal_topic_edit.py b/loopx/extensions/lark/goal_topic_edit.py index e6f371ae59..1b2df704ac 100644 --- a/loopx/extensions/lark/goal_topic_edit.py +++ b/loopx/extensions/lark/goal_topic_edit.py @@ -85,7 +85,8 @@ def resolve_existing_goal_topic( agents = registered_agent_ids_for_goal(goal) if len(agents) == 1: agent_id = next(iter(agents)) - old_routing = editing.get("routing") or {} + raw_routing = editing.get("routing") + old_routing = raw_routing if isinstance(raw_routing, Mapping) else {} stored_scope = str( old_routing.get("capture_scope") or ( diff --git a/loopx/extensions/lark/manager_routing.py b/loopx/extensions/lark/manager_routing.py index 1a7332cf0f..433f5fb285 100644 --- a/loopx/extensions/lark/manager_routing.py +++ b/loopx/extensions/lark/manager_routing.py @@ -94,7 +94,8 @@ def has_manager_binding(payloads: Mapping[str, Any], target_ref: str) -> bool: return any( item.get("enabled") is True and item.get("target_ref") == target_ref - and (item.get("routing") or {}).get("conversation_kind") == "manager" + and isinstance((routing := item.get("routing")), Mapping) + and routing.get("conversation_kind") == "manager" for goal_id, payload in payloads.items() if isinstance(payload, Mapping) for item in bindings_for_goal(payload, str(goal_id)) @@ -137,10 +138,15 @@ def decide_manager_event( ) if (target.get("channel") or {}).get("chat_id") != chat_id: continue - routing = binding.get("routing") or {} + raw_routing = binding.get("routing") + routing = raw_routing if isinstance(raw_routing, Mapping) else {} + raw_topic = binding.get("topic") + b_topic = raw_topic if isinstance(raw_topic, Mapping) else {} + raw_channel = binding.get("channel") + b_channel = raw_channel if isinstance(raw_channel, Mapping) else {} topic_root = str( - (binding.get("topic") or {}).get("root_message_id") - or (binding.get("channel") or {}).get("pinned_message_id") + b_topic.get("root_message_id") + or b_channel.get("pinned_message_id") or "" ) if routing.get("conversation_kind") != "manager": @@ -167,9 +173,10 @@ def ignored(reason: str) -> dict[str, Any]: if not _valid_manager_binding(goal_id, binding, routing): return ignored("invalid_routing_state") profile = str(identity.get("sender_profile") or "default") + raw_trigger = routing.get("turn_trigger") try: trigger = conversation_trigger( - routing.get("turn_trigger"), + raw_trigger if raw_trigger is None or isinstance(raw_trigger, str) else str(raw_trigger), addressed=is_event_addressed_to_bot(event, identity), bot_message=event.get("sender_type") == "app", human=event.get("sender_type") == "user" and bool(event.get("sender_id")), @@ -212,7 +219,7 @@ def ignored(reason: str) -> dict[str, Any]: ), "ingress_mode": "session_queue", "reply_mode": "topic_reply", - "connector": dict(connector), + "connector": dict(connector) if isinstance(connector, Mapping) else {}, }, } @@ -253,7 +260,8 @@ def authorized_manager_goal_ids( targets = snapshot.get("target_payload") or {} for goal_id, payload in (snapshot.get("binding_payloads") or {}).items(): for binding in bindings_for_goal(payload, goal_id): - routing = binding.get("routing") or {} + raw_routing = binding.get("routing") + routing = raw_routing if isinstance(raw_routing, Mapping) else {} if ( binding.get("enabled") is not True or routing.get("conversation_kind") != "manager" diff --git a/loopx/extensions/lark/periodic_report_delivery.py b/loopx/extensions/lark/periodic_report_delivery.py index 8c384c0571..971de3c22c 100644 --- a/loopx/extensions/lark/periodic_report_delivery.py +++ b/loopx/extensions/lark/periodic_report_delivery.py @@ -237,10 +237,11 @@ def _resolved_goal_channel_binding( raise ValueError("periodic report Goal Channel target is missing") resolution_payload = payload if binding_for_goal(payload, goal_id) is None: + raw_bindings = payload.get("bindings") resolution_payload = { **payload, "bindings": { - **dict(payload.get("bindings") or {}), + **(dict(raw_bindings) if isinstance(raw_bindings, Mapping) else {}), goal_id: raw, }, } diff --git a/loopx/extensions/lark/team_plan_confirmation.py b/loopx/extensions/lark/team_plan_confirmation.py index 51a7d7438c..89d105a113 100644 --- a/loopx/extensions/lark/team_plan_confirmation.py +++ b/loopx/extensions/lark/team_plan_confirmation.py @@ -438,6 +438,21 @@ def _digest(value: object) -> str: return hashlib.sha256(encoded).hexdigest() +def _binding_matches_audience( + binding: Mapping[str, Any], *, manager_audience: bool +) -> bool: + routing = binding.get("routing") + if isinstance(routing, Mapping): + is_manager = routing.get("conversation_kind") == "manager" + elif routing: + raise ValueError("team plan review audience routing is invalid") + else: + # Older Goal-only bindings predate the routing object and still select + # the Goal audience. Empty scalar containers retain that compatibility. + is_manager = False + return is_manager is manager_audience + + def _resolved_binding( *, registry_path: Path, @@ -461,11 +476,9 @@ def _resolved_binding( if ( isinstance(default_binding, Mapping) and default_binding.get("enabled") is True - and ( - (default_binding.get("routing") or {}).get("conversation_kind") - == "manager" + and _binding_matches_audience( + default_binding, manager_audience=manager_audience ) - is manager_audience ): selected_connection_id = str( default_binding.get("connection_id") or "" @@ -474,10 +487,9 @@ def _resolved_binding( item for item in bindings_for_goal(payload, goal_id) if item.get("enabled") is True - and ( - (item.get("routing") or {}).get("conversation_kind") == "manager" + and _binding_matches_audience( + item, manager_audience=manager_audience ) - is manager_audience ] if selected_connection_id is None and candidates: selected_connection_id = str( @@ -492,10 +504,7 @@ def _resolved_binding( ) if raw is None: raise ValueError("team plan review audience binding is unavailable") - if ( - ((raw.get("routing") or {}).get("conversation_kind") == "manager") - is not manager_audience - ): + if not _binding_matches_audience(raw, manager_audience=manager_audience): raise ValueError("team plan review audience kind is unavailable") target_path = default_goal_channel_target_path(runtime_root) target_ref = str(raw.get("target_ref") or "") diff --git a/tests/extensions/test_lark_goal_channel_contracts_contract.py b/tests/extensions/test_lark_goal_channel_contracts_contract.py new file mode 100644 index 0000000000..db18e12ee1 --- /dev/null +++ b/tests/extensions/test_lark_goal_channel_contracts_contract.py @@ -0,0 +1,388 @@ +"""Contract, Zero-Any, and boundary tests for Lark Goal Channel contracts.""" + +from __future__ import annotations + +import ast +from collections.abc import Mapping +import json +from pathlib import Path +from types import MappingProxyType +import tokenize +from typing import cast + +import pytest + +from loopx.extensions.lark import goal_channel_contracts, goal_channel_gate_contracts +from loopx.registry import registry_goals as real_registry_goals + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def _ast_any_lines(path: Path) -> list[int]: + tree = ast.parse(path.read_text(encoding="utf-8")) + return [node.lineno for node in ast.walk(tree) if isinstance(node, ast.Name) and node.id == "Any"] + + +def _suppression_lines(path: Path) -> list[int]: + lines: list[int] = [] + with path.open("r", encoding="utf-8") as handle: + for tok in tokenize.generate_tokens(handle.readline): + if tok.type == tokenize.COMMENT and ("type: ignore" in tok.string or "noqa" in tok.string): + lines.append(tok.start[0]) + return lines + + +def test_goal_channel_modules_meet_ceiling_zero_any_and_inventory_invariants() -> None: + contracts_path = REPO_ROOT / "loopx/extensions/lark/goal_channel_contracts.py" + gate_path = REPO_ROOT / "loopx/extensions/lark/goal_channel_gate_contracts.py" + test_path = Path(__file__).resolve() + + assert len(contracts_path.read_text(encoding="utf-8").splitlines()) <= 550 + assert len(gate_path.read_text(encoding="utf-8").splitlines()) < 750 + assert len(test_path.read_text(encoding="utf-8").splitlines()) < 500 + for path in (contracts_path, gate_path, test_path): + assert _ast_any_lines(path) == [], str(path) + assert _suppression_lines(path) == [], str(path) + + inventory = json.loads( + (REPO_ROOT / "loopx/semantics/goal_instance_binding_inventory_v1.json").read_text(encoding="utf-8") + ) + owners = inventory.get("owners") or inventory.get("entries") or inventory + assert "loopx/extensions/lark/goal_channel_contracts.py::save_goal_binding" in json.dumps(owners) + assert goal_channel_contracts.save_goal_binding.__module__ == "loopx.extensions.lark.goal_channel_contracts" + + shared_gate_exports = ( + "DEFAULT_GATE_COOLDOWN_SECONDS", + "HUMAN_GATE_AUTO_NOTIFY_SETTING", + "BLOCKED_NOTICE_AUTO_NOTIFY_SETTING", + "HUMAN_GATE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION", + "BLOCKED_NOTICE_AUTO_NOTIFY_MARKER_SCHEMA_VERSION", + "BlockedNoticeReceiptState", + "BLOCKED_NOTICE_RETIRED_STATES", + "blocked_notice_receipt_matches_target", + "human_gate_auto_notify_enabled", + "blocked_notice_auto_notify_enabled", + "human_gate_auto_notify_marker_path", + "human_gate_auto_notify_marker_enabled", + "write_human_gate_auto_notify_marker", + "clear_human_gate_auto_notify_marker", + "blocked_notice_auto_notify_marker_path", + "blocked_notice_auto_notify_marker_enabled", + "write_blocked_notice_auto_notify_marker", + "clear_blocked_notice_auto_notify_marker", + "quota_human_gate_identity", + "_quota_human_gate_items", + "notification_request_snapshot", + "_gate_notice_projection", + "quota_human_gate_state_generation", + "quota_human_gate_reminder_generation", + "quota_human_gate_notification_suppressed", + "quota_selects_human_gate", + "semantic_key", + ) + for name in shared_gate_exports: + assert getattr(goal_channel_contracts, name) is getattr(goal_channel_gate_contracts, name), name + + +def test_routing_enum_serializer_registry_and_binding_storage( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + assert goal_channel_contracts.normalize_lark_topic_event_rejection_reason("matched") is None + assert goal_channel_contracts.normalize_lark_topic_event_rejection_reason("unknown") is None + assert ( + goal_channel_contracts.normalize_lark_topic_event_rejection_reason(" self_message ") + == "self_message" + ) + + locks: list[Path] = [] + + class _FakeLock: + def __init__(self, path: Path) -> None: + self._path = path + + def __enter__(self) -> None: + locks.append(self._path) + + def __exit__(self, *_args: object) -> None: + return None + + monkeypatch.setattr( + goal_channel_contracts, + "exclusive_file_lock", + lambda path, operation="": _FakeLock(path), + ) + + @goal_channel_contracts.serialize_goal_binding_mutation + def _mutate(*, binding_path: Path, execute: bool = True) -> Path: + return binding_path + + with pytest.raises(TypeError, match="binding_path must be a Path"): + _mutate(binding_path=cast(Path, "not-a-path")) + target_file = tmp_path / ".loopx" / "goal-channel.json" + assert _mutate(binding_path=target_file, execute=False) == target_file + assert locks == [] + assert _mutate(binding_path=target_file) == target_file + assert locks == [target_file] + + with pytest.raises(ValueError, match="project source registry"): + goal_channel_contracts.default_goal_channel_binding_path(tmp_path / "other" / "registry.json") + assert goal_channel_contracts.default_goal_channel_binding_path( + tmp_path / ".loopx" / "registry.json" + ) == (tmp_path / ".loopx" / "goal-channel.json").resolve() + + missing = goal_channel_contracts.read_goal_channel_binding(target_file) + assert missing == { + "schema_version": goal_channel_contracts.GOAL_CHANNEL_BINDING_SCHEMA_VERSION, + "bindings": {}, + } + target_file.parent.mkdir(parents=True) + for bad_text, msg in ( + ("[]", "JSON object"), + (json.dumps({"schema_version": "old", "bindings": {}}), "must use"), + ( + json.dumps( + {"schema_version": goal_channel_contracts.GOAL_CHANNEL_BINDING_SCHEMA_VERSION, "bindings": []} + ), + "object `bindings`", + ), + ): + target_file.write_text(bad_text, encoding="utf-8") + with pytest.raises(ValueError, match=msg): + goal_channel_contracts.read_goal_channel_binding(target_file) + + registry_dict: dict[str, object] = {"goals": [{"id": "g-1", "objective": "Deliver"}]} + seen_registry_objs: list[object] = [] + + def _spy_registry_goals(reg: dict[str, object]) -> list[dict[str, object]]: + seen_registry_objs.append(reg) + return list(real_registry_goals(reg)) + + monkeypatch.setattr(goal_channel_contracts, "registry_goals", _spy_registry_goals) + assert goal_channel_contracts.goal_from_registry(registry_dict, " g-1 ") == {"id": "g-1", "objective": "Deliver"} + assert seen_registry_objs[0] is registry_dict + assert goal_channel_contracts.goal_from_registry(MappingProxyType(registry_dict), "g-1") == { + "id": "g-1", + "objective": "Deliver", + } + with pytest.raises(ValueError, match="not registered"): + goal_channel_contracts.goal_from_registry(registry_dict, "missing") + + +def test_connection_set_selection_legacy_migration_and_save_preservation(tmp_path: Path) -> None: + binding_path = tmp_path / ".loopx" / "goal-channel.json" + binding_path.parent.mkdir(parents=True) + legacy_payload: dict[str, object] = { + "schema_version": goal_channel_contracts.GOAL_CHANNEL_BINDING_SCHEMA_VERSION, + "bindings": { + "g-1": { + "enabled": True, + "agent_id": "author", + "target_ref": "main-group", + "provider": "lark", + "channel": {"pinned_message_id": "om_root1", "chat_id": "oc_old"}, + } + }, + } + legacy_cid = goal_channel_contracts.goal_channel_connection_id("g-1", "author") + legacy_list = goal_channel_contracts.bindings_for_goal(legacy_payload, "g-1") + assert len(legacy_list) == 1 and legacy_list[0]["connection_id"] == legacy_cid + assert goal_channel_contracts.binding_for_goal(legacy_payload, "g-1", agent_id="other") is None + assert goal_channel_contracts.binding_for_goal(legacy_payload, "g-1", connection_id="other") is None + + resolved = goal_channel_contracts.binding_for_goal( + legacy_payload, + "g-1", + agent_id="author", + provider_target={ + "name": "main-group", + "provider": "lark", + "channel": {"chat_id": "oc_new"}, + "identity": {"bot_app_id": "cli_123"}, + }, + ) + assert resolved is not None + assert resolved["channel"] == {"chat_id": "oc_new", "pinned_message_id": "om_root1"} + assert resolved["identity"] == {"bot_app_id": "cli_123"} + + with pytest.raises(ValueError, match="target_ref"): + goal_channel_contracts.binding_for_goal( + legacy_payload, "g-1", provider_target={"name": "other", "provider": "lark"} + ) + + peer_cid = goal_channel_contracts.save_goal_connection( + binding_path=binding_path, + payload=legacy_payload, + goal_id="g-1", + binding={"enabled": True, "agent_id": "peer", "target_ref": "peer-group", "provider": "lark"}, + make_default=False, + ) + migrated = goal_channel_contracts.read_goal_channel_binding(binding_path) + selected_peer = goal_channel_contracts.binding_for_goal( + migrated, + "g-1", + agent_id="peer", + provider_target={ + "name": "peer-group", + "provider": "lark", + "channel": {"chat_id": "oc_peer"}, + "identity": {"bot_app_id": "cli_peer"}, + }, + ) + assert selected_peer is not None and selected_peer["connection_id"] == peer_cid + + # Mutate default_connection_id to a stale value: fallback must deterministically pick min(connection_id). + migrated_bindings = migrated["bindings"] + assert isinstance(migrated_bindings, Mapping) + raw_stored_set = migrated_bindings["g-1"] + assert isinstance(raw_stored_set, Mapping) + stored_set = dict(raw_stored_set) + stored_set["default_connection_id"] = "missing_cid" + fallback_payload: dict[str, object] = {**migrated, "bindings": {"g-1": stored_set}} + fallback = goal_channel_contracts.binding_for_goal(fallback_payload, "g-1") + assert fallback is not None and fallback["connection_id"] == min(legacy_cid, peer_cid) + + goal_channel_contracts.save_goal_binding( + binding_path=binding_path, + payload=migrated, + goal_id="g-1", + binding={"enabled": True, "agent_id": "author", "target_ref": "updated-default", "provider": "lark"}, + ) + after_save = goal_channel_contracts.read_goal_channel_binding(binding_path) + assert len(goal_channel_contracts.bindings_for_goal(after_save, "g-1")) == 2 + + +def test_public_packets_objective_redaction_and_reusable_topic_root() -> None: + packet = goal_channel_contracts.operation_packet( + ok=True, + goal_id="g-1", + operation="inspect", + execute=False, + status="ok", + public_summary="clean summary", + details={"note": "safe"}, + ) + assert packet["private_provider_payload_captured"] is False + + for bad_details in ( + {"chat_id": "secret"}, + {"nested": [{"text": "leak oc_abc123"}]}, + {"nested": {"msg": "om_xyz987"}}, + ): + with pytest.raises(ValueError, match="public Goal Channel packet"): + goal_channel_contracts.operation_packet( + ok=True, + goal_id="g-1", + operation="inspect", + execute=False, + status="ok", + public_summary="summary", + details=bad_details, + ) + + assert goal_channel_contracts.goal_objective({}) is None + assert goal_channel_contracts.goal_objective({"objective": "api_key=sk-secret1234567890"}) is None + msg = goal_channel_contracts.control_message(goal_id="g-1", objective="Ship fix", kanban_url="https://example.test") + assert "Kanban: https://example.test" in msg + + payload: dict[str, object] = { + "schema_version": goal_channel_contracts.GOAL_CHANNEL_BINDING_SCHEMA_VERSION, + "bindings": { + "g-1": { + "enabled": True, + "target_ref": "grp", + "provider": "lark", + "topic": {"root_message_id": "om_root99"}, + "channel": {"chat_id": "oc_chat1"}, + } + }, + } + cid = goal_channel_contracts.goal_channel_connection_id("g-1", None) + assert ( + goal_channel_contracts.reusable_goal_topic_root( + payload, + "g-1", + connection_id=cid, + provider_target={ + "name": "grp", + "provider": "lark", + "channel": {"chat_id": "oc_chat1"}, + "identity": {"bot_app_id": "cli_1"}, + }, + chat_id="oc_chat1", + ) + == "om_root99" + ) + assert ( + goal_channel_contracts.reusable_goal_topic_root( + payload, + "g-1", + connection_id=cid, + provider_target={"name": "wrong", "provider": "lark"}, + chat_id="oc_chat1", + ) + == "" + ) + + +def test_gate_markers_receipt_matching_and_quota_projections( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + binding_path = tmp_path / ".loopx" / "goal-channel.json" + for bad_goal in ("", ".", "..", "a/b", r"a\b"): + with pytest.raises(ValueError, match="single path segment"): + goal_channel_contracts.human_gate_auto_notify_marker_path(binding_path, bad_goal) + + h_marker = goal_channel_contracts.human_gate_auto_notify_marker_path(binding_path, "g-1") + b_marker = goal_channel_contracts.blocked_notice_auto_notify_marker_path(binding_path, "g-1") + assert not goal_channel_contracts.human_gate_auto_notify_marker_enabled(h_marker) + goal_channel_contracts.write_human_gate_auto_notify_marker(h_marker) + assert goal_channel_contracts.human_gate_auto_notify_marker_enabled(h_marker) + goal_channel_contracts.clear_human_gate_auto_notify_marker(h_marker) + assert not goal_channel_contracts.human_gate_auto_notify_marker_enabled(h_marker) + b_marker.parent.mkdir(parents=True, exist_ok=True) + b_marker.write_text("{broken-json", encoding="utf-8") + assert goal_channel_contracts.blocked_notice_auto_notify_marker_enabled(b_marker) + + legacy_key = goal_channel_contracts.semantic_key("g-1", "lark", "blocked_notice", "b1", "r1", "oc_1") + assert goal_channel_contracts.blocked_notice_receipt_matches_target( + legacy_key, {"kind": "blocked_notice", "blocker_identity": "b1", "blocker_revision": "r1"}, goal_id="g-1", chat_id="oc_1" + ) + assert not goal_channel_contracts.blocked_notice_receipt_matches_target( + legacy_key, {"kind": "blocked_notice", "chat_id": "oc_other"}, goal_id="g-1", chat_id="oc_1" + ) + + monkeypatch.setattr( + "loopx.control_plane.effect_runtime.effect_runtime_result", + lambda _m, payload: {"goal_id": payload["goal_id"], "items": payload["requests"]}, + ) + quota_packet: dict[str, object] = { + "goal_id": "g-1", + "state": "operator_gate", + "user_todo_summary": { + "gate_open_items": [ + {"status": "open", "text": "item 0"}, + {"status": "open", "text": "item 1"}, + {"status": "open", "text": "item 2"}, + {"todo_id": "t4", "status": "open", "text": "item 3"}, + ] + }, + "request_snapshot": {"goal_id": "g-1", "items": [{"todo_id": "t4", "note": "need review"}]}, + "user_gate_notification_cooldown": {"notification_due": True, "policy": "daily", "cooldown_minutes": 60}, + } + assert goal_channel_contracts.quota_human_gate_identity(quota_packet) == "t4" + assert len(goal_channel_contracts._quota_human_gate_items(quota_packet)) == 3 + gen = goal_channel_contracts.quota_human_gate_state_generation(quota_packet) + assert gen.startswith("sha256:") + assert goal_channel_contracts.quota_human_gate_reminder_generation(quota_packet) is not None + assert goal_channel_contracts.quota_selects_human_gate(quota_packet) is True + assert ( + goal_channel_contracts.quota_selects_human_gate( + {**quota_packet, "user_gate_notification_cooldown": {"notification_suppressed": True}} + ) + is False + ) + snap = goal_channel_contracts.notification_request_snapshot( + {"attention_queue": {"items": [{"goal_id": "g-1", "user_todos": {"items": [{"todo_id": "t4"}]}}]}}, + "g-1", + ) + assert snap == {"goal_id": "g-1", "items": [{"todo_id": "t4"}]} diff --git a/tests/extensions/test_lark_team_plan_confirmation.py b/tests/extensions/test_lark_team_plan_confirmation.py index 7fc72da2a9..9d168a96b6 100644 --- a/tests/extensions/test_lark_team_plan_confirmation.py +++ b/tests/extensions/test_lark_team_plan_confirmation.py @@ -528,6 +528,52 @@ def readback(self, message_id: str) -> dict[str, Any]: ] == "goal-profile" +def test_resolved_binding_rejects_non_mapping_routing_before_delivery( + tmp_path: Path, monkeypatch: Any +) -> None: + import loopx.extensions.lark.team_plan_confirmation as confirmation + + binding_path = tmp_path / "goal-channel.json" + binding_path.write_text( + json.dumps( + { + "schema_version": "loopx_goal_channel_lark_binding_v0", + "bindings": { + "goal-alpha": { + "goal_id": "goal-alpha", + "provider": "lark", + "enabled": True, + "connection_id": "goal-connection", + "target_ref": "goal-target", + "routing": "invalid-routing", + } + }, + } + ), + encoding="utf-8", + ) + monkeypatch.setattr(confirmation, "load_registry", lambda _path: {}) + monkeypatch.setattr( + confirmation, + "resolve_goal_source_runtime_route", + lambda **_kwargs: {"source_registry": tmp_path / ".loopx" / "registry.json"}, + ) + monkeypatch.setattr( + confirmation, "default_goal_channel_binding_path", lambda _path: binding_path + ) + + with pytest.raises( + ValueError, match="team plan review audience routing is invalid" + ): + confirmation._resolved_binding( + registry_path=tmp_path / ".loopx" / "registry.json", + runtime_root=tmp_path, + goal_id="goal-alpha", + connection_id=None, + manager_audience=False, + ) + + def test_delivery_retry_resumes_after_the_first_audience_checkpoint( tmp_path: Path, monkeypatch: Any ) -> None: