Skip to content

The agent that grows with you

fix(plugin): classify Buzz DMs by p-tag so un-mentioned DMs dispatch

Rob Zehner7e1e3b92f8ff
diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.py
index 27bd03c6117..4752e77c041 100644
--- a/plugins/platforms/buzz/adapter.py
+++ b/plugins/platforms/buzz/adapter.py
@@ -67,7 +67,8 @@ _CHAT_KIND = 9
_FETCH_LIMIT = 50
# Bound on the per-channel de-dupe set (events, not bytes).
_SEEN_CAP = 500
-# Re-run ``buzz dms list`` every N poll sweeps to pick up new conversations.
+# Re-run DM discovery (``dms list`` plus the channels-list fallback) every
+# N poll sweeps to pick up conversations opened mid-run.
_DM_DISCOVERY_EVERY = 5
_DEFAULT_POLL_INTERVAL = 4.0
@@ -362,6 +363,9 @@ class BuzzAdapter(BasePlatformAdapter):
# channel_id -> {"chat_type", "last_ts", "seen": OrderedDict[event_id, None]}
self._channel_state: Dict[str, dict] = {}
self._channel_names: Dict[str, str] = {}
+ # channel_id -> raw ``channels list`` entry; drives DM-vs-channel
+ # classification (see _may_reclassify_as_dm).
+ self._channel_meta: Dict[str, dict] = {}
self._user_names: Dict[str, str] = {}
self._poll_count = 0
@@ -430,6 +434,9 @@ class BuzzAdapter(BasePlatformAdapter):
for ch in listed
if ch.get("channel_id")
}
+ for ch in listed:
+ if ch.get("channel_id"):
+ self._channel_meta[str(ch["channel_id"])] = ch
watch = self.channels or list(self._channel_names)
if not watch:
logger.error("Buzz: no channels to watch (configure BUZZ_CHANNELS or join a channel)")
@@ -629,24 +636,52 @@ class BuzzAdapter(BasePlatformAdapter):
if event_id:
state["seen"][str(event_id)] = None
state["last_ts"] = max(state["last_ts"], created_at)
+ # History is never dispatched, but it still classifies: a DM that
+ # leaked in via ``channels list`` latches to chat_type="dm" here,
+ # so it bypasses the mention gate from the very first poll.
+ self._maybe_latch_dm(channel_id, state, event)
self._trim_seen(state)
async def _discover_dms(self, *, seed: bool) -> None:
"""Watch DM conversations. New ones found mid-run dispatch from their
beginning (a fresh conversation has no history worth suppressing);
- ones present at startup are seeded like channels."""
+ ones present at startup are seeded like channels.
+
+ ``dms list`` is only a best-effort source: on some hosted relays it
+ returns ``[]`` even when DM conversations exist (#68871). Those DMs
+ DO surface in ``channels list`` as entries named "DM" with an empty
+ description, so that listing is scanned as a fallback. Fallback
+ finds are watched as ``group`` and latch to ``dm`` via p-tag
+ detection (_is_direct_message_event) rather than trusting the name
+ alone to unlock the mention-free DM path.
+ """
code, out, _err = await self._run_cli(["dms", "list"])
+ if code == 0:
+ for dm in _parse_json_list(out):
+ dm_id = str(dm.get("dm_id") or "")
+ if not dm_id or dm_id in self._channel_state:
+ continue
+ if seed:
+ await self._seed_channel(dm_id, chat_type="dm")
+ else:
+ self._channel_state[dm_id] = {"chat_type": "dm", "last_ts": 0, "seen": OrderedDict()}
+ self._channel_names.setdefault(dm_id, "DM")
+
+ code, out, _err = await self._run_cli(["channels", "list"])
if code != 0:
return
- for dm in _parse_json_list(out):
- dm_id = str(dm.get("dm_id") or "")
- if not dm_id or dm_id in self._channel_state:
+ for ch in _parse_json_list(out):
+ ch_id = str(ch.get("channel_id") or "")
+ if not ch_id:
+ continue
+ self._channel_meta[ch_id] = ch
+ self._channel_names.setdefault(ch_id, str(ch.get("name") or ch_id))
+ if ch_id in self._channel_state or not self._may_reclassify_as_dm(ch_id):
continue
if seed:
- await self._seed_channel(dm_id, chat_type="dm")
+ await self._seed_channel(ch_id, chat_type="group")
else:
- self._channel_state[dm_id] = {"chat_type": "dm", "last_ts": 0, "seen": OrderedDict()}
- self._channel_names.setdefault(dm_id, "DM")
+ self._channel_state[ch_id] = {"chat_type": "group", "last_ts": 0, "seen": OrderedDict()}
async def _poll_channel(self, channel_id: str) -> None:
state = self._channel_state.get(channel_id)
@@ -687,6 +722,10 @@ class BuzzAdapter(BasePlatformAdapter):
if pubkey == self._self_pubkey:
return
+ # Reclassify a leaked DM before gating so its first un-mentioned
+ # message both latches the conversation and dispatches.
+ self._maybe_latch_dm(channel_id, state, event)
+
is_dm = state["chat_type"] == "dm"
# In shared channels, respond only when addressed — unless
# require_mention is disabled, in which case respond to every message.
@@ -700,10 +739,11 @@ class BuzzAdapter(BasePlatformAdapter):
logger.debug("Buzz: ignoring message from unauthorized pubkey %s…", pubkey[:8])
return
- # In channels the message addressed us with a leading @mention; strip
- # it so slash commands (@Chip /whoami -> /whoami) and clean prompts are
- # recognized. DMs are already clean.
- dispatch_text = content if is_dm else self._strip_mention(content)
+ # Strip a leading @mention so slash commands (@Chip /whoami ->
+ # /whoami) and clean prompts are recognized. DM messages often still
+ # open with "@Chip" even though no mention is required there, so the
+ # strip applies to both chat types.
+ dispatch_text = self._strip_mention(content)
await self._dispatch_message(
text=dispatch_text,
@@ -715,6 +755,84 @@ class BuzzAdapter(BasePlatformAdapter):
created_at=created_at,
)
+ # ── DM classification (issue #68871) ──────────────────────────────────
+ #
+ # ``buzz dms list`` returns [] on some hosted relays even when DM
+ # conversations exist, so DMs leak in via ``channels list`` and get
+ # watched as chat_type="group" — which wrongly puts them behind the
+ # channel mention gate. Classification therefore keys off the Nostr
+ # tags of the messages themselves. Observed on a live hosted relay:
+ #
+ # * every message another user sends IN A DM carries a structural
+ # ["p", <our pubkey>] tag, even when the text never mentions us
+ # (recipient addressing);
+ # * in a real channel, a ["p", <our pubkey>] tag appears only when the
+ # text visibly @mentions us (typed mention, with or without a reply
+ # ["e", ...] tag) — never on plain broadcasts.
+ #
+ # So "p-tagged to self WITHOUT a visible mention in the content" is the
+ # DM discriminator: in a channel that combination does not occur, and a
+ # channel reply/mention that p-tags us is excluded because the mention
+ # is right there in the text. As a second, independent guard, a
+ # conversation whose ``channels list`` metadata looks like a real
+ # community channel (real name / non-empty description) is never
+ # reclassified at all, whereas relay-materialized DMs are always named
+ # "DM" with an empty description. Nothing is lost while unlatched: a
+ # DM message that DOES mention us dispatches through the mention gate
+ # anyway, so the latch flips exactly on the first message that needs it.
+
+ def _may_reclassify_as_dm(self, channel_id: str) -> bool:
+ """True when the conversation's metadata does not rule out a DM.
+
+ Known real community channels (real name or non-empty description in
+ ``channels list``) must never turn into DMs just because a message
+ p-tags us. A conversation with no metadata at all is trusted only
+ when the user did not explicitly configure it as a watched channel.
+ """
+ meta = self._channel_meta.get(channel_id)
+ if meta is None:
+ return channel_id not in self.channels
+ name = str(meta.get("name") or "").strip()
+ description = str(meta.get("description") or "").strip()
+ return name == "DM" and not description
+
+ def _is_direct_message_event(self, channel_id: str, event: dict) -> bool:
+ """True when ``event`` is shaped like a direct message to us: a chat
+ message from another user, p-tagged to our pubkey, whose content does
+ NOT visibly mention us — i.e. the p-tag is structural DM addressing,
+ not the artifact of a typed @mention (see block comment above)."""
+ if not self._self_pubkey or not self._may_reclassify_as_dm(channel_id):
+ return False
+ if int(event.get("kind") or 0) != _CHAT_KIND:
+ return False
+ pubkey = str(event.get("pubkey") or "").lower()
+ if not pubkey or pubkey == self._self_pubkey:
+ return False
+ tags = event.get("tags")
+ if not isinstance(tags, list):
+ return False
+ p_tagged_to_self = any(
+ isinstance(tag, (list, tuple))
+ and len(tag) > 1
+ and tag[0] == "p"
+ and str(tag[1]).lower() == self._self_pubkey
+ for tag in tags
+ )
+ if not p_tagged_to_self:
+ return False
+ content = event.get("content")
+ return isinstance(content, str) and not self._is_mentioned(content)
+
+ def _maybe_latch_dm(self, channel_id: str, state: dict, event: dict) -> None:
+ """Latch a group conversation to chat_type="dm" once any direct
+ message is seen; the classification then sticks so subsequent
+ un-mentioned messages in the conversation dispatch too."""
+ if state["chat_type"] == "dm" or not self._is_direct_message_event(channel_id, event):
+ return
+ state["chat_type"] = "dm"
+ self._channel_names.setdefault(channel_id, "DM")
+ logger.info("Buzz: conversation %s reclassified as DM (message p-tagged to self)", channel_id)
+
def _is_mentioned(self, content: str) -> bool:
"""True when the message addresses this agent (npub, hex, or name)."""
lowered = content.lower()
diff --git a/tests/gateway/test_buzz_adapter.py b/tests/gateway/test_buzz_adapter.py
index db1468cffa0..8ec0fba1280 100644
--- a/tests/gateway/test_buzz_adapter.py
+++ b/tests/gateway/test_buzz_adapter.py
@@ -30,6 +30,10 @@ SELF_PUBKEY = "9fd5c7ba6d3ef224da78f541e0fcb9c50f72cc63edb19aae76ac6a0474dfa860"
SELF_NPUB = "npub1nl2u0wnd8mezfknc74q7pl9ec58h9nrrakce4tnk434qgaxl4psqe5twr6"
OTHER_PUBKEY = "a" * 64
CHANNEL = "ccc2bc1a-7a82-5a8f-8c4e-57a070cbe7cd"
+# Real DM conversation as materialized by a hosted relay: `dms list` returns
+# [] for it (#68871) while `channels list` shows it as name "DM", empty
+# description, indistinguishable from a channel except via message p-tags.
+DM_CHANNEL = "6468cc16-a114-4f23-8b8c-02c1655cbf6b"
_ENV_VARS = (
"BUZZ_RELAY_URL",
@@ -377,6 +381,223 @@ class TestMentionGating:
assert len(a._dispatched) == 1
+# ── DM classification via p-tags (issue #68871) ──────────────────────────
+#
+# `buzz dms list` returns [] on some hosted relays, so DM conversations leak
+# in via `channels list` and get seeded chat_type="group". The adapter must
+# reclassify them from the Nostr tags of real traffic: DM messages are
+# p-tagged to our own pubkey WITHOUT the text mentioning us, while channel
+# messages only ever p-tag us when the text visibly @mentions us.
+
+
+def _tagged_event(event_id, channel, *, content, pubkey=OTHER_PUBKEY,
+ created_at=1000, kind=9, p=None, reply_to=None):
+ """Event with the tag shapes observed on a live relay (h/p/e tags)."""
+ tags = [["h", channel]]
+ if reply_to:
+ tags.append(["e", reply_to, "", "reply"])
+ if p:
+ tags.append(["p", p])
+ return {
+ "id": event_id,
+ "pubkey": pubkey,
+ "content": content,
+ "created_at": created_at,
+ "kind": kind,
+ "tags": tags,
+ }
+
+
+class TestDmClassification:
+
+ @pytest.fixture
+ def adapter(self):
+ a = _make_adapter()
+ a._dispatched = []
+
+ async def capture(**kwargs):
+ a._dispatched.append(kwargs)
+
+ a._dispatch_message = capture
+ a._message_handler = AsyncMock()
+ # Metadata exactly as `channels list` returns it on the hosted relay.
+ a._channel_meta = {
+ DM_CHANNEL: {"channel_id": DM_CHANNEL, "name": "DM", "description": ""},
+ CHANNEL: {
+ "channel_id": CHANNEL,
+ "name": "general",
+ "description": "General conversation and community updates.",
+ },
+ }
+ a._channel_names = {DM_CHANNEL: "DM", CHANNEL: "general"}
+ # Both leaked in as group — the bug under test.
+ a._channel_state[DM_CHANNEL] = {"chat_type": "group", "last_ts": 0, "seen": {}}
+ a._channel_state[CHANNEL] = {"chat_type": "group", "last_ts": 0, "seen": {}}
+ return a
+
+ async def _poll_with(self, adapter, channel, *events):
+ cli = _ScriptedCli()
+ cli.script("messages", "get", list(events))
+ adapter._run_cli = cli
+ await adapter._poll_channel(channel)
+
+ @pytest.mark.asyncio
+ async def test_unmentioned_ptagged_dm_latches_and_dispatches(self, adapter):
+ """The reported bug: a DM without an @mention must dispatch."""
+ await self._poll_with(
+ adapter, DM_CHANNEL,
+ _tagged_event("e1", DM_CHANNEL, content="here's a test message", p=SELF_PUBKEY),
+ )
+ assert adapter._channel_state[DM_CHANNEL]["chat_type"] == "dm"
+ assert [d["message_id"] for d in adapter._dispatched] == ["e1"]
+ assert adapter._dispatched[0]["chat_type"] == "dm"
+
+ @pytest.mark.asyncio
+ async def test_dm_latch_persists_for_followup_messages(self, adapter):
+ await self._poll_with(
+ adapter, DM_CHANNEL,
+ _tagged_event("e1", DM_CHANNEL, content="first direct message", p=SELF_PUBKEY),
+ )
+ # Follow-up carries no p-tag at all — the latched state must carry it.
+ await self._poll_with(
+ adapter, DM_CHANNEL,
+ _tagged_event("e2", DM_CHANNEL, content="and a follow-up", created_at=1001),
+ )
+ assert [d["message_id"] for d in adapter._dispatched] == ["e1", "e2"]
+
+ @pytest.mark.asyncio
+ async def test_general_broadcast_without_mention_still_gated(self, adapter):
+ await self._poll_with(
+ adapter, CHANNEL,
+ _tagged_event("e1", CHANNEL, content="just chatting away"),
+ )
+ assert adapter._dispatched == []
+ assert adapter._channel_state[CHANNEL]["chat_type"] == "group"
+
+ @pytest.mark.asyncio
+ async def test_general_reply_ptagging_self_stays_channel(self, adapter):
+ """A #general reply to us p-tags our pubkey (observed live) — that
+ must NOT reclassify the channel; mention gating still applies."""
+ await self._poll_with(
+ adapter, CHANNEL,
+ _tagged_event("e1", CHANNEL, content="@chip what's up?",
+ p=SELF_PUBKEY, reply_to="root-event"),
+ )
+ assert adapter._channel_state[CHANNEL]["chat_type"] == "group"
+ # It carried a mention, so it dispatches — but as a group message.
+ assert [d["chat_type"] for d in adapter._dispatched] == ["group"]
+
+ # And once the mention is absent, the channel gate drops the message
+ # even though the earlier reply p-tagged us.
+ await self._poll_with(
+ adapter, CHANNEL,
+ _tagged_event("e2", CHANNEL, content="thanks everyone", created_at=1001),
+ )
+ assert len(adapter._dispatched) == 1
+
+ @pytest.mark.asyncio
+ async def test_general_nonreply_mention_ptag_stays_channel(self, adapter):
+ """Typed channel mentions p-tag us WITHOUT a reply tag (observed
+ live: '@Chip are you up and running?') — still not a DM: the p-tag
+ is explained by the visible mention, and the metadata guard protects
+ real channels regardless."""
+ await self._poll_with(
+ adapter, CHANNEL,
+ _tagged_event("e1", CHANNEL, content="@Chip are you up and running?", p=SELF_PUBKEY),
+ )
+ assert adapter._channel_state[CHANNEL]["chat_type"] == "group"
+ assert [d["chat_type"] for d in adapter._dispatched] == ["group"]
+
+ @pytest.mark.asyncio
+ async def test_channel_like_metadata_blocks_latch_even_without_mention(self, adapter):
+ """Second guard on its own: even a p-tagged, un-mentioned message
+ cannot reclassify a conversation whose metadata says real channel."""
+ adapter._channel_meta[CHANNEL]["description"] = ""
+ adapter._channel_meta[CHANNEL]["name"] = "announcements"
+ await self._poll_with(
+ adapter, CHANNEL,
+ _tagged_event("e1", CHANNEL, content="fyi everyone", p=SELF_PUBKEY),
+ )
+ assert adapter._channel_state[CHANNEL]["chat_type"] == "group"
+ assert adapter._dispatched == []
+
+ @pytest.mark.asyncio
+ async def test_configured_channel_without_metadata_not_latched(self):
+ a = _make_adapter({"channels": ["private-chan"]})
+ a._dispatched = []
+
+ async def capture(**kwargs):
+ a._dispatched.append(kwargs)
+
+ a._dispatch_message = capture
+ a._message_handler = AsyncMock()
+ a._channel_state["private-chan"] = {"chat_type": "group", "last_ts": 0, "seen": {}}
+ cli = _ScriptedCli()
+ cli.script("messages", "get", [
+ _tagged_event("e1", "private-chan", content="no mention here", p=SELF_PUBKEY),
+ ])
+ a._run_cli = cli
+ await a._poll_channel("private-chan")
+ assert a._channel_state["private-chan"]["chat_type"] == "group"
+ assert a._dispatched == []
+
+ @pytest.mark.asyncio
+ async def test_seed_latches_dm_from_history_without_dispatch(self, adapter):
+ cli = _ScriptedCli()
+ cli.script("messages", "get", [
+ _tagged_event("h1", DM_CHANNEL, content="@Chip hello there", p=SELF_PUBKEY, created_at=100),
+ _tagged_event("h2", DM_CHANNEL, content="here's a test message", p=SELF_PUBKEY, created_at=200),
+ _tagged_event("h3", DM_CHANNEL, content="my own reply", pubkey=SELF_PUBKEY, created_at=300),
+ ])
+ adapter._run_cli = cli
+ await adapter._seed_channel(DM_CHANNEL, chat_type="group")
+ assert adapter._channel_state[DM_CHANNEL]["chat_type"] == "dm"
+ # Seeding classifies but never replays history into the agent.
+ assert adapter._dispatched == []
+
+ @pytest.mark.asyncio
+ async def test_non_chat_kind_ptag_does_not_latch(self, adapter):
+ """Housekeeping events (joins, member adds) may p-tag members —
+ only kind-9 chat traffic classifies."""
+ cli = _ScriptedCli()
+ cli.script("messages", "get", [
+ _tagged_event("h1", DM_CHANNEL, content="member added", p=SELF_PUBKEY, kind=40002),
+ ])
+ adapter._run_cli = cli
+ await adapter._seed_channel(DM_CHANNEL, chat_type="group")
+ assert adapter._channel_state[DM_CHANNEL]["chat_type"] == "group"
+
+ @pytest.mark.asyncio
+ async def test_dm_leading_mention_stripped_for_commands(self, adapter):
+ adapter._channel_state[DM_CHANNEL]["chat_type"] = "dm"
+ await self._poll_with(
+ adapter, DM_CHANNEL,
+ _tagged_event("e1", DM_CHANNEL, content="@chip /whoami", p=SELF_PUBKEY),
+ )
+ assert adapter._dispatched[0]["text"] == "/whoami"
+
+ @pytest.mark.asyncio
+ async def test_dm_shaped_channel_discovered_when_dms_list_empty(self):
+ """Fallback discovery: with `dms list` broken (returns []), a
+ DM-shaped `channels list` entry gets watched; real channels not
+ already watched are left alone."""
+ a = _make_adapter()
+ cli = _ScriptedCli()
+ cli.script("dms", "list", [])
+ cli.script("channels", "list", [
+ {"channel_id": DM_CHANNEL, "name": "DM", "description": "", "created_at": 1},
+ {"channel_id": CHANNEL, "name": "general",
+ "description": "General conversation and community updates.", "created_at": 2},
+ ])
+ a._run_cli = cli
+ await a._discover_dms(seed=False)
+ # Watched as group; the p-tag latch flips it on the first real DM.
+ assert a._channel_state[DM_CHANNEL]["chat_type"] == "group"
+ assert a._may_reclassify_as_dm(DM_CHANNEL) is True
+ assert CHANNEL not in a._channel_state
+ assert a._may_reclassify_as_dm(CHANNEL) is False
+
+
# ── Sending ───────────────────────────────────────────────────────────────