From 8c2adfcddf6cee34c65ffc6037b86ece39d4e97a Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:20:58 +0800 Subject: [PATCH 1/2] Keep private steward mentions in their original topics Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../native_chat/external_conversations.py | 74 +++++++++ .../extensions/lark/private_conversations.py | 100 ++++++++++++- tests/test_lark_private_conversations.py | 140 ++++++++++++++++++ 3 files changed, 313 insertions(+), 1 deletion(-) diff --git a/loopx/capabilities/native_chat/external_conversations.py b/loopx/capabilities/native_chat/external_conversations.py index cd587e8d5c..8f021c5032 100644 --- a/loopx/capabilities/native_chat/external_conversations.py +++ b/loopx/capabilities/native_chat/external_conversations.py @@ -29,6 +29,7 @@ _atomic_write_json as _atomic_write_json, _read_json as _read_json, RESUMABLE_SESSION_STATES, + TERMINAL_TURN_STATES, ) from ...control_plane import effect_runtime from ...control_plane.quota.automation_cadence_readback import ( @@ -1541,6 +1542,79 @@ def _reject_prepared(path: Path, row: dict[str, Any]) -> None: row.update(status="rejected", response="原授权或命令格式不可用,本条未进入执行队列;请用 /agents 或 /project 查看可用入口。") _atomic_write_json(path, row) + def requeue_rejected_mention(self, request_ref: str, *, original_turn_id: str, + source_preflight: Callable[[dict[str, Any]], None]) -> dict[str, Any]: + """Admit an explicitly selected, independently verified private source once.""" + from ...chat import require_matching_replay + from ...chat_manager_context import manager_authorization_scope_is_current + + if not _REQUEST_JOURNAL_STEM.fullmatch(request_ref) or not callable(source_preflight): + raise ValueError("invalid original mention replay") + path = self.root / f"{request_ref}.json" + error = "live_steering_session_not_attached" + with exclusive_file_lock(path, operation="admit_external_chat_request"): + row = self.read_request(request_ref) + replay = row.get("rejected_mention_replay") + if replay is not None: + if replay["target_turn_id"] != original_turn_id: + raise ValueError("the original mention replay target changed") + if row["status"] == "accepted": + return row # Repair transport correlation after a committed admission. + sid = row["session_id"] + capture = row.get("mention_capture") or {} + if (row["status"] != "command_completed" or row.get("delivery_verified") is not True + or row.get("origin") != "lark" or row.get("command") or row.get("agent_target") + or row.get("attachments") or row.get("native_mention") is not True + or row["source"].get("private_human_message") is not True + or row.get("mention_delivery") != {"action": "reject", "error_code": error} + or row["turn_id"] != original_turn_id or capture.get("target_turn_id") != original_turn_id + or capture.get("session_id") != sid): + raise ValueError("the original mention lacks a pre-dispatch rejection") + route_lock = external_source_route_path(self.root, row["binding_id"], row["source"]["source_ref"]) + with exclusive_file_lock(route_lock, operation="route_external_chat_request"): + store = self.controller.store + client = f"external-{request_ref}" + session = store.load_session(sid) + prior = store.load_turn(sid, original_turn_id) + receipt = store.steering_receipt(sid, client) or {} + if (receipt.get("mode") != "live_steering" or receipt.get("status") != "failed" + or receipt.get("error_code") != error or receipt.get("expected_turn_id") != original_turn_id + or receipt.get("active_turn_id") is not None or receipt.get("native_steering") is not None + or receipt.get("message") != row["message"]): + raise ValueError("the original steering receipt does not prove non-delivery") + turn = store.turn_for_client(sid, client) + if turn is not None: + if replay is None: + raise ValueError("the original client identity already has a Turn") + require_matching_replay( + {**turn, "message": turn.get("_queue_original_message", turn.get("message"))}, + identity="client_turn_id", request={"message": row["message"], "attachments": None, + "origin": "lark", "external_agent_target": None}, + ) + else: + if (not session or session.get("status") == "closed" or not session.get("steward_context") + or not prior or prior["status"] not in TERMINAL_TURN_STATES + or self._source_stop_observed(row, prior, store.events_after(sid, original_turn_id, None))): + raise ValueError("the original mention replay is not eligible") + selected = resolve_external_admission_source( + self.bindings, row["binding_id"], row["source"], source_preflight, session=session, + ) + if (selected["owner_manager_audience"] is not True + or selected["channel_id"] != capture.get("channel_id") + or not manager_authorization_scope_is_current(self.controller.registry_path, + self.controller.manager_scope_resolver, session, session.get("manager_authorization_scope_id"), + runtime_root=self.controller.coordination_runtime_root)): + raise ValueError("the original steward source or authority changed") + if replay is None: + row["rejected_mention_replay"] = {"target_turn_id": original_turn_id, "original_response": row["response"]} + _atomic_write_json(path, row) + self._record_steward_ingress(row, selected, session, client) + turn, _ = self.controller.enqueue_turn(session_id=sid, client_turn_id=client, + message=row["message"], attachments=None, work_dir=Path("."), objective="", origin="lark") + row.update(status="accepted", turn_id=turn["turn_id"], response=None, delivery_verified=False) + _atomic_write_json(path, row) + return row + def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, Any], *, recovering_request: bool = False, source_preflight: Callable[[dict[str, Any]], None] | None = None) -> dict[str, Any]: diff --git a/loopx/extensions/lark/private_conversations.py b/loopx/extensions/lark/private_conversations.py index ecdbf67f57..324872d053 100644 --- a/loopx/extensions/lark/private_conversations.py +++ b/loopx/extensions/lark/private_conversations.py @@ -634,6 +634,8 @@ def _record_admission(path: Path, record: dict[str, Any], admitted: dict[str, An response=admitted.get("response"), response_code=admitted.get("response_code")) if admitted.get("context_recovery"): record["context_recovery"] = admitted["context_recovery"] + elif admitted["status"] == "accepted" and admitted.get("rejected_mention_replay"): + record["context_recovery"] = {"presentation_key": "rejected-mention.1"} if admitted.get("mention_delivery"): record["mention_delivery"] = admitted["mention_delivery"] _atomic_write_json(path, record) @@ -761,6 +763,32 @@ def read(args: Sequence[str], **_kwargs: Any) -> subprocess.CompletedProcess[str _atomic_write_json(path, record) return message + def _distinct_steward_reply_topic(self, record: dict[str, Any], binding: Mapping[str, Any]) -> bool: + if (binding.get("context_kind") != "steward" or binding.get("audience", "owner") != "owner" + or record["event"].get("chat_type") != "p2p"): + return False + root_id = record["event"].get("root_id") + capture = record.get("mention_capture") or {} + if (not root_id or record.get("reply_context_message") is None + or not capture.get("session_id") or not capture.get("target_turn_id")): + return False + turn = self.core.controller.store.load_turn(capture["session_id"], capture["target_turn_id"]) + match = re.fullmatch(r"external-([a-f0-9]{24})", str((turn or {}).get("client_turn_id") or "")) + if match is None or (turn or {}).get("origin") != "lark": + return False + try: + original = _read_json(self.root / f"{match[1]}.json") + except (OSError, ValueError): + return False + previous = original["event"] + return (original.get("turn_id") == capture["target_turn_id"] + and original.get("session_id") == capture["session_id"] + and original.get("reply_context_message") is not None + and _same_fields(original, record, "binding_id", "profile", "source") + and previous.get("chat_id") == record["event"].get("chat_id") + and bool(previous.get("root_id")) + and previous["root_id"] != root_id) + @effect_runtime_request_scope() def admit(self, profile: str, event: dict[str, Any], *, defer_background_stop: bool = False, history_review: bool = False, @@ -967,6 +995,13 @@ def verify_mention(fresh: dict[str, Any]) -> None: raise ValueError("native mention source changed") preflight = verify_mention + if (not (self.core.root / f"{request}.json").exists() + and self._distinct_steward_reply_topic(record, binding)): + # A verified reply to another topic belongs to the + # ordinary queue, even when it addresses this Bot. + record["mention_topic_queue"] = True + _atomic_write_json(path, record) + native_mention = not record.get("mention_topic_queue", False) admitted = self.core.admit(binding_id=binding["binding_id"], source=source, request_ref=request, message=text, command=command, attachments=attachments, defer_background_stop=defer_background_stop, source_preflight=preflight, @@ -1569,6 +1604,64 @@ def _record_context_recovery_noop_backoff(self, path: Path, row: Mapping[str, An delay = float(60 + stagger if stagger_first else 60) if streak <= 1 else float(min(1800, 60 * (2 ** min(streak - 1, 5))) + stagger) self._context_recovery_probe_at[path] = time.monotonic() + delay + def _pending_rejected_mention_replays(self) -> Iterator[Path]: + folder = self.root / "rejected-mention-replays" + if folder.is_symlink(): + return + for plan in sorted(folder.glob("*.json")): + path = self.root / plan.name + if not re.fullmatch(r"[a-f0-9]{24}", path.stem) or plan.is_symlink() or not plan.is_file(): + continue + if time.monotonic() < self._context_recovery_probe_at.get(plan, 0): + continue + try: + row = _read_json(path) + except (OSError, ValueError): + continue + if (row.get("status") == "delivered" and not row.get("context_recovery") + and row.get("mention_delivery", {}).get("action") == "reject"): + yield path + + def _reconcile_rejected_mention(self, path: Path) -> None: + plan_path = self.root / "rejected-mention-replays" / path.name + if plan_path.parent.is_symlink() or plan_path.is_symlink() or not plan_path.is_file(): + return + self._context_recovery_probe_at[plan_path] = time.monotonic() + 60 + with exclusive_file_lock(path, operation="deliver_private_chat_request"): + record = _read_json(path) + if record.get("status") != "delivered" or record.get("context_recovery"): + return + terminal = record["deliveries"].get("terminal") or {} + try: + with plan_path.open("rb") as handle: + raw = handle.read(4097) + if len(raw) > 4096: + return + plan = json.loads(raw) + event = record["event"] + if (terminal.get("verified") is not True or plan != { + "message_id": event["message_id"], + "rejection_message_id": (terminal.get("attempt") or {}).get("message_ref"), + "target_turn_id": record["turn_id"], + } or not plan["rejection_message_id"] or record["request_ref"] != path.stem): + return + + def verify_source(selected: dict[str, Any]) -> None: + source = self._recovery_source_observation(record, selected) + if (source is None or source.get("_native_mention") is not True + or any(str(source.get(key) or "") != str(event.get(key) or "") for key in ("root_id", "parent_id")) + or (event.get("thread_id") and source.get("thread_id") != event["thread_id"]) + or not self._distinct_steward_reply_topic(record, selected["binding"])): + raise ValueError("the original distinct topic could not be verified") + + recovered = self.core.requeue_rejected_mention(record["request_ref"], + original_turn_id=plan["target_turn_id"], source_preflight=verify_source) + self._record_admission(path, record, recovered) + except (KeyError, ValueError, OSError, RuntimeError): + # An unavailable plan or uncertain source stays beside the + # original failure for a later independent observation. + return + @effect_runtime_request_scope() def pending_delivery_paths(self) -> list[Path]: """The durable transport store is the queue; no in-memory admission.""" @@ -1613,7 +1706,7 @@ def pending_delivery_paths(self) -> list[Path]: paths.append(path) else: self._record_context_recovery_noop_backoff(path, row, stagger_first=True) - return [*paths, *self._web_projection_paths()] + return list(dict.fromkeys([*paths, *self._pending_rejected_mention_replays(), *self._web_projection_paths()])) def is_recovery_path(self, path: Path) -> bool: """Schedule recovery of persisted attempts after fresh replies.""" @@ -1719,6 +1812,11 @@ def reconcile_request(self, path: Path) -> int: row = _read_json(path) if "triage" in row: return triage.reconcile(self, path) + if (row.get("status") == "delivered" and not row.get("context_recovery") + and row.get("mention_delivery", {}).get("action") == "reject" + and (self.root / "rejected-mention-replays" / path.name).is_file()): + self._reconcile_rejected_mention(path) + return 0 historical_images = row.get("historical_answer_images") if (row.get("status") == "delivered" and ( (historical_images or {}).get("status") == "pending" diff --git a/tests/test_lark_private_conversations.py b/tests/test_lark_private_conversations.py index de28d414a3..bca50931f0 100644 --- a/tests/test_lark_private_conversations.py +++ b/tests/test_lark_private_conversations.py @@ -7422,6 +7422,146 @@ def test_private_steward_native_mention_uses_original_manager_turn(tmp_path, mon fixture.close() +@pytest.mark.parametrize("case", [ + "fresh", "admission-crash", "replay", "replay-crash", "edited", "unknown", "same-topic", "stale-scope", +]) +def test_private_steward_distinct_topic_keeps_its_own_request(tmp_path, monkeypatch, case): + from loopx.capabilities.native_chat import external_conversations + from test_native_steward_private import finish, steward + + fixture = steward.__wrapped__(tmp_path) + store, runtime, provider, transport, binding, capture, _ = next(fixture) + profile = "steward-app" + + def reply(event, root): + event.update(root_id=root, parent_id=root, thread_id=f"omt_{root}") + provider.messages[event["message_id"]].update( + {key: event[key] for key in ("root_id", "parent_id", "thread_id")}, + ) + return event + + def path_for(event): + request_ref = identity_ref(binding["provider_ref"], event["message_id"]) + return transport.root / f"{request_ref}.json" + + try: + first_root = provider.event(profile, "first-topic", "Original topic")["message_id"] + second_root = provider.event(profile, "second-topic", "Independent topic")["message_id"] + original_event = reply(provider.event(profile, "topic-work", "wait for steer"), first_root) + assert transport.admit(profile, original_event)["status"] == "durably_accepted" + original = transport.core.read_request(path_for(original_event).stem) + _wait_private_upstream(store, original) + sid, old_turn = original["session_id"], original["turn_id"] + different = reply(_private_mention_event(provider, profile, "topic-ask", "Answer this topic independently."), + first_root if case == "same-topic" else second_root) + path = path_for(different) + old_notice = None + if case in {"fresh", "admission-crash"}: + if case == "admission-crash": + with monkeypatch.context() as crash: + def lose_transport_write(*_args): + raise OSError("lost transport admission projection") + + crash.setattr(transport, "_record_admission", lose_transport_write) + with pytest.raises(OSError, match="lost transport admission"): + transport.admit(profile, different) + assert json.loads(path.read_text())["status"] == "captured" + assert transport.admit(profile, different)["status"] == "durably_accepted" + queued = transport.core.read_request(path.stem) + assert queued["turn_id"] != old_turn and queued["session_id"] == sid + assert store.load_turn(sid, queued["turn_id"])["status"] == "queued" + else: + with monkeypatch.context() as old_behavior: + old_behavior.setattr(transport, "_distinct_steward_reply_topic", lambda *args: False, raising=False) + old_behavior.setattr(runtime.adapters[sid], "healthcheck", lambda: False) + assert transport.admit(profile, different)["status"] == "command_recorded" + transport.reconcile_request(path) + row = json.loads(path.read_text()) + old_notice = row["deliveries"]["terminal"] + assert row["status"] == "delivered" and old_notice["verified"] + assert not store.queued_turns(sid) + assert not any(call["method"] == "turn/steer" for call in map(json.loads, capture.read_text().splitlines())) + + completed = reply(_private_mention_event(provider, profile, "topic-finish", "Finish this original topic."), first_root) + assert transport.admit(profile, completed)["status"] == "command_recorded" + assert finish(runtime, original)["status"] == "completed" + + if old_notice is not None: + transport.reconcile_request(path) + assert transport.core.read_request(path.stem)["status"] == "command_completed" + old_bytes = path.read_bytes() + plan = transport.root / "rejected-mention-replays" / path.name + plan.parent.mkdir() + plan.write_text(json.dumps({"message_id": different["message_id"], + "rejection_message_id": old_notice["attempt"]["message_ref"], "target_turn_id": old_turn})) + if case == "edited": + provider.messages[different["message_id"]]["content"] = "A different instruction." + elif case == "unknown": + store.update_ingress_receipt(sid, f"external-{path.stem}", native_steering={"may_have_sent": True}) + elif case == "stale-scope": + store.update_session(sid, manager_authorization_scope_id="replaced-scope") + restarted = LarkPrivateConversations(controller=runtime, runtime_root=transport.runtime_root, + runner=provider, cli_bin="lark-cli") + assert path in restarted.pending_delivery_paths() + if case == "replay-crash": + write = external_conversations._atomic_write_json + + def lose_core_projection(target, row): + if target.stem == path.stem and row["status"] == "accepted": + raise OSError("lost Core admission projection") + write(target, row) + + with monkeypatch.context() as crash: + crash.setattr(external_conversations, "_atomic_write_json", lose_core_projection) + restarted.reconcile_request(path) + assert path.read_bytes() == old_bytes + committed = store.turn_for_client(sid, f"external-{path.stem}") + assert committed is not None + restarted = LarkPrivateConversations(controller=runtime, runtime_root=transport.runtime_root, + runner=provider, cli_bin="lark-cli") + restarted.reconcile_request(path) + assert restarted.core.read_request(path.stem)["turn_id"] == committed["turn_id"] + # A redelivery may race the original reply worker after recovery. + assert restarted.admit(profile, different)["status"] == "durably_accepted" + else: + restarted.reconcile_request(path) + if case in {"edited", "unknown", "same-topic", "stale-scope"}: + assert path.read_bytes() == old_bytes + assert store.turn_for_client(sid, f"external-{path.stem}") is None + return + transport = restarted + queued = transport.core.read_request(path.stem) + assert queued["turn_id"] != old_turn and queued["session_id"] == sid + assert queued["mention_delivery"]["action"] == "reject" + result = finish(runtime, queued) + assert result["status"] == "completed" + + def delivered(): + return json.loads(path.read_text())["status"] == "delivered" + + _drain_app_projection(transport, delivered) + row = json.loads(path.read_text()) + phase = "terminal" + if old_notice is not None: + assert row["deliveries"][phase] == old_notice + phase = "terminal.recovery.rejected-mention.1" + reply_ref = row["deliveries"][phase]["attempt"]["message_ref"] + assert row["deliveries"][phase]["verified"] + assert provider.messages[reply_ref]["chat_id"] == different["chat_id"] + assert provider.messages[reply_ref]["parent_id"] == different["message_id"] + before = capture.read_bytes(), list(provider.writes) + for _ in range(2): + transport.reconcile() + assert before == (capture.read_bytes(), provider.writes) + calls = [json.loads(line) for line in capture.read_text().splitlines()] + assert sum(call["method"] == "turn/steer" for call in calls) == 1 + assert sum(call["method"] == "turn/start" and "Answer this topic independently." in json.dumps(call.get("params")) + for call in calls) == 1 + finally: + runtime.close() + fixture.close() + + def test_private_steward_mention_requires_current_active_turn_authorization(tmp_path): from test_native_steward_private import steward from loopx.chat_manager_context import manager_authorization_scope_is_current From 3ac92c23cf1b689dd187389593dc03554766a8b5 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:32:11 +0800 Subject: [PATCH 2/2] Keep mention routing and replay in scoped modules Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../native_chat/external_conversations.py | 74 ---------- .../native_chat/external_mention_recovery.py | 90 ++++++++++++ .../extensions/lark/private_conversations.py | 106 +------------- .../extensions/lark/private_mention_topics.py | 132 ++++++++++++++++++ tests/test_lark_private_conversations.py | 11 +- 5 files changed, 235 insertions(+), 178 deletions(-) create mode 100644 loopx/capabilities/native_chat/external_mention_recovery.py create mode 100644 loopx/extensions/lark/private_mention_topics.py diff --git a/loopx/capabilities/native_chat/external_conversations.py b/loopx/capabilities/native_chat/external_conversations.py index 8f021c5032..cd587e8d5c 100644 --- a/loopx/capabilities/native_chat/external_conversations.py +++ b/loopx/capabilities/native_chat/external_conversations.py @@ -29,7 +29,6 @@ _atomic_write_json as _atomic_write_json, _read_json as _read_json, RESUMABLE_SESSION_STATES, - TERMINAL_TURN_STATES, ) from ...control_plane import effect_runtime from ...control_plane.quota.automation_cadence_readback import ( @@ -1542,79 +1541,6 @@ def _reject_prepared(path: Path, row: dict[str, Any]) -> None: row.update(status="rejected", response="原授权或命令格式不可用,本条未进入执行队列;请用 /agents 或 /project 查看可用入口。") _atomic_write_json(path, row) - def requeue_rejected_mention(self, request_ref: str, *, original_turn_id: str, - source_preflight: Callable[[dict[str, Any]], None]) -> dict[str, Any]: - """Admit an explicitly selected, independently verified private source once.""" - from ...chat import require_matching_replay - from ...chat_manager_context import manager_authorization_scope_is_current - - if not _REQUEST_JOURNAL_STEM.fullmatch(request_ref) or not callable(source_preflight): - raise ValueError("invalid original mention replay") - path = self.root / f"{request_ref}.json" - error = "live_steering_session_not_attached" - with exclusive_file_lock(path, operation="admit_external_chat_request"): - row = self.read_request(request_ref) - replay = row.get("rejected_mention_replay") - if replay is not None: - if replay["target_turn_id"] != original_turn_id: - raise ValueError("the original mention replay target changed") - if row["status"] == "accepted": - return row # Repair transport correlation after a committed admission. - sid = row["session_id"] - capture = row.get("mention_capture") or {} - if (row["status"] != "command_completed" or row.get("delivery_verified") is not True - or row.get("origin") != "lark" or row.get("command") or row.get("agent_target") - or row.get("attachments") or row.get("native_mention") is not True - or row["source"].get("private_human_message") is not True - or row.get("mention_delivery") != {"action": "reject", "error_code": error} - or row["turn_id"] != original_turn_id or capture.get("target_turn_id") != original_turn_id - or capture.get("session_id") != sid): - raise ValueError("the original mention lacks a pre-dispatch rejection") - route_lock = external_source_route_path(self.root, row["binding_id"], row["source"]["source_ref"]) - with exclusive_file_lock(route_lock, operation="route_external_chat_request"): - store = self.controller.store - client = f"external-{request_ref}" - session = store.load_session(sid) - prior = store.load_turn(sid, original_turn_id) - receipt = store.steering_receipt(sid, client) or {} - if (receipt.get("mode") != "live_steering" or receipt.get("status") != "failed" - or receipt.get("error_code") != error or receipt.get("expected_turn_id") != original_turn_id - or receipt.get("active_turn_id") is not None or receipt.get("native_steering") is not None - or receipt.get("message") != row["message"]): - raise ValueError("the original steering receipt does not prove non-delivery") - turn = store.turn_for_client(sid, client) - if turn is not None: - if replay is None: - raise ValueError("the original client identity already has a Turn") - require_matching_replay( - {**turn, "message": turn.get("_queue_original_message", turn.get("message"))}, - identity="client_turn_id", request={"message": row["message"], "attachments": None, - "origin": "lark", "external_agent_target": None}, - ) - else: - if (not session or session.get("status") == "closed" or not session.get("steward_context") - or not prior or prior["status"] not in TERMINAL_TURN_STATES - or self._source_stop_observed(row, prior, store.events_after(sid, original_turn_id, None))): - raise ValueError("the original mention replay is not eligible") - selected = resolve_external_admission_source( - self.bindings, row["binding_id"], row["source"], source_preflight, session=session, - ) - if (selected["owner_manager_audience"] is not True - or selected["channel_id"] != capture.get("channel_id") - or not manager_authorization_scope_is_current(self.controller.registry_path, - self.controller.manager_scope_resolver, session, session.get("manager_authorization_scope_id"), - runtime_root=self.controller.coordination_runtime_root)): - raise ValueError("the original steward source or authority changed") - if replay is None: - row["rejected_mention_replay"] = {"target_turn_id": original_turn_id, "original_response": row["response"]} - _atomic_write_json(path, row) - self._record_steward_ingress(row, selected, session, client) - turn, _ = self.controller.enqueue_turn(session_id=sid, client_turn_id=client, - message=row["message"], attachments=None, work_dir=Path("."), objective="", origin="lark") - row.update(status="accepted", turn_id=turn["turn_id"], response=None, delivery_verified=False) - _atomic_write_json(path, row) - return row - def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, Any], *, recovering_request: bool = False, source_preflight: Callable[[dict[str, Any]], None] | None = None) -> dict[str, Any]: diff --git a/loopx/capabilities/native_chat/external_mention_recovery.py b/loopx/capabilities/native_chat/external_mention_recovery.py new file mode 100644 index 0000000000..5280523f15 --- /dev/null +++ b/loopx/capabilities/native_chat/external_mention_recovery.py @@ -0,0 +1,90 @@ +"""Recover only a selected external mention with a proved pre-dispatch failure.""" + +from __future__ import annotations + +import re +from collections.abc import Callable +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from ...chat_ingress import resolve_external_admission_source +from ...chat_store import TERMINAL_TURN_STATES, _atomic_write_json +from ...file_lock import exclusive_file_lock +from .file_discovery import external_source_route_path + +if TYPE_CHECKING: + from .external_conversations import ChatExternalConversations + + +def requeue_rejected_mention(core: ChatExternalConversations, request_ref: str, *, original_turn_id: str, + source_preflight: Callable[[dict[str, Any]], None]) -> dict[str, Any]: + """Admit an explicitly selected, independently verified private source once.""" + from ...chat import require_matching_replay + from ...chat_manager_context import manager_authorization_scope_is_current + + if not re.fullmatch(r"[a-f0-9]{24}", request_ref) or not callable(source_preflight): + raise ValueError("invalid original mention replay") + path = core.root / f"{request_ref}.json" + error = "live_steering_session_not_attached" + with exclusive_file_lock(path, operation="admit_external_chat_request"): + row = core.read_request(request_ref) + replay = row.get("rejected_mention_replay") + if replay is not None: + if replay["target_turn_id"] != original_turn_id: + raise ValueError("the original mention replay target changed") + if row["status"] == "accepted": + return row # Repair transport correlation after a committed admission. + sid = row["session_id"] + capture = row.get("mention_capture") or {} + if (row["status"] != "command_completed" or row.get("delivery_verified") is not True + or row.get("origin") != "lark" or row.get("command") or row.get("agent_target") + or row.get("attachments") or row.get("native_mention") is not True + or row["source"].get("private_human_message") is not True + or row.get("mention_delivery") != {"action": "reject", "error_code": error} + or row["turn_id"] != original_turn_id or capture.get("target_turn_id") != original_turn_id + or capture.get("session_id") != sid): + raise ValueError("the original mention lacks a pre-dispatch rejection") + route_lock = external_source_route_path(core.root, row["binding_id"], row["source"]["source_ref"]) + with exclusive_file_lock(route_lock, operation="route_external_chat_request"): + store = core.controller.store + client = f"external-{request_ref}" + session = store.load_session(sid) + prior = store.load_turn(sid, original_turn_id) + receipt = store.steering_receipt(sid, client) or {} + if (receipt.get("mode") != "live_steering" or receipt.get("status") != "failed" + or receipt.get("error_code") != error or receipt.get("expected_turn_id") != original_turn_id + or receipt.get("active_turn_id") is not None or receipt.get("native_steering") is not None + or receipt.get("message") != row["message"]): + raise ValueError("the original steering receipt does not prove non-delivery") + turn = store.turn_for_client(sid, client) + if turn is not None: + if replay is None: + raise ValueError("the original client identity already has a Turn") + require_matching_replay( + {**turn, "message": turn.get("_queue_original_message", turn.get("message"))}, + identity="client_turn_id", request={"message": row["message"], "attachments": None, + "origin": "lark", "external_agent_target": None}, + ) + else: + if (not session or session.get("status") == "closed" or not session.get("steward_context") + or not prior or prior["status"] not in TERMINAL_TURN_STATES + or core._source_stop_observed(row, prior, store.events_after(sid, original_turn_id, None))): + raise ValueError("the original mention replay is not eligible") + selected = resolve_external_admission_source( + core.bindings, row["binding_id"], row["source"], source_preflight, session=session, + ) + if (selected["owner_manager_audience"] is not True + or selected["channel_id"] != capture.get("channel_id") + or not manager_authorization_scope_is_current(core.controller.registry_path, + core.controller.manager_scope_resolver, session, session.get("manager_authorization_scope_id"), + runtime_root=core.controller.coordination_runtime_root)): + raise ValueError("the original steward source or authority changed") + if replay is None: + row["rejected_mention_replay"] = {"target_turn_id": original_turn_id, "original_response": row["response"]} + _atomic_write_json(path, row) + core._record_steward_ingress(row, selected, session, client) + turn, _ = core.controller.enqueue_turn(session_id=sid, client_turn_id=client, + message=row["message"], attachments=None, work_dir=Path("."), objective="", origin="lark") + row.update(status="accepted", turn_id=turn["turn_id"], response=None, delivery_verified=False) + _atomic_write_json(path, row) + return row diff --git a/loopx/extensions/lark/private_conversations.py b/loopx/extensions/lark/private_conversations.py index 324872d053..f84b7bb7de 100644 --- a/loopx/extensions/lark/private_conversations.py +++ b/loopx/extensions/lark/private_conversations.py @@ -34,6 +34,7 @@ from ...control_plane.collaboration import conversation_reply_context from ...control_plane.effect_runtime import effect_runtime_request_scope from ...file_lock import exclusive_file_lock +from . import private_mention_topics from .conversation_identity import identity_ref, lark_private_source from .event_inbox import acknowledge_lark_event_inbox, ingest_lark_event_inbox from .event_collector_runtime import enrich_lark_event_reply_context @@ -632,10 +633,8 @@ def _record_admission(path: Path, record: dict[str, Any], admitted: dict[str, An record.update(status="captured" if admitted["status"] == "prepared" else admitted["status"], session_id=admitted["session_id"], turn_id=admitted["turn_id"], response=admitted.get("response"), response_code=admitted.get("response_code")) - if admitted.get("context_recovery"): - record["context_recovery"] = admitted["context_recovery"] - elif admitted["status"] == "accepted" and admitted.get("rejected_mention_replay"): - record["context_recovery"] = {"presentation_key": "rejected-mention.1"} + if recovery := admitted.get("context_recovery") or private_mention_topics.replay_presentation(admitted): + record["context_recovery"] = recovery if admitted.get("mention_delivery"): record["mention_delivery"] = admitted["mention_delivery"] _atomic_write_json(path, record) @@ -763,32 +762,6 @@ def read(args: Sequence[str], **_kwargs: Any) -> subprocess.CompletedProcess[str _atomic_write_json(path, record) return message - def _distinct_steward_reply_topic(self, record: dict[str, Any], binding: Mapping[str, Any]) -> bool: - if (binding.get("context_kind") != "steward" or binding.get("audience", "owner") != "owner" - or record["event"].get("chat_type") != "p2p"): - return False - root_id = record["event"].get("root_id") - capture = record.get("mention_capture") or {} - if (not root_id or record.get("reply_context_message") is None - or not capture.get("session_id") or not capture.get("target_turn_id")): - return False - turn = self.core.controller.store.load_turn(capture["session_id"], capture["target_turn_id"]) - match = re.fullmatch(r"external-([a-f0-9]{24})", str((turn or {}).get("client_turn_id") or "")) - if match is None or (turn or {}).get("origin") != "lark": - return False - try: - original = _read_json(self.root / f"{match[1]}.json") - except (OSError, ValueError): - return False - previous = original["event"] - return (original.get("turn_id") == capture["target_turn_id"] - and original.get("session_id") == capture["session_id"] - and original.get("reply_context_message") is not None - and _same_fields(original, record, "binding_id", "profile", "source") - and previous.get("chat_id") == record["event"].get("chat_id") - and bool(previous.get("root_id")) - and previous["root_id"] != root_id) - @effect_runtime_request_scope() def admit(self, profile: str, event: dict[str, Any], *, defer_background_stop: bool = False, history_review: bool = False, @@ -995,13 +968,7 @@ def verify_mention(fresh: dict[str, Any]) -> None: raise ValueError("native mention source changed") preflight = verify_mention - if (not (self.core.root / f"{request}.json").exists() - and self._distinct_steward_reply_topic(record, binding)): - # A verified reply to another topic belongs to the - # ordinary queue, even when it addresses this Bot. - record["mention_topic_queue"] = True - _atomic_write_json(path, record) - native_mention = not record.get("mention_topic_queue", False) + native_mention = private_mention_topics.steer_in_topic(self, path, record, binding) admitted = self.core.admit(binding_id=binding["binding_id"], source=source, request_ref=request, message=text, command=command, attachments=attachments, defer_background_stop=defer_background_stop, source_preflight=preflight, @@ -1604,64 +1571,6 @@ def _record_context_recovery_noop_backoff(self, path: Path, row: Mapping[str, An delay = float(60 + stagger if stagger_first else 60) if streak <= 1 else float(min(1800, 60 * (2 ** min(streak - 1, 5))) + stagger) self._context_recovery_probe_at[path] = time.monotonic() + delay - def _pending_rejected_mention_replays(self) -> Iterator[Path]: - folder = self.root / "rejected-mention-replays" - if folder.is_symlink(): - return - for plan in sorted(folder.glob("*.json")): - path = self.root / plan.name - if not re.fullmatch(r"[a-f0-9]{24}", path.stem) or plan.is_symlink() or not plan.is_file(): - continue - if time.monotonic() < self._context_recovery_probe_at.get(plan, 0): - continue - try: - row = _read_json(path) - except (OSError, ValueError): - continue - if (row.get("status") == "delivered" and not row.get("context_recovery") - and row.get("mention_delivery", {}).get("action") == "reject"): - yield path - - def _reconcile_rejected_mention(self, path: Path) -> None: - plan_path = self.root / "rejected-mention-replays" / path.name - if plan_path.parent.is_symlink() or plan_path.is_symlink() or not plan_path.is_file(): - return - self._context_recovery_probe_at[plan_path] = time.monotonic() + 60 - with exclusive_file_lock(path, operation="deliver_private_chat_request"): - record = _read_json(path) - if record.get("status") != "delivered" or record.get("context_recovery"): - return - terminal = record["deliveries"].get("terminal") or {} - try: - with plan_path.open("rb") as handle: - raw = handle.read(4097) - if len(raw) > 4096: - return - plan = json.loads(raw) - event = record["event"] - if (terminal.get("verified") is not True or plan != { - "message_id": event["message_id"], - "rejection_message_id": (terminal.get("attempt") or {}).get("message_ref"), - "target_turn_id": record["turn_id"], - } or not plan["rejection_message_id"] or record["request_ref"] != path.stem): - return - - def verify_source(selected: dict[str, Any]) -> None: - source = self._recovery_source_observation(record, selected) - if (source is None or source.get("_native_mention") is not True - or any(str(source.get(key) or "") != str(event.get(key) or "") for key in ("root_id", "parent_id")) - or (event.get("thread_id") and source.get("thread_id") != event["thread_id"]) - or not self._distinct_steward_reply_topic(record, selected["binding"])): - raise ValueError("the original distinct topic could not be verified") - - recovered = self.core.requeue_rejected_mention(record["request_ref"], - original_turn_id=plan["target_turn_id"], source_preflight=verify_source) - self._record_admission(path, record, recovered) - except (KeyError, ValueError, OSError, RuntimeError): - # An unavailable plan or uncertain source stays beside the - # original failure for a later independent observation. - return - @effect_runtime_request_scope() def pending_delivery_paths(self) -> list[Path]: """The durable transport store is the queue; no in-memory admission.""" @@ -1706,7 +1615,7 @@ def pending_delivery_paths(self) -> list[Path]: paths.append(path) else: self._record_context_recovery_noop_backoff(path, row, stagger_first=True) - return list(dict.fromkeys([*paths, *self._pending_rejected_mention_replays(), *self._web_projection_paths()])) + return [*paths, *private_mention_topics.pending_replays(self, set(paths)), *self._web_projection_paths()] def is_recovery_path(self, path: Path) -> bool: """Schedule recovery of persisted attempts after fresh replies.""" @@ -1812,10 +1721,7 @@ def reconcile_request(self, path: Path) -> int: row = _read_json(path) if "triage" in row: return triage.reconcile(self, path) - if (row.get("status") == "delivered" and not row.get("context_recovery") - and row.get("mention_delivery", {}).get("action") == "reject" - and (self.root / "rejected-mention-replays" / path.name).is_file()): - self._reconcile_rejected_mention(path) + if private_mention_topics.reconcile_rejection(self, path, row): return 0 historical_images = row.get("historical_answer_images") if (row.get("status") == "delivered" and ( diff --git a/loopx/extensions/lark/private_mention_topics.py b/loopx/extensions/lark/private_mention_topics.py new file mode 100644 index 0000000000..df172e26cd --- /dev/null +++ b/loopx/extensions/lark/private_mention_topics.py @@ -0,0 +1,132 @@ +"""Keep verified private steward reply topics distinct at mention admission.""" + +from __future__ import annotations + +import json +import re +import time +from collections.abc import Iterator, Mapping +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from ...capabilities.native_chat.external_mention_recovery import requeue_rejected_mention +from ...chat_store import _atomic_write_json, _read_json +from ...file_lock import exclusive_file_lock +from .private_web_projection import _same_fields + +if TYPE_CHECKING: + from .private_conversations import LarkPrivateConversations + +_REPLAY_FOLDER = "rejected-mention-replays" + + +def distinct_reply_topic(transport: LarkPrivateConversations, record: dict[str, Any], binding: Mapping[str, Any]) -> bool: + if (binding.get("context_kind") != "steward" or binding.get("audience", "owner") != "owner" + or record["event"].get("chat_type") != "p2p"): + return False + root_id = record["event"].get("root_id") + capture = record.get("mention_capture") or {} + if (not root_id or record.get("reply_context_message") is None + or not capture.get("session_id") or not capture.get("target_turn_id")): + return False + turn = transport.core.controller.store.load_turn(capture["session_id"], capture["target_turn_id"]) + match = re.fullmatch(r"external-([a-f0-9]{24})", str((turn or {}).get("client_turn_id") or "")) + if match is None or (turn or {}).get("origin") != "lark": + return False + try: + original = _read_json(transport.root / f"{match[1]}.json") + except (OSError, ValueError): + return False + previous = original["event"] + return (original.get("turn_id") == capture["target_turn_id"] + and original.get("session_id") == capture["session_id"] + and original.get("reply_context_message") is not None + and _same_fields(original, record, "binding_id", "profile", "source") + and previous.get("chat_id") == record["event"].get("chat_id") + and bool(previous.get("root_id")) + and previous["root_id"] != root_id) + +def steer_in_topic(transport: LarkPrivateConversations, path: Path, record: dict[str, Any], + binding: Mapping[str, Any]) -> bool: + # Freeze this decision before Core admission so redelivery can restore a + # missing transport projection with the same request identity and mode. + if record.get("mention_topic_queue"): + return False + if (transport.core.root / path.name).exists() or not distinct_reply_topic(transport, record, binding): + return True + record["mention_topic_queue"] = True + _atomic_write_json(path, record) + return False + + +def replay_presentation(admitted: Mapping[str, Any]) -> dict[str, str] | None: + if admitted["status"] == "accepted" and admitted.get("rejected_mention_replay"): + return {"presentation_key": "rejected-mention.1"} + return None + + +def pending_replays(transport: LarkPrivateConversations, scheduled: set[Path]) -> Iterator[Path]: + folder = transport.root / _REPLAY_FOLDER + if folder.is_symlink(): + return + for plan in sorted(folder.glob("*.json")): + path = transport.root / plan.name + if path in scheduled or not re.fullmatch(r"[a-f0-9]{24}", path.stem) or plan.is_symlink() or not plan.is_file(): + continue + if time.monotonic() < transport._context_recovery_probe_at.get(plan, 0): + continue + try: + row = _read_json(path) + except (OSError, ValueError): + continue + if (row.get("status") == "delivered" and not row.get("context_recovery") + and row.get("mention_delivery", {}).get("action") == "reject"): + yield path + +def reconcile_rejection(transport: LarkPrivateConversations, path: Path, row: dict[str, Any]) -> bool: + if (row.get("status") != "delivered" or row.get("context_recovery") + or row.get("mention_delivery", {}).get("action") != "reject"): + return False + plan_path = transport.root / _REPLAY_FOLDER / path.name + if plan_path.parent.is_symlink() or plan_path.is_symlink() or not plan_path.is_file(): + return False + _apply_replay(transport, path, plan_path) + return True + + +def _apply_replay(transport: LarkPrivateConversations, path: Path, plan_path: Path) -> None: + transport._context_recovery_probe_at[plan_path] = time.monotonic() + 60 + with exclusive_file_lock(path, operation="deliver_private_chat_request"): + record = _read_json(path) + if record.get("status") != "delivered" or record.get("context_recovery"): + return + terminal = record["deliveries"].get("terminal") or {} + try: + with plan_path.open("rb") as handle: + raw = handle.read(4097) + if len(raw) > 4096: + return + plan = json.loads(raw) + event = record["event"] + if (terminal.get("verified") is not True or plan != { + "message_id": event["message_id"], + "rejection_message_id": (terminal.get("attempt") or {}).get("message_ref"), + "target_turn_id": record["turn_id"], + } or not plan["rejection_message_id"] or record["request_ref"] != path.stem): + return + + def verify_source(selected: dict[str, Any]) -> None: + source = transport._recovery_source_observation(record, selected) + if (source is None or source.get("_native_mention") is not True + or any(str(source.get(key) or "") != str(event.get(key) or "") for key in ("root_id", "parent_id")) + or (event.get("thread_id") and source.get("thread_id") != event["thread_id"]) + or not distinct_reply_topic(transport, record, selected["binding"])): + raise ValueError("the original distinct topic could not be verified") + + recovered = requeue_rejected_mention(transport.core, record["request_ref"], + original_turn_id=plan["target_turn_id"], source_preflight=verify_source) + transport._record_admission(path, record, recovered) + except (KeyError, ValueError, OSError, RuntimeError): + # An unavailable plan or uncertain source stays beside the + # original failure for a later independent observation. + return diff --git a/tests/test_lark_private_conversations.py b/tests/test_lark_private_conversations.py index bca50931f0..4e43e167bb 100644 --- a/tests/test_lark_private_conversations.py +++ b/tests/test_lark_private_conversations.py @@ -7426,7 +7426,6 @@ def test_private_steward_native_mention_uses_original_manager_turn(tmp_path, mon "fresh", "admission-crash", "replay", "replay-crash", "edited", "unknown", "same-topic", "stale-scope", ]) def test_private_steward_distinct_topic_keeps_its_own_request(tmp_path, monkeypatch, case): - from loopx.capabilities.native_chat import external_conversations from test_native_steward_private import finish, steward fixture = steward.__wrapped__(tmp_path) @@ -7471,8 +7470,10 @@ def lose_transport_write(*_args): assert queued["turn_id"] != old_turn and queued["session_id"] == sid assert store.load_turn(sid, queued["turn_id"])["status"] == "queued" else: + from loopx.extensions.lark import private_mention_topics + with monkeypatch.context() as old_behavior: - old_behavior.setattr(transport, "_distinct_steward_reply_topic", lambda *args: False, raising=False) + old_behavior.setattr(private_mention_topics, "distinct_reply_topic", lambda *args: False) old_behavior.setattr(runtime.adapters[sid], "healthcheck", lambda: False) assert transport.admit(profile, different)["status"] == "command_recorded" transport.reconcile_request(path) @@ -7504,7 +7505,9 @@ def lose_transport_write(*_args): runner=provider, cli_bin="lark-cli") assert path in restarted.pending_delivery_paths() if case == "replay-crash": - write = external_conversations._atomic_write_json + from loopx.capabilities.native_chat import external_mention_recovery + + write = external_mention_recovery._atomic_write_json def lose_core_projection(target, row): if target.stem == path.stem and row["status"] == "accepted": @@ -7512,7 +7515,7 @@ def lose_core_projection(target, row): write(target, row) with monkeypatch.context() as crash: - crash.setattr(external_conversations, "_atomic_write_json", lose_core_projection) + crash.setattr(external_mention_recovery, "_atomic_write_json", lose_core_projection) restarted.reconcile_request(path) assert path.read_bytes() == old_bytes committed = store.turn_for_client(sid, f"external-{path.stem}")