: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): resolve repos from thread links, unblock ci asks (#77555)
Raúl Negrón-Otero1af2e10a5fab
diff --git a/posthog/git.py b/posthog/git.pyindex 5dcba76caebb..df515438f50e 100644--- a/posthog/git.py+++ b/posthog/git.py@@ -1,7 +1,9 @@import reimport subprocess+from collections.abc import Iteratorfrom functools import cachefrom typing import Optional+from urllib.parse import urlsplit_git_commit_baked_in: Optional[str] = Nonetry:@@ -49,13 +51,44 @@ def get_git_branch() -> Optional[str]:return None+_TOKEN_PUNCTUATION = "`'\"()[]{}<>,.;:!?"+_GITHUB_HOSTS = frozenset({"github.com", "www.github.com"})+_REPO_TOKEN = re.compile(r"[\w.-]+/[\w.-]+")+# Slack formats links as <url|label> and either side can carry the repo, so `|` separates+# candidates the same way whitespace does.+_CANDIDATE_SEPARATOR = re.compile(r"[\s|]+")+++def _repo_from_github_url(token: str) -> str | None:+ """`owner/repo` from a GitHub URL token, or None if it isn't one."""+ candidate = token.replace("[email protected]:", "https://github.com/", 1)+ if "//" not in candidate:+ candidate = f"https://{candidate}" # urlsplit only populates netloc when a scheme is present+ try:+ parts = urlsplit(candidate)+ except ValueError:+ return None+ # Exact host match, so `mygithub.com` and `github.com.evil.tld` can never resolve.+ if parts.hostname not in _GITHUB_HOSTS:+ return None+ segments = [segment for segment in parts.path.split("/") if segment]+ if len(segments) < 2:+ return None+ return f"{segments[0]}/{segments[1].removesuffix('.git')}"+++def _candidates(text: str) -> Iterator[str]:+ for part in _CANDIDATE_SEPARATOR.split(text):+ candidate = part.strip(_TOKEN_PUNCTUATION)+ if candidate:+ yield candidate++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.+ """Return the first bare `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.+ Matches case-insensitively and strips surrounding punctuation. `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."""@@ -63,21 +96,44 @@ def extract_explicit_repo(text: str, all_repos: list[str]) -> str | None:return Nonenormalized_repos = {repo.lower(): repo for repo in all_repos}+ for candidate in _candidates(text):+ if _REPO_TOKEN.fullmatch(candidate) and (match := normalized_repos.get(candidate.lower())):+ return match+ return None- 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("`'\"()[]{}<>,.;:!?")+def extract_linked_repo(text: str, all_repos: list[str]) -> str | None:+ """Return the connected repo `text` links to, if it links to exactly one.- if not candidate or "://" in candidate or candidate.startswith("http"):- continue- if not re.fullmatch(r"[\w.-]+/[\w.-]+", candidate):- continue+ Resolves a `github.com/owner/repo…` URL of any depth: a run, a pull request, a file+ permalink. Two different linked repos is genuine ambiguity and resolves to nothing, so a+ caller can fall back to asking rather than acting on whichever was pasted first.- match = normalized_repos.get(candidate.lower())- if match:- return match+ Weaker evidence than `extract_explicit_repo`, since a link can be in a message for reasons+ unrelated to the ask. Callers wanting both tiers take the typed token first.+ """+ if not text or not all_repos:+ return None+ normalized_repos = {repo.lower(): repo for repo in all_repos}+ linked = {+ match+ for candidate in _candidates(text)+ if (from_url := _repo_from_github_url(candidate)) and (match := normalized_repos.get(from_url.lower()))+ }+ return next(iter(linked)) if len(linked) == 1 else None+++def extract_repo_from_scopes(scopes: list[str], all_repos: list[str]) -> str | None:+ """Return the repo named by the first of `scopes` to name one, a typed token beating a+ link within each scope. Callers order the scopes strongest evidence first.++ Each scope is matched on its own rather than joined into one string, which keeps the+ ambiguity rule in `extract_linked_repo` meaningful: two repos linked inside one scope is+ someone naming two things at once and resolves to nothing, while two repos linked across+ separate scopes is a thread accumulating links and lets the stronger scope answer.+ """+ for scope in scopes:+ if match := extract_explicit_repo(scope, all_repos) or extract_linked_repo(scope, all_repos):+ return matchreturn Nonediff --git a/posthog/temporal/ai/slack_app/activities/classifiers.py b/posthog/temporal/ai/slack_app/activities/classifiers.pyindex cc7cc14a9428..90f411334505 100644--- a/posthog/temporal/ai/slack_app/activities/classifiers.py+++ b/posthog/temporal/ai/slack_app/activities/classifiers.py@@ -125,6 +125,11 @@ def classify_task_needs_repo(r"\bserializer\b",r"\bviewset\b",r"\bmigration\b",+ # A failing test is code work, but it is named after the feature it covers, so the+ # product terms above would answer no-repo first. Keep these narrow: they match the+ # whole thread, and a bare "ci" would also catch confidence intervals.+ r"\bflak(?:y|e|es|iness)\b",+ r"\bmerge queue\b",)if any(term in normalized for term in product_debug_terms) and not any(@@ -150,7 +155,12 @@ def classify_task_needs_repo("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 "+ "needs_repo.\n\n"+ "A failing, broken, or flaky CI run, test suite, or build is work in the team's own "+ "repository → needs_repo, including when the test is named after a PostHog feature "+ "('the experiment insight test is flaky'): the subject is their test, not our "+ "product.\n\n"+ "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 send ""us hunting for a repository on a guess.\n\n"diff --git a/posthog/temporal/ai/slack_app/activities/repo_selection.py b/posthog/temporal/ai/slack_app/activities/repo_selection.pyindex 519706a4719d..848d7c4a0c87 100644--- a/posthog/temporal/ai/slack_app/activities/repo_selection.py+++ b/posthog/temporal/ai/slack_app/activities/repo_selection.py@@ -1,4 +1,5 @@import asyncio+from decimal import Decimal, InvalidOperationfrom typing import Anyimport structlog@@ -22,17 +23,32 @@ def cascade_posthog_code_repository_activity(inputs: PostHogCodeSlackMentionWorkflowInputs,event_text: str,user_id: int,+ thread_messages: list[dict[str, str]] | None = None,+ mention_ts: str | None = None,) -> PostHogCodeRepoCascadeOutcome:"""Synchronous fast-path before the discovery agent.- Resolves the trivial cases — no GitHub repos connected to the mentioning user's- personal install, exactly one connected, or an explicit `org/repo` mentioned in the- message — without paying for the sandbox-backed agent. Anything else returns- `mode='agent_needed'` and the workflow takes over.+ Resolves the trivial cases without paying for the sandbox-backed agent: no GitHub+ repos connected to the mentioning user's personal install, exactly one connected, or+ an explicit `org/repo` named in the mention or in the thread it sits in. Anything+ else returns `mode='agent_needed'` and the workflow takes over.++ The discovery agent this preempts reads the whole thread, so the fast path must too:+ a mention-only read sends every ask whose link sits in an earlier message to a+ sandbox run that then finds the repo in text the fast path skipped. Only messages at+ or before ``mention_ts`` may name the repo, though: the snapshot is taken when the+ activity runs, so it can contain replies posted after the mention, and letting those+ win the newest-first scan would let any channel participant redirect someone else's+ ask by pasting a repo link right after it.++ ``thread_messages`` and ``mention_ts`` default to ``None`` for backwards+ compatibility with calls recorded before the parameters existed: if a worker drains+ an activity task scheduled by an older workflow, the call still binds and degrades+ to the mention-only behavior."""from posthog.models.integration import Integration- from products.slack_app.backend.api import _extract_explicit_repo, _get_full_repo_names+ from products.slack_app.backend.api import _get_full_repo_namesintegration = Integration.objects.select_related("team", "team__organization").get(id=inputs.integration_id,@@ -51,10 +67,48 @@ def cascade_posthog_code_repository_activity(if len(all_repos) == 1:return PostHogCodeRepoCascadeOutcome(mode="auto", repository=all_repos[0], reason="single_repo")+ outcome = _resolve_explicit_repo(event_text, _messages_at_or_before(thread_messages or [], mention_ts), all_repos)+ # Logged so the share of mentions each resolution tier saves from the discovery agent is measurable.+ logger.info(+ "posthog_code_cascade_outcome",+ reason=outcome.reason,+ integration_id=inputs.integration_id,+ )+ return outcome+++def _messages_at_or_before(messages: list[dict[str, str]], mention_ts: str | None) -> list[dict[str, str]]:+ """Messages eligible as repo-selection evidence: posted at or before the mention.++ Fail-closed: without a parseable bound, or for a message without a parseable ``ts``,+ the message contributes nothing and resolution degrades to the mention text alone.+ """++ def at_or_before(ts: str, bound: str) -> bool:+ try:+ return Decimal(ts) <= Decimal(bound)+ except InvalidOperation:+ return False++ if not mention_ts:+ return []+ return [message for message in messages if at_or_before(message.get("ts", ""), mention_ts)]+++def _resolve_explicit_repo(+ event_text: str, thread_messages: list[dict[str, str]], all_repos: list[str]+) -> PostHogCodeRepoCascadeOutcome:+ """Repo named by the mention, then by the thread, each reported under its own reason."""+ from products.slack_app.backend.api import _extract_explicit_repo, _extract_explicit_repo_from_thread+explicit_repo = _extract_explicit_repo(event_text, all_repos)if explicit_repo:return PostHogCodeRepoCascadeOutcome(mode="auto", repository=explicit_repo, reason="explicit_mention")+ thread_repo = _extract_explicit_repo_from_thread(thread_messages, all_repos)+ if thread_repo:+ return PostHogCodeRepoCascadeOutcome(mode="auto", repository=thread_repo, reason="explicit_thread_mention")+return PostHogCodeRepoCascadeOutcome(mode="agent_needed", repository=None, reason="needs_agent")diff --git a/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py b/posthog/temporal/ai/slack_app/eval_slack_repo_selection.pyindex 74f204f41f76..b8b054609836 100644--- a/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py+++ b/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py@@ -83,7 +83,7 @@ from posthog.models import Teamfrom posthog.temporal.ai.slack_app import POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCEfrom posthog.temporal.ai.slack_app.activities.classifiers import classify_task_needs_repo-from products.slack_app.backend.api import _extract_explicit_repo+from products.slack_app.backend.api import _extract_explicit_repo, _extract_explicit_repo_from_threadfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.repo_selection import (RepoSelectionRejectedError,@@ -148,6 +148,33 @@ CASES: list[Case] = [expected_stage="cascade",expected_outcome="auto",),+ Case(+ name="ci_run_link",+ description="Cascade reads the repo out of a workflow-run link, so a CI ask never reaches the agent.",+ text_template="@PostHog is this flaky? https://github.com/{first_repo}/actions/runs/30560492835",+ thread_messages=[+ {+ "user": "tester",+ "text": "@PostHog is this flaky? https://github.com/{first_repo}/actions/runs/30560492835",+ }+ ],+ expected_stage="cascade",+ expected_outcome="auto",+ ),+ Case(+ name="ci_run_link_earlier_in_the_thread",+ description="Cascade reads the repo from a link someone posted before the mention, the usual shape of a CI ask.",+ text_template="@PostHog is this one flaky?",+ thread_messages=[+ {+ "user": "tester",+ "text": "https://github.com/{first_repo}/actions/runs/30560492835 went red again",+ },+ {"user": "tester", "text": "@PostHog is this one flaky?"},+ ],+ expected_stage="cascade",+ expected_outcome="auto",+ ),# --- Haiku gate short-circuits (heuristic + LLM) ---------------------------Case(name="billing_question",@@ -425,8 +452,11 @@ class Command:self.stdout.write(f" text: {text}")self.stdout.write(f" expected: {case.expected_stage}/{case.expected_outcome}")- # Stage 1: cascade (synchronous, no LLM)- explicit = _extract_explicit_repo(text, ctx.all_repos)+ # Stage 1: cascade (synchronous, no LLM). Mirrors `cascade_posthog_code_repository_activity`,+ # because reading only the mention here would pass cases that production sends to the agent.+ explicit = _extract_explicit_repo(text, ctx.all_repos) or _extract_explicit_repo_from_thread(+ thread_messages, ctx.all_repos+ )if explicit:self.stdout.write(self.style.SUCCESS(f" cascade → auto: {explicit}"))return CaseResult(case=case, actual_stage="cascade", actual_outcome="auto", detail=explicit)diff --git a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.pyindex 1a78403b4dc7..2bf9476945f3 100644--- a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py@@ -181,6 +181,8 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):inputs,event.get("text", ""),user_id,+ thread_messages,+ event.get("ts"),)if cascade.mode == "auto":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.pyindex 4b8314e93e1e..a0d3e06158c1 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@@ -128,7 +128,11 @@ def _fake_activities(rec: _Recorder) -> list:@activity.defn(name="cascade_posthog_code_repository_activity")async def cascade(- inputs: PostHogCodeSlackMentionWorkflowInputs, event_text: str, user_id: int | None = None+ inputs: PostHogCodeSlackMentionWorkflowInputs,+ event_text: str,+ user_id: int | None = None,+ thread_messages: list[dict[str, str]] | None = None,+ mention_ts: str | None = None,) -> PostHogCodeRepoCascadeOutcome:mode = rec.cascade_modes.get(inputs.event["ts"], "auto")repository = "org/auto-repo" if mode == "auto" else Nonediff --git a/posthog/temporal/tests/ai/test_cascade_team_install.py b/posthog/temporal/tests/ai/test_cascade_team_install.pyindex c654df7c3165..97e4806352ec 100644--- a/posthog/temporal/tests/ai/test_cascade_team_install.py+++ b/posthog/temporal/tests/ai/test_cascade_team_install.py@@ -83,3 +83,87 @@ class TestCascadeTeamInstall(TestCase):assert outcome.mode == "auto"assert outcome.repository == "posthog/posthog"++ @parameterized.expand(+ [+ (+ "link_sits_in_the_thread_and_the_mention_carries_none",+ "<@BOT> is this one flaky?",+ [+ {+ "user": "amy",+ "text": "https://github.com/posthog/posthog-js/actions/runs/2 failed again",+ "ts": "1.000000",+ },+ {"user": "bo", "text": "<@BOT> is this one flaky?", "ts": "2.000000"},+ ],+ "auto",+ "posthog/posthog-js",+ "explicit_thread_mention",+ ),+ (+ "mention_names_a_repo_the_thread_did_not",+ "<@BOT> look at posthog/posthog instead",+ [+ {+ "user": "amy",+ "text": "https://github.com/posthog/posthog-js/actions/runs/2 failed again",+ "ts": "1.000000",+ },+ {"user": "bo", "text": "<@BOT> look at posthog/posthog instead", "ts": "2.000000"},+ ],+ "auto",+ "posthog/posthog",+ "explicit_mention",+ ),+ (+ "link_posted_after_the_mention_cannot_select_the_repo",+ "<@BOT> is this one flaky?",+ [+ {"user": "bo", "text": "<@BOT> is this one flaky?", "ts": "2.000000"},+ {+ "user": "mallory",+ "text": "https://github.com/posthog/posthog-js/actions/runs/2",+ "ts": "3.000000",+ },+ ],+ "agent_needed",+ None,+ "needs_agent",+ ),+ ]+ )+ @patch("products.slack_app.backend.api.UserGitHubIntegration")+ def test_thread_evidence_counts_only_up_to_the_mention(+ self,+ _name,+ event_text,+ thread_messages,+ expected_mode,+ expected_repository,+ expected_reason,+ mock_user_github_class,+ ):+ from posthog.models.user_integration import UserIntegration++ UserIntegration.objects.create(+ user=self.user,+ kind=UserIntegration.IntegrationKind.GITHUB,+ integration_id="gh-user-1",+ config={},+ sensitive_config={"access_token": "gh-user-token"},+ )+ mock_user_github = MagicMock()+ mock_user_github.list_all_cached_repositories.return_value = [+ {"id": 1, "name": "posthog", "full_name": "posthog/posthog"},+ {"id": 2, "name": "posthog-js", "full_name": "posthog/posthog-js"},+ ]+ mock_user_github_class.return_value = mock_user_github++ outcome = cascade_posthog_code_repository_activity(+ _make_inputs(self.slack_integration.id, self.user.id), event_text, self.user.id, thread_messages, "2.000000"+ )++ assert outcome.mode == expected_mode+ assert outcome.repository == expected_repository+ assert outcome.reason == expected_reasondiff --git a/posthog/temporal/tests/ai/test_classify_task_needs_repo.py b/posthog/temporal/tests/ai/test_classify_task_needs_repo.pyindex bb8ed9b32c77..2352058f955f 100644--- a/posthog/temporal/tests/ai/test_classify_task_needs_repo.py+++ b/posthog/temporal/tests/ai/test_classify_task_needs_repo.py@@ -43,6 +43,43 @@ class TestClassifyTaskNeedsRepo:result = classify_task_needs_repo(text, [{"user": "Alessandro", "text": text}])assert result is expected+ @parameterized.expand(+ [+ # Each ask carries a product noun that short-circuits the heuristic to+ # no-repo unless the CI vocabulary vetoes it first.+ ("flaky_test_named_after_a_feature", "the experiment insight test is flaky"),+ ("merge_queue", "the merge queue keeps failing on the experiment insight tests"),+ ]+ )+ def test_ci_vocabulary_leaves_the_call_to_the_llm(self, _name, text):+ assert self._run_with_llm_content(text, '{"needs_repo": true}') is True++ @parameterized.expand(+ [+ # Both halves of a CI ask, split across a thread the way people actually talk.+ # A vocabulary that pairs any subject word with any failure word reads these as+ # CI and spends a discovery-agent sandbox run on an analytics question.+ (+ "tests_and_errors_in_an_analytics_thread",+ [+ {"user": "amy", "text": "we ran some tests on the signup funnel yesterday"},+ {"user": "bo", "text": "the numbers look off, error rate is way up in the dashboard"},+ ],+ "why did conversion drop?",+ ),+ (+ "master_chatter_beside_a_product_bug",+ [+ {"user": "amy", "text": "just merged that to master"},+ {"user": "bo", "text": "the survey widget throws an error on mobile"},+ ],+ "what does the data say?",+ ),+ ]+ )+ def test_product_ask_short_circuits_before_the_llm(self, _name, thread_messages, event_text):+ assert self._run_with_llm_content(event_text, '{"needs_repo": true}', thread_messages) is False+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"@@ -71,7 +108,9 @@ class TestClassifyTaskNeedsRepo:result = self._run_with_llm_content(text, content)assert result is expected- def _run_with_llm_content(self, text: str, content: str) -> bool:+ def _run_with_llm_content(+ self, text: str, content: str, thread_messages: list[dict[str, str]] | None = None+ ) -> bool:fake_response = MagicMock()fake_response.choices = [MagicMock(message=MagicMock(content=content))]fake_client = MagicMock()@@ -80,7 +119,7 @@ class TestClassifyTaskNeedsRepo:"posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",return_value=fake_client,):- return classify_task_needs_repo(text, [{"user": "Alessandro", "text": text}])+ return classify_task_needs_repo(text, thread_messages or [{"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."""diff --git a/posthog/test/test_git.py b/posthog/test/test_git.pyindex 987b0314c2da..a057d35ef1dd 100644--- a/posthog/test/test_git.py+++ b/posthog/test/test_git.py@@ -1,6 +1,6 @@from parameterized import parameterized-from posthog.git import extract_explicit_repo+from posthog.git import extract_explicit_repo, extract_linked_repo, extract_repo_from_scopesREPOS = ["posthog/posthog", "posthog/posthog-js", "posthog/posthog.com"]@@ -20,6 +20,8 @@ class TestExtractExplicitRepo:("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),+ ("github_url_is_not_a_typed_token", "see https://github.com/posthog/posthog/pull/1", None),+ ("two_bare_tokens_first_wins", "check posthog/posthog-js then posthog/posthog", "posthog/posthog-js"),])def test_extracts_matching_repo(self, _name: str, text: str, expected: str | None):@@ -33,3 +35,83 @@ class TestExtractExplicitRepo:)def test_returns_none_on_empty_inputs(self, _name: str, text: str, repos: list[str]):assert extract_explicit_repo(text, repos) is None+++class TestExtractLinkedRepo:+ @parameterized.expand(+ [+ (+ "actions_run_url",+ "is this flaky? https://github.com/posthog/posthog/actions/runs/30560492835/job/90936416640",+ "posthog/posthog",+ ),+ (+ "slack_wrapped_actions_url_with_label",+ "why did this fail? <https://github.com/posthog/posthog-js/actions/runs/29764624536|"+ "github.com/posthog/posthog-js/…/29764624536>",+ "posthog/posthog-js",+ ),+ ("clone_url_suffix", "cloned from [email protected]:posthog/posthog.git", "posthog/posthog"),+ ("unconnected_repo_url", "see https://github.com/acme/widgets/pull/1", None),+ ("lookalike_host", "see https://mygithub.com/posthog/posthog/pull/1", None),+ ("host_prefix_spoof", "see https://github.com.evil.tld/posthog/posthog", None),+ ("userinfo_spoof", "see https://[email protected]/posthog/posthog", None),+ ("org_url_names_no_repo", "see https://github.com/posthog", None),+ ("unparseable_url_is_not_an_error", "see https://[::1/posthog/posthog", None),+ ("bare_token_is_not_a_link", "fix posthog/posthog-js now", None),+ (+ "two_linked_repos_is_ambiguous",+ "https://github.com/posthog/posthog/pull/1 broke https://github.com/posthog/posthog-js/actions/runs/2",+ None,+ ),+ (+ "same_repo_linked_twice_is_not_ambiguous",+ "https://github.com/posthog/posthog/pull/1 and https://github.com/posthog/posthog/actions/runs/2",+ "posthog/posthog",+ ),+ ]+ )+ def test_resolves_a_single_linked_repo(self, _name: str, text: str, expected: str | None):+ assert extract_linked_repo(text, REPOS) == expected+++class TestExtractRepoFromScopes:+ @parameterized.expand(+ [+ (+ "later_scope_answers_when_earlier_names_nothing",+ ["can you look at this?", "https://github.com/posthog/posthog-js/actions/runs/2"],+ "posthog/posthog-js",+ ),+ (+ "typed_token_in_an_earlier_scope_beats_a_link_in_a_later_one",+ ["fix posthog/posthog", "https://github.com/posthog/posthog-js/actions/runs/2"],+ "posthog/posthog",+ ),+ (+ "typed_token_beats_a_link_in_the_same_scope",+ ["fix posthog/posthog-js, context https://github.com/posthog/posthog/pull/1"],+ "posthog/posthog-js",+ ),+ (+ "two_repos_in_one_scope_stay_ambiguous",+ [+ "https://github.com/posthog/posthog/pull/1 broke https://github.com/posthog/posthog-js/actions/runs/2",+ "https://github.com/posthog/posthog.com/pull/3",+ ],+ "posthog/posthog.com",+ ),+ (+ "two_repos_across_separate_scopes_resolve_to_the_first",+ [+ "https://github.com/posthog/posthog/pull/1",+ "https://github.com/posthog/posthog-js/actions/runs/2",+ ],+ "posthog/posthog",+ ),+ ("no_scope_names_a_repo", ["can you look at this?", "it broke again"], None),+ ("no_scopes_at_all", [], None),+ ]+ )+ def test_first_scope_to_name_a_repo_answers(self, _name: str, scopes: list[str], expected: str | None):+ assert extract_repo_from_scopes(scopes, REPOS) == expecteddiff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex c4e401afd88d..7ad8e1349e52 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -24,7 +24,7 @@ from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicyfrom posthog.dataclasses import frozenfrom posthog.event_usage import groups-from posthog.git import extract_explicit_repo+from posthog.git import extract_explicit_repo, extract_linked_repo, extract_repo_from_scopesfrom posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPESfrom posthog.models.integration import (SLACK_INTEGRATION_KINDS,@@ -929,8 +929,22 @@ def _post_repo_picker_message(def _extract_explicit_repo(text: str, all_repos: list[str]) -> str | 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)+ """Repo named by Slack message text, as a typed org/repo token or as a GitHub link."""+ cleaned = _strip_bot_mentions(text)+ return extract_explicit_repo(cleaned, all_repos) or extract_linked_repo(cleaned, all_repos)+++def _extract_explicit_repo_from_thread(thread_messages: list[dict[str, str]], all_repos: list[str]) -> str | None:+ """Repo named by the thread around a mention, newest message first.++ People paste the link into the thread and mention the bot in a later reply that carries no+ link of its own. Reading only the mention hands those asks to the discovery agent, which+ answers them from this same thread text. Newest first because the link under discussion is+ the one most recently posted.+ """+ return extract_repo_from_scopes(+ [_strip_bot_mentions(message.get("text", "")) for message in reversed(thread_messages)], all_repos+ )def _get_full_repo_names(integration: Integration, *, user_id: int | None) -> list[str]:diff --git a/products/slack_app/backend/tests/test_guess_repository.py b/products/slack_app/backend/tests/test_guess_repository.pyindex ab14b90f595b..719fba564b0f 100644--- a/products/slack_app/backend/tests/test_guess_repository.py+++ b/products/slack_app/backend/tests/test_guess_repository.py@@ -319,23 +319,15 @@ class TestPostRepoPickerPrewarm:class TestExtractExplicitRepo:+ # Matching is covered where the helpers live, in posthog/test/test_git.py. All this+ # wrapper adds is stripping the bot mention and composing the token tier over the link tier.@parameterized.expand([- ("simple", "fix posthog/posthog-js please", "posthog/posthog-js"),- ("no_match", "hello world", None),- ("case_insensitive", "check PostHog/PostHog", "posthog/posthog"),- ("url_false_positive", "see https://github.com/posthog/posthog/issues/1", None),- ("backticks", "please fix `posthog/posthog-js`", "posthog/posthog-js"),- (- "slack_link_label",- "use <https://github.com/posthog/posthog-js|posthog/posthog-js>",- "posthog/posthog-js",- ),- ("multiple_first_wins", "check posthog/posthog-js then posthog/posthog", "posthog/posthog-js"),- ("with_bot_mention", "<@U123> fix posthog/posthog-js", "posthog/posthog-js"),+ ("typed_token", "<@U123> fix posthog/posthog-js", "posthog/posthog-js"),+ ("github_link", "<@U123> is https://github.com/posthog/posthog/actions/runs/2 flaky?", "posthog/posthog"),])- def test_extract_explicit_repo(self, _name, text, expected):+ def test_strips_bot_mention_and_matches_both_tiers(self, _name, text, expected):repos = ["posthog/posthog", "posthog/posthog-js", "posthog/plugin-server"]assert _extract_explicit_repo(text, repos) == expected