:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(slack_app): only wake the agent on replies addressed to it (#78270)
Vojta Bartoš4f3bd3aea67d
diff --git a/posthog/temporal/ai/slack_app/activities/classifiers.py b/posthog/temporal/ai/slack_app/activities/classifiers.pyindex 944701f75659..1b240ad41966 100644--- a/posthog/temporal/ai/slack_app/activities/classifiers.py+++ b/posthog/temporal/ai/slack_app/activities/classifiers.py@@ -27,22 +27,32 @@ logger = structlog.get_logger(__name__)CLASSIFIER_THREAD_HISTORY_MESSAGES = 10CLASSIFIER_MODEL = "claude-haiku-4-5-20251001"-# The override classifier runs on a reasoning model, which draws its reasoning from the-# same token budget as the reply. The reply itself is one short JSON object; the headroom-# is for the thinking in front of it, and a truncated turn reads as an unusable reply and-# falls back to saved preferences.+++# The model-override and agent-directed classifiers both run on a reasoning model, which+# draws its reasoning from the same token budget as the reply. The reply is one short JSON+# object; the headroom is for the thinking in front of it, and a truncated turn falls back+# to the safe answer.+#+# The gateway client defaults to a 600s read and two retries, which is the right shape for+# a generation call and the wrong one here. Left unbounded these never get to fall back,+# because the activity's own deadline expires first. Bounding the retries matters as much+# as the timeout: the activity is sync, so a thread Temporal has stopped waiting on keeps+# blocking until the client itself returns.MODEL_OVERRIDE_CLASSIFIER_MODEL = "gpt-5.6-luna"MODEL_OVERRIDE_MAX_TOKENS = 2048-# The gateway client defaults to a 600s read and two retries of its own, which is the-# right shape for a generation call and the wrong one here: this classifier gates task-# creation, and its answer is optional — any failure falls back to saved preferences. Left-# unbounded it never gets to fall back, because the activity's own 600s deadline expires-# first and fails the mention outright. Bounding the retries matters as much as the-# deadline: the activity is sync, so a thread Temporal has stopped waiting on keeps-# blocking until the client itself returns. Measured mean is ~1.7s per call.+# One call per `@PostHog`, on the mention text alone. Measured mean is ~1.7s per call.MODEL_OVERRIDE_TIMEOUT_SECONDS = 10.0MODEL_OVERRIDE_MAX_RETRIES = 1+AGENT_DIRECTED_CLASSIFIER_MODEL = "gpt-5.6-luna"+AGENT_DIRECTED_MAX_TOKENS = 2048+# One call per reply in every thread the agent is working in, and its prompt carries the+# thread the override classifier's does not. The eval suite sees 3-9s on that shape, close+# enough to a 10s ceiling that the tail would drop instructions rather than misread them.+AGENT_DIRECTED_TIMEOUT_SECONDS = 20.0+AGENT_DIRECTED_MAX_RETRIES = 1+def classify_task_needs_repo(event_text: str,@@ -176,77 +186,108 @@ def classify_posthog_code_task_needs_repo_activity(return classify_task_needs_repo(event_text, thread_messages)+def _agent_directed_response_format() -> ResponseFormatJSONSchema:+ """A strict JSON schema pinning the reply to a single boolean.++ The schema is what stops a reasoning model answering with its reasoning — prose parses+ to nothing, which reads the same as a refused call and silently drops the message.+ """+ return {+ "type": "json_schema",+ "json_schema": {+ "name": "slack_app_agent_directed",+ "strict": True,+ "schema": {+ "type": "object",+ "properties": {"agent_directed": {"type": "boolean"}},+ "required": ["agent_directed"],+ "additionalProperties": False,+ },+ },+ }++def classify_message_is_agent_directed(event_text: str,task_title: str,thread_history: list[dict[str, str]],) -> bool:- """Classify whether a Slack thread reply is addressing the running PostHog- Slack App or pure side chatter between humans.+ """Classify whether an untagged Slack thread reply is an instruction to the running+ PostHog Slack App, or people talking to each other.- The prompt leans toward forwarding when the message could plausibly help- the agent or advance the task — a false positive is a single wasted turn- the human can correct; a false negative forces the human to re-tag- ``@PostHog`` to recover. Cheap pre-LLM heuristics still drop trivial- messages (one word, emoji-only, very short) before paying for Haiku, and- the function still returns ``False`` on a Haiku call error so a transient- LLM outage can't fan out spurious forwards.+ Deliberately defensive. Waking the agent is not private: it reacts in the channel, so a+ thread of humans discussing the work watches it interject on messages nobody addressed+ to it. A missed follow-up costs one ``@PostHog``, which the author would have typed+ anyway. So the bar is that the message reads as addressed to the agent — talking+ *about* the task, or about the agent, is not talking *to* it. Any failure returns+ ``False`` for the same reason.``thread_history`` is the conversation so far (oldest first), as returnedby ``collect_thread_messages`` — each entry is ``{"user", "text", "ts"}``.++ Whether the prompt holds that line is measured by+ ``products/slack_app/evals/eval_followup_classifier.py``."""stripped = event_text.strip()- # Emoji-only / reaction-only replies are never agent-directed; drop before- # paying for Haiku.if re.fullmatch(r"(?:\s*:[a-z0-9_+-]+:\s*)+", stripped):logger.info("classify_message_is_agent_directed_heuristic_emoji_only", event_text=event_text)return False- # Render the tail of the thread for context. Bound the number of lines and- # the per-line length to keep the prompt small and predictable.+ # Bound the number of lines and the per-line length to keep the prompt predictable.recent = thread_history[-CLASSIFIER_THREAD_HISTORY_MESSAGES:]history_block = "\n".join(f"{m.get('user', 'Unknown')}: {m.get('text', '')[:500]}" for m in recent) or "(empty)"prompt = (- "You are routing replies in a Slack thread where the PostHog Slack App is "- "currently working on a task. Decide whether the latest message is meant "- "for the Slack App to read — instructions, corrections, follow-up asks, "- "questions about the task, or context that helps it — versus pure side "- "chatter between humans.\n\n"- "Lean toward true when the message could plausibly help the Slack App or "- "advance the task. Examples of agent_directed=true:\n"- " - Direct address ('@PostHog', 'agent, please…', 'bot, …').\n"- " - Instructions, corrections, or scope changes ('also handle the empty "- " case', 'use the new helper instead', 'actually skip the migration').\n"- " - Questions about the task or the Slack App's last update ('why did "- " you skip X?', 'what does this PR cover?', 'can you also do Y?').\n"- " - Task-relevant context (an error message, a URL, a file path, an "- " affected team/customer ID, a stack trace, a reproduction).\n"- " - Replies that elaborate on the human's earlier ask in this thread.\n\n"- "Return agent_directed=false for clearly off-topic side chatter:\n"- " - Pure acknowledgements with no new info ('thanks', 'lgtm', 'nice', "- " 'cool', emoji-only, '+1').\n"- " - Conversation clearly directed at another human (mentions another "- " user, answers their question, refers to people in third person).\n"- " - Off-topic chat unrelated to the task ('lunch in 5?', 'gn').\n\n"- "When you're genuinely on the fence, prefer true — the human can correct "- "the agent if it misreads, but a missed follow-up means the human has to "- "re-tag @PostHog.\n\n"- f"Task the Slack App is working on: {task_title or '(unknown)'}\n\n"+ "The PostHog agent is working on a task in this Slack thread. People in the thread "+ "have stopped tagging it. Decide whether the latest message is an instruction to "+ "the agent that happens to omit the @mention.\n\n"+ "Answer true only when the message is addressed to the agent:\n"+ " - An order or request to do something ('also handle the empty case', 'skip the "+ "migration', 'open a PR for that too', 'try again with the other helper').\n"+ " - A question put to the agent about its own work ('why did you skip the "+ "redesign commit?', 'does your PR cover the mobile breakpoint?').\n"+ " - An answer to something the agent just asked in this thread.\n"+ " - A correction of what the agent said or did ('no, the bug is in the handler, "+ "not the wrapper').\n\n"+ "Answer false for everything else. This is the common case, and the mistake to "+ "avoid — people talk about the work far more often than they talk to the agent:\n"+ " - Opinions and discussion about the task or the product, addressed to the room "+ "('this needs a stronger label', 'it should probably live under settings', 'I've "+ "seen this set back and forth so much'). Relevant to the task is not the same as "+ "addressed to the agent.\n"+ " - Talk about the agent in the third person ('why is the bot reacting to me?', "+ "'it keeps replying', 'is it supposed to do that?'). Being the topic is not being "+ "the audience.\n"+ " - Conversation between humans — answering each other, tagging each other, "+ "deciding something among themselves.\n"+ " - Acknowledgements, praise, and reactions ('thanks', 'lgtm', 'nice', '+1').\n"+ " - Context dropped into the thread with no instruction attached — a link, a "+ "stack trace, a screenshot — unless the message asks the agent to act on it.\n"+ " - Anything off-topic.\n\n"+ "When you are unsure, answer false. A missed instruction costs the author one "+ "@PostHog; a wrong wake-up makes the agent interrupt a conversation it was not "+ "part of, in public, where everyone sees it.\n\n"+ f"Task the agent is working on: {task_title or '(unknown)'}\n\n"f"Thread so far (oldest first):\n{history_block}\n\n"f"Latest message (from a human in this thread): {event_text}\n\n"- 'Respond with ONLY a JSON object: {"agent_directed": true} or {"agent_directed": false}'+ 'Answer with the one field, e.g. {"agent_directed": false}')try:- client = get_llm_client("slack_app_routing")+ client = get_llm_client("slack_app_routing").with_options(+ timeout=AGENT_DIRECTED_TIMEOUT_SECONDS, max_retries=AGENT_DIRECTED_MAX_RETRIES+ )response = client.chat.completions.create(- model=CLASSIFIER_MODEL,+ model=AGENT_DIRECTED_CLASSIFIER_MODEL,messages=[{"role": "user", "content": prompt}],- max_tokens=64,- temperature=0,+ max_tokens=AGENT_DIRECTED_MAX_TOKENS,+ response_format=_agent_directed_response_format(),)+ # Tolerant parse on top of the schema on purpose: the gateway fronts several+ # providers and does not honour a response format identically on every route, so+ # a reply that arrives fenced still lands rather than dropping the message.parsed = extract_json_object(response.choices[0].message.content or "") or {}- return bool(parsed.get("agent_directed", False))+ # Anything but the schema's boolean drops: a truthy string would invert the bias.+ return parsed.get("agent_directed") is Trueexcept Exception:logger.exception("classify_message_is_agent_directed_failed")return Falsediff --git a/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_message_is_agent_directed.ambr b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_message_is_agent_directed.ambrnew file mode 100644index 000000000000..db8398790242--- /dev/null+++ b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_message_is_agent_directed.ambr@@ -0,0 +1,32 @@+# serializer version: 1+# name: TestClassifyMessageIsAgentDirected.test_prompt_snapshot_matches+ '''+ The PostHog agent is working on a task in this Slack thread. People in the thread have stopped tagging it. Decide whether the latest message is an instruction to the agent that happens to omit the @mention.++ Answer true only when the message is addressed to the agent:+ - An order or request to do something ('also handle the empty case', 'skip the migration', 'open a PR for that too', 'try again with the other helper').+ - A question put to the agent about its own work ('why did you skip the redesign commit?', 'does your PR cover the mobile breakpoint?').+ - An answer to something the agent just asked in this thread.+ - A correction of what the agent said or did ('no, the bug is in the handler, not the wrapper').++ Answer false for everything else. This is the common case, and the mistake to avoid — people talk about the work far more often than they talk to the agent:+ - Opinions and discussion about the task or the product, addressed to the room ('this needs a stronger label', 'it should probably live under settings', 'I've seen this set back and forth so much'). Relevant to the task is not the same as addressed to the agent.+ - Talk about the agent in the third person ('why is the bot reacting to me?', 'it keeps replying', 'is it supposed to do that?'). Being the topic is not being the audience.+ - Conversation between humans — answering each other, tagging each other, deciding something among themselves.+ - Acknowledgements, praise, and reactions ('thanks', 'lgtm', 'nice', '+1').+ - Context dropped into the thread with no instruction attached — a link, a stack trace, a screenshot — unless the message asks the agent to act on it.+ - Anything off-topic.++ When you are unsure, answer false. A missed instruction costs the author one @PostHog; a wrong wake-up makes the agent interrupt a conversation it was not part of, in public, where everyone sees it.++ Task the agent is working on: Fix the checkout button not firing autocapture events++ Thread so far (oldest first):+ alice: @PostHog autocapture isn't picking up clicks on our checkout button+ posthog: Looking into it — checking how the button is rendered.++ Latest message (from a human in this thread): this whole thing would benefit from a Settings section++ Answer with the one field, e.g. {"agent_directed": false}+ '''+# ---diff --git a/posthog/temporal/tests/ai/slack_app/activities/test_classify_message_is_agent_directed.py b/posthog/temporal/tests/ai/slack_app/activities/test_classify_message_is_agent_directed.pynew file mode 100644index 000000000000..bd552b652cfe--- /dev/null+++ b/posthog/temporal/tests/ai/slack_app/activities/test_classify_message_is_agent_directed.py@@ -0,0 +1,116 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.temporal.ai.slack_app.activities.classifiers import classify_message_is_agent_directed+from posthog.temporal.ai.slack_app.posthog_code_slack_mention import POSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS++TASK_TITLE = "Fix the checkout button not firing autocapture events"+THREAD = [+ {"user": "alice", "text": "@PostHog autocapture isn't picking up clicks on our checkout button", "ts": "1.0"},+ {"user": "posthog", "text": "Looking into it — checking how the button is rendered.", "ts": "2.0"},+]+++class TestClassifyMessageIsAgentDirected:+ def test_emoji_only_is_dropped_without_paying_for_the_model(self):+ with patch("posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client") as get_client:+ assert classify_message_is_agent_directed(":thumbsup: :tada:", TASK_TITLE, THREAD) is False+ get_client.assert_not_called()++ @parameterized.expand(+ [+ ("instruction", '{"agent_directed": true}', True),+ ("chatter", '{"agent_directed": false}', False),+ # Replies are not reliably unfenced through the gateway.+ ("fenced_json", '```json\n{"agent_directed": true}\n```', True),+ # Anything but the schema's boolean drops: a truthy string would invert the bias.+ ("stringified_bool", '{"agent_directed": "true"}', False),+ ("prose_instead_of_json", "The message looks like an instruction to me.", False),+ ("empty_reply", "", False),+ ]+ )+ def test_parses_the_reply(self, _name, content, expected):+ assert self._classify("also check the mobile breakpoint", content) is expected++ def test_llm_failure_drops_the_message(self):+ client = self._fake_client("")+ client.chat.completions.create.side_effect = RuntimeError("boom")+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ return_value=client,+ ):+ assert classify_message_is_agent_directed("also check the breakpoint", TASK_TITLE, THREAD) is False++ def test_call_is_bounded_so_a_slow_gateway_falls_back(self):+ # Unbounded, the activity's deadline expires before the client's own 600s read, so+ # the reply is lost outright instead of taking the drop this is built around.+ client = self._fake_client('{"agent_directed": false}')+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ return_value=client,+ ):+ classify_message_is_agent_directed("lunch in 5?", TASK_TITLE, THREAD)++ assert client.with_options.called, "the classifier must bound the gateway client"+ options = client.with_options.call_args.kwargs+ assert options["timeout"] < POSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS+ assert options["max_retries"] * options["timeout"] < POSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS++ def test_reply_is_pinned_to_a_single_boolean(self):+ # The schema, not the prompt, is what stops a reasoning model answering with its+ # reasoning — prose parses to nothing, which reads as a refused call.+ client = self._fake_client('{"agent_directed": false}')+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ return_value=client,+ ):+ classify_message_is_agent_directed("lunch in 5?", TASK_TITLE, THREAD)++ schema = client.chat.completions.create.call_args.kwargs["response_format"]["json_schema"]+ assert schema["strict"] is True+ assert schema["schema"]["properties"]["agent_directed"]["type"] == "boolean"+ assert schema["schema"]["additionalProperties"] is False++ def test_prompt_snapshot_matches(self, snapshot):+ """The prompt is the whole classifier — where it draws the line between talking to+ the agent and talking about it. Pinning it means a reworded rule shows up as a+ reviewable diff rather than a silent behaviour change. Update with+ ``--snapshot-update`` after auditing the diff, then re-run+ ``hogli evals eval_followup_classifier`` before trusting it.+ """+ assert self._render_prompt("this whole thing would benefit from a Settings section") == snapshot++ def test_prompt_carries_the_thread_and_the_task(self):+ # Several eval cases are decidable only from what came before them, so a prompt+ # that rendered the reply alone would grade a different classifier.+ prompt = self._render_prompt("it only happens for logged-out users")+ assert TASK_TITLE in prompt+ assert THREAD[0]["text"] in prompt+ assert "it only happens for logged-out users" in prompt++ def _render_prompt(self, text: str) -> str:+ client = self._fake_client('{"agent_directed": false}')+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ return_value=client,+ ):+ classify_message_is_agent_directed(text, TASK_TITLE, THREAD)+ return client.chat.completions.create.call_args.kwargs["messages"][0]["content"]++ def _classify(self, text: str, content: str) -> bool:+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ return_value=self._fake_client(content),+ ):+ return classify_message_is_agent_directed(text, TASK_TITLE, THREAD)++ def _fake_client(self, content: str) -> MagicMock:+ response = MagicMock()+ response.choices = [MagicMock(message=MagicMock(content=content))]+ client = MagicMock()+ # `with_options` returns a configured copy, so the fake hands back itself to keep+ # one set of call records no matter how the call site bounds the client.+ client.with_options.return_value = client+ client.chat.completions.create.return_value = response+ return clientdiff --git a/posthog/temporal/tests/ai/test_classify_untagged_followup_activity.py b/posthog/temporal/tests/ai/test_classify_untagged_followup_activity.pyindex 7f483edea0e6..826924751dca 100644--- a/posthog/temporal/tests/ai/test_classify_untagged_followup_activity.py+++ b/posthog/temporal/tests/ai/test_classify_untagged_followup_activity.py@@ -7,19 +7,18 @@ from posthog.models.integration import Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from posthog.temporal.ai.slack_app import (- PostHogCodeSlackMentionWorkflowInputs,- classify_message_is_agent_directed,- classify_untagged_followup_activity,-)+from posthog.temporal.ai.slack_app import PostHogCodeSlackMentionWorkflowInputs, classify_untagged_followup_activityfrom products.slack_app.backend.models import SlackThreadTaskMappingclass TestClassifyUntaggedFollowupActivity(TestCase):"""Activity-level tests for the classifier that now lives inside the- mention workflow. The activity owns mapping lookup, thread-history fetch,- and the LLM call; the webhook handler is no longer involved."""+ mention workflow. The activity owns mapping lookup and thread-history fetch;+ the webhook handler is no longer involved.++ The classifier it calls has its own tests next to the model-override one, in+ ``slack_app/activities/test_classify_message_is_agent_directed.py``."""def setUp(self):self.Task = apps.get_model("tasks", "Task")@@ -111,58 +110,8 @@ class TestClassifyUntaggedFollowupActivity(TestCase):assert mock_classify.call_args[0][2] == []-class TestClassifyMessageIsAgentDirected(TestCase):- """The Haiku-backed classifier with cheap pre-LLM heuristics. Moved from- the API module to the workflow module along with the rest of the LLM- work."""-- def test_emoji_only_dropped_without_llm(self):- with patch("posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client") as mock_client:- assert classify_message_is_agent_directed(":thumbsup: :tada:", "do thing", []) is False- mock_client.assert_not_called()-- def test_haiku_directed_true(self):- fake_response = type(- "Resp",- (),- {- "choices": [- type(- "Choice",- (),- {"message": type("Msg", (), {"content": '{"agent_directed": true}'})()},- )()- ]- },- )()- with patch("posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client") as mock_client:- mock_client.return_value.chat.completions.create.return_value = fake_response- result = classify_message_is_agent_directed("Please also check the auth flow on safari", "fix the bug", [])- assert result is True-- def test_haiku_directed_false(self):- fake_response = type(- "Resp",- (),- {- "choices": [- type(- "Choice",- (),- {"message": type("Msg", (), {"content": '{"agent_directed": false}'})()},- )()- ]- },- )()- with patch("posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client") as mock_client:- mock_client.return_value.chat.completions.create.return_value = fake_response- result = classify_message_is_agent_directed("nice work team, going to lunch now", "fix the bug", [])- assert result is False-- def test_haiku_failure_defaults_to_drop(self):- """Conservative default: a false positive interrupts the agent on- every chit-chat reply; a false negative just means the user re-tags."""- with patch("posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client") as mock_client:- mock_client.return_value.chat.completions.create.side_effect = RuntimeError("boom")- result = classify_message_is_agent_directed("Please also check the auth flow on safari", "fix the bug", [])- assert result is False+# The classifier itself — parsing, the pre-LLM heuristic, the bounded client, and the+# prompt snapshot — is covered in+# `posthog/temporal/tests/ai/slack_app/activities/test_classify_message_is_agent_directed.py`,+# next to the model-override classifier's own tests. This file covers the activity around+# it: the thread mapping, the history fetch, and what happens when either is missing.diff --git a/products/posthog_ai/eval_harness/test/test_slack_app_scorers.py b/products/posthog_ai/eval_harness/test/test_slack_app_scorers.pyindex ddc8dbb389ce..afb296d18b05 100644--- a/products/posthog_ai/eval_harness/test/test_slack_app_scorers.py+++ b/products/posthog_ai/eval_harness/test/test_slack_app_scorers.py@@ -2,10 +2,17 @@ from __future__ import annotationsfrom parameterized import parameterized-from products.slack_app.evals.model_classifier_scorers import EXPECTATION_KEY, ModelOverrideMatch, NoUnaskedOverride+from products.slack_app.evals.scorers import (+ FOLLOWUP_KEY,+ MODEL_OVERRIDE_KEY,+ FollowupRoutingMatch,+ ModelOverrideMatch,+ NoUnaskedOverride,+ NoUnaskedWake,+)-ASKS_FOR_FABLE = {EXPECTATION_KEY: {"model": "claude-fable-5", "reasoning_effort": None}}-ASKS_FOR_NOTHING = {EXPECTATION_KEY: {"model": None, "reasoning_effort": None}}+ASKS_FOR_FABLE = {MODEL_OVERRIDE_KEY: {"model": "claude-fable-5", "reasoning_effort": None}}+ASKS_FOR_NOTHING = {MODEL_OVERRIDE_KEY: {"model": None, "reasoning_effort": None}}def _output(model: str | None = None, effort: str | None = None) -> dict:@@ -74,3 +81,63 @@ class TestNoUnaskedOverride:"""score = NoUnaskedOverride().eval(output={"override": None, "error": "boom"}, expected=ASKS_FOR_NOTHING)assert score.score is None+++class TestNoUnaskedWake:+ """The follow-up suite's headline metric, so its denominator has to be right.++ It reports a rate over the replies the agent should have stayed out of. Scoring the+ instruction cases too would dilute it with cases that were never at risk of a wrong+ wake-up.+ """++ @parameterized.expand(+ [+ ("stayed_asleep", {"agent_directed": False}, 1.0),+ ("woke_on_chatter", {"agent_directed": True}, 0.0),+ ]+ )+ def test_scores_chatter_cases(self, _name, output, want):+ expected = {FOLLOWUP_KEY: {"agent_directed": False}}+ assert NoUnaskedWake().eval(output=output, expected=expected).score == want++ @parameterized.expand([("forwarded", {"agent_directed": True}), ("dropped", {"agent_directed": False})])+ def test_skips_instruction_cases(self, _name, output):+ expected = {FOLLOWUP_KEY: {"agent_directed": True}}+ assert NoUnaskedWake().eval(output=output, expected=expected).score is None++ def test_skips_on_classifier_error(self):+ """A failed call returns False, which is this scorer's passing answer — counting it+ as one would let a wholly broken classifier post a perfect rate.+ """+ expected = {FOLLOWUP_KEY: {"agent_directed": False}}+ score = NoUnaskedWake().eval(output={"agent_directed": None, "error": "boom"}, expected=expected)+ assert score.score is None+++class TestFollowupRoutingMatch:+ """The skip/fail protocol, which is where a routing scorer goes quietly wrong.++ Skipping where it should fail inflates its own average, and the errored call is the+ case that tempts it: the classifier returns False there, which is a real answer for+ some cases and a crash for others.+ """++ @parameterized.expand(+ [+ ("forwarded_as_expected", {"agent_directed": True}, True, 1.0),+ ("dropped_a_real_reply", {"agent_directed": False}, True, 0.0),+ # Opting in by presence, not truthiness — the chatter cases all expect False,+ # and a truthiness check would skip every one of them.+ ("chatter_left_alone", {"agent_directed": False}, False, 1.0),+ ("woke_on_chatter", {"agent_directed": True}, False, 0.0),+ ("errored_call", {"agent_directed": None, "error": "boom"}, True, 0.0),+ ]+ )+ def test_scores(self, _name, output, want, expected_score):+ expected = {FOLLOWUP_KEY: {"agent_directed": want}}+ assert FollowupRoutingMatch().eval(output=output, expected=expected).score == expected_score++ def test_skips_cases_that_declare_no_expectation(self):+ score = FollowupRoutingMatch().eval(output={"agent_directed": True}, expected={FOLLOWUP_KEY: {}})+ assert score.score is Nonediff --git a/products/slack_app/evals/eval_followup_classifier.py b/products/slack_app/evals/eval_followup_classifier.pynew file mode 100644index 000000000000..7395c93aeeff--- /dev/null+++ b/products/slack_app/evals/eval_followup_classifier.py@@ -0,0 +1,161 @@+"""In a thread the agent is working in, which untagged replies are instructions to it?++Once the Slack App picks up a task, people stop tagging it. They talk about the work,+about the product, about the agent, and occasionally to it. Every reply hits+`classify_message_is_agent_directed`, which decides whether the agent wakes up.++The errors are not symmetric, which is why `no_unasked_wake` is the number to watch rather+than accuracy — see `classify_message_is_agent_directed` for why.++The chatter cases are the point of the suite: they are the shapes the classifier woke on+in real threads. None of the cases reuses the prompt's own examples, which would measure+whether the model can copy a list it was just handed.++To run:+ hogli evals eval_followup_classifier+ hogli evals eval_followup_classifier --eval opinion_about_the_product+"""++from __future__ import annotations++import asyncio++from posthog.temporal.ai.slack_app.activities import classifiers++from products.posthog_ai.eval_harness.config import BaseEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.harness.requirements import SuiteKind+from products.posthog_ai.eval_harness.one_shot import OneShotPublicEval+from products.slack_app.evals.scorers import FOLLOWUP_KEY, FollowupRoutingMatch, NoUnaskedWake++SUITE_KIND = SuiteKind.ONE_SHOT++TASK_TITLE = "Fix the checkout button not firing autocapture events"++# The thread every case continues: a human asked, the agent acknowledged.+THREAD = [+ {"user": "alice", "text": "@PostHog autocapture isn't picking up clicks on our checkout button", "ts": "1.0"},+ {"user": "posthog", "text": "Looking into it — checking how the button is rendered.", "ts": "2.0"},+]+++def _routes(agent_directed: bool) -> dict:+ return {FOLLOWUP_KEY: {"agent_directed": agent_directed}}+++# Instructions. Only the first addresses the agent by name; the rest are what people+# actually type once they have stopped tagging.+DIRECTED_CASES = [+ BaseEvalCase(+ name="direct_instruction",+ prompt="@PostHog one more thing while you're in there — make sure it doesn't double-fire",+ expected=_routes(True),+ ),+ BaseEvalCase(+ name="scope_correction",+ prompt="leave the analytics wrapper alone, only touch the click handler",+ expected=_routes(True),+ ),+ BaseEvalCase(+ name="question_about_the_work",+ prompt="what did you end up changing in the tracking snippet?",+ expected=_routes(True),+ ),+ BaseEvalCase(+ name="order_to_retry",+ prompt="start over from the cart page instead, that's where it actually breaks",+ expected=_routes(True),+ ),+ BaseEvalCase(+ name="correction_of_the_agent",+ prompt="that's the wrong file — it's the one under components/, not lib/",+ expected=_routes(True),+ ),+ BaseEvalCase(+ name="follow_up_ask",+ prompt="can you add a test for the logged-out case as well",+ expected=_routes(True),+ ),+]++# What the agent should stay out of. Every one is about the work or about the agent, and+# none is addressed to it.+CHATTER_CASES = [+ BaseEvalCase(name="bare_acknowledgement", prompt="cheers", expected=_routes(False)),+ BaseEvalCase(+ name="human_to_human",+ prompt="@bob any idea when we added that debounce?",+ expected=_routes(False),+ ),+ BaseEvalCase(name="off_topic", prompt="standup moved to 3 btw", expected=_routes(False)),+ BaseEvalCase(name="approval_without_content", prompt="oh nice, that was fast", expected=_routes(False)),+ # Opinions said to the room. Task-relevant, and the biggest source of spurious+ # wake-ups: relevant is not the same as addressed.+ BaseEvalCase(+ name="opinion_about_the_product",+ prompt="honestly the whole checkout flow could use a rethink at some point",+ expected=_routes(False),+ ),+ BaseEvalCase(+ name="design_opinion",+ prompt="the copy on that button has bugged me for ages",+ expected=_routes(False),+ ),+ BaseEvalCase(+ name="shared_frustration",+ prompt="this exact thing bit us last quarter too",+ expected=_routes(False),+ ),+ # Talk about the agent. Being the topic is not being the audience.+ BaseEvalCase(+ name="question_about_the_bot",+ prompt="wait, why did it just eyes-react to my message?",+ expected=_routes(False),+ ),+ BaseEvalCase(+ name="commentary_on_the_bot",+ prompt="lol it's lurking in every thread now",+ expected=_routes(False),+ ),+ BaseEvalCase(+ name="link_without_an_ask",+ prompt="related: https://posthog.slack.com/archives/C123/p456",+ expected=_routes(False),+ ),+ BaseEvalCase(+ name="agreement_between_humans",+ prompt="yep, same conclusion I came to",+ expected=_routes(False),+ ),+]+++async def eval_followup_classifier(ctx: EvalContext) -> None:+ async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:+ # Recorded per case so an experiment says which model produced its scores.+ classifier_model = classifiers.AGENT_DIRECTED_CLASSIFIER_MODEL+ try:+ # Sync and blocking on the gateway — off the event loop so cases still run+ # concurrently under the harness's limiter.+ agent_directed = await asyncio.to_thread(+ classifiers.classify_message_is_agent_directed, case.prompt, TASK_TITLE, THREAD+ )+ except Exception as error:+ return {+ "classifier_model": classifier_model,+ "agent_directed": None,+ "error": f"{type(error).__name__}: {error}",+ }+ return {+ "classifier_model": classifier_model,+ "agent_directed": agent_directed,+ "last_message": f"{classifier_model}: agent_directed={agent_directed}",+ }++ await OneShotPublicEval(+ experiment_name="slack-app-followup-classifier",+ cases=[*DIRECTED_CASES, *CHATTER_CASES],+ scorers=[FollowupRoutingMatch(), NoUnaskedWake()],+ task=task,+ ctx=ctx,+ )diff --git a/products/slack_app/evals/eval_model_classifier.py b/products/slack_app/evals/eval_model_classifier.pyindex 13195173a05a..69d552b44d34 100644--- a/products/slack_app/evals/eval_model_classifier.py+++ b/products/slack_app/evals/eval_model_classifier.py@@ -31,7 +31,7 @@ from products.posthog_ai.eval_harness.harness.context import EvalContextfrom products.posthog_ai.eval_harness.harness.requirements import SuiteKindfrom products.posthog_ai.eval_harness.one_shot import OneShotPublicEvalfrom products.slack_app.backend.services.model_catalogue import ModelChoice-from products.slack_app.evals.model_classifier_scorers import EXPECTATION_KEY, ModelOverrideMatch, NoUnaskedOverride+from products.slack_app.evals.scorers import MODEL_OVERRIDE_KEY, ModelOverrideMatch, NoUnaskedOverrideSUITE_KIND = SuiteKind.ONE_SHOT@@ -49,7 +49,7 @@ CHOICES: tuple[ModelChoice, ...] = (def _asks(model: str | None = None, reasoning_effort: str | None = None) -> dict:- return {EXPECTATION_KEY: {"model": model, "reasoning_effort": reasoning_effort}}+ return {MODEL_OVERRIDE_KEY: {"model": model, "reasoning_effort": reasoning_effort}}# Deliberately not the prompt's own few-shot examples. Reusing those would measure@@ -143,9 +143,7 @@ SUBJECT_MATTER_CASES = [async def eval_model_classifier(ctx: EvalContext) -> None:async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:- # Recorded on every case so an experiment says which model produced its scores —- # otherwise two runs of the same suite are indistinguishable in the history, which- # is exactly what you go to the history to compare.+ # Recorded per case so an experiment says which model produced its scores.classifier_model = classifiers.MODEL_OVERRIDE_CLASSIFIER_MODELtry:# Sync, and blocking on the gateway — keep it off the event loop so casesdiff --git a/products/slack_app/evals/model_classifier_scorers.py b/products/slack_app/evals/model_classifier_scorers.pydeleted file mode 100644index f9dd0e3d2ddc..000000000000--- a/products/slack_app/evals/model_classifier_scorers.py+++ /dev/null@@ -1,87 +0,0 @@-"""Scorers for the Slack model-override classifier suite."""--from __future__ import annotations--from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer--# Both scorers read the same expectation: one case states the answer once, and the-# false-positive scorer derives "this case asks for nothing" from it rather than-# carrying a second, separately-maintained flag that could disagree.-EXPECTATION_KEY = "model_override_match"---def _reads(output: dict | None) -> tuple[str | None, str | None]:- """The classifier's answer as a `(model, reasoning_effort)` pair.-- A `None` override — the classifier declining to steer the run — reads the same as an- explicit pair of nulls, because that is what it means downstream.- """- override = (output or {}).get("override") or {}- return override.get("model"), override.get("reasoning_effort")---class ModelOverrideMatch(Scorer):- """Did the classifier read the mention the way a person would?-- Scores both fields at once: a run launched on the right model at the wrong effort is- still not what the author asked for.- """-- def _name(self) -> str:- return EXPECTATION_KEY-- def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:- if output and output.get("error"):- return Score(name=self._name(), score=0.0, metadata={"reason": output["error"]})-- want = (expected or {}).get(EXPECTATION_KEY)- if want is None:- return Score(name=self._name(), score=None, metadata={"reason": "No expectation for this case"})-- got_model, got_effort = _reads(output)- want_model, want_effort = want.get("model"), want.get("reasoning_effort")- matched = got_model == want_model and got_effort == want_effort- return Score(- name=self._name(),- score=1.0 if matched else 0.0,- metadata={- "expected_model": want_model,- "actual_model": got_model,- "expected_effort": want_effort,- "actual_effort": got_effort,- },- )---class NoUnaskedOverride(Scorer):- """The failure that actually costs the user something.-- The two error directions are not symmetric. Missing a real instruction falls back to- the author's saved preferences — they notice and rephrase. Inventing an instruction- out of subject matter silently moves someone's run onto a model they never chose, and- nothing in the thread says so.-- Skips (`None`) on cases that do ask for something, so the score reads as a rate over- the mentions that merely *mention* a model.- """-- def _name(self) -> str:- return "no_unasked_override"-- def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:- want = (expected or {}).get(EXPECTATION_KEY) or {}- if want.get("model") or want.get("reasoning_effort"):- return Score(name=self._name(), score=None, metadata={"reason": "Case asks for an override"})-- if output and output.get("error"):- # An erroring call yields no override, which is the safe answer here — but- # scoring it as a pass would hide a broken classifier behind a good rate.- return Score(name=self._name(), score=None, metadata={"reason": output["error"]})-- got_model, got_effort = _reads(output)- invented = got_model is not None or got_effort is not None- return Score(- name=self._name(),- score=0.0 if invented else 1.0,- metadata={"actual_model": got_model, "actual_effort": got_effort},- )diff --git a/products/slack_app/evals/scorers.py b/products/slack_app/evals/scorers.pyindex 4b8fc12387c5..8fd421a32d8a 100644--- a/products/slack_app/evals/scorers.py+++ b/products/slack_app/evals/scorers.py@@ -1,4 +1,11 @@-"""Scorers for the Slack app's answers to "how do I set up X?" questions."""+"""Scorers for every Slack app eval suite.++One module rather than one per suite: the suites grade a handful of recurring shapes —+did a classifier read a mention the way a person would, did it invent an instruction+nobody gave — and keeping those side by side is what makes the asymmetry between them+legible. Each scorer opts into a case through its own ``expected`` key and skips+(``score=None``) when that key is absent, so a suite lists only the scorers it wants.+"""from __future__ import annotations@@ -6,7 +13,7 @@ from typing import Anyfrom products.posthog_ai.eval_harness.log_parser import LogParserfrom products.posthog_ai.eval_harness.scorers import BINARY_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer-from products.posthog_ai.eval_harness.scorers.contract import Score+from products.posthog_ai.eval_harness.scorers.contract import Score, ScorerDOCS_SEARCH_TOOL_NAME = "docs-search"@@ -129,3 +136,149 @@ Is the answer free of recommendations to use a non-PostHog product for this capamax_completion_tokens=256,**kwargs,)+++# ---------------------------------------------------------------------------+# Model-override classifier+# ---------------------------------------------------------------------------++# Both scorers read the same expectation: one case states the answer once, and the+# false-positive scorer derives "this case asks for nothing" from it rather than+# carrying a second, separately-maintained flag that could disagree.+MODEL_OVERRIDE_KEY = "model_override_match"+++def _reads(output: dict | None) -> tuple[str | None, str | None]:+ """The classifier's answer as a `(model, reasoning_effort)` pair.++ A `None` override — the classifier declining to steer the run — reads the same as an+ explicit pair of nulls, because that is what it means downstream.+ """+ override = (output or {}).get("override") or {}+ return override.get("model"), override.get("reasoning_effort")+++class ModelOverrideMatch(Scorer):+ """Did the classifier read the mention the way a person would?++ Scores both fields at once: a run launched on the right model at the wrong effort is+ still not what the author asked for.+ """++ def _name(self) -> str:+ return MODEL_OVERRIDE_KEY++ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:+ if output and output.get("error"):+ return Score(name=self._name(), score=0.0, metadata={"reason": output["error"]})++ want = (expected or {}).get(MODEL_OVERRIDE_KEY)+ if want is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No expectation for this case"})++ got_model, got_effort = _reads(output)+ want_model, want_effort = want.get("model"), want.get("reasoning_effort")+ matched = got_model == want_model and got_effort == want_effort+ return Score(+ name=self._name(),+ score=1.0 if matched else 0.0,+ metadata={+ "expected_model": want_model,+ "actual_model": got_model,+ "expected_effort": want_effort,+ "actual_effort": got_effort,+ },+ )+++class NoUnaskedOverride(Scorer):+ """The failure that actually costs the user something.++ The two error directions are not symmetric. Missing a real instruction falls back to+ the author's saved preferences — they notice and rephrase. Inventing an instruction+ out of subject matter silently moves someone's run onto a model they never chose, and+ nothing in the thread says so.++ Skips (`None`) on cases that do ask for something, so the score reads as a rate over+ the mentions that merely *mention* a model.+ """++ def _name(self) -> str:+ return "no_unasked_override"++ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:+ want = (expected or {}).get(MODEL_OVERRIDE_KEY) or {}+ if want.get("model") or want.get("reasoning_effort"):+ return Score(name=self._name(), score=None, metadata={"reason": "Case asks for an override"})++ if output and output.get("error"):+ # An erroring call yields no override, which is the safe answer here — but+ # scoring it as a pass would hide a broken classifier behind a good rate.+ return Score(name=self._name(), score=None, metadata={"reason": output["error"]})++ got_model, got_effort = _reads(output)+ invented = got_model is not None or got_effort is not None+ return Score(+ name=self._name(),+ score=0.0 if invented else 1.0,+ metadata={"actual_model": got_model, "actual_effort": got_effort},+ )+++# ---------------------------------------------------------------------------+# Untagged follow-up routing+# ---------------------------------------------------------------------------++FOLLOWUP_KEY = "followup_routing"+++class FollowupRoutingMatch(Scorer):+ """Did the classifier route the reply the way a person in the thread would?++ Opting in is by *presence* of the field, not truthiness — the chatter cases expect+ ``False``, and a truthiness check would skip every one of them.+ """++ def _name(self) -> str:+ return FOLLOWUP_KEY++ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:+ want = (expected or {}).get(FOLLOWUP_KEY) or {}+ if "agent_directed" not in want:+ return Score(name=self._name(), score=None, metadata={"reason": "No expectation for this case"})+ if output and output.get("error"):+ return Score(name=self._name(), score=0.0, metadata={"reason": output["error"]})++ got = (output or {}).get("agent_directed")+ return Score(+ name=self._name(),+ score=1.0 if got == want["agent_directed"] else 0.0,+ metadata={"expected": want["agent_directed"], "actual": got},+ )+++class NoUnaskedWake(Scorer):+ """The expensive direction: waking the agent on a message nobody addressed to it.++ See ``classify_message_is_agent_directed`` for why the two errors cost differently.+ Skips on cases that really are instructions, so the score reads as a rate over the+ replies the agent should have stayed out of.+ """++ def _name(self) -> str:+ return "no_unasked_wake"++ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:+ want = (expected or {}).get(FOLLOWUP_KEY) or {}+ if want.get("agent_directed", True):+ return Score(name=self._name(), score=None, metadata={"reason": "Case is a real instruction"})+ if output and output.get("error"):+ # A failed call returns False, this scorer's passing answer — scoring it would+ # let a wholly broken classifier post a perfect rate.+ return Score(name=self._name(), score=None, metadata={"reason": output["error"]})++ return Score(+ name=self._name(),+ score=0.0 if (output or {}).get("agent_directed") else 1.0,+ metadata={"actual": (output or {}).get("agent_directed")},+ )