Skip to content

Commit 5d5a9df

Browse files
committed
fix(lark): require native worker group eligibility before dual-@ manager dedup
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 65ff228 commit 5d5a9df

4 files changed

Lines changed: 207 additions & 6 deletions

File tree

‎loopx/extensions/lark/goal_topic_runtime.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ def _active_group_profile_configs(snapshot: Mapping[str, object]) -> dict[str, d
250250
return profiles
251251

252252

253-
def _active_profile_configs(snapshot: Mapping[str, object]) -> dict[str, dict[str, str]]:
253+
def _active_profile_configs(snapshot: Mapping[str, object]) -> dict[str, dict[str, object]]:
254254
from .conversation_identity import identity_ref
255255

256256
profiles = _active_group_profile_configs(snapshot)

‎loopx/extensions/lark/manager_routing.py‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,40 @@ def text_field(key: str) -> str:
323323
}
324324

325325

326+
def _native_group_worker_eligible(
327+
raw_config: Mapping[str, Any],
328+
*,
329+
event: Mapping[str, Any] | None,
330+
) -> bool:
331+
from .conversation_identity import identity_ref, lark_private_source
332+
333+
if raw_config.get("audience") != "group" or raw_config.get("enabled") is False or event is None:
334+
return False
335+
raw_groups = raw_config.get("group_refs")
336+
if not isinstance(raw_groups, (list, tuple, set)):
337+
return False
338+
granted_groups = {str(ref).strip() for ref in raw_groups if str(ref).strip()}
339+
if not granted_groups:
340+
return False
341+
provider_ref = str(raw_config.get("provider_ref") or "").strip()
342+
bot_app_id = str(raw_config.get("bot_app_id") or "").strip()
343+
if not provider_ref:
344+
if not bot_app_id:
345+
return False
346+
provider_ref = identity_ref(bot_app_id)
347+
elif bot_app_id and identity_ref(bot_app_id) != provider_ref:
348+
return False
349+
try:
350+
source = lark_private_source(provider_ref=provider_ref, event=event)
351+
except ValueError:
352+
return False
353+
return (
354+
event.get("chat_type") == "group"
355+
and source.get("group_human_message") is True
356+
and str(source.get("group_ref") or "") in granted_groups
357+
)
358+
359+
326360
def group_peer_worker_identities(
327361
snapshot: Mapping[str, Any],
328362
*,
@@ -337,7 +371,7 @@ def group_peer_worker_identities(
337371
for peer_profile, raw_config in raw_profiles.items():
338372
if str(peer_profile) == profile or not isinstance(raw_config, Mapping):
339373
continue
340-
if raw_config.get("audience") != "group":
374+
if not _native_group_worker_eligible(raw_config, event=event):
341375
continue
342376
entry: dict[str, str] = {"sender_profile": str(peer_profile)}
343377
for key in ("bot_app_id", "bot_open_id", "bot_display_name"):

‎loopx/extensions/lark/private_conversations.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from pathlib import Path
1616
import re
1717
import time
18-
from typing import TYPE_CHECKING, Protocol, cast
18+
from typing import TYPE_CHECKING, Any, Protocol, cast
1919
import zlib
2020

2121
from ...capabilities.native_chat.external_conversations import (
@@ -149,24 +149,27 @@ def __init__(
149149
self.steward_reports = LarkStewardReports(self)
150150
setattr(controller, "steward_report_provider", self.steward_reports)
151151

152-
def profiles(self) -> dict[str, dict[str, str]]:
152+
def profiles(self) -> dict[str, dict[str, Any]]:
153153
"""Discover current App configuration, never authorize a conversation."""
154154
bindings = self.bindings.read()["bindings"]
155155
if not bindings:
156156
return {}
157157
apps = self.configured_profile_apps()
158-
profiles: dict[str, dict[str, str]] = {}
158+
profiles: dict[str, dict[str, Any]] = {}
159159
for row in bindings:
160160
transport_ref = str(row["transport_ref"])
161161
app_id = apps.get(transport_ref, "")
162162
if row.get("enabled") is not True or not app_id or identity_ref(app_id) != row["provider_ref"]:
163163
continue
164-
profiles[transport_ref] = {
164+
entry: dict[str, Any] = {
165165
"cli_bin": self.cli_bin, "provider_ref": str(row["provider_ref"]),
166166
"bot_app_id": app_id, "audience": str(row.get("audience", "owner")),
167167
"context_kind": str(row["context_kind"]), "binding_id": str(row["binding_id"]),
168168
"consumer_ref": hashlib.sha256(app_id.encode("utf-8")).hexdigest()[:32],
169169
}
170+
if row.get("audience") == "group" and isinstance(row.get("group_refs"), list):
171+
entry["group_refs"] = [str(ref) for ref in row["group_refs"]]
172+
profiles[transport_ref] = entry
170173
return profiles
171174

172175
def configured_profile_apps(self, *, cli_bin: str | None = None) -> dict[str, str]:

‎tests/extensions/test_lark_direct_group_dispatch.py‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
"""Real binding/inbox/receipt checks; model and provider replies are doubles."""
22

33
import json
4+
from contextlib import closing
45
from datetime import UTC, datetime
56

67
import pytest
8+
from test_chat_ordinary_project import ordinary # noqa: F401
79

810
from loopx.extensions.lark import goal_topic_runtime as runtime
911
from loopx.extensions.lark.goal_channel_contracts import (
@@ -650,3 +652,165 @@ def test_dual_mention_top_level_ambiguous_multi_topic_worker_executes_steward(
650652
assert steward_poll["replied_count"] == 1
651653
assert steward_poll["event_statuses"] == ["replied_and_acknowledged"]
652654
assert answers == [top_event["content"]]
655+
656+
657+
def test_dual_mention_with_native_group_worker_respects_granted_groups(
658+
ordinary, tmp_path, monkeypatch # noqa: F811
659+
):
660+
from loopx.extensions.lark.conversation_identity import identity_ref
661+
from test_lark_private_conversations import connect_group
662+
663+
monkeypatch.setattr(
664+
runtime, "ensure_lark_event_inbox_received_reaction", lambda **_: {"ok": True}
665+
)
666+
_store, priv_runtime, provider, transport = connect_group(ordinary)
667+
with closing(priv_runtime):
668+
profiles = transport.profiles()
669+
native_cfg = profiles["notes-app"]
670+
assert len(native_cfg["group_refs"]) == 2
671+
native_provider_ref = native_cfg["provider_ref"]
672+
assert set(native_cfg["group_refs"]) == {
673+
identity_ref(native_provider_ref, "oc_community"),
674+
identity_ref(native_provider_ref, "oc_second"),
675+
}
676+
677+
steward_dir = tmp_path / "steward-g1-g3"
678+
steward_fixture = _dual_mention_fixture(steward_dir, turn_trigger="addressed")
679+
steward_targets = {
680+
k: v for k, v in steward_fixture["target_payload"]["targets"].items() if k != "lark_worker"
681+
}
682+
g1_target_ref, g1_target = next(iter(steward_targets.items()))
683+
targets = {
684+
**steward_fixture["target_payload"],
685+
"targets": {
686+
g1_target_ref: g1_target,
687+
"lark_g3": {
688+
**g1_target,
689+
"channel": {**g1_target["channel"], "chat_id": "oc_third"},
690+
},
691+
},
692+
}
693+
g1_chat_id = g1_target["channel"]["chat_id"]
694+
# Grant native worker [g1_chat_id, oc_second]; oc_third remains Steward-only.
695+
binding_row = transport.bindings.read()["bindings"][0]
696+
refs = [identity_ref(native_provider_ref, chat) for chat in (g1_chat_id, "oc_second")]
697+
transport.bindings.configure(
698+
transport_ref="notes-app",
699+
project_ref=binding_row["project_ref"],
700+
executor_endpoint_id="codex",
701+
audience="group",
702+
group_refs=refs,
703+
available_group_refs=refs,
704+
)
705+
profiles = transport.profiles()
706+
707+
g1_bindings = steward_fixture["steward_bindings"]["goal-alpha"]
708+
g1_conn_id, g1_conn = next(
709+
iter(g1_bindings["bindings"]["goal-alpha"]["connections"].items())
710+
)
711+
g3_conn = {
712+
**g1_conn,
713+
"connection_id": "conn_manager_g3",
714+
"target_ref": "lark_g3",
715+
}
716+
binding_payloads = {
717+
"goal-alpha": {
718+
**g1_bindings,
719+
"bindings": {
720+
"goal-alpha": {
721+
**g1_bindings["bindings"]["goal-alpha"],
722+
"connections": {
723+
g1_conn_id: g1_conn,
724+
"conn_manager_g3": g3_conn,
725+
},
726+
}
727+
},
728+
}
729+
}
730+
snapshot = {
731+
"target_payload": targets,
732+
"binding_payloads": binding_payloads,
733+
"private_profiles": profiles,
734+
}
735+
736+
def make_dual_event(name: str, chat_id: str) -> dict[str, object]:
737+
mentions = [
738+
{"id": {"open_id": "ou_steward_bot"}, "name": "LoopX Mew"},
739+
{"id": {"app_id": native_cfg["bot_app_id"], "open_id": "ou_notes_app_bot"}, "name": "Notes App"},
740+
]
741+
ev = provider.topic(name, "@LoopX Mew @Notes App handle this", chat=chat_id, sender="ou_public_owner")
742+
ev["chat_mode"] = "group"
743+
ev["mentions"] = mentions
744+
provider.messages[ev["message_id"]]["mentions"] = mentions
745+
return ev
746+
747+
# Case 1: Dual-@ in G3 (oc_third) where native worker is NOT granted -> worker rejects, Steward replies once.
748+
g3_event = make_dual_event("dual_g3", "oc_third")
749+
worker_g3 = runtime.poll_lark_goal_topic_profile_once(
750+
profile="notes-app",
751+
snapshot=snapshot,
752+
runtime_root=transport.runtime_root,
753+
answer=lambda *_a: pytest.fail("ungranted native worker must not answer"),
754+
consume_runner=lambda _a: {"returncode": 0, "stdout": json.dumps(g3_event), "stderr": ""},
755+
private_admitter=transport.admit,
756+
)
757+
assert worker_g3["event_statuses"] == ["audience_rejected"]
758+
759+
steward_answers = []
760+
_sstate, srunner = _steward_poll_runner()
761+
def g3_reply_runner(args):
762+
if "chats" in args:
763+
return {"returncode": 0, "stdout": json.dumps({"data": {"chat_id": "oc_third"}})}
764+
if "+messages-send" in args:
765+
content = args[args.index("--content") + 1]
766+
if "--dry-run" in args:
767+
return {"returncode": 0, "stdout": json.dumps({"api": [{"body": {"msg_type": "post", "content": content}}]})}
768+
_sstate.setdefault("calls", []).append(args)
769+
_sstate["last_content"] = content
770+
return {"returncode": 0, "stdout": json.dumps({"data": {"message_id": "om_g3_reply"}})}
771+
if "+messages-mget" in args:
772+
return {"returncode": 0, "stdout": json.dumps({"data": {"items": [{
773+
"message_id": "om_g3_reply", "msg_type": "post", "chat_id": "oc_third",
774+
"body": {"content": _sstate["last_content"]},
775+
"sender": {"id": "cli_steward", "sender_type": "app"},
776+
}]}})}
777+
return srunner(args)
778+
779+
steward_g3 = runtime.poll_lark_goal_topic_profile_once(
780+
profile="mew",
781+
snapshot=snapshot,
782+
runtime_root=steward_dir / "runtime",
783+
answer=lambda route, text: steward_answers.append(text) or {
784+
"response_text": "Steward replied in G3.",
785+
"effect_receipt": runtime._session_turn_effect(route),
786+
},
787+
consume_runner=lambda _a: {"returncode": 0, "stdout": json.dumps(g3_event), "stderr": ""},
788+
reply_runner=g3_reply_runner,
789+
)
790+
assert steward_g3["replied_count"] == 1, steward_g3
791+
assert steward_g3["event_statuses"] == ["replied_and_acknowledged"]
792+
assert steward_answers == [g3_event["content"]]
793+
794+
# Case 2: Dual-@ in G1 (granted to native worker) -> native worker admits, Steward stays context-only silent.
795+
g1_event = make_dual_event("dual_g1", g1_chat_id)
796+
worker_g1 = runtime.poll_lark_goal_topic_profile_once(
797+
profile="notes-app",
798+
snapshot=snapshot,
799+
runtime_root=transport.runtime_root,
800+
answer=lambda *_a: pytest.fail("native path owns admission"),
801+
consume_runner=lambda _a: {"returncode": 0, "stdout": json.dumps(g1_event), "stderr": ""},
802+
private_admitter=transport.admit,
803+
)
804+
assert worker_g1["event_statuses"] == ["durably_accepted"]
805+
806+
steward_g1 = runtime.poll_lark_goal_topic_profile_once(
807+
profile="mew",
808+
snapshot=snapshot,
809+
runtime_root=steward_dir / "runtime",
810+
answer=lambda *_a: pytest.fail("Steward must stay silent when granted native worker handles dual-@"),
811+
consume_runner=lambda _a: {"returncode": 0, "stdout": json.dumps(g1_event), "stderr": ""},
812+
reply_runner=srunner,
813+
)
814+
assert steward_g1["replied_count"] == 0
815+
assert steward_g1["event_statuses"] == ["context_only_captured"]
816+
assert steward_g1["event_reasons"] == ["worker_co_addressed"]

0 commit comments

Comments
 (0)