: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): bias classify_task_needs_repo toward no-repo (#64470)
Vojta Bartoš171d7b334283
diff --git a/posthog/temporal/ai/slack_app/activities/__init__.py b/posthog/temporal/ai/slack_app/activities/__init__.pyindex 4d9d15a2ede7..e926a587c7e6 100644--- a/posthog/temporal/ai/slack_app/activities/__init__.py+++ b/posthog/temporal/ai/slack_app/activities/__init__.py@@ -2,6 +2,8 @@ from posthog.temporal.ai.slack_app.activities.billing import enforce_posthog_codfrom posthog.temporal.ai.slack_app.activities.classifiers import (CLASSIFIER_THREAD_HISTORY_MESSAGES,classify_message_is_agent_directed,+ classify_posthog_code_task_needs_repo_activity,+ classify_task_needs_repo,classify_untagged_followup_activity,)from posthog.temporal.ai.slack_app.activities.messaging import (@@ -15,7 +17,6 @@ from posthog.temporal.ai.slack_app.activities.messaging import ()from posthog.temporal.ai.slack_app.activities.repo_selection import (cascade_posthog_code_repository_activity,- classify_posthog_code_task_needs_repo_activity,discover_posthog_code_repository_via_agent_activity,)from posthog.temporal.ai.slack_app.activities.rules import (@@ -42,6 +43,7 @@ __all__ = ["cascade_posthog_code_repository_activity","classify_message_is_agent_directed","classify_posthog_code_task_needs_repo_activity",+ "classify_task_needs_repo","classify_untagged_followup_activity","collect_posthog_code_thread_messages_activity","create_posthog_code_routing_rule_activity",diff --git a/posthog/temporal/ai/slack_app/activities/classifiers.py b/posthog/temporal/ai/slack_app/activities/classifiers.pyindex 51fae895700c..7952c178859f 100644--- a/posthog/temporal/ai/slack_app/activities/classifiers.py+++ b/posthog/temporal/ai/slack_app/activities/classifiers.py@@ -16,6 +16,141 @@ logger = structlog.get_logger(__name__)CLASSIFIER_THREAD_HISTORY_MESSAGES = 10+def classify_task_needs_repo(+ event_text: str,+ thread_messages: list[dict[str, str]],+) -> bool:+ """Classify whether a Slack conversation requires code repository access.++ Returns True if the task likely needs a repo (writing code, fixing bugs, PRs),+ False if it does not (analytics, data queries, PostHog config).++ Biased toward False: a false negative answers an analytics ask with no repo+ (recoverable — the user re-asks with code intent), while a false positive+ walls the user behind the Connect-GitHub gate even for "what's my DAU".+ Defaults to False on error for the same reason.+ """+ conversation = "\n".join(f"{msg['user']}: {msg['text']}" for msg in thread_messages)+ normalized = f"{conversation}\nLatest message: {event_text}".lower()++ # Substring match: keep the shortest form that uniquely identifies the+ # concept without colliding with code-review vocabulary. Plurals are used+ # only when the singular substring-matches a common non-analytics word+ # (e.g. `event` → `eventually`, `person` → `personal`).+ product_debug_terms = (+ # Product/config debugging+ "automation",+ "destination",+ "posthog ai feedback",+ "feature flag",+ "experiment",+ "survey",+ "dashboard",+ "insight",+ "recording",+ "mcp",+ "webhook",+ # Analytics primitives and data asks+ "events",+ "persons",+ "cohort",+ "trend",+ "funnel",+ "retention",+ "hogql",+ "replay",+ "breakdown",+ "dau",+ "mau",+ "error tracking",+ "llm analytics",+ "revenue",+ "marketing analytics",+ )+ explicit_code_patterns = (+ r"\brepository\b",+ r"\brepo\b",+ r"\bpull request\b",+ r"\bopen a pr\b",+ r"\bcreate a pr\b",+ r"\bcommit\b",+ r"\bbranch\b",+ r"\bmodify code\b",+ r"\bchange code\b",+ r"\bwrite code\b",+ r"\bimplement\b",+ r"\.py\b",+ r"\.ts\b",+ r"\.tsx\b",+ r"\.js\b",+ r"\bserializer\b",+ r"\bviewset\b",+ r"\bmigration\b",+ )++ if any(term in normalized for term in product_debug_terms) and not any(+ re.search(pattern, normalized) for pattern in explicit_code_patterns+ ):+ logger.info("slack_app_classify_task_needs_repo_heuristic_non_repo", event_text=event_text)+ return False++ prompt = (+ "You are a task classifier. Given a Slack conversation, determine whether the task "+ "requires access to a code repository (e.g. writing code, fixing bugs, creating PRs, "+ "reviewing code, modifying files) or NOT (e.g. answering questions about analytics, "+ "querying data, PostHog configuration, general knowledge questions, planning, or "+ "investigating product behavior in a PostHog workspace using MCP/tools).\n\n"+ "Return needs_repo=false for tasks that are primarily about debugging or investigating "+ "automations, destinations, feature flags, experiments, surveys, dashboards, insights, "+ "recordings, traces, or Slack integrations inside PostHog, unless the user explicitly "+ "asks to change code, open a PR, edit files, or work in a specific repository.\n\n"+ "A complaint about something the team's own app, site, or SDK does (crashes, broken pages, "+ "wrong rendering, slow loads of a site they ship) is a code change in a repo they own → "+ "needs_repo. But complaints about PostHog itself as a product (its dashboards hanging, "+ "product pages loading slowly, UI bugs in PostHog screens) are SaaS product issues, not "+ "the team's code → no_repo. Important exception: 'wrong data', 'missing events', or "+ "'numbers look off' in PostHog usually means the team's tracking code is broken (wrong "+ "event names, identification logic, SDK setup) — that's a code fix in their repo → "+ "needs_repo. When in doubt, lean needs_repo=false — code-focused tasks usually carry "+ "explicit signals (file extensions, 'PR', 'commit', framework names, function or class "+ "names). Analytics, data, and configuration asks are the common case and should not be "+ "walled behind a Connect-GitHub prompt on a guess.\n\n"+ f"Conversation:\n{conversation}\n\n"+ f"Latest message: {event_text}\n\n"+ 'Respond with ONLY a JSON object: {{"needs_repo": true}} or {{"needs_repo": false}}'+ )+ try:+ client = get_llm_client("slack_app_routing")+ response = client.chat.completions.create(+ model="claude-haiku-4-5-20251001",+ messages=[{"role": "user", "content": prompt}],+ max_tokens=64,+ temperature=0,+ )+ content = (response.choices[0].message.content or "").strip()+ if content.startswith("```"):+ content = content.strip("`").removeprefix("json").strip()+ parsed = json.loads(content)+ # Haiku occasionally stringifies the bool ({"needs_repo": "false"}).+ # bool("false") is True, which would flip the defensive bias — handle+ # strings explicitly and treat any other unexpected shape as False.+ value = parsed.get("needs_repo", False)+ if isinstance(value, str):+ return value.strip().lower() == "true"+ return value is True+ except Exception:+ logger.exception("slack_app_classify_task_needs_repo_failed")+ return False+++def classify_posthog_code_task_needs_repo_activity(+ event_text: str,+ thread_messages: list[dict[str, str]],+) -> bool:+ return classify_task_needs_repo(event_text, thread_messages)++def classify_message_is_agent_directed(event_text: str,task_title: str,diff --git a/posthog/temporal/ai/slack_app/activities/repo_selection.py b/posthog/temporal/ai/slack_app/activities/repo_selection.pyindex e4ec3a463c5d..428cfa1f605a 100644--- a/posthog/temporal/ai/slack_app/activities/repo_selection.py+++ b/posthog/temporal/ai/slack_app/activities/repo_selection.py@@ -197,13 +197,3 @@ async def discover_posthog_code_repository_via_agent_activity(repo_research_task_id=research_ids.get("task_id"),repo_research_run_id=research_ids.get("run_id"),)---def classify_posthog_code_task_needs_repo_activity(- event_text: str,- thread_messages: list[dict[str, str]],-) -> bool:- from products.slack_app.backend.api import classify_task_needs_repo-- return classify_task_needs_repo(event_text, thread_messages)diff --git a/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py b/posthog/temporal/ai/slack_app/eval_slack_repo_selection.pyindex b632c2061a62..3f7dea91b33a 100644--- a/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py+++ b/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py@@ -81,8 +81,9 @@ from django.conf import settingsfrom posthog.models import Teamfrom posthog.temporal.ai.slack_app import POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE+from posthog.temporal.ai.slack_app.activities.classifiers import classify_task_needs_repo-from products.slack_app.backend.api import _extract_explicit_repo, classify_task_needs_repo+from products.slack_app.backend.api import _extract_explicit_repofrom products.tasks.backend.models import Taskfrom products.tasks.backend.repo_selection import (RepoSelectionRejectedError,diff --git a/posthog/temporal/tests/ai/test_classify_task_needs_repo.py b/posthog/temporal/tests/ai/test_classify_task_needs_repo.pynew file mode 100644index 000000000000..bb8ed9b32c77--- /dev/null+++ b/posthog/temporal/tests/ai/test_classify_task_needs_repo.py@@ -0,0 +1,93 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.temporal.ai.slack_app.activities.classifiers import classify_task_needs_repo+++class TestClassifyTaskNeedsRepo:+ @parameterized.expand(+ [+ (+ "product_debug_automation",+ "debug why the automation that sends PostHog AI Feedback always gives a thumbs down",+ False,+ ),+ (+ "product_debug_destination",+ "investigate the slack destination configuration for this automation",+ False,+ ),+ (+ "product_debug_report_not_repo",+ "debug why this dashboard report always shows a thumbs down",+ False,+ ),+ # Analytics / data asks — the common no-GitHub case from the+ # 2026-06-17 UPchieve report. None of these should wall a user+ # behind the Connect-GitHub gate.+ ("analytics_dau", "what was our DAU yesterday?", False),+ ("analytics_event_count", "how many pageview events did we get last week", False),+ ("analytics_trend", "show me the trend of signups over the last 30 days", False),+ ("analytics_funnel", "build a funnel from landing page to signup", False),+ ("analytics_retention", "what's our 7-day retention for new users", False),+ ("analytics_breakdown", "break down events by browser", False),+ ("analytics_persons", "find persons who triggered checkout last week", False),+ ("analytics_cohort", "create a cohort of power users", False),+ ("analytics_hogql", "write a hogql query to count signups by country", False),+ ("flag_search", "find the feature flag for the new onboarding", False),+ ("replay_question", "show me session replays of failed checkouts", False),+ ]+ )+ def test_heuristic_classification(self, _name, text, expected):+ result = classify_task_needs_repo(text, [{"user": "Alessandro", "text": text}])+ assert result is expected++ def test_llm_path_returns_true_when_model_says_needs_repo(self):+ """Ask with no heuristic signal — classifier must defer to the LLM."""+ text = "open a PR in posthog/posthog to fix this serializer"+ result = self._run_with_llm_content(text, '{"needs_repo": true}')+ assert result is True++ @parameterized.expand(+ [+ # JSON booleans round-trip to Python bools as expected.+ ("json_bool_true", '{"needs_repo": true}', True),+ ("json_bool_false", '{"needs_repo": false}', False),+ # Haiku occasionally stringifies the bool — bool("false") would be+ # True and silently flip the defensive bias. Parse strings instead.+ ("stringified_true", '{"needs_repo": "true"}', True),+ ("stringified_false", '{"needs_repo": "false"}', False),+ ("stringified_true_upper", '{"needs_repo": "TRUE"}', True),+ ("stringified_padded", '{"needs_repo": " true "}', True),+ # Garbage values default to False (no-repo) per the defensive bias.+ ("unexpected_int", '{"needs_repo": 1}', False),+ ("unexpected_null", '{"needs_repo": null}', False),+ ("missing_key", "{}", False),+ ]+ )+ def test_llm_response_shapes(self, _name, content, expected):+ text = "ambiguous ask the heuristic does not catch"+ result = self._run_with_llm_content(text, content)+ assert result is expected++ def _run_with_llm_content(self, text: str, content: str) -> bool:+ fake_response = MagicMock()+ fake_response.choices = [MagicMock(message=MagicMock(content=content))]+ fake_client = MagicMock()+ fake_client.chat.completions.create.return_value = fake_response+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ return_value=fake_client,+ ):+ return classify_task_needs_repo(text, [{"user": "Alessandro", "text": text}])++ def test_llm_failure_defaults_to_false(self):+ """A flaky LLM call must not wall users behind the Connect-GitHub gate."""+ text = "something the heuristic can't classify on its own"+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ side_effect=RuntimeError("boom"),+ ):+ result = classify_task_needs_repo(text, [{"user": "Alessandro", "text": text}])+ assert result is Falsediff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 6191eb962c81..7c39eec8f682 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -23,7 +23,6 @@ from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicyfrom posthog.event_usage import groupsfrom posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES-from posthog.llm.gateway_client import get_llm_clientfrom posthog.models.integration import (SLACK_INTEGRATION_KINDS,Integration,@@ -1092,102 +1091,6 @@ def _resolve_pending_repo_picker_from_followup(event: dict[str, Any], integratioreturn True-def classify_task_needs_repo(- event_text: str,- thread_messages: list[dict[str, str]],-) -> bool:- """Classify whether a Slack conversation requires code repository access.-- Returns True if the task likely needs a repo (writing code, fixing bugs, PRs),- False if it does not (analytics, data queries, PostHog config).- Defaults to True on error (conservative — falls back to picker).- """- conversation = "\n".join(f"{msg['user']}: {msg['text']}" for msg in thread_messages)- normalized = f"{conversation}\nLatest message: {event_text}".lower()-- product_debug_terms = (- "automation",- "destination",- "slack destination",- "posthog ai feedback",- "feature flag",- "experiment",- "survey",- "dashboard",- "insight",- "session replay",- "recording",- "mcp",- "webhook",- )- explicit_code_patterns = (- r"\brepository\b",- r"\brepo\b",- r"\bpull request\b",- r"\bopen a pr\b",- r"\bcreate a pr\b",- r"\bcommit\b",- r"\bbranch\b",- r"\bmodify code\b",- r"\bchange code\b",- r"\bwrite code\b",- r"\bimplement\b",- r"\.py\b",- r"\.ts\b",- r"\.tsx\b",- r"\.js\b",- r"\bserializer\b",- r"\bviewset\b",- r"\bmigration\b",- )-- if any(term in normalized for term in product_debug_terms) and not any(- re.search(pattern, normalized) for pattern in explicit_code_patterns- ):- logger.info("classify_task_needs_repo_heuristic_non_repo", event_text=event_text)- return False-- prompt = (- "You are a task classifier. Given a Slack conversation, determine whether the task "- "requires access to a code repository (e.g. writing code, fixing bugs, creating PRs, "- "reviewing code, modifying files) or NOT (e.g. answering questions about analytics, "- "querying data, PostHog configuration, general knowledge questions, planning, or "- "investigating product behavior in a PostHog workspace using MCP/tools).\n\n"- "Return needs_repo=false for tasks that are primarily about debugging or investigating "- "automations, destinations, feature flags, experiments, surveys, dashboards, insights, "- "recordings, traces, or Slack integrations inside PostHog, unless the user explicitly "- "asks to change code, open a PR, edit files, or work in a specific repository.\n\n"- "A complaint about something the team's own app, site, or SDK does (crashes, broken pages, "- "wrong rendering, slow loads of a site they ship) is a code change in a repo they own → "- "needs_repo. But complaints about PostHog itself as a product (its dashboards hanging, "- "product pages loading slowly, UI bugs in PostHog screens) are SaaS product issues, not "- "the team's code → no_repo. Important exception: 'wrong data', 'missing events', or "- "'numbers look off' in PostHog usually means the team's tracking code is broken (wrong "- "event names, identification logic, SDK setup) — that's a code fix in their repo → "- "needs_repo. When in doubt, lean needs_repo=true — the discovery agent can still report "- "there's no good match.\n\n"- f"Conversation:\n{conversation}\n\n"- f"Latest message: {event_text}\n\n"- 'Respond with ONLY a JSON object: {{"needs_repo": true}} or {{"needs_repo": false}}'- )- try:- client = get_llm_client("slack_app_routing")- response = client.chat.completions.create(- model="claude-haiku-4-5-20251001",- messages=[{"role": "user", "content": prompt}],- max_tokens=64,- temperature=0,- )- content = (response.choices[0].message.content or "").strip()- if content.startswith("```"):- content = content.strip("`").removeprefix("json").strip()- parsed = json.loads(content)- return bool(parsed.get("needs_repo", True))- except Exception:- logger.exception("classify_task_needs_repo_failed")- return True--def _app_mention_ignore_reason(event: dict[str, Any]) -> str | None:"""Return a short reason if this app_mention shouldn't trigger the coding agent, else None.diff --git a/products/slack_app/backend/tests/test_guess_repository.py b/products/slack_app/backend/tests/test_guess_repository.pyindex ec856c5b517c..9bccdd8fb194 100644--- a/products/slack_app/backend/tests/test_guess_repository.py+++ b/products/slack_app/backend/tests/test_guess_repository.py@@ -21,7 +21,6 @@ from products.slack_app.backend.api import (_invalidate_user_repo_list_cache,_parse_rules_command,_user_repo_list_cache_key,- classify_task_needs_repo,)@@ -660,33 +659,3 @@ class TestRepoRoutingRuleModel:team_a_rules = list(RepoRoutingRule.objects.filter(team=self.team_a))assert len(team_a_rules) == 1assert team_a_rules[0].rule_text == "Team A rule"---class TestClassifyTaskNeedsRepo:- @parameterized.expand(- [- (- "product_debug_automation",- "debug why the automation that sends PostHog AI Feedback always gives a thumbs down",- False,- ),- (- "product_debug_destination",- "investigate the slack destination configuration for this automation",- False,- ),- (- "product_debug_report_not_repo",- "debug why this dashboard report always shows a thumbs down",- False,- ),- (- "explicit_repo_request",- "open a PR in posthog/posthog to fix this serializer",- True,- ),- ]- )- def test_heuristic_classification(self, _name, text, expected):- result = classify_task_needs_repo(text, [{"user": "Alessandro", "text": text}])- assert result is expected