Skip to content

: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.

feat(slack): read the project out of the message that opens a thread (#102781)

Vojta Bartoš57a0606e4d06
diff --git a/posthog/temporal/ai/slack_app/__init__.py b/posthog/temporal/ai/slack_app/__init__.py
index e51051ef03aa..1ed2ac48b3d9 100644
--- a/posthog/temporal/ai/slack_app/__init__.py
+++ b/posthog/temporal/ai/slack_app/__init__.py
@@ -14,6 +14,7 @@ from posthog.temporal.ai.slack_app.activities import (
classify_message_is_agent_directed,
classify_posthog_code_task_needs_repo_activity,
classify_slack_app_model_override_activity,
+ classify_slack_app_project_route_activity,
classify_untagged_followup_activity,
collect_posthog_code_thread_messages_activity,
create_posthog_code_routing_rule_activity,
@@ -48,6 +49,8 @@ from posthog.temporal.ai.slack_app.types import (
SlackAppMessageReactionInput,
SlackAppModelOverride,
SlackAppModelOverrideInput,
+ SlackAppProjectRoute,
+ SlackAppProjectRouteInput,
SlackRepoSelectionOutcome,
)
@@ -61,6 +64,7 @@ SLACK_APP_ACTIVITIES = [
discover_posthog_code_repository_via_agent_activity,
classify_posthog_code_task_needs_repo_activity,
classify_slack_app_model_override_activity,
+ classify_slack_app_project_route_activity,
enforce_posthog_code_billing_quota_activity,
post_posthog_code_no_repos_activity,
post_posthog_code_repo_picker_activity,
@@ -95,12 +99,15 @@ __all__ = [
"SlackAppMentionWorkflowInputs",
"SlackAppModelOverride",
"SlackAppModelOverrideInput",
+ "SlackAppProjectRoute",
+ "SlackAppProjectRouteInput",
"SlackRepoSelectionOutcome",
"block_posthog_code_task_if_no_personal_github_activity",
"cascade_posthog_code_repository_activity",
"classify_message_is_agent_directed",
"classify_posthog_code_task_needs_repo_activity",
"classify_slack_app_model_override_activity",
+ "classify_slack_app_project_route_activity",
"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/__init__.py b/posthog/temporal/ai/slack_app/activities/__init__.py
index 47f239801c16..bb41f63a1786 100644
--- a/posthog/temporal/ai/slack_app/activities/__init__.py
+++ b/posthog/temporal/ai/slack_app/activities/__init__.py
@@ -5,6 +5,8 @@ from posthog.temporal.ai.slack_app.activities.classifiers import (
classify_posthog_code_task_needs_repo_activity,
classify_slack_app_model_override,
classify_slack_app_model_override_activity,
+ classify_slack_app_project_route,
+ classify_slack_app_project_route_activity,
classify_task_needs_repo,
classify_untagged_followup_activity,
)
@@ -52,6 +54,8 @@ __all__ = [
"classify_posthog_code_task_needs_repo_activity",
"classify_slack_app_model_override",
"classify_slack_app_model_override_activity",
+ "classify_slack_app_project_route",
+ "classify_slack_app_project_route_activity",
"classify_task_needs_repo",
"classify_untagged_followup_activity",
"collect_posthog_code_thread_messages_activity",
diff --git a/posthog/temporal/ai/slack_app/activities/classifiers.py b/posthog/temporal/ai/slack_app/activities/classifiers.py
index 68f4d4d27a7f..e77847a49a87 100644
--- a/posthog/temporal/ai/slack_app/activities/classifiers.py
+++ b/posthog/temporal/ai/slack_app/activities/classifiers.py
@@ -3,17 +3,20 @@ from pathlib import Path
import structlog
from openai.types.shared_params import ResponseFormatJSONSchema
-from pydantic import ValidationError
+from pydantic import BaseModel, ValidationError
from temporalio import activity
from posthog.llm.gateway_client import build_anthropic_client, build_openai_client
from posthog.llm.semantic_enrichment import extract_json_object
from posthog.models.integration import Integration, SlackIntegration
from posthog.models.repo_routing_rule import RepoRoutingRule
+from posthog.models.user import User
from posthog.temporal.ai.slack_app.types import (
PostHogCodeSlackMentionWorkflowInputs,
SlackAppModelOverride,
SlackAppModelOverrideInput,
+ SlackAppProjectRoute,
+ SlackAppProjectRouteInput,
)
from posthog.temporal.common.utils import close_db_connections
@@ -23,8 +26,10 @@ from products.slack_app.backend.facade.run_preferences import (
find_model_choice,
group_by_runtime,
)
+from products.slack_app.backend.feature_flags import is_slack_app_project_routing_enabled
from products.slack_app.backend.models import SlackThreadTaskMapping
from products.slack_app.backend.prompt_templates import PromptTemplates
+from products.slack_app.backend.services.integration_resolver import format_project_candidate_list, routable_projects
from products.slack_app.backend.services.slack_messages import SlackThreadMessage
logger = structlog.get_logger(__name__)
@@ -52,6 +57,14 @@ MODEL_OVERRIDE_MAX_COMPLETION_TOKENS = 2048
MODEL_OVERRIDE_TIMEOUT_SECONDS = 10.0
MODEL_OVERRIDE_MAX_RETRIES = 1
+# Same shape of call as the model override, so it takes the same bounds — including the
+# cap riding on `max_completion_tokens`. The reasoning-class chat-completions route
+# rejects `max_tokens` outright, and the classifier would swallow that into its fallback.
+PROJECT_ROUTE_CLASSIFIER_MODEL = "gpt-5.6-luna"
+PROJECT_ROUTE_MAX_COMPLETION_TOKENS = 2048
+PROJECT_ROUTE_TIMEOUT_SECONDS = 10.0
+PROJECT_ROUTE_MAX_RETRIES = 1
+
AGENT_DIRECTED_CLASSIFIER_MODEL = "gpt-5.6-luna"
AGENT_DIRECTED_MAX_COMPLETION_TOKENS = 2048
# One call per reply in every thread the agent is working in, and its prompt carries the
@@ -526,3 +539,136 @@ def classify_slack_app_model_override_activity(input: SlackAppModelOverrideInput
reasoning_effort=override.reasoning_effort,
)
return override
+
+
+def _project_route_response_format(projects: list[Integration]) -> ResponseFormatJSONSchema:
+ """A strict JSON schema pinning the reply to one id from ``projects``.
+
+ The enum is what stops the classifier naming a project this mentioner cannot reach.
+ `routable_projects` bounds the list by access, and that bound only reaches the model
+ through this field.
+ """
+ return {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "slack_app_project_route",
+ "strict": True,
+ "schema": {
+ "type": "object",
+ "properties": {
+ "project_id": {"type": ["integer", "null"], "enum": [*(p.team_id for p in projects), None]},
+ },
+ "required": ["project_id"],
+ "additionalProperties": False,
+ },
+ },
+ }
+
+
+class _ProjectRouteReply(BaseModel):
+ project_id: int | None = None
+
+
+def classify_slack_app_project_route(event_text: str, projects: list[Integration]) -> Integration | None:
+ """Read the project a mention asked to be answered from, out of its text.
+
+ Returns ``None`` when the author named none, which is the overwhelming majority of
+ mentions, and on a reply this cannot parse.
+
+ A gateway failure raises instead of returning ``None``. The activity turns that into
+ the same fallback, so production behaviour is unchanged; the eval suite calls this
+ function directly, and a swallowed failure there is indistinguishable from a clean
+ "no project" — it would score a dead gateway as a pass on every negative case.
+
+ It takes the opposite rule to the model classifier: a model named as the subject of a
+ question is never an instruction, while a project named as the subject usually is
+ where the answer has to come from, because that is where the data lives. Quality on
+ that is measured by ``products/slack_app/evals/eval_project_classifier.py``.
+ """
+ prompt = prompts.render(
+ "project_route",
+ projects=format_project_candidate_list(projects),
+ event_text=event_text,
+ )
+
+ try:
+ client = build_openai_client(product="slack_app_routing", ai_product="slack_app_routing").with_options(
+ timeout=PROJECT_ROUTE_TIMEOUT_SECONDS, max_retries=PROJECT_ROUTE_MAX_RETRIES
+ )
+ response = client.chat.completions.create(
+ model=PROJECT_ROUTE_CLASSIFIER_MODEL,
+ messages=[{"role": "user", "content": prompt}],
+ max_completion_tokens=PROJECT_ROUTE_MAX_COMPLETION_TOKENS,
+ response_format=_project_route_response_format(projects),
+ )
+ # Tolerant parse on top of the schema, matching the model-override classifier:
+ # the gateway does not honour a response format identically on every route.
+ parsed = extract_json_object(response.choices[0].message.content or "")
+ reply = _ProjectRouteReply.model_validate(parsed)
+ except (ValidationError, ValueError):
+ logger.info("slack_app_project_route_unusable_reply")
+ return None
+
+ if reply.project_id is None:
+ return None
+ chosen = next((p for p in projects if p.team_id == reply.project_id), None)
+ if chosen is None:
+ # The classifier was told to copy an id from the list; anything else is a
+ # hallucination or a project this mentioner cannot open.
+ logger.info("slack_app_project_route_unknown_project", requested_team_id=reply.project_id)
+ return chosen
+
+
+@close_db_connections
+def classify_slack_app_project_route_activity(input: SlackAppProjectRouteInput) -> SlackAppProjectRoute | None:
+ """Resolve the project a mention asked for, or ``None`` to stay on the resolved one.
+
+ The workflow calls this only for a message that opens a thread. A task, its thread
+ mapping and its run all belong to one project, so a reply cannot move the thread.
+ """
+ if not input.event_text.strip():
+ return None
+ # Cheapest gate first, and the one that answers most workspaces. Everything below is
+ # two queries and a blocking flag call, and a workspace connected to one project has
+ # nothing to route between however they come out.
+ if Integration.objects.filter(kind="slack", integration_id=input.slack_team_id).count() < 2:
+ return None
+
+ integration = Integration.objects.select_related("team", "team__organization").get(
+ id=input.integration_id,
+ kind="slack",
+ integration_id=input.slack_team_id,
+ )
+ user = User.objects.filter(id=input.user_id).first()
+ if user is None:
+ return None
+ if not is_slack_app_project_routing_enabled(integration, distinct_id=user.distinct_id):
+ return None
+
+ projects = routable_projects(
+ slack_team_id=input.slack_team_id,
+ slack_user_id=input.slack_user_id,
+ user=user,
+ )
+ if not projects:
+ return None
+
+ try:
+ chosen = classify_slack_app_project_route(input.event_text, projects)
+ except Exception:
+ # The fallback boundary: a mention we cannot classify stays on the project
+ # routing already resolved, which is what it would have done anyway.
+ logger.exception("slack_app_project_route_classify_failed")
+ return None
+ # A message naming the project the run was already going to use asked for nothing.
+ if chosen is None or chosen.id == integration.id:
+ return None
+
+ logger.info(
+ "slack_app_project_route_classified",
+ integration_id=integration.id,
+ routed_integration_id=chosen.id,
+ project_candidate_count=len(projects),
+ )
+ return SlackAppProjectRoute(integration_id=chosen.id)
diff --git a/posthog/temporal/ai/slack_app/activities/prompts/project_route.md.j2 b/posthog/temporal/ai/slack_app/activities/prompts/project_route.md.j2
new file mode 100644
index 000000000000..b1f8d911c068
--- /dev/null
+++ b/posthog/temporal/ai/slack_app/activities/prompts/project_route.md.j2
@@ -0,0 +1,24 @@
+You are routing a Slack message addressed to the PostHog agent. This Slack workspace is connected to several PostHog projects, each holding separate data, and this message opens a new thread. Decide which project it should be answered from.
+
+Only these projects can be selected, and the id is the number:
+{{ projects }}
+
+Most messages name no project at all, and null is the answer for those. Only name one when the message points at it.
+
+Name a project when the message says where to look:
+ - "check the error rate on Endpaper staging", "in the website project, why did signups drop", "for production, which exports failed yesterday".
+ - The project can be named anywhere in the sentence, and the rest of the message is still the request.
+ - A project named as the place a problem lives is still where to look: "why is Endpaper production throwing 500s" is answered from Endpaper production. A project is usually the subject of the question AND the place the answer comes from.
+
+Answer with null when the project is the thing being worked on rather than the place to look:
+ - "rename the Website project", "add staging to the project dropdown" (a project as the object of a change).
+ - "we should split staging and production" (a proposal about projects).
+ - A word that only happens to match a project name. With a project called "Website", "the website is down" names no project.
+ - "I already checked staging, look at the SDK instead" (an account of a place already ruled out — past tense is the tell).
+ - Two projects at once, as in "compare staging and production". One task answers from one project, and picking one of the two on a guess is worse than staying on the default.
+
+When you are unsure, answer with null — the default is the right place to look.
+
+Message: {{ event_text }}
+
+Answer with the one field, e.g. {"project_id": 42} or {"project_id": null}
diff --git a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py
index 9026de7d7708..4861296e24b7 100644
--- a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py
+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py
@@ -1,5 +1,6 @@
# Workflows in this module run on the max-ai temporal task queue.
import json
+from dataclasses import replace
from datetime import timedelta
from typing import Any
@@ -11,9 +12,11 @@ from posthog.temporal.ai.slack_app import (
PostHogCodeSlackMentionWorkflowInputs,
SlackAppModelOverride,
SlackAppModelOverrideInput,
+ SlackAppProjectRouteInput,
cascade_posthog_code_repository_activity,
classify_posthog_code_task_needs_repo_activity,
classify_slack_app_model_override_activity,
+ classify_slack_app_project_route_activity,
classify_untagged_followup_activity,
collect_posthog_code_thread_messages_activity,
create_posthog_code_task_for_repo_activity,
@@ -30,19 +33,20 @@ from posthog.temporal.common.base import PostHogWorkflow
POSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS = 10 * 60
POSTHOG_CODE_SLACK_PICKER_TIMEOUT_MINUTES = 15
-# Temporal patch IDs — arbitrary strings recorded in workflow history. The
-# pre-patch histories behind the first three have drained: this workflow's
-# longest wait is the 15-minute repo picker, and it is bounded at an hour as a
-# child of the queue workflow. Their gates are gone and only `deprecate_patch`
-# remains, keeping the recorded marker compatible for executions in flight
-# across the deploy that removes them. Standard two-step Temporal patch
-# lifecycle: those calls come out once the histories that recorded a plain
-# marker have drained in turn. The last two are younger and still gated, so they
-# stay full `workflow.patched` branches until they drain too.
+# Temporal patch IDs — arbitrary strings recorded in workflow history. The pre-patch
+# histories behind the older ones have drained: this workflow's longest wait is the
+# 15-minute repo picker, and it is bounded at an hour as a child of the queue workflow.
+# Their gates are gone and only `deprecate_patch` remains, keeping the recorded marker
+# compatible for executions in flight across the deploy that removes them. Standard
+# two-step Temporal patch lifecycle: those calls come out once the histories that
+# recorded a plain marker have drained in turn. The younger ones stay full
+# `workflow.patched` branches until they drain too — grep a name to see which it is.
_PATCH_ID_FILE_ONLY_FOLLOWUP_BYPASS = "slack-file-only-followup-bypass-v1"
_PATCH_ID_FOLLOWUP_MODEL_CLASSIFIER = "slack-app-followup-model-classifier-v1"
_PATCH_ID_MODEL_CLASSIFIER = "slack-app-model-classifier-v1"
_PATCH_ID_NO_PERSONAL_GITHUB_GATE = "slack-no-personal-github-gate-v1"
+_PATCH_ID_PROJECT_ROUTE_CLASSIFIER = "slack-app-project-route-classifier-v1"
+_PATCH_ID_PROJECT_ROUTE_QUOTA = "slack-app-project-route-quota-v1"
_PATCH_ID_UNTAGGED_FOLLOWUP_CONFIRMATION = "slack-untagged-followup-confirmation-v1"
@@ -195,6 +199,42 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
if inputs.untagged_followup:
return
+ # Past both returns above the message opens a thread: explicit @mention, and
+ # the forward activity found no task mapped to it. Only such a message may
+ # pick its own project, because a task, its mapping and its run all belong to
+ # one. Everything below reads the integration from `inputs`, so the switch
+ # lands above the repo cascade. Eligibility and the flag are decided inside
+ # the activity, since branching the workflow on a flag would break replay.
+ if workflow.patched(_PATCH_ID_PROJECT_ROUTE_CLASSIFIER):
+ project_route = await _execute_posthog_code_activity(
+ classify_slack_app_project_route_activity,
+ SlackAppProjectRouteInput(
+ integration_id=inputs.integration_id,
+ slack_team_id=inputs.slack_team_id,
+ event_text=event.get("text", ""),
+ user_id=inputs.user_id,
+ slack_user_id=slack_user_id,
+ ),
+ )
+ if project_route is not None:
+ inputs = replace(inputs, integration_id=project_route.integration_id)
+ # The gate at the top of the run checked the project routing had
+ # resolved, not the one the message named. Without this the run
+ # spends the thread fetch, the needs-repo classifier and possibly a
+ # discovery sandbox before task creation refuses on the same quota.
+ # Its own patch: a history that recorded the classifier marker above
+ # would not have recorded this activity.
+ if workflow.patched(_PATCH_ID_PROJECT_ROUTE_QUOTA):
+ blocked = await _execute_posthog_code_activity(
+ enforce_posthog_code_billing_quota_activity,
+ inputs,
+ channel,
+ thread_ts,
+ slack_user_id,
+ )
+ if blocked:
+ return
+
user_id = inputs.user_id
# A forked run is the one case where the thread we read and the thread we
diff --git a/posthog/temporal/ai/slack_app/types.py b/posthog/temporal/ai/slack_app/types.py
index df62567b2b6f..1bd18b41bb7c 100644
--- a/posthog/temporal/ai/slack_app/types.py
+++ b/posthog/temporal/ai/slack_app/types.py
@@ -160,6 +160,32 @@ class SlackAppModelOverride(BaseModel):
reasoning_effort: str | None = None
+class SlackAppProjectRouteInput(BaseModel):
+ """Single-argument input for the project-route classifier activity.
+
+ ``integration_id`` is the project routing already resolved, which the classifier
+ reads as the default it may move the run off.
+ """
+
+ integration_id: int
+ slack_team_id: str
+ event_text: str
+ user_id: int
+ slack_user_id: str
+
+
+class SlackAppProjectRoute(BaseModel):
+ """The project a message asked to be answered from.
+
+ ``integration_id`` is always an install the mentioner can reach (the activity offers
+ the classifier a list bounded by their access and drops anything off it), and never
+ the one routing already resolved. The activity returns ``None`` rather than this when
+ the message named no project, which is the overwhelming majority of mentions.
+ """
+
+ integration_id: int
+
+
@dataclass
class PostHogCodeSlackMentionCommandWorkflowInputs:
event: dict[str, Any]
diff --git a/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_slack_app_project_route.ambr b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_slack_app_project_route.ambr
new file mode 100644
index 000000000000..1d9c6e8b6b8d
--- /dev/null
+++ b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_slack_app_project_route.ambr
@@ -0,0 +1,30 @@
+# serializer version: 1
+# name: TestClassifySlackAppProjectRoute.test_prompt_snapshot_matches
+ '''
+ You are routing a Slack message addressed to the PostHog agent. This Slack workspace is connected to several PostHog projects, each holding separate data, and this message opens a new thread. Decide which project it should be answered from.
+
+ Only these projects can be selected, and the id is the number:
+ • `41` — Northwind · Staging
+ • `42` — Northwind · Production
+
+ Most messages name no project at all, and null is the answer for those. Only name one when the message points at it.
+
+ Name a project when the message says where to look:
+ - "check the error rate on Endpaper staging", "in the website project, why did signups drop", "for production, which exports failed yesterday".
+ - The project can be named anywhere in the sentence, and the rest of the message is still the request.
+ - A project named as the place a problem lives is still where to look: "why is Endpaper production throwing 500s" is answered from Endpaper production. A project is usually the subject of the question AND the place the answer comes from.
+
+ Answer with null when the project is the thing being worked on rather than the place to look:
+ - "rename the Website project", "add staging to the project dropdown" (a project as the object of a change).
+ - "we should split staging and production" (a proposal about projects).
+ - A word that only happens to match a project name. With a project called "Website", "the website is down" names no project.
+ - "I already checked staging, look at the SDK instead" (an account of a place already ruled out — past tense is the tell).
+ - Two projects at once, as in "compare staging and production". One task answers from one project, and picking one of the two on a guess is worse than staying on the default.
+
+ When you are unsure, answer with null — the default is the right place to look.
+
+ Message: how many signups on staging yesterday
+
+ Answer with the one field, e.g. {"project_id": 42} or {"project_id": null}
+ '''
+# ---
diff --git a/posthog/temporal/tests/ai/slack_app/activities/test_classify_slack_app_project_route.py b/posthog/temporal/tests/ai/slack_app/activities/test_classify_slack_app_project_route.py
new file mode 100644
index 000000000000..60b4d506c438
--- /dev/null
+++ b/posthog/temporal/tests/ai/slack_app/activities/test_classify_slack_app_project_route.py
@@ -0,0 +1,115 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+from posthog.temporal.ai.slack_app.activities.classifiers import classify_slack_app_project_route
+from posthog.temporal.ai.slack_app.posthog_code_slack_mention import POSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS
+
+
+def _project(*, team_id: int, integration_id: int, name: str) -> Integration:
+ """An unsaved `Integration` row, which is all the classifier reads."""
+ return Integration(
+ id=integration_id,
+ kind="slack",
+ team=Team(id=team_id, name=name, organization=Organization(name="Northwind")),
+ )
+
+
+# Team ids and integration ids differ so a case fails if the two are ever swapped.
+STAGING = _project(team_id=41, integration_id=410, name="Staging")
+PRODUCTION = _project(team_id=42, integration_id=420, name="Production")
+PROJECTS = [STAGING, PRODUCTION]
+
+CLASSIFIER = "posthog.temporal.ai.slack_app.activities.classifiers.build_openai_client"
+
+
+class TestClassifySlackAppProjectRoute:
+ @parameterized.expand(
+ [
+ ("named_project", '{"project_id": 41}', STAGING),
+ ("no_project", '{"project_id": null}', None),
+ ("field_missing", "{}", None),
+ # An id outside the offered list is a hallucination or a project this
+ # mentioner cannot open. Either way it must not route a run into its data.
+ ("unoffered_project", '{"project_id": 99}', None),
+ ("fenced_json", '```json\n{"project_id": 42}\n```', PRODUCTION),
+ ("empty_reply", "", None),
+ ("prose_reply", "I think they mean staging.", None),
+ ("wrong_type", '{"project_id": "staging"}', None),
+ ]
+ )
+ def test_resolves_to_an_offered_project(self, _name, content, expected):
+ assert self._classify(content) == expected
+
+ def test_llm_failure_propagates_rather_than_reading_as_no_route(self):
+ # The eval suite calls this function directly. A swallowed gateway failure is
+ # indistinguishable from a clean "no project", so an outage would score as a pass
+ # on every negative case and report a healthy mean. The activity does the falling
+ # back; this must not.
+ with patch(CLASSIFIER, side_effect=RuntimeError("boom")), pytest.raises(RuntimeError):
+ classify_slack_app_project_route("check staging", PROJECTS)
+
+ def test_token_cap_uses_the_reasoning_model_parameter(self):
+ # `gpt-5.6-luna` rejects `max_tokens` on chat completions, and the activity turns
+ # that rejection into its fallback — a mention would silently never route.
+ fake_client = self._fake_client('{"project_id": null}')
+ with patch(CLASSIFIER, return_value=fake_client):
+ classify_slack_app_project_route("check staging", PROJECTS)
+
+ kwargs = fake_client.chat.completions.create.call_args.kwargs
+ assert "max_tokens" not in kwargs
+ assert kwargs["max_completion_tokens"] > 0
+
+ def test_reply_is_pinned_to_the_offered_projects(self):
+ # The enum is the only thing that keeps the classifier from naming a team this
+ # mentioner cannot reach. `routable_projects` bounds the list by access, and that
+ # bound only reaches the model through this field.
+ fake_client = self._fake_client('{"project_id": null}')
+ with patch(CLASSIFIER, return_value=fake_client):
+ classify_slack_app_project_route("check staging", PROJECTS)
+
+ schema = fake_client.chat.completions.create.call_args.kwargs["response_format"]["json_schema"]
+ assert schema["strict"] is True
+ assert schema["schema"]["properties"]["project_id"]["enum"] == [41, 42, None]
+
+ def test_call_is_bounded_so_a_slow_gateway_falls_back(self):
+ # The gateway client's own defaults are a 600s read and two retries. Unbounded,
+ # the activity's deadline expires first, so the mention fails outright instead of
+ # taking the fallback this classifier is built around.
+ fake_client = self._fake_client('{"project_id": null}')
+ with patch(CLASSIFIER, return_value=fake_client):
+ classify_slack_app_project_route("check staging", PROJECTS)
+
+ options = fake_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_prompt_snapshot_matches(self, snapshot):
+ """The prompt is the whole classifier — the projects it offers, the
+ where-to-look versus what-to-change examples, and the reply contract. Pinning it
+ means a reworded rule shows up as a reviewable diff in the ``.ambr`` snapshot
+ rather than as a silent behaviour change. Update intentionally by re-running with
+ ``--snapshot-update`` after auditing the diff.
+ """
+ fake_client = self._fake_client('{"project_id": null}')
+ with patch(CLASSIFIER, return_value=fake_client):
+ classify_slack_app_project_route("how many signups on staging yesterday", PROJECTS)
+ assert fake_client.chat.completions.create.call_args.kwargs["messages"][0]["content"] == snapshot
+
+ 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 client
+
+ def _classify(self, content: str):
+ with patch(CLASSIFIER, return_value=self._fake_client(content)):
+ return classify_slack_app_project_route("check staging", PROJECTS)
diff --git a/posthog/temporal/tests/ai/slack_app/activities/test_project_route_activity.py b/posthog/temporal/tests/ai/slack_app/activities/test_project_route_activity.py
new file mode 100644
index 000000000000..d48878b488ed
--- /dev/null
+++ b/posthog/temporal/tests/ai/slack_app/activities/test_project_route_activity.py
@@ -0,0 +1,101 @@
+"""Gate tests for ``classify_slack_app_project_route_activity``.
+
+The classifier's own prompt and parse behaviour is covered in
+``test_classify_slack_app_project_route.py``, and which projects are eligible in
+``products/slack_app/backend/tests/services/test_project_routing.py``. What matters here
+is what the activity does with both.
+"""
+
+from contextlib import contextmanager
+
+import pytest
+from unittest.mock import patch
+
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.temporal.ai.slack_app.activities.classifiers import classify_slack_app_project_route_activity
+from posthog.temporal.ai.slack_app.types import SlackAppProjectRouteInput
+
+ACTIVITY_MODULE = "posthog.temporal.ai.slack_app.activities.classifiers"
+WORKSPACE = "T_WS"
+SLACK_USER = "U001"
+
+
+class TestClassifySlackAppProjectRouteActivity:
+ @pytest.fixture(autouse=True)
+ def setup(self, db):
+ organization = Organization.objects.create(name="Org")
+ self.default_team = Team.objects.create(organization=organization, name="Production")
+ self.other_team = Team.objects.create(organization=organization, name="Staging")
+ self.user = User.objects.create(email="[email protected]", distinct_id="u-1")
+ OrganizationMembership.objects.create(user=self.user, organization=organization)
+
+ self.default = Integration.objects.create(
+ team=self.default_team,
+ kind="slack",
+ integration_id=WORKSPACE,
+ sensitive_config={"access_token": "xoxb"},
+ )
+ self.other = Integration.objects.create(
+ team=self.other_team,
+ kind="slack",
+ integration_id=WORKSPACE,
+ sensitive_config={"access_token": "xoxb"},
+ )
+ self.offered = [self.default, self.other]
+
+ def _input(self, text: str = "how many signups on staging yesterday") -> SlackAppProjectRouteInput:
+ return SlackAppProjectRouteInput(
+ integration_id=self.default.id,
+ slack_team_id=WORKSPACE,
+ event_text=text,
+ user_id=self.user.id,
+ slack_user_id=SLACK_USER,
+ )
+
+ @contextmanager
+ def _classifier(self, *, flag: bool = True, projects: list | None = None, **kwargs):
+ """Run the activity with the LLM call stubbed, yielding the stub."""
+ with (
+ patch(f"{ACTIVITY_MODULE}.is_slack_app_project_routing_enabled", return_value=flag),
+ patch(f"{ACTIVITY_MODULE}.routable_projects", return_value=self.offered if projects is None else projects),
+ patch(f"{ACTIVITY_MODULE}.classify_slack_app_project_route", **kwargs) as classify,
+ ):
+ yield classify
+
+ @pytest.mark.parametrize(
+ "reason",
+ [
+ # A follow-up that is only an attachment carries no sentence to read.
+ "blank_text",
+ "flag_is_off",
+ "no_eligible_projects",
+ ],
+ )
+ def test_gates_return_no_route_without_calling_the_llm(self, reason):
+ text = " " if reason == "blank_text" else "how many signups on staging yesterday"
+ with self._classifier(
+ flag=reason != "flag_is_off",
+ projects=[] if reason == "no_eligible_projects" else None,
+ ) as classify:
+ assert classify_slack_app_project_route_activity(self._input(text)) is None
+ classify.assert_not_called()
+
+ def test_named_project_is_returned_as_its_integration(self):
+ with self._classifier(return_value=self.other):
+ result = classify_slack_app_project_route_activity(self._input())
+
+ assert result is not None
+ assert result.integration_id == self.other.id
+
+ def test_a_gateway_failure_leaves_the_run_where_routing_put_it(self):
+ with self._classifier(side_effect=RuntimeError("boom")):
+ assert classify_slack_app_project_route_activity(self._input()) is None
+
+ def test_naming_the_project_the_run_already_had_reports_no_route(self):
+ # A returned route is what drives both the rebind and the notice posted in the
+ # thread, so naming the default must not read as a move.
+ with self._classifier(return_value=self.default):
+ assert classify_slack_app_project_route_activity(self._input()) is None
diff --git a/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
index 1c8bf202715c..fe373eb7243d 100644
--- a/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
+++ b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
@@ -21,6 +21,8 @@ from posthog.temporal.ai.slack_app.types import (
SlackAppMessageReactionInput,
SlackAppModelOverride,
SlackAppModelOverrideInput,
+ SlackAppProjectRoute,
+ SlackAppProjectRouteInput,
SlackRepoSelectionOutcome,
)
@@ -52,6 +54,12 @@ class _Recorder:
self.model_overrides: dict[str, SlackAppModelOverride] = {}
# ts -> model override the create-task call actually received.
self.created_with_override: dict[str, SlackAppModelOverride | None] = {}
+ # event text -> project route the classifier returns; missing means no route.
+ self.project_routes: dict[str, SlackAppProjectRoute] = {}
+ # ts -> integration id each activity was given, so a project the message routed
+ # itself to can be shown to reach the whole run rather than only its tail.
+ self.cascade_integration_ids: dict[str, int] = {}
+ self.created_integration_ids: dict[str, int] = {}
# ts per hourglass reaction (message queued behind another), in execution order.
self.queued_marked: list[str] = []
# ts per hourglass->eyes reaction swap, in execution order.
@@ -140,6 +148,7 @@ def _fake_activities(rec: _Recorder) -> list:
thread_messages: list[SlackThreadMessage] | None = None,
mention_ts: str | None = None,
) -> PostHogCodeRepoCascadeOutcome:
+ rec.cascade_integration_ids[inputs.event["ts"]] = inputs.integration_id
mode = rec.cascade_modes.get(inputs.event["ts"], "auto")
repository = "org/auto-repo" if mode == "auto" else None
return PostHogCodeRepoCascadeOutcome(mode=mode, repository=repository, reason="test")
@@ -194,6 +203,10 @@ def _fake_activities(rec: _Recorder) -> list:
async def classify_model_override(input: SlackAppModelOverrideInput) -> SlackAppModelOverride | None:
return rec.model_overrides.get(input.event_text)
+ @activity.defn(name="classify_slack_app_project_route_activity")
+ async def classify_project_route(input: SlackAppProjectRouteInput) -> SlackAppProjectRoute | None:
+ return rec.project_routes.get(input.event_text)
+
@activity.defn(name="create_posthog_code_task_for_repo_activity")
async def create_task(
inputs: PostHogCodeSlackMentionWorkflowInputs,
@@ -210,6 +223,7 @@ def _fake_activities(rec: _Recorder) -> list:
) -> None:
ts = inputs.event["ts"]
rec.created_with_override[ts] = model_override
+ rec.created_integration_ids[ts] = inputs.integration_id
reached = rec.create_reached.get(ts)
if reached:
reached.set()
@@ -248,6 +262,7 @@ def _fake_activities(rec: _Recorder) -> list:
post_picker,
block_github,
classify_model_override,
+ classify_project_route,
create_task,
picker_timeout,
internal_error,
@@ -360,6 +375,31 @@ async def test_model_override_reaches_task_creation():
assert rec.created_with_override == {"1.1": None, "1.2": override}
+async def test_project_route_reaches_the_repo_cascade_and_task_creation():
+ """A mention that names a project moves the whole run to it, not just the task.
+
+ The cascade is the assertion that matters: it reads the team's connected
+ repositories, so a rebind placed after it would pick a repo from the project the
+ mention left.
+ """
+ rec = _Recorder()
+ plain, routed = _message("1.1"), _message("1.2", text="how many signups on staging yesterday")
+ rec.project_routes["how many signups on staging yesterday"] = SlackAppProjectRoute(integration_id=77)
+ rec.create_reached["1.1"] = asyncio.Event()
+ rec.create_gates["1.1"] = asyncio.Event()
+
+ async with _Harness(rec) as h:
+ handle = await _signal_with_start(h.env, h.task_queue, f"wf-{uuid.uuid4()}", plain)
+ await asyncio.wait_for(rec.create_reached["1.1"].wait(), timeout=30)
+ await handle.signal(SlackAppMentionWorkflow.new_message, routed)
+ rec.create_gates["1.1"].set()
+ await asyncio.wait_for(handle.result(), timeout=30)
+
+ assert rec.cascade_integration_ids == {"1.1": 1, "1.2": 77}
+ assert rec.created_integration_ids == {"1.1": 1, "1.2": 77}
+
+
@pytest.mark.asyncio
async def test_model_override_reaches_a_followup_without_creating_a_task():
"""The classifier runs above the follow-up/new-task split, so a reply naming a model
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.py
index b06b65b7d3f6..a848e4a4a200 100644
--- a/products/slack_app/backend/feature_flags.py
+++ b/products/slack_app/backend/feature_flags.py
@@ -46,6 +46,7 @@ logger = structlog.get_logger(__name__)
SLACK_APP_AGENT_DESIGN_FLAG = "slack-app-agent-design"
SLACK_APP_FORKING_FLAG = "slack-app-forking"
+SLACK_APP_PROJECT_ROUTING_FLAG = "slack-app-project-routing"
# Linking a Slack identity to a PostHog user resolves the Slack profile and its email.
@@ -124,6 +125,22 @@ def is_slack_app_agent_design_enabled(integration: Integration, distinct_id: str
)
+def is_slack_app_project_routing_enabled(integration: Integration, distinct_id: str | None = None) -> bool:
+ """Gate for reading a project out of the message that opens a thread, instead of
+ always running against the saved default.
+
+ Keyed on the person as well as the workspace: which projects are on offer is bounded
+ by the mentioner's access, so the decision is about them and an internal rollout can
+ name them the way every other one does.
+ """
+ return _workspace_flag_enabled(
+ SLACK_APP_PROJECT_ROUTING_FLAG,
+ integration,
+ failure_log_key="slack_app_project_routing_feature_flag_check_failed",
+ distinct_id=distinct_id,
+ )
+
+
def is_slack_app_assistant_enabled(integration: Integration) -> bool:
"""Gate for the DM assistant: the install must hold the scopes the DM surface
calls — ``im:history`` in particular, without which the assistant would answer
diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.py
index a7ac207968ed..9d6a3e0a0a24 100644
--- a/products/slack_app/backend/services/integration_resolver.py
+++ b/products/slack_app/backend/services/integration_resolver.py
@@ -5,6 +5,7 @@ from django.db.models import Q
import structlog
+from posthog.helpers.slack_scopes import bot_is_ready
from posthog.models.integration import Integration
from posthog.models.user import User
from posthog.user_permissions import UserPermissions
@@ -76,8 +77,17 @@ class ResolutionResult:
return min(self.candidates, key=lambda candidate: candidate.id, default=None)
+def project_label(integration: Integration) -> str:
+ """One project named the way every Slack surface names it.
+
+ Shared so a prompt that lists candidates and names a default in prose cannot spell
+ the two differently, which would break the comparison it asks the model to make.
+ """
+ return f"{integration.team.organization.name} · {integration.team.name}"
+
+
def format_project_candidate_list(candidates: list[Integration]) -> str:
- return "\n".join(f"• `{c.team_id}` — {c.team.organization.name} · {c.team.name}" for c in candidates)
+ return "\n".join(f"• `{c.team_id}` — {project_label(c)}" for c in candidates)
def resolve_from_candidates(
@@ -203,6 +213,28 @@ def load_integrations(
)
+def routable_projects(*, slack_team_id: str, slack_user_id: str, user: User) -> list[Integration]:
+ """The projects a message from this user may route itself to, in this workspace.
+
+ Empty when there is nothing to choose between, which is the common answer. Installs
+ missing the scopes the mention flow needs are dropped: routing onto one would trade a
+ working run for a project the app cannot post into. That is stricter than the saved
+ default, which may point anywhere — there is a difference between a project someone
+ chose and one we moved them to.
+
+ Callers must already have established that the message opens a thread. Project is
+ fixed for the life of a thread, and this does not check that.
+ """
+ candidates = load_integrations(
+ slack_team_id=slack_team_id,
+ kinds=["slack"],
+ slack_user_id=slack_user_id,
+ user=user,
+ ).candidates
+ reachable = [candidate for candidate in candidates if bot_is_ready(candidate)]
+ return reachable if len(reachable) > 1 else []
+
+
@dataclass
class UserAndIntegrationsResolution:
"""Outcome of the user identification + access-filter step.
diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.py
index 7dfcc8cd130e..dc8033376418 100644
--- a/products/slack_app/backend/services/slack_app_home.py
+++ b/products/slack_app/backend/services/slack_app_home.py
@@ -2373,6 +2373,10 @@ def _accessible_integrations(integration: Integration, slack_user_id: str) -> li
build plus three queries, and all three cards want the same answer. It is also the
authorization boundary for the whole tab, so it should have exactly one definition.
"""
+ # Deliberately not health-filtered, unlike the mention path. There, dropping an
+ # install with a dead token lets resolution fall through to the next candidate; here
+ # it would blank the whole tab whenever `auth.test` is unreachable, since every card
+ # hangs off this list.
return _filter_accessible_integrations(
integration, slack_user_id, _workspace_integrations(integration.integration_id)
)
@@ -2466,23 +2470,23 @@ def _resolve_project_state(
def _filter_accessible_integrations(
integration: Integration, slack_user_id: str, candidates: list[Integration]
) -> list[Integration]:
- # Falls back to the full candidate list when we can't identify the user —
- # hiding the picker would mean an unidentified user has no way to change
- # their routing at all.
- profile = SlackUserProfileCache.objects.filter(integration_id=integration.id, slack_user_id=slack_user_id).first()
- if profile is None or not profile.email:
- return candidates
- membership = (
- OrganizationMembership.objects.filter(
- user__email=profile.email,
- organization_id__in={c.team.organization_id for c in candidates},
- )
- .select_related("user")
- .first()
- )
- if membership is None:
- return candidates
- permissions = UserPermissions(user=membership.user)
+ """The candidates this Slack identity can reach.
+
+ A viewer we cannot identify is narrowed to the one project the tab is already being
+ rendered for, rather than shown the whole list. A Slack workspace can carry several
+ organizations, so the old behaviour of returning every candidate published the
+ project and organization names of orgs the viewer has no membership in to anyone in
+ the workspace. Narrowing keeps every card working and the routing picker usable,
+ which is what returning the full list was protecting, without that disclosure.
+
+ `_apply_project_pick` gates on this too, so the same narrowing stops an unidentified
+ viewer saving a personal default for any team in the workspace, which the old
+ behaviour allowed. Such a default is rejected on the mention path anyway.
+ """
+ user = _resolve_home_user(integration, slack_user_id)
+ if user is None:
+ return [c for c in candidates if c.id == integration.id]
+ permissions = UserPermissions(user=user)
return [c for c in candidates if permissions.team(c.team).effective_membership_level is not None]
diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.py
index 9437751f7182..3a4a4871f76b 100644
--- a/products/slack_app/backend/services/slack_messages.py
+++ b/products/slack_app/backend/services/slack_messages.py
@@ -34,6 +34,7 @@ from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler
+from posthog.comment.formatting import escape_slack_mrkdwn
from posthog.dataclasses import frozen
from posthog.models.integration import Integration, SlackIntegration
from posthog.utils import absolute_uri
@@ -675,6 +676,9 @@ class RunFooter:
reasoning_effort: str | None = None
run_id: str | None = None
task_id: str | None = None
+ # The project the thread's task belongs to, so a reader can tell which project's
+ # data the answer was drawn from.
+ project: str | None = None
def has_content(self) -> bool:
"""Whether this would render as anything.
@@ -684,7 +688,25 @@ class RunFooter:
keeps meaning "None-coalesce" and cannot silently discard a partial instance.
The ids are not part of the answer — they say nothing on their own.
"""
- return any((self.task_url, self.desktop_url, self.model))
+ return any((self.task_url, self.desktop_url, self.model, self.project))
+
+
+def _project_name(team_id: int) -> str | None:
+ """The project a run answered from, named for the footer.
+
+ The run's own team is the project, so this needs no join through the thread mapping:
+ a task, its mapping and every run on it belong to one project.
+ """
+ from posthog.models.team.team import Team # noqa: PLC0415 — keeps the model off this module's import path
+
+ try:
+ team = Team.objects.filter(pk=team_id).only("name").first()
+ except Exception:
+ # Its own guard, not the caller's: a failed lookup must cost the reader one
+ # segment, not the links and the model with it.
+ logger.warning("slack_app_footer_project_lookup_failed", team_id=team_id)
+ return None
+ return team.name if team else None
def load_run_footer(run_id: str | UUID | None) -> RunFooter:
@@ -720,6 +742,7 @@ def load_run_footer(run_id: str | UUID | None) -> RunFooter:
desktop_url=_desktop_bridge_url(run.task_id),
model=state.model,
reasoning_effort=state.reasoning_effort,
+ project=_project_name(run.team_id),
)
except Exception:
logger.exception("slack_app_run_footer_load_failed", run_id=str(run_id))
@@ -738,6 +761,11 @@ def reply_footer_block(footer: RunFooter, configure_url: str | None = None) -> d
segments.append(f"<{footer.task_url}|View on web>")
if footer.desktop_url:
segments.append(f"<{footer.desktop_url}|View on desktop>")
+ if footer.project:
+ # A project name is tenant text in a `mrkdwn` block, so `<!channel>` broadcasts
+ # and `<url|label>` renders a link the reader reads as the bot's. Escaped here
+ # rather than on the way in, so `RunFooter.project` stays the plain name.
+ segments.append(f"Project: *{escape_slack_mrkdwn(footer.project)}*")
if footer.model:
segments.append(describe_run_model(footer.model, footer.reasoning_effort))
if configure_url:
diff --git a/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py b/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py
index fab1b1f770f3..3650851698b9 100644
--- a/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py
+++ b/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py
@@ -38,6 +38,23 @@ class TestRunFooter(SimpleTestCase):
f"<{TASK_URL}|View on web> · <{DESKTOP_URL}|View on desktop>",
),
("model_without_effort", RunFooter(model="claude-opus-5"), None, "*Claude Opus 5*"),
+ # A workspace connected to several projects answers from one of them, and the
+ # answer looks the same whichever it was, so the footer has to name it.
+ (
+ "project_precedes_the_model",
+ RunFooter(model="claude-opus-5", project="Endpaper staging"),
+ None,
+ "Project: *Endpaper staging* · *Claude Opus 5*",
+ ),
+ # A project name is tenant text with no character validation, and the footer
+ # rides under every reply. Unescaped, `<!channel>` broadcasts to everyone in
+ # the channel from a message they read as the bot's.
+ (
+ "project_name_cannot_inject_mrkdwn",
+ RunFooter(project="<!channel> & <https://evil/|View on web>"),
+ None,
+ "Project: *&lt;!channel&gt; &amp; &lt;https://evil/|View on web&gt;*",
+ ),
(
"configure_only",
RunFooter(),
@@ -55,6 +72,11 @@ class TestRunFooter(SimpleTestCase):
assert block == {"type": "context", "elements": [{"type": "mrkdwn", "text": expected}]}
+ def test_a_project_alone_still_renders(self) -> None:
+ # `has_content` gates whether callers bother building a footer at all, so a run
+ # known only by its project must not read as nothing to say.
+ assert RunFooter(project="Endpaper staging").has_content()
+
def test_contributes_no_block_when_there_is_nothing_to_say(self) -> None:
# A context block with an empty `elements` list is rejected by Slack, which would
# fail the whole message post rather than just dropping the footer.
@@ -123,3 +145,44 @@ class TestViewerHasCodeAccess(SimpleTestCase):
)
def test_a_lookup_failure_withholds_the_links_rather_than_guessing(self, _mock_find) -> None:
assert viewer_has_code_access(self._integration(), "U1") is False
+
+
+class TestFooterProject:
+ """The footer names the project a thread's task belongs to.
+
+ Covers what the `SimpleTestCase` classes above cannot: those run without a database,
+ so the mapping lookup takes its failure path there and the segment is always absent.
+ """
+
+ def test_names_the_project_the_thread_is_pinned_to(self, db):
+ from django.apps import apps
+
+ from posthog.models.organization import Organization
+ from posthog.models.team.team import Team
+
+ from products.slack_app.backend.models import SlackThreadTaskMapping
+
+ organization = Organization.objects.create(name="Org")
+ routed_team = Team.objects.create(organization=organization, name="Staging")
+ integration = Integration.objects.create(
+ team=routed_team, kind="slack", integration_id="T_WS", sensitive_config={"access_token": "xoxb"}
+ )
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ task = Task.objects.create(team=routed_team, title="t")
+ run = TaskRun.objects.create(team=routed_team, task=task)
+ SlackThreadTaskMapping.objects.create(
+ integration=integration,
+ team=routed_team,
+ slack_workspace_id="T_WS",
+ channel="C1",
+ thread_ts="1.1",
+ task=task,
+ task_run=run,
+ mentioning_slack_user_id="U1",
+ )
+
+ footer = load_run_footer(run.id)
+
+ # The routed project, not the one the workspace would otherwise have answered from.
+ assert footer.project == "Staging"
diff --git a/products/slack_app/backend/tests/services/test_project_routing.py b/products/slack_app/backend/tests/services/test_project_routing.py
new file mode 100644
index 000000000000..adad96f7dc03
--- /dev/null
+++ b/products/slack_app/backend/tests/services/test_project_routing.py
@@ -0,0 +1,76 @@
+import pytest
+
+from posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.slack_app.backend.services.integration_resolver import routable_projects
+
+WORKSPACE = "T_WS"
+SLACK_USER = "U001"
+
+
+class TestRoutableProjects:
+ @pytest.fixture(autouse=True)
+ def setup(self, db):
+ from django.core.cache import cache
+
+ from products.slack_app.backend.services.slack_auth import write_auth_state_ok
+
+ cache.clear()
+ self.organization = Organization.objects.create(name="Org")
+ self.other_organization = Organization.objects.create(name="Other org")
+ self.default_team = Team.objects.create(organization=self.organization, name="Production")
+ self.other_team = Team.objects.create(organization=self.organization, name="Staging")
+ self.unreachable_team = Team.objects.create(organization=self.other_organization, name="Someone else")
+
+ self.user = User.objects.create(email="[email protected]", distinct_id="u-1")
+ OrganizationMembership.objects.create(user=self.user, organization=self.organization)
+
+ self.default = self._integration(self.default_team)
+ self.other = self._integration(self.other_team)
+ self.unreachable = self._integration(self.unreachable_team)
+ # Seed every install as healthy so `load_integrations` short-circuits on a cache
+ # hit rather than filtering the whole candidate list away on a failed `auth.test`,
+ # which would make a broken rule look like a passing one.
+ for candidate in (self.default, self.other, self.unreachable):
+ write_auth_state_ok(candidate.id, bot_user_id="U_BOT")
+ yield
+ cache.clear()
+
+ def _integration(self, team: Team, *, scopes: frozenset[str] = REQUIRED_SLACK_SCOPES) -> Integration:
+ return Integration.objects.create(
+ team=team,
+ kind="slack",
+ integration_id=WORKSPACE,
+ config={"scope": ",".join(sorted(scopes))},
+ sensitive_config={"access_token": "xoxb"},
+ )
+
+ def _routable(self):
+ return routable_projects(slack_team_id=WORKSPACE, slack_user_id=SLACK_USER, user=self.user)
+
+ def test_offers_every_project_the_mentioner_can_reach(self):
+ offered = self._routable()
+ assert {project.team_id for project in offered} == {self.default_team.id, self.other_team.id}
+ assert {project.id for project in offered} == {self.default.id, self.other.id}
+
+ @pytest.mark.parametrize(
+ "reason",
+ [
+ "only_one_reachable_project",
+ # Routing onto an install without the mention scopes would trade a working
+ # run for one that cannot post its answer.
+ "candidate_is_missing_scopes",
+ ],
+ )
+ def test_routing_is_withheld(self, reason):
+ if reason == "only_one_reachable_project":
+ self.other.delete()
+ if reason == "candidate_is_missing_scopes":
+ self.other.config = {"scope": "chat:write"}
+ self.other.save()
+
+ assert self._routable() == []
diff --git a/products/slack_app/backend/tests/services/test_slack_app_home.py b/products/slack_app/backend/tests/services/test_slack_app_home.py
index 42b3a1e8c1a3..63d139011fc8 100644
--- a/products/slack_app/backend/tests/services/test_slack_app_home.py
+++ b/products/slack_app/backend/tests/services/test_slack_app_home.py
@@ -1559,3 +1559,44 @@ class TestNoProjectAccessCard:
def test_normal_tab_is_untouched_when_a_project_is_reachable(self):
assert "No project to show yet" not in _all_text(self._view(has_project_access=True))
+
+
+class TestUnidentifiedViewerProjectList:
+ """What the tab lists for a Slack user it cannot map to a PostHog account.
+
+ The regression to catch is the list widening again. A Slack workspace can connect
+ several organizations, so returning every candidate publishes the project and
+ organization names of orgs the viewer is not a member of to anyone in the workspace.
+ """
+
+ @pytest.fixture(autouse=True)
+ def setup(self, db):
+ from posthog.models.integration import Integration
+ from posthog.models.organization import Organization
+ from posthog.models.team.team import Team
+
+ self.own_org = Organization.objects.create(name="Acme")
+ self.other_org = Organization.objects.create(name="Umbrella")
+ self.rendered_for = Integration.objects.create(
+ team=Team.objects.create(organization=self.own_org, name="Acme prod"),
+ kind="slack",
+ integration_id="T_WS",
+ sensitive_config={"access_token": "xoxb"},
+ )
+ self.other_org_install = Integration.objects.create(
+ team=Team.objects.create(organization=self.other_org, name="Umbrella prod"),
+ kind="slack",
+ integration_id="T_WS",
+ sensitive_config={"access_token": "xoxb"},
+ )
+
+ def test_shows_only_the_project_the_tab_renders_for(self):
+ from products.slack_app.backend.services.slack_app_home import _filter_accessible_integrations
+
+ # No SlackUserProfileCache row and no OAuth link, so the viewer is unidentifiable.
+ accessible = _filter_accessible_integrations(
+ self.rendered_for, "U_STRANGER", [self.rendered_for, self.other_org_install]
+ )
+
+ assert [i.id for i in accessible] == [self.rendered_for.id]
+ assert self.other_org_install.id not in {i.id for i in accessible}
diff --git a/products/slack_app/evals/eval_project_classifier.py b/products/slack_app/evals/eval_project_classifier.py
new file mode 100644
index 000000000000..569e45f44fef
--- /dev/null
+++ b/products/slack_app/evals/eval_project_classifier.py
@@ -0,0 +1,169 @@
+"""Does the project classifier pick the project a person in the thread would have?
+
+A Slack workspace connected to several PostHog projects answers every mention from one
+saved default, so a question about another project is answered from the wrong data. The
+classifier reads the project out of the message that opens a thread. The unit tests around
+`classify_slack_app_project_route` cover parsing and the schema; this suite covers the only
+part they can't, which is whether the model can tell "answer this from staging" from a
+sentence that merely says the word.
+
+A missed project falls back to the default, which is today's behavior, and the author
+rephrases. An invented project answers a different question in a shape that reads like an
+answer to this one. `NoUnaskedProjectSwitch` is therefore the number to watch, not the
+overall rate.
+
+The projects below are invented, and the phrasings with them. No customer's project names
+or messages appear here.
+
+Every case is held out of the prompt on purpose. An earlier revision paraphrased the
+prompt's own few-shot examples, which measures whether the model repeats them rather than
+whether it reads an unseen sentence — and it scored 100% doing so. When adding a case,
+check it against `project_route.md.j2` first.
+
+To run:
+ hogli evals eval_project_classifier
+ hogli evals eval_project_classifier --eval project_named_in_a_config_value
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+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 PROJECT_ROUTE_KEY, NoUnaskedProjectSwitch, ProjectRouteMatch
+
+SUITE_KIND = SuiteKind.ONE_SHOT
+
+
+def _project(*, team_id: int, integration_id: int, name: str) -> Integration:
+ """An unsaved `Integration` row, which is all the classifier reads."""
+ return Integration(
+ id=integration_id,
+ kind="slack",
+ team=Team(id=team_id, name=name, organization=Organization(name="Northwind")),
+ )
+
+
+# An environment pair differing by one word, plus a project whose name is also an ordinary
+# noun: the two shapes that make the task hard. Team ids and integration ids differ so a
+# case fails if the two are ever swapped.
+STAGING = _project(team_id=41, integration_id=410, name="Staging")
+PRODUCTION = _project(team_id=42, integration_id=420, name="Production")
+WEBSITE = _project(team_id=43, integration_id=430, name="Website")
+PROJECTS = [STAGING, PRODUCTION, WEBSITE]
+
+
+def _routes_to(project: Integration | None = None) -> dict:
+ return {PROJECT_ROUTE_KEY: {"integration_id": project.id if project else None}}
+
+
+ROUTING_CASES = [
+ BaseEvalCase(
+ name="explicit_on_project",
+ prompt="@PostHog how many signups did we get on Northwind staging yesterday?",
+ expected=_routes_to(STAGING),
+ ),
+ BaseEvalCase(
+ name="project_as_a_prefix",
+ prompt="@PostHog on website: what share of sessions bounce off the pricing page?",
+ expected=_routes_to(WEBSITE),
+ ),
+ # The rule that inverts the model classifier: a model named as the subject of a
+ # question is never an instruction, a project named as the subject is where the
+ # answer comes from.
+ BaseEvalCase(
+ name="project_is_the_subject_of_the_problem",
+ prompt="@PostHog production has been shedding mobile sessions since the 4.2 release, dig into it",
+ expected=_routes_to(PRODUCTION),
+ ),
+ BaseEvalCase(
+ name="environment_word_alone",
+ prompt="@PostHog how many people hit the paywall on staging last week?",
+ expected=_routes_to(STAGING),
+ ),
+ BaseEvalCase(
+ name="project_at_the_end",
+ prompt="@PostHog which feature flags haven't been evaluated in a month? staging please",
+ expected=_routes_to(STAGING),
+ ),
+]
+
+NO_ROUTE_CASES = [
+ BaseEvalCase(
+ name="project_as_the_object_of_a_change",
+ prompt="@PostHog our onboarding doc still tells people to make a Website project, bring it up to date",
+ expected=_routes_to(),
+ ),
+ BaseEvalCase(
+ name="project_in_a_proposal",
+ prompt="@PostHog write up the case for folding Website into Production so we stop paying for both",
+ expected=_routes_to(),
+ ),
+ # One task answers from one project, so picking either silently answers half.
+ BaseEvalCase(
+ name="two_projects_at_once",
+ prompt="@PostHog which had more failed exports this week, staging or production?",
+ expected=_routes_to(),
+ ),
+ BaseEvalCase(
+ name="project_name_as_an_ordinary_noun",
+ prompt="@PostHog add a link to our website in the survey footer copy",
+ expected=_routes_to(),
+ ),
+ BaseEvalCase(
+ name="project_named_in_a_config_value",
+ prompt="@PostHog our deploy script has PROJECT=northwind-staging hardcoded, make it an env var",
+ expected=_routes_to(),
+ ),
+ # Past tense is the tell, the same one the model classifier turns on.
+ BaseEvalCase(
+ name="project_already_ruled_out",
+ prompt="@PostHog staging came back clean when I looked yesterday, so start from the ingestion pipeline",
+ expected=_routes_to(),
+ ),
+ BaseEvalCase(
+ name="no_project_mentioned",
+ prompt="@PostHog the checkout funnel drops 40% between steps 2 and 3, can you work out why",
+ expected=_routes_to(),
+ ),
+]
+
+
+async def eval_project_classifier(ctx: EvalContext) -> None:
+ async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:
+ classifier_model = classifiers.PROJECT_ROUTE_CLASSIFIER_MODEL
+ try:
+ # Sync, and blocking on the gateway — keep it off the event loop so cases
+ # still run concurrently under the harness's limiter.
+ chosen = await asyncio.to_thread(
+ classifiers.classify_slack_app_project_route,
+ case.prompt,
+ PROJECTS,
+ )
+ except Exception as error:
+ return {
+ "classifier_model": classifier_model,
+ "route": None,
+ "error": f"{type(error).__name__}: {error}",
+ }
+ return {
+ "classifier_model": classifier_model,
+ "route": {"integration_id": chosen.id} if chosen else None,
+ "last_message": f"{classifier_model}: {chosen.team.name if chosen else None}",
+ }
+
+ await OneShotPublicEval(
+ experiment_name="slack-app-project-classifier",
+ cases=[*ROUTING_CASES, *NO_ROUTE_CASES],
+ scorers=[ProjectRouteMatch(), NoUnaskedProjectSwitch()],
+ task=task,
+ ctx=ctx,
+ )
diff --git a/products/slack_app/evals/scorers.py b/products/slack_app/evals/scorers.py
index 8fd421a32d8a..944f01b2d04f 100644
--- a/products/slack_app/evals/scorers.py
+++ b/products/slack_app/evals/scorers.py
@@ -225,6 +225,73 @@ class NoUnaskedOverride(Scorer):
)
+# ---------------------------------------------------------------------------
+# Project-route classifier
+# ---------------------------------------------------------------------------
+
+PROJECT_ROUTE_KEY = "project_route_match"
+
+
+def _routes_to(output: dict | None) -> int | None:
+ """The integration the classifier moved the run to, or `None` for the default."""
+ return ((output or {}).get("route") or {}).get("integration_id")
+
+
+class ProjectRouteMatch(Scorer):
+ """Did the classifier answer from the project a person would have picked?"""
+
+ def _name(self) -> str:
+ return PROJECT_ROUTE_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(PROJECT_ROUTE_KEY)
+ if want is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "No expectation for this case"})
+
+ got = _routes_to(output)
+ wanted = want.get("integration_id")
+ return Score(
+ name=self._name(),
+ score=1.0 if got == wanted else 0.0,
+ metadata={"expected_integration_id": wanted, "actual_integration_id": got},
+ )
+
+
+class NoUnaskedProjectSwitch(Scorer):
+ """The expensive direction, and worse here than for a model.
+
+ A run moved onto the wrong model still answers the question. A run moved onto the
+ wrong project answers a different question and reads as though it answered this one.
+ Missing a real request only costs the author a rephrase.
+
+ Skips (`None`) on cases that really do name a project, so the score reads as a rate
+ over the mentions that should have stayed on the default.
+ """
+
+ def _name(self) -> str:
+ return "no_unasked_project_switch"
+
+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:
+ want = (expected or {}).get(PROJECT_ROUTE_KEY) or {}
+ if want.get("integration_id"):
+ return Score(name=self._name(), score=None, metadata={"reason": "Case names a project"})
+
+ if output and output.get("error"):
+ # A failed call routes nowhere, 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"]})
+
+ got = _routes_to(output)
+ return Score(
+ name=self._name(),
+ score=0.0 if got is not None else 1.0,
+ metadata={"actual_integration_id": got},
+ )
+
+
# ---------------------------------------------------------------------------
# Untagged follow-up routing
# ---------------------------------------------------------------------------