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(phai): add shared repository selection cascade (#65022)

Georgiy Tarasov66a40126647b
diff --git a/posthog/git.py b/posthog/git.py
index 7f019a641282..2c160a45b28a 100644
--- a/posthog/git.py
+++ b/posthog/git.py
@@ -1,3 +1,4 @@
+import re
import subprocess
from typing import Optional
@@ -38,3 +39,37 @@ def get_git_branch() -> Optional[str]:
)
except Exception:
return None
+
+
+def extract_explicit_repo(text: str, all_repos: list[str]) -> str | None:
+ """Return the first explicit `owner/repo` token in `text` that matches a connected repo.
+
+ Tokenizes on whitespace and matches bare `owner/repo` tokens (no `@` prefix needed)
+ case-insensitively against `all_repos`. Strips surrounding punctuation and handles
+ Slack's `<url|label>` link form. `text` is assumed already cleaned of any
+ platform-specific noise (e.g. bot mentions) by the caller.
+
+ Pure helper (no Django / heavy deps) so any product can import it downward from core.
+ """
+ if not text or not all_repos:
+ return None
+
+ normalized_repos = {repo.lower(): repo for repo in all_repos}
+
+ for token in text.split():
+ candidate = token.strip("`'\"()[]{}<>,.;:!?")
+
+ # Slack can format links as <url|label>; for repo tokens we want the label.
+ if "|" in candidate:
+ candidate = candidate.split("|", 1)[1].strip("`'\"()[]{}<>,.;:!?")
+
+ if not candidate or "://" in candidate or candidate.startswith("http"):
+ continue
+ if not re.fullmatch(r"[\w.-]+/[\w.-]+", candidate):
+ continue
+
+ match = normalized_repos.get(candidate.lower())
+ if match:
+ return match
+
+ return None
diff --git a/posthog/test/test_git.py b/posthog/test/test_git.py
new file mode 100644
index 000000000000..987b0314c2da
--- /dev/null
+++ b/posthog/test/test_git.py
@@ -0,0 +1,35 @@
+from parameterized import parameterized
+
+from posthog.git import extract_explicit_repo
+
+REPOS = ["posthog/posthog", "posthog/posthog-js", "posthog/posthog.com"]
+
+
+class TestExtractExplicitRepo:
+ @parameterized.expand(
+ [
+ ("bare_token", "please fix posthog/posthog-js now", "posthog/posthog-js"),
+ ("case_insensitive", "look at PostHog/PostHog-JS", "posthog/posthog-js"),
+ ("dotted_repo_name", "the posthog/posthog.com site is slow", "posthog/posthog.com"),
+ ("surrounding_punctuation", "is it in `posthog/posthog`?", "posthog/posthog"),
+ (
+ "slack_link_label",
+ "see <https://github.com/posthog/posthog-js|posthog/posthog-js>",
+ "posthog/posthog-js",
+ ),
+ ("no_repo_token", "the dashboards are slow", None),
+ ("unconnected_repo", "fix acme/widgets please", None),
+ ("bare_url_ignored", "https://posthog.com/posthog is down", None),
+ ]
+ )
+ def test_extracts_matching_repo(self, _name: str, text: str, expected: str | None):
+ assert extract_explicit_repo(text, REPOS) == expected
+
+ @parameterized.expand(
+ [
+ ("empty_text", "", REPOS),
+ ("empty_repo_list", "posthog/posthog", []),
+ ]
+ )
+ def test_returns_none_on_empty_inputs(self, _name: str, text: str, repos: list[str]):
+ assert extract_explicit_repo(text, repos) is None
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 8f58842f7a39..01af3089a832 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -22,6 +22,7 @@ from slack_sdk.errors import SlackApiError
from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy
from posthog.event_usage import groups
+from posthog.git import extract_explicit_repo
from posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES
from posthog.models.integration import (
SLACK_INTEGRATION_KINDS,
@@ -743,30 +744,8 @@ def _post_repo_picker_message(
def _extract_explicit_repo(text: str, all_repos: list[str]) -> str | None:
- """Extract an explicit org/repo token from message text, if it matches connected repos."""
- if not text or not all_repos:
- return None
-
- normalized_repos = {repo.lower(): repo for repo in all_repos}
- cleaned_text = _strip_bot_mentions(text)
-
- for token in cleaned_text.split():
- candidate = token.strip("`'\"()[]{}<>,.;:!?")
-
- # Slack can format links as <url|label>; for repo tokens we want the label.
- if "|" in candidate:
- candidate = candidate.split("|", 1)[1].strip("`'\"()[]{}<>,.;:!?")
-
- if not candidate or "://" in candidate or candidate.startswith("http"):
- continue
- if not re.fullmatch(r"[\w.-]+/[\w.-]+", candidate):
- continue
-
- match = normalized_repos.get(candidate.lower())
- if match:
- return match
-
- return None
+ """Extract an explicit org/repo token from Slack message text, if it matches connected repos."""
+ return extract_explicit_repo(_strip_bot_mentions(text), all_repos)
def _get_full_repo_names(integration: Integration, *, user_id: int | None) -> list[str]:
diff --git a/products/tasks/backend/logic/repo_selection/__init__.py b/products/tasks/backend/logic/repo_selection/__init__.py
index 736e79d94dc5..144ed43099a6 100644
--- a/products/tasks/backend/logic/repo_selection/__init__.py
+++ b/products/tasks/backend/logic/repo_selection/__init__.py
@@ -6,6 +6,7 @@ from products.tasks.backend.logic.repo_selection.agent import (
resolve_team_github_integration,
select_repository,
)
+from products.tasks.backend.logic.repo_selection.cascade import select_repository_for_message
__all__ = [
"REPO_SELECTION_DUMMY_REPOSITORY",
@@ -14,4 +15,5 @@ __all__ = [
"RepoSelectionUnavailableError",
"resolve_team_github_integration",
"select_repository",
+ "select_repository_for_message",
]
diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.py
index f829e25a5700..4c1f23d699ea 100644
--- a/products/tasks/backend/logic/repo_selection/agent.py
+++ b/products/tasks/backend/logic/repo_selection/agent.py
@@ -303,6 +303,8 @@ async def select_repository(
context: str,
*,
origin_product: Task.OriginProduct,
+ github: GitHubIntegrationBase | None = None,
+ candidate_repos: list[str] | None = None,
step_name: str = "repo_selection",
signal_report_id: str | None = None,
sandbox_environment_id: str | None = None,
@@ -315,18 +317,24 @@ async def select_repository(
`context` is a pre-rendered string describing the request — callers must serialize their
domain types (SignalData, Slack thread messages, etc.) before invoking.
+ Callers that have already resolved the integration and candidate list (e.g. to run their
+ own cheap early-exit first) may pass `github` and `candidate_repos` to skip the redundant
+ fetches; otherwise they're resolved here.
+
Raises `RepoSelectionRejectedError` when the LLM returns a repository that isn't in the
candidate list (hallucination). Callers that need to distinguish that failure mode from
a legitimate "no plausible candidate" decision (`RepoSelectionResult(repository=None, ...)`)
should catch the exception.
"""
- github = await database_sync_to_async(resolve_team_github_integration, thread_sensitive=False)(team_id)
+ if github is None:
+ github = await database_sync_to_async(resolve_team_github_integration, thread_sensitive=False)(team_id)
if github is None:
return RepoSelectionResult(
repository=None,
reason="No GitHub repositories connected to this team.",
)
- candidate_repos = await database_sync_to_async(_list_candidate_repos, thread_sensitive=False)(github, team_id)
+ if candidate_repos is None:
+ candidate_repos = await database_sync_to_async(_list_candidate_repos, thread_sensitive=False)(github, team_id)
if len(candidate_repos) == 0:
return RepoSelectionResult(
repository=None,
diff --git a/products/tasks/backend/logic/repo_selection/cascade.py b/products/tasks/backend/logic/repo_selection/cascade.py
new file mode 100644
index 000000000000..1fb2ee00d794
--- /dev/null
+++ b/products/tasks/backend/logic/repo_selection/cascade.py
@@ -0,0 +1,63 @@
+import logging
+
+from posthog.git import extract_explicit_repo
+from posthog.sync import database_sync_to_async
+
+from products.tasks.backend.logic.repo_selection.agent import (
+ RepoSelectionRejectedError,
+ RepoSelectionUnavailableError,
+ _list_candidate_repos,
+ resolve_team_github_integration,
+ select_repository,
+)
+from products.tasks.backend.models import Task
+
+logger = logging.getLogger(__name__)
+
+
+async def select_repository_for_message(
+ team_id: int,
+ user_id: int,
+ message: str,
+ *,
+ origin_product: Task.OriginProduct,
+) -> str | None:
+ """Pick the repository a free-form chat message is most likely about, cheapest strategy first.
+
+ 1. An explicit `owner/repo` token in the message that matches a connected repo.
+ 2. Delegated to `select_repository`, which returns the team's single eligible repo instantly,
+ or runs the sandbox LLM agent when there are several candidates.
+
+ Returns `None` when nothing connects (no integration, no candidates, the agent finds no
+ plausible subject, or selection fails for any reason). Selection must never block the
+ conversation from starting, so this never raises — every failure degrades to "no repo".
+ """
+ try:
+ github = await database_sync_to_async(resolve_team_github_integration, thread_sensitive=False)(team_id)
+ if github is None:
+ return None
+ candidates = await database_sync_to_async(_list_candidate_repos, thread_sensitive=False)(github, team_id)
+ if not candidates:
+ return None
+
+ explicit = extract_explicit_repo(message, candidates)
+ if explicit:
+ return explicit
+
+ # Reuse the integration and candidate list already resolved above so the heavy
+ # multi-repo path doesn't re-run both queries inside `select_repository`.
+ result = await select_repository(
+ team_id,
+ user_id,
+ context=message,
+ origin_product=origin_product,
+ github=github,
+ candidate_repos=candidates,
+ )
+ return result.repository
+ except (RepoSelectionRejectedError, RepoSelectionUnavailableError) as e:
+ logger.info("repo_selection_for_message.no_selection team_id=%s reason=%s", team_id, e)
+ return None
+ except Exception:
+ logger.warning("repo_selection_for_message.failed team_id=%s", team_id, exc_info=True)
+ return None
diff --git a/products/tasks/backend/tests/test_repo_selection_cascade.py b/products/tasks/backend/tests/test_repo_selection_cascade.py
new file mode 100644
index 000000000000..21249879418e
--- /dev/null
+++ b/products/tasks/backend/tests/test_repo_selection_cascade.py
@@ -0,0 +1,81 @@
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from parameterized import parameterized
+
+from products.tasks.backend.logic.repo_selection.agent import (
+ RepoSelectionRejectedError,
+ RepoSelectionResult,
+ RepoSelectionUnavailableError,
+)
+from products.tasks.backend.logic.repo_selection.cascade import select_repository_for_message
+from products.tasks.backend.models import Task
+
+_CASCADE = "products.tasks.backend.logic.repo_selection.cascade"
+
+
+def _patch_candidates(github: object | None, candidates: list[str]):
+ return (
+ patch(f"{_CASCADE}.resolve_team_github_integration", return_value=github),
+ patch(f"{_CASCADE}._list_candidate_repos", return_value=candidates),
+ )
+
+
+async def _run(message: str) -> str | None:
+ return await select_repository_for_message(1, 2, message, origin_product=Task.OriginProduct.POSTHOG_AI)
+
+
+class TestSelectRepositoryForMessage:
+ async def test_no_github_integration_returns_none(self):
+ resolve, list_repos = _patch_candidates(None, [])
+ with resolve, list_repos, patch(f"{_CASCADE}.select_repository", new=AsyncMock()) as select:
+ assert await _run("anything") is None
+ select.assert_not_called()
+
+ async def test_no_candidates_returns_none(self):
+ resolve, list_repos = _patch_candidates(MagicMock(), [])
+ with resolve, list_repos, patch(f"{_CASCADE}.select_repository", new=AsyncMock()) as select:
+ assert await _run("anything") is None
+ select.assert_not_called()
+
+ async def test_explicit_mention_short_circuits(self):
+ resolve, list_repos = _patch_candidates(MagicMock(), ["posthog/posthog", "posthog/posthog-js"])
+ with resolve, list_repos, patch(f"{_CASCADE}.select_repository", new=AsyncMock()) as select:
+ assert await _run("please fix posthog/posthog-js") == "posthog/posthog-js"
+ select.assert_not_called()
+
+ async def test_delegates_to_select_repository_without_explicit_mention(self):
+ resolve, list_repos = _patch_candidates(MagicMock(), ["posthog/posthog", "posthog/posthog-js"])
+ result = RepoSelectionResult(repository="posthog/posthog", reason="agent picked it")
+ with resolve, list_repos, patch(f"{_CASCADE}.select_repository", new=AsyncMock(return_value=result)) as select:
+ assert await _run("the dashboards are slow") == "posthog/posthog"
+ select.assert_awaited_once()
+
+ async def test_forwards_resolved_integration_and_candidates(self):
+ github = MagicMock()
+ candidates = ["posthog/posthog", "posthog/posthog-js"]
+ resolve, list_repos = _patch_candidates(github, candidates)
+ result = RepoSelectionResult(repository="posthog/posthog", reason="agent picked it")
+ with resolve, list_repos, patch(f"{_CASCADE}.select_repository", new=AsyncMock(return_value=result)) as select:
+ await _run("the dashboards are slow")
+ await_args = select.await_args
+ assert await_args is not None
+ assert await_args.kwargs["github"] is github
+ assert await_args.kwargs["candidate_repos"] == candidates
+
+ async def test_select_repository_null_returns_none(self):
+ resolve, list_repos = _patch_candidates(MagicMock(), ["posthog/posthog", "posthog/posthog-js"])
+ result = RepoSelectionResult(repository=None, reason="no plausible candidate")
+ with resolve, list_repos, patch(f"{_CASCADE}.select_repository", new=AsyncMock(return_value=result)):
+ assert await _run("a question about billing") is None
+
+ @parameterized.expand(
+ [
+ ("rejected", RepoSelectionRejectedError("posthog/hallucinated", "made it up")),
+ ("unavailable", RepoSelectionUnavailableError("all archived")),
+ ("unexpected", RuntimeError("sandbox boot failed")),
+ ]
+ )
+ async def test_selection_failure_degrades_to_none(self, _name: str, error: Exception):
+ resolve, list_repos = _patch_candidates(MagicMock(), ["posthog/posthog", "posthog/posthog-js"])
+ with resolve, list_repos, patch(f"{_CASCADE}.select_repository", new=AsyncMock(side_effect=error)):
+ assert await _run("the dashboards are slow") is None