diff --git a/README.md b/README.md index 9499dbc..a9b793a 100644 --- a/README.md +++ b/README.md @@ -365,6 +365,8 @@ while tool_calls and rounds < profile.max_rounds: ### Trajectory Replay (`CONVERSATIONS_TRAJECTORY_*`) Each turn captures the **exact rendered user message** plus the serialized internal loop (assistant tool calls, tool results, final answer). On follow-ups, the most recent `CONVERSATIONS_TRAJECTORY_TURNS` turns are replayed **verbatim** — the model literally sees its own prior tool calls and their results instead of a distilled Q/A pair. Older turns (and turns captured before this feature, or whose trajectory was dropped as invalid/oversized) fall back to the compact attributed rendering. +Everyone in a conversation is the `user` role, so when the speaker changes from one turn to the next the `[Por …]` tag says so (`outra pessoa — antes falava Ana (@ana)`). The mark is written when the turn is captured, so verbatim replay keeps it without re-rendering; compact turns get the same mark. + Replay windows advance in `CONVERSATIONS_TRAJECTORY_STEP`-turn steps (hysteresis), so the replayed prefix only changes at deliberate collapse boundaries — not sliding every turn — which is what keeps the provider prefix cache effective. Explicit `cache_control` breakpoints mark the system prompt and the last replayed history message for Anthropic/Gemini via OpenRouter; OpenAI-compatible endpoints ignore them and cache automatically. Captured trajectories are sanitized on persist (no `reasoning`/thinking payloads, tool-call/result pairing enforced). ### Rate Limiting @@ -373,7 +375,7 @@ Conversations (`/chat`, `/ask`, mentions, replies, name calls, monitors) use the ### Context Injection Every AI call receives a `` block with user (display name, account age, join date, roles), guild (name, member count, channels, roles), channel, and temporal (BRT + UTC) context, plus a `` block with the channel's `instructions` setting when it has one. -When `CHANNEL_CONTEXT_MESSAGES` > 0 (default `30`), every conversational turn also receives a `` block — the latest N channel messages in chronological order, trimmed from the oldest side to `CHANNEL_CONTEXT_MAX_CHARS` (in a fast chat ten messages is a minute of talk, and what "esse sinal" points at can be further back), same format as the `get_channel_history` tool. Image attachments in that context are persisted and sent as vision parts, up to the four-image per-message budget (current-message images take priority, then the newest channel images); filenames remain visible in the text context. Only images posted within `CHANNEL_CONTEXT_IMAGE_MAX_AGE_MINUTES` (default `60`) are sent, and `CHANNEL_CONTEXT_IMAGES_ENABLED=false` turns channel images off entirely (use it with text-only `CHAT_MODEL`s). Attachments are downloaded once and reused by attachment id. Stickers (`[figurinha:Nome]`) and GIF/image link embeds (Tenor, Giphy, direct image links; `[gif: …]`) count as images too; animated GIFs and stickers are sent as one numbered sheet of four evenly spaced frames, and Tenor/Giphy links use a small animated rendition with the still preview as fallback. Lottie stickers are shown by name only. Custom emojis appear as `:nome:` in the text, and each message's custom emojis are drawn on one labelled sheet that only uses image slots left over after real media. The same media from the triggering message (and the message it replies to) is sent as the user's own images. Reactions are listed on each line before `msg_id` as `[reações: 👍 3 (Ana, Bruno +1)]`, with up to `REACTION_USERS_LIMIT` reactor names per reaction. The triggering message is excluded; set `0` to disable. Reply follow-ups use the captured gap block (`prior_context`, see `CONVERSATIONS_GAP_MESSAGES`) instead of this recent-channel window whenever a gap was captured, including images from those gap messages. +When `CHANNEL_CONTEXT_MESSAGES` > 0 (default `30`), every conversational turn also receives a `` block — the latest N channel messages in chronological order, trimmed from the oldest side to `CHANNEL_CONTEXT_MAX_CHARS` (in a fast chat ten messages is a minute of talk, and what "esse sinal" points at can be further back), same format as the `get_channel_history` tool. Image attachments in that context are persisted and sent as vision parts, up to the four-image per-message budget (current-message images take priority, then the newest channel images); filenames remain visible in the text context. Only images posted within `CHANNEL_CONTEXT_IMAGE_MAX_AGE_MINUTES` (default `60`) are sent, and `CHANNEL_CONTEXT_IMAGES_ENABLED=false` turns channel images off entirely (use it with text-only `CHAT_MODEL`s). Attachments are downloaded once and reused by attachment id. Stickers (`[figurinha:Nome]`) and GIF/image link embeds (Tenor, Giphy, direct image links; `[gif: …]`) count as images too; animated GIFs and stickers are sent as one numbered sheet of four evenly spaced frames, and Tenor/Giphy links use a small animated rendition with the still preview as fallback. Lottie stickers are shown by name only. Custom emojis appear as `:nome:` in the text, and each message's custom emojis are drawn on one labelled sheet that only uses image slots left over after real media. The same media from the triggering message (and the message it replies to) is sent as the user's own images. Reactions are listed on each line before `msg_id` as `[reações: 👍 3 (Ana, Bruno +1)]`, with up to `REACTION_USERS_LIMIT` reactor names per reaction. The triggering message is excluded; set `0` to disable. The block opens with a note that it is only context, and the system prompt tells the model that everything above the question's `[Por …]` tag is background: it answers only what that person wrote, and uses the channel's other messages to understand it, not to answer them. Reply follow-ups use the captured gap block (`prior_context`, see `CONVERSATIONS_GAP_MESSAGES`) instead of this recent-channel window whenever a gap was captured, including images from those gap messages. ### Prefix-Cache-Friendly Message Layout The LLM message list is ordered so conversation follow-ups reuse a cached prefix: `[system (persona + static conversation summary)] → [replayed history turns] → [current message]`. All per-request blocks — `` (clock), the semantically-selected memory block, and the recent channel window — ride on the **final user message** instead of the system prompt, so the system prompt + history stay byte-identical across turns and providers can prefix-cache them (typically 80–95% input-token savings on cached prefixes). @@ -751,10 +753,11 @@ ruff check . # lint (rules configured in pyproject.toml) | File | Covers | |---|---| | `test_api_logger.py` | Request logging for aiohttp/httpx/httpx2, redaction, body capture, inbound interactions (runs in its own process) | -| `test_attribution.py` | Author tags on every question, byte-identical replay of per-turn blocks, memory block labels and person-memory rules | +| `test_attribution.py` | Author tags on every question, speaker changes marked in the tag (verbatim and compact replay), the conversation block naming who speaks now, byte-identical replay of per-turn blocks, memory block labels and person-memory rules | | `test_channel_context_images.py` | Images from automatically fetched channel context | | `test_chat_threads.py` | When conversations move into threads (incl. the `threads` setting; one person's back-and-forth, not name calls or a group), delivery and pings, reusing a moved conversation's thread, mentions and name calls in the channel not following it there, un-mentioned messages and silence in bot threads, the `open_thread` tool (only for long or off-topic subjects), the model naming threads it opens on its own (falling back to the first question) | | `test_context_and_requests.py` | The wider channel window and its budget, waiting for the image after "ai oh @bot", sharper shown images labelled apart from channel images, the search hint | +| `test_context_framing.py` | Channel chatter labelled as context (recent window and gap block), the prompt saying to answer only the tagged message, the new speaker marked in the real request | | `test_conversation_flow.py` | Bursts (follow-ups while answering only after a mention or reply), budget, name calls, aliases and `respond` settings, channel instructions, reply style, staying quiet, edits and deletes, `/chat` and `/ask` | | `test_delivery.py` | Plain vs embed, splitting long answers (code blocks stay valid), real pings for humans only, sources line, threads | | `test_conversation_participants.py` | Participant scope for shared conversations and memory writes | diff --git a/core/context.py b/core/context.py index 7db3082..cfd90af 100644 --- a/core/context.py +++ b/core/context.py @@ -25,6 +25,7 @@ CONVERSATIONS_GAP_MESSAGES, ) from core import image_store, message_media +from core.conversations import CONTEXT_ONLY_NOTE from core.discord_text import _fmt_dt, format_message_lines logger = logging.getLogger(__name__) @@ -276,6 +277,9 @@ async def fetch_recent_channel_context( when disabled or without a readable channel. Image attachments are persisted and returned separately from the formatted text. ``before`` excludes the triggering message from the window (mention/follow-up flows). + The block opens with a note that it is background: the window rides in + the same user message as the question, and without it the model answers + the channel's other topics too. """ n = CHANNEL_CONTEXT_MESSAGES if limit is None else limit if n <= 0 or channel is None: @@ -291,7 +295,11 @@ async def fetch_recent_channel_context( getattr(channel, 'id', None), len(context.lines), len(context.images), ) return ChannelContext( - text=f"\n{context.text}\n", + text=( + "\n" + f"(O que o canal falava antes da mensagem que você vai responder — {CONTEXT_ONLY_NOTE}.)\n" + f"{context.text}\n" + ), lines=context.lines, images=context.images, ) diff --git a/core/conversations.py b/core/conversations.py index 38ecf97..21ea685 100644 --- a/core/conversations.py +++ b/core/conversations.py @@ -50,6 +50,9 @@ logger = logging.getLogger(__name__) PRIOR_CONTEXT_HEADER = 'Mensagens no canal antes desta pergunta' +# Labels the channel messages a turn carries as background: they were written +# for the channel, not to the bot, and are only there to understand the question. +CONTEXT_ONLY_NOTE = 'só contexto: não são pedidos para você' # Expired conversations waiting for their episode summary are dropped after this. EPISODE_GRACE_SECONDS = 24 * 3600 @@ -429,13 +432,30 @@ def _author_label(author: dict | None) -> str: return f'{display} (@{name})' if name else display +def speaker_change(previous: dict | None, author: dict | None) -> str: + """``outra pessoa — antes falava …`` when *author* is not who spoke in the previous turn, else ``''``. + + In a shared conversation every person is the ``user`` role, so without + this the only sign that someone else took over is the name in the tag, + which models easily read past. + """ + prev_id = str((previous or {}).get('id') or '') + author_id = str((author or {}).get('id') or '') + if not prev_id or not author_id or prev_id == author_id: + return '' + return f'outra pessoa — antes falava {_author_label(previous)}' + + def author_tag( author: dict | None, ts: float | None, *, reply_to: str | int | None = None, + previous: dict | None = None, ) -> str: """``[Por Autor (@handle) • author_id=… • data hora]`` or ``''`` without an author. Used on every user message sent to the LLM. It never says "now", so the stored copy stays accurate when replayed byte-identically in later turns. + *previous* is the author of the conversation's previous turn: when it is + someone else, the tag says so (:func:`speaker_change`). """ a = author or {} if not (a.get('id') or a.get('name') or a.get('display')): @@ -444,6 +464,9 @@ def author_tag( if a.get('id'): meta.append(f"author_id={a['id']}") meta.append(_fmt_ts(ts)) + change = speaker_change(previous, a) + if change: + meta.append(change) if reply_to: meta.append(f'↩ reply_to={reply_to}') return f"[{' • '.join(meta)}]" @@ -462,9 +485,8 @@ def _prior_context_head(lines: list[str], channel_id: str | int | None) -> str: """Render the prior-context header (with channel when known) and its lines.""" if not lines: return '' - header = f'[{PRIOR_CONTEXT_HEADER}]' - if channel_id: - header = f'[{PRIOR_CONTEXT_HEADER} (channel_id={channel_id})]' + where = f' (channel_id={channel_id})' if channel_id else '' + header = f'[{PRIOR_CONTEXT_HEADER}{where} — {CONTEXT_ONLY_NOTE}]' return header + '\n' + '\n'.join(lines) + '\n\n' @@ -578,7 +600,8 @@ def build_history_messages( ``↩ reply_to=``, ``msg_id=``), channel chatter captured between turns (``prior_context``) is injected above the question, and sources used in a turn are appended to its assistant message. Verbatim turns rely on the - attribution baked into their captured text instead of these prefixes. + attribution baked into their captured text instead of these prefixes + (:func:`build_current_message` writes the same speaker change there). Both windows advance in ``trajectory_step`` increments (see :func:`stepped_floor`) so the rendered history only changes at deliberate @@ -608,10 +631,12 @@ def build_history_messages( verbatim_from = min(len(turns), verbatim_from + step) messages: list[dict] = [] - prev_author_id: str | None = None + prev_author: dict | None = None image_budget = max_images inline_from = max(0, len(turns) - image_turns) for idx, turn in enumerate(turns): + author = turn.get('author') or {} + previous, prev_author = prev_author, author if idx >= verbatim_from: replayed = _replay_verbatim_turn(turn, image_budget) if replayed is not None: @@ -619,15 +644,13 @@ def build_history_messages( image_budget -= images_used messages.extend(replayed_messages) continue - author = turn.get('author') or {} meta = [f"Por {_author_label(author)}"] if author.get('id'): meta.append(f"author_id={author['id']}") meta.append(_fmt_ts(turn.get('ts'))) - author_id = author.get('id') - if prev_author_id is not None and author_id and author_id != prev_author_id: - meta.append('nova pessoa na conversa') - prev_author_id = author_id + change = speaker_change(previous, author) + if change: + meta.append(change) if turn.get('reply_to'): meta.append(f"↩ reply_to={turn['reply_to']}") if turn.get('message_id'): @@ -673,6 +696,7 @@ def build_current_message( channel_id: str | int | None = None, context_blocks: str | None = None, context_image_urls: list[str] | None = None, + previous_author: dict | None = None, ) -> dict: """Build the current user message, attributed to its author (:func:`author_tag`). @@ -681,6 +705,9 @@ def build_current_message( persisted images from that context. Keeping both in the *tail* message — instead of the system prompt — leaves the history prefix byte-identical across follow-ups, which makes provider prefix caching effective. + ``previous_author`` (who spoke in the conversation's previous turn) marks + a change of speaker in the tag; it is stored with the turn, so verbatim + replay keeps it without re-rendering. """ current_images, context_images, dropped = select_image_refs(image_urls, context_image_urls) inline: list[dict] = [] @@ -689,7 +716,7 @@ def build_current_message( [line for line in (prior_context or []) if line], channel_id ) text = question - tag = author_tag(author, ts, reply_to=reply_to) + tag = author_tag(author, ts, reply_to=reply_to, previous=previous_author) if tag: # The tag sits right above the question — also on the first turn — so # the asker is never inferred from the last channel line above it. It @@ -729,7 +756,8 @@ def build_conversation_block(history: list[dict]) -> str: never on the current request's clock or current sender. This lets the rendered history that follows it stay byte-identical across follow-ups so providers can prefix-cache it. The current sender is instead signalled by - the ``[Agora — …]`` prefix of the current message. + the ``[Por …]`` tag of the current message — which is why the participant + list says "até agora": whoever speaks now may not be in it yet. """ participants: list[dict] = [] for turn in history: @@ -739,21 +767,24 @@ def build_conversation_block(history: list[dict]) -> str: lines = [ '', f'Conversa iniciada em {_fmt_ts(start_ts)}.', - f'Participantes: {", ".join(_author_label(p) for p in participants)}.', + f'Participantes até agora: {", ".join(_author_label(p) for p in participants)}.', ] if last_channel_id: lines.append(f'Canal atual da conversa: channel_id={last_channel_id} (use com get_message_context).') lines.extend([ 'Cada mensagem de usuário traz, logo acima do texto, a marca [Por Autor (@usuário) • author_id=… • data hora] —', 'use essas marcas para saber quem perguntou o quê, e a qual resposta SUA (do bot) se referem.', - 'A mensagem a que você deve responder agora é sempre a ÚLTIMA mensagem de usuário; as anteriores são histórico.', + 'Mais de uma pessoa pode falar com você na mesma conversa: quando quem fala muda de uma mensagem para a', + 'outra, a marca traz "outra pessoa — antes falava …".', + 'Quem fala com você agora é o autor da marca [Por …] da ÚLTIMA mensagem de usuário — pode ser alguém que', + 'ainda não participou. Responda a essa pessoa e ao que ela escreveu; as mensagens anteriores são histórico.', 'Cada mensagem pode trazer seus próprios blocos e : eles descrevem o momento em que AQUELA', 'mensagem foi enviada (autor, horário, memórias da época). Se blocos de mensagens diferentes divergirem,', 'vale o da mensagem mais recente. Marcas antigas "[Agora — …]" também se referem ao momento da própria mensagem.', 'Mensagens do canal (ferramentas de histórico) usam o mesmo author_id/msg_id —', 'correlacione-as para saber quem disse o quê na conversa do canal.', - f'Blocos "[{PRIOR_CONTEXT_HEADER}]" trazem a conversa do canal', - 'que aconteceu entre as perguntas direcionadas ao bot.', + f'Blocos "[{PRIOR_CONTEXT_HEADER} …]" trazem a conversa do canal', + 'que aconteceu entre as perguntas direcionadas ao bot: só contexto, não pedidos para você.', 'Nos blocos de mensagens do canal, as suas respostas (do bot) e perguntas já registradas como ' 'turnos são omitidas; use get_channel_history para vê-las.', '', diff --git a/core/prompts.py b/core/prompts.py index b0e7b6f..942178f 100644 --- a/core/prompts.py +++ b/core/prompts.py @@ -26,6 +26,7 @@ WRAPPED_ENABLED, ) from core.chat_threads import UNPROMPTED_HEADER +from core.conversations import PRIOR_CONTEXT_HEADER from core.turn import FOLLOW_HEADER, NAME_HEADER, NO_REPLY_TOKEN ROLE = ( @@ -58,6 +59,23 @@ "para fatos centrais e permanentes.\n" ) if MEMORY_ENABLED else "" +# How to read a turn: the channel chatter rides in the same user message as the +# question, so the model must be told it is background, or it answers all of it. +CONTEXT_INSTRUCTIONS = ( + "- Na mensagem que você recebe, o que vem antes da marca [Por Autor (@usuário) • author_id=… • " + "data hora] foi preparado para você (blocos , , , " + f" e \"[{PRIOR_CONTEXT_HEADER} …]\"); depois da marca vem o que essa " + "pessoa escreveu. É a essa pessoa, e só ao que ela escreveu, que você responde. Se ela respondeu a " + "outra mensagem, essa vem logo abaixo da marca como \"[Mensagem respondida — …]\", antes de um ---: " + "é o que ela está apontando.\n" + "- As mensagens do canal nesses blocos foram escritas para o canal, por outras pessoas ou por você — " + "não são pedidos para você. Use-as para entender a mensagem que está respondendo (do que o canal está " + "falando, a que \"isso\" ou \"ele\" se referem), mas não responda, comente nem resuma os outros " + "assuntos delas, a menos que a pessoa peça.\n" + "- Numa conversa que já vinha acontecendo, siga o assunto da mensagem atual: se a pessoa mudou de " + "assunto, responda só ao novo, sem voltar aos anteriores.\n" +) + EPISODE_INSTRUCTIONS = ( "- Memórias do tipo conversa resumem conversas suas que já terminaram (com quem, " "quando, o que ficou pendente). Use-as para retomar o assunto com naturalidade — " @@ -172,8 +190,8 @@ f"- Mensagens que começam com {UNPROMPTED_HEADER}, {NAME_HEADER} ou {FOLLOW_HEADER} não foram dirigidas " "diretamente a você: responda só se falarem com você ou se tiver algo útil a acrescentar; " f"caso contrário, {NO_REPLY_TOKEN}.\n" - "- Várias mensagens seguidas da mesma pessoa chegam juntas, uma por linha: responda a " - "todas de uma vez.\n" + "- Várias mensagens seguidas da mesma pessoa chegam juntas abaixo da marca [Por …], uma por " + "linha: responda a todas de uma vez. As mensagens do canal que vêm antes da marca não contam.\n" "- Se o bloco trouxer instruções do canal, siga-as.\n" ) @@ -209,6 +227,7 @@ CHAT_SYSTEM_PROMPT = ( ROLE + "\n\n" "\n" + + CONTEXT_INSTRUCTIONS + MEMORY_INSTRUCTIONS + EPISODE_INSTRUCTIONS + TASK_INSTRUCTIONS @@ -232,6 +251,7 @@ "- Esta conversa começou com /ask: o foco é administração de servidores Minecraft.\n" "- Para qualquer pergunta técnica sobre configuração, administração ou otimização de " "servidores Minecraft, chame `search_docs` imediatamente.\n" + + CONTEXT_INSTRUCTIONS + MEMORY_INSTRUCTIONS + EPISODE_INSTRUCTIONS + TASK_INSTRUCTIONS diff --git a/core/runner.py b/core/runner.py index 1b8acef..1f9e38e 100644 --- a/core/runner.py +++ b/core/runner.py @@ -191,6 +191,7 @@ async def run_turn(ctx: TurnContext) -> TurnResult: channel_id=getattr(ctx.channel, 'id', None), context_blocks='\n\n'.join(blocks) or None, context_image_urls=context_images, + previous_author=ctx.history[-1].get('author') if ctx.history else None, ) messages.append(current) diff --git a/tests/test_attribution.py b/tests/test_attribution.py index bff5b0f..04d3298 100644 --- a/tests/test_attribution.py +++ b/tests/test_attribution.py @@ -55,6 +55,41 @@ def test_replayed_turns_stay_byte_identical_and_timeless(): check('conversation block says newer per-turn blocks win', 'vale o da mensagem mais recente' in block) +def test_speaker_change_is_marked_in_the_tag(): + text = build_current_message('e eu?', author=BOB, ts=1.7e9, reply_to=99, previous_author=ALICE)['content'] + tag = text.split('\n')[-2] + check('tag says someone else took over, and from whom', + 'outra pessoa — antes falava Alice (@alice_h)' in tag, tag) + check('reply target still closes the tag', tag.endswith('• ↩ reply_to=99]'), tag) + for previous in (BOB, None, {'id': '', 'name': 'x', 'display': 'X'}): + same = build_current_message('e eu?', author=BOB, ts=1.7e9, previous_author=previous)['content'] + check(f'no mark when the previous speaker is {previous}', 'outra pessoa' not in same, same) + + +def test_speaker_changes_survive_replay(): + sent, turns, previous = [], [], None + for i, author in enumerate([ALICE, BOB, BOB, ALICE]): + um = build_current_message(f'pergunta {i}', author=author, ts=1.7e9 + i, previous_author=previous) + sent.append(um['content']) + turns.append(make_turn(f'pergunta {i}', f'resposta {i}', author=author, ts=1.7e9 + i, user_message=um)) + previous = author + users = [m['content'] for m in build_history_messages(turns) if m['role'] == 'user'] + check('verbatim replay is still exactly what was sent (prefix cache)', users == sent, users) + marked = ['outra pessoa' in u for u in users] + check('marked only where the speaker changed', marked == [False, True, False, True], marked) + + compact = [m['content'] for m in build_history_messages(turns, trajectory_turns=0) if m['role'] == 'user'] + marked = ['outra pessoa — antes falava' in u for u in compact] + check('compact rendering marks the same turns', marked == [False, True, False, True], compact) + + +def test_conversation_block_points_at_the_current_speaker(): + block = build_conversation_block([make_turn('q', 'a', author=ALICE, ts=1.7e9)]) + check('participants are the ones so far', 'Participantes até agora: Alice (@alice_h).' in block, block) + check('explains the speaker-change mark', 'outra pessoa — antes falava' in block, block) + check('whoever speaks now may be new', 'ainda não participou' in block, block) + + def _member(uid, name, display): return SimpleNamespace(id=uid, name=name, display_name=display, nick=None, global_name=None) diff --git a/tests/test_context_framing.py b/tests/test_context_framing.py new file mode 100644 index 0000000..303b4ad --- /dev/null +++ b/tests/test_context_framing.py @@ -0,0 +1,114 @@ +"""The question stands apart from its context. + +The channel chatter rides in the same user message as the question, so it is +labelled as background, the prompt says to answer only what the person under +the ``[Por …]`` tag wrote, and a change of speaker is marked on the turn that +brings it. +""" + +import datetime +from types import SimpleNamespace as NS + +import core.runner as runner_mod +from core import context as context_mod +from core.conversations import CONTEXT_ONLY_NOTE, PRIOR_CONTEXT_HEADER, build_current_message, make_turn +from core.profiles import ASK, CHAT, SPARK +from core.prompts import CONTEXT_INSTRUCTIONS +from core.runner import run_turn +from core.turn import TurnContext + +from chat_fakes import make_services +from helpers import as_stream, check + +ALICE = {'id': '111', 'name': 'alice_h', 'display': 'Alice'} +BOB_USER = NS(id=222, name='bob_h', display_name='Bob', bot=False) +NOW = datetime.datetime(2026, 11, 13, 18, 0, tzinfo=datetime.timezone.utc) + + +class FakeChannel: + id = 10 + name = 'geral' + + def __init__(self, messages): + self._messages = messages # newest first, like Discord's history() + + def history(self, *, limit, before=None): + async def _iterate(): + for message in self._messages[:limit]: + if before is None or message.id < before.id: + yield message + return _iterate() + + +def _line(mid, content): + author = NS(display_name='Ana', name='ana', id=333, bot=False) + return NS(id=mid, content=content, attachments=[], embeds=[], author=author, created_at=NOW, reference=None) + + +def test_prompts_say_to_answer_only_the_tagged_message(): + for profile in (CHAT, ASK, SPARK): + check(f'{profile.name} prompt explains how to read a turn', CONTEXT_INSTRUCTIONS in profile.system_prompt) + check('bursts are the lines under the tag, not the channel messages', + 'As mensagens do canal que vêm antes da marca não contam' in CHAT.system_prompt) + + +def test_gap_chatter_is_labelled_as_context(): + text = build_current_message( + 'pesquisa isso', author=ALICE, ts=1.7e9, channel_id=10, + prior_context=['[13/11/2026 15:06] Ana (@ana) : saiu snapshot nova [msg_id=300]'], + )['content'] + header = f'[{PRIOR_CONTEXT_HEADER} (channel_id=10) — {CONTEXT_ONLY_NOTE}]' + check('gap header says it is only context', text.startswith(header), text) + check('the question still comes last, under its tag', text.endswith('\npesquisa isso') + and text.split('\n')[-2].startswith('[Por Alice'), text) + + +async def test_recent_window_is_labelled_as_context(): + channel = FakeChannel([_line(2, 'de novo?? kkkk'), _line(1, 'mexeram no combate')]) + recent = await context_mod.fetch_recent_channel_context(NS(), channel, before=NS(id=3), limit=5) + lines = recent.text.split('\n') + check('block opens with the background note', lines[0] == '' + and CONTEXT_ONLY_NOTE in lines[1], recent.text) + check('then the messages, oldest first', lines[2].startswith('Histórico de #geral') + and 'mexeram no combate' in lines[3] and 'de novo' in lines[4], recent.text) + + +def _current(messages): + """Text of the last user message sent (the loop appends its answer to the same list).""" + return [m for m in messages if isinstance(m, dict) and m.get('role') == 'user'][-1]['content'] + + +async def test_request_marks_the_new_speaker(tmp_path, monkeypatch): + monkeypatch.setattr(runner_mod, 'CHANNEL_CONTEXT_MESSAGES', 0) + services = make_services(tmp_path) + calls = [] + + class Completions: + async def create(self, **kwargs): + calls.append(kwargs) + msg = NS(role='assistant', content='ok', tool_calls=None) + return as_stream(NS(choices=[NS(message=msg, finish_reason='stop')], usage=None)) + + services.llm.client = NS(chat=NS(completions=Completions())) + bot = NS(user=NS(id=900, name='quill', display_name='Quill'), services=services) + history = [make_turn('qual plugin de proteção?', 'GriefPrevention.', author=ALICE, ts=1.7e9)] + + def last_request(user): + calls.clear() + return run_turn(TurnContext( + bot=bot, profile=CHAT, question='e o combate?', user=user, created_at=NOW, history=list(history), + )) + + await last_request(BOB_USER) + messages = calls[0]['messages'] + current = _current(messages) + tag = current.split('\n')[-2] + check('a new speaker is marked on their turn', tag.startswith('[Por Bob (@bob_h)') + and 'outra pessoa — antes falava Alice (@alice_h)' in tag, current) + system = messages[0]['content'] + system = system if isinstance(system, str) else system[0]['text'] + check('system block lists participants so far', 'Participantes até agora: Alice (@alice_h).' in system) + + await last_request(NS(id=111, name='alice_h', display_name='Alice', bot=False)) + current = _current(calls[0]['messages']) + check('the same speaker is not marked', 'outra pessoa' not in current, current)