: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(signals): pin the repository a GitHub issue names through selection (#105789)
posthog[bot]4d43651711bb
diff --git a/posthog/git.py b/posthog/git.pyindex 088c4e5b8d08..d418c3ab7dad 100644--- a/posthog/git.py+++ b/posthog/git.py@@ -60,7 +60,7 @@ _REPO_TOKEN = re.compile(r"[\w.-]+/[\w.-]+")_CANDIDATE_SEPARATOR = re.compile(r"[\s|()\[\]<>]+")-def _repo_from_github_url(token: str) -> str | None:+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:@@ -120,7 +120,7 @@ def extract_linked_repo(text: str, all_repos: list[str]) -> str | None:linked = {matchfor candidate in _candidates(text)- if (from_url := _repo_from_github_url(candidate)) and (match := normalized_repos.get(from_url.lower()))+ 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 Nonediff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.mdindex 3d3648650708..154c17decab9 100644--- a/products/signals/backend/report_generation/AGENTS.md+++ b/products/signals/backend/report_generation/AGENTS.md@@ -13,6 +13,9 @@ It is exercised locally via management commands, and it is also used by the prod- Output: `RepoSelectionResult(repository: str | None, reason: str)`.- Persisted as a `repo_selection` artefact on the report (by the caller activity, not here).- On re-promotion, the activity reuses the previous artefact instead of re-running selection.+ - A repository the signals name themselves is pinned before the agent runs. See `source_repository.py`.+- `source_repository.py`+ The repository a report's signals were filed against. A GitHub issue names its own repository in its URL, so `select_repo.py` pins it: the selector returns it when the team can reach it, and `repository=None` carrying the mismatch when it cannot, so a PR never lands in a repository the report never pointed at. Only one unambiguous repository counts; issues from two repositories name neither.- `research.py`Orchestrates a multi-turn sandbox session over a report's signals.The agent researches each signal, then produces:diff --git a/products/signals/backend/report_generation/select_repo.py b/products/signals/backend/report_generation/select_repo.pyindex dbbe9982da43..7ac4d9ad56a9 100644--- a/products/signals/backend/report_generation/select_repo.py+++ b/products/signals/backend/report_generation/select_repo.py@@ -19,6 +19,7 @@ from posthog.sync import database_sync_to_asyncfrom products.signals.backend.agent_runtime import STEP_REPO_SELECTION, resolve_agent_runtimefrom products.signals.backend.models import SignalReportArtefactfrom products.signals.backend.repo_corrections import wrong_repo_corrections_block+from products.signals.backend.report_generation.source_repository import source_repository_from_signalsfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.repo_selection import (REPO_SELECTION_DUMMY_REPOSITORY,@@ -75,6 +76,7 @@ async def select_repository_for_team(sandbox_environment_id: str | None = None,verbose: bool = False,output_fn: OutputFn = None,+ pinned_repository: str | None = None,) -> RepoSelectionResult:"""Select the most relevant repository for a free-form request against the team's repos.@@ -83,16 +85,27 @@ async def select_repository_for_team(unavailability (no eligible repos) collapse into ``RepoSelectionResult(repository=None, ...)``— Signals/custom agents have no picker fallback, so callers treat ``repository=None`` as"no match / requires human input".++ ``pinned_repository`` is a repository the request names itself (see+ :mod:`~products.signals.backend.report_generation.source_repository`). The shared selector+ returns it when the team can reach it, and ``repository=None`` with the mismatch when it+ cannot — it never substitutes a different repository for one the request named."""- # Resolved at the single repo-selection chokepoint so both callers (custom agent +- # report flow) pick it up.- agent_runtime = await database_sync_to_async(resolve_agent_runtime, thread_sensitive=False)(- team_id, STEP_REPO_SELECTION+ # Both inputs below only ever reach the agent, and a pin answers without it, so neither is+ # resolved on that path — the corrections block alone scans hundreds of artefact rows.+ agent_runtime = (+ None+ if pinned_repository is not None+ else await database_sync_to_async(resolve_agent_runtime, thread_sensitive=False)(team_id, STEP_REPO_SELECTION)+ )+ # Resolved at the single repo-selection chokepoint so every signals selection (report pipeline,+ # custom agents, scout emit) sees the project's past wrong-repo corrections, rather than per+ # caller. Best-effort inside (None on failure or no corrections).+ past_corrections = (+ None+ if pinned_repository is not None+ else await database_sync_to_async(wrong_repo_corrections_block, thread_sensitive=False)(team_id))- # Same chokepoint reasoning: every signals selection (report pipeline, custom agents, scout- # emit) should see the project's past wrong-repo corrections, so the block is built here- # rather than per caller. Best-effort inside (None on failure or no corrections).- past_corrections = await database_sync_to_async(wrong_repo_corrections_block, thread_sensitive=False)(team_id)try:return await select_repository(team_id=team_id,@@ -104,11 +117,12 @@ async def select_repository_for_team(sandbox_environment_id=sandbox_environment_id,verbose=verbose,output_fn=output_fn,- model=agent_runtime.model,- runtime_adapter=agent_runtime.runtime_adapter,- reasoning_effort=agent_runtime.reasoning_effort,- service_tier=agent_runtime.service_tier,+ model=agent_runtime.model if agent_runtime else None,+ runtime_adapter=agent_runtime.runtime_adapter if agent_runtime else None,+ reasoning_effort=agent_runtime.reasoning_effort if agent_runtime else None,+ service_tier=agent_runtime.service_tier if agent_runtime else None,past_corrections=past_corrections,+ pinned_repository=pinned_repository,)except RepoSelectionRejectedError as exc:# Preserve legacy behavior: surface validation reject as null with reason so callers'@@ -140,7 +154,11 @@ async def select_repository_for_report(verbose: bool = False,output_fn: OutputFn = None,) -> RepoSelectionResult:- """Select the most relevant repository for a set of signals."""+ """Select the most relevant repository for a set of signals.++ Signals that name their own repository pin it, so a report built from a GitHub issue targets+ the repository the issue was filed against.+ """from products.signals.backend.temporal.types import render_signals_to_text # noqa: PLC0415request_section = render_signals_to_text(signals)@@ -153,4 +171,5 @@ async def select_repository_for_report(sandbox_environment_id=sandbox_environment_id,verbose=verbose,output_fn=output_fn,+ pinned_repository=source_repository_from_signals(signals),)diff --git a/products/signals/backend/report_generation/source_repository.py b/products/signals/backend/report_generation/source_repository.pynew file mode 100644index 000000000000..549a77f4bfe2--- /dev/null+++ b/products/signals/backend/report_generation/source_repository.py@@ -0,0 +1,33 @@+"""The GitHub repository a report's signals were filed against.++A GitHub issue is the one inbox source that states its own repository: the issue URL names it.+That is an answer, not a question, so repository selection pins it (see `select_repo.py`) instead+of asking the selection agent to reason its way back to it.++Only a single unambiguous repository counts. A report that merges issues from two repositories+names neither, and guessing between them is the failure this module exists to prevent.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from posthog.models.github_integration_base import GitHubIntegrationBase++from products.signals.backend.enums import SignalSourceProduct, SignalSourceType++if TYPE_CHECKING:+ from products.signals.backend.temporal.types import SignalData+++def _issue_repository(signal: SignalData) -> str | None:+ if signal.source_product != SignalSourceProduct.GITHUB or signal.source_type != SignalSourceType.ISSUE:+ return None+ ref = GitHubIntegrationBase.parse_issue_url(str((signal.extra or {}).get("html_url") or ""))+ return ref.repository.lower() if ref is not None else None+++def source_repository_from_signals(signals: list[SignalData]) -> str | None:+ """The one repository these signals come from, lowercased, or None when they name none or many."""+ repositories = {repository for signal in signals if (repository := _issue_repository(signal))}+ return next(iter(repositories)) if len(repositories) == 1 else Nonediff --git a/products/signals/backend/test/test_source_repository.py b/products/signals/backend/test/test_source_repository.pynew file mode 100644index 000000000000..4b2eefafc61f--- /dev/null+++ b/products/signals/backend/test/test_source_repository.py@@ -0,0 +1,66 @@+from datetime import UTC, datetime++import pytest+from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, patch++from asgiref.sync import async_to_sync++from products.signals.backend.agent_runtime import DEFAULT_RUNTIME+from products.signals.backend.report_generation import select_repo+from products.signals.backend.report_generation.source_repository import source_repository_from_signals+from products.signals.backend.temporal.types import SignalData+from products.tasks.backend.facade.repo_selection_types import RepoSelectionResult++ISSUE_URL = "https://github.com/PostHog/posthog/issues/105295"+++def _signal(+ *,+ source_product: str = "github",+ source_type: str = "issue",+ extra: dict | None = None,+) -> SignalData:+ return SignalData(+ signal_id="s1",+ content="Something is broken",+ source_product=source_product,+ source_type=source_type,+ source_id="1",+ weight=1.0,+ timestamp=datetime(2026, 1, 1, tzinfo=UTC),+ extra={"html_url": ISSUE_URL} if extra is None else extra,+ )+++ "signals,expected",+ [+ ([_signal()], "posthog/posthog"),+ ([_signal(), _signal(extra={"html_url": "https://github.com/PostHog/posthog/issues/999"})], "posthog/posthog"),+ # Two repositories name neither: picking between them is the wrong-repo failure itself.+ ([_signal(), _signal(extra={"html_url": "https://github.com/posthog/posthog-js/issues/1"})], None),+ # A support ticket that quotes an issue link does not make that repository its source.+ ([_signal(source_product="zendesk", source_type="ticket")], None),+ ([_signal(extra={})], None),+ ([_signal(extra={"html_url": "https://github.com.evil.tld/posthog/posthog/issues/1"})], None),+ ([_signal(extra={"html_url": 42})], None),+ ([], None),+ ],+)+def test_source_repository_from_signals(signals: list[SignalData], expected: str | None) -> None:+ assert source_repository_from_signals(signals) == expected+++class TestSelectRepositoryPinsTheSourceRepository(BaseTest):+ def test_report_selection_pins_the_repository_its_issue_was_filed_against(self):+ select = AsyncMock(return_value=RepoSelectionResult(repository="posthog/posthog", reason="pinned"))+ with (+ patch.object(select_repo, "select_repository", new=select),+ patch.object(select_repo, "resolve_agent_runtime", return_value=DEFAULT_RUNTIME),+ patch.object(select_repo, "wrong_repo_corrections_block", return_value=None),+ ):+ async_to_sync(select_repo.select_repository_for_report)(self.team.id, self.user.id, [_signal()])++ assert select.await_args is not None+ assert select.await_args.kwargs["pinned_repository"] == "posthog/posthog"diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.pyindex d464271a8bd9..3f94d044e6e8 100644--- a/products/tasks/backend/logic/repo_selection/agent.py+++ b/products/tasks/backend/logic/repo_selection/agent.py@@ -519,6 +519,32 @@ context and repo names alone.</jsonschema>"""+# Tells a pinned pick from an agent's pick when reading a stored `repo_selection` artefact.+PINNED_REPOSITORY_REASON = "The request names this repository as its source."+++def _pinned_selection(pinned_repository: str, candidate_repos: list[str]) -> RepoSelectionResult:+ """Honor a repository the request names, or refuse to select a different one.++ Matched against the eligible candidates rather than the raw connected list, so the pin and the+ agent agree on what is reachable: a repository the agent could not have picked is not one a pin+ may reach either. That is what puts this check after the cache hydration above, whose result the+ pinned path otherwise does not need. Candidates are lowercased, so the pin is too.+ """+ pinned = pinned_repository.strip().lower()+ if pinned in candidate_repos:+ return RepoSelectionResult(repository=pinned, reason=PINNED_REPOSITORY_REASON)+ logger.info("repo_selection.pinned_repository_unavailable", extra={"pinned": pinned})+ return RepoSelectionResult(+ repository=None,+ reason=(+ f"This report comes from `{pinned}`, which this project's GitHub installation cannot "+ "reach. Connect that repository, or pick one yourself. No other repository is a "+ "substitute for the one the report names."+ ),+ )++async def select_repository(team_id: int,user_id: int,@@ -538,6 +564,7 @@ async def select_repository(reasoning_effort: str | None = None,service_tier: str | None = None,past_corrections: str | None = None,+ pinned_repository: str | None = None,) -> RepoSelectionResult:"""Select the most relevant repository for a free-form request context.@@ -547,6 +574,12 @@ async def select_repository(`past_corrections` is an optional pre-rendered block of the caller's previous selectionsthat a reviewer marked wrong; see `_build_repo_selection_prompt`.+ `pinned_repository` is a repository the request itself names — a GitHub issue says which+ repository it was filed against, and that is the answer, not a question for the agent. When it+ is an eligible candidate it is returned as-is. When it is not, the result is `repository=None`+ carrying the mismatch: the agent would otherwise pick a similar-looking repository and send the+ work somewhere the request never pointed at.+Callers that have already resolved the integration and candidate list (e.g. to run theirown cheap early-exit first) may pass `github` and `candidate_repos` to skip the redundantfetches; otherwise they're resolved here.@@ -593,6 +626,8 @@ async def select_repository(raise RepoSelectionUnavailableError("No connected GitHub repositories are eligible (archived or missing cache data).")+ if pinned_repository is not None:+ return _pinned_selection(pinned_repository, candidate_repos)if len(candidate_repos) == 1:return RepoSelectionResult(repository=candidate_repos[0],diff --git a/products/tasks/backend/tests/test_repo_selection_prompt.py b/products/tasks/backend/tests/test_repo_selection_prompt.pyindex 1520170ffa1a..975883d2cbf1 100644--- a/products/tasks/backend/tests/test_repo_selection_prompt.py+++ b/products/tasks/backend/tests/test_repo_selection_prompt.py@@ -6,6 +6,7 @@ from asgiref.sync import async_to_syncfrom posthog.models.repo_routing_rule import RepoRoutingRulefrom products.tasks.backend.logic.repo_selection.agent import (+ PINNED_REPOSITORY_REASON,_build_repo_selection_prompt,_routing_rules_block,select_repository,@@ -120,3 +121,58 @@ def test_select_repository_renders_team_rules_and_visibility_into_prompt() -> Noassert "1. Support app asks → `acme/b`" in promptassert "1. `acme/a` (private)" in promptassert "2. `acme/b` (visibility unknown)" in prompt+++ "pinned,expected_repository",+ [("Acme/B", "acme/b"), (" acme/b ", "acme/b"), ("acme/gone", None)],+)+def test_pinned_repository_answers_without_running_the_agent(pinned: str, expected_repository: str | None) -> None:+ start = AsyncMock()+ github = MagicMock()+ github.list_all_cached_repositories.return_value = [{"full_name": "acme/a"}, {"full_name": "acme/b"}]++ with (+ patch(f"{_AGENT}.GitHubRepositoryFullCache") as cache,+ patch(f"{_AGENT}._list_eligible_full_names", return_value={"acme/a", "acme/b"}),+ patch(f"{_AGENT}.MultiTurnSession.start", start),+ ):+ cache.return_value.sync_full_cache = AsyncMock()+ selected = async_to_sync(select_repository)(+ 1,+ 1,+ "which repo?",+ origin_product=Task.OriginProduct.SLACK,+ github=github,+ candidate_repos=["acme/a", "acme/b"],+ pinned_repository=pinned,+ )++ assert selected.repository == expected_repository+ if expected_repository:+ assert selected.reason == PINNED_REPOSITORY_REASON+ else:+ assert "acme/gone" in selected.reason+ start.assert_not_awaited()+++def test_pinned_repository_beats_the_single_candidate_shortcut() -> None:+ github = MagicMock()+ github.list_all_cached_repositories.return_value = [{"full_name": "acme/a"}]++ with (+ patch(f"{_AGENT}.GitHubRepositoryFullCache") as cache,+ patch(f"{_AGENT}._list_eligible_full_names", return_value={"acme/a"}),+ ):+ cache.return_value.sync_full_cache = AsyncMock()+ selected = async_to_sync(select_repository)(+ 1,+ 1,+ "which repo?",+ origin_product=Task.OriginProduct.SLACK,+ github=github,+ candidate_repos=["acme/a"],+ pinned_repository="acme/b",+ )++ assert selected.repository is None