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(signals): resolve report repo implicitly for Create PR/Discuss (#73648)

Michael Matloka6b623f634259
diff --git a/frontend/src/scenes/inbox/inboxTaskKickoffLogic.ts b/frontend/src/scenes/inbox/inboxTaskKickoffLogic.ts
index 2988bcc72733..382004a50079 100644
--- a/frontend/src/scenes/inbox/inboxTaskKickoffLogic.ts
+++ b/frontend/src/scenes/inbox/inboxTaskKickoffLogic.ts
@@ -29,11 +29,6 @@ import { aiConsentDisabledReason } from './utils/aiConsent'
// NOT a live chat surface. The created task carries the SignalReport linkage so the
// backend's agent pipeline can pick it up.
-// Report artefacts are paginated newest-first (default page size 100); `repo_selection` is
-// written early in a research run, so a generous limit keeps it on the fetched page even for
-// reports with many findings.
-const REPO_SELECTION_ARTEFACT_FETCH_LIMIT = 1000
-
// The run endpoint rejects a model without its runtime adapter, so the two are always sent together.
type ClaudeRuntimeSelection = Pick<ClaudeTaskRunCreateSchemaApi, 'runtime_adapter' | 'model' | 'reasoning_effort'>
@@ -68,41 +63,13 @@ async function createReportTask(
relationship: SignalReportTaskRelationship,
prompt: string,
fallbackTitle: string,
- requireRepository = false,
runtimeSelection?: ClaudeRuntimeSelection
): Promise<void> {
- // Use the repository the signals pipeline already selected for this report (its
- // `repo_selection` artefact), matching the desktop app and the auto-start flow. Never fall
- // back to an arbitrary project repo — `repositories[0]` previously leaked whichever repo
- // sorted first (e.g. a personal repo) and pinned the task to the wrong codebase.
- // Artefacts are paginated newest-first and `repo_selection` is written early in the run, so
- // fetch a high limit to keep it on the page even for reports with many findings.
- let repository: string | undefined
- try {
- const { results } = await api.signalReports.artefacts(report.id, { limit: REPO_SELECTION_ARTEFACT_FETCH_LIMIT })
- const selected = results.find((a) => a.type === 'repo_selection')?.content?.repository
- repository = typeof selected === 'string' && selected ? selected : undefined
- } catch (e) {
- // A genuine fetch failure must not masquerade as "no repository selected" — when a repo
- // is required, surface the real error so the user retries instead of waiting on analysis.
- if (requireRepository) {
- throw e
- }
- repository = undefined
- }
-
- // Opening a PR needs a concrete target repo. If selection hasn't resolved one (e.g. a
- // pending-input report), fail with a clear message instead of creating a task pinned to no
- // repository that can never open a PR. Discuss doesn't require a repo.
- if (requireRepository && !repository) {
- throw new Error('No repository has been selected for this report yet — try again once analysis finishes.')
- }
-
+ // `repository` is intentionally omitted: the backend resolves it for signal_report tasks.
const task = await api.tasks.create({
title: report.title?.trim() || fallbackTitle,
description: prompt,
origin_product: OriginProduct.SIGNAL_REPORT,
- repository,
// Linkage fields accepted by the tasks backend for the signal_report origin.
signal_report: report.id,
signal_report_task_relationship: relationship,
@@ -240,7 +207,6 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([
SIGNAL_REPORT_TASK_DISCUSSION_RELATIONSHIP,
buildDiscussReportPrompt(reportUrl, question),
'Discuss report',
- false,
DISCUSS_RUNTIME
)
actions.discussReportSuccess()
@@ -260,8 +226,7 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([
report,
SIGNAL_REPORT_TASK_IMPLEMENTATION_RELATIONSHIP,
buildCreatePrReportPrompt(report),
- 'Implement report fix',
- true
+ 'Implement report fix'
)
actions.createPrSuccess()
} catch (error: any) {
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index ea8867ac119e..91250903c1da 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -1692,10 +1692,12 @@ class GitHubIntegrationBase:
has_more = offset + limit < len(filtered)
return result, has_more
- def list_all_cached_repositories(self, max_repos: int | None = None) -> list[dict]:
+ def list_all_cached_repositories(self, max_repos: int | None = None, *, allow_refresh: bool = True) -> list[dict]:
cached_repositories = self._get_stored_repository_list()
has_cached_snapshot = self.integration.repository_cache_updated_at is not None
- should_refresh = cached_repositories is None or self.repository_cache_is_stale()
+ # `allow_refresh=False` keeps this a pure cache read — no live GitHub sync, no token refresh,
+ # no DB write — for callers on a latency-sensitive path that accept a stale snapshot.
+ should_refresh = allow_refresh and (cached_repositories is None or self.repository_cache_is_stale())
self._record_github_cache_access("repositories", "miss" if should_refresh else "hit", "__all__")
if should_refresh:
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index eb3791f11706..4a7feb962635 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -1,6 +1,7 @@
import dataclasses
from collections.abc import Sequence
from datetime import timedelta
+from typing import TYPE_CHECKING
from django.conf import settings
from django.db import transaction
@@ -20,6 +21,9 @@ from posthog.temporal.common.client import async_connect
from products.signals.backend.contracts import SIGNAL_VARIANT_LOOKUP, SignalRemediation
from products.signals.backend.models import SignalSourceConfig
+if TYPE_CHECKING:
+ from products.tasks.backend.facade.repo_selection import RepoSelectionResult
+
logger = structlog.get_logger(__name__)
MAX_SIGNAL_DESCRIPTION_TOKENS = 8000
@@ -139,6 +143,15 @@ def dismiss_report_from_slack(
return suppress_report_from_slack(team_id, report_id, slack_user_id=slack_user_id, user_id=user_id)
+def persisted_repo_selection(report_id: str) -> "RepoSelectionResult | None":
+ """Facade entrypoint for a report's latest repo selection. See select_repo.persisted_repo_selection."""
+ from products.signals.backend.report_generation.select_repo import (
+ persisted_repo_selection as persisted_repo_selection_impl, # noqa: PLC0415 — avoids importing model layer at facade import time
+ )
+
+ return persisted_repo_selection_impl(report_id)
+
+
def get_default_slack_notification_channel(team_id: int) -> str | None:
"""Team-default Slack channel for signal notifications, stored as "<channel_id>|#name"."""
from products.signals.backend.models import (
diff --git a/products/signals/backend/report_generation/select_repo.py b/products/signals/backend/report_generation/select_repo.py
index ed9b1f5f3931..d194c056fe05 100644
--- a/products/signals/backend/report_generation/select_repo.py
+++ b/products/signals/backend/report_generation/select_repo.py
@@ -17,6 +17,7 @@ from typing import TYPE_CHECKING
from posthog.sync import database_sync_to_async
from products.signals.backend.agent_runtime import STEP_REPO_SELECTION, resolve_agent_runtime
+from products.signals.backend.models import SignalReportArtefact
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.repo_selection import (
REPO_SELECTION_DUMMY_REPOSITORY,
@@ -40,12 +41,29 @@ __all__ = [
"REPO_SELECTION_DUMMY_REPOSITORY",
"RepoSelectionRejectedError",
"RepoSelectionResult",
+ "persisted_repo_selection",
"resolve_team_github_integration",
"select_repository_for_report",
"select_repository_for_team",
]
+def persisted_repo_selection(report_id: str) -> RepoSelectionResult | None:
+ """The report's latest ``repo_selection`` artefact, or ``None`` if it has none yet.
+
+ A result with ``repository=None`` is a deliberate no-repo decision (nothing to fix in code),
+ not "unresolved" — callers must not treat the two the same.
+ """
+ artefact = (
+ SignalReportArtefact.objects.filter(report_id=report_id, type=SignalReportArtefact.ArtefactType.REPO_SELECTION)
+ .order_by("-created_at")
+ .first()
+ )
+ if artefact is None:
+ return None
+ return RepoSelectionResult.model_validate_json(artefact.content)
+
+
async def select_repository_for_team(
team_id: int,
user_id: int,
diff --git a/products/signals/backend/temporal/agentic/select_repository.py b/products/signals/backend/temporal/agentic/select_repository.py
index 6ba792df4513..d4d0c57f6c5d 100644
--- a/products/signals/backend/temporal/agentic/select_repository.py
+++ b/products/signals/backend/temporal/agentic/select_repository.py
@@ -13,9 +13,9 @@ from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import aretry_on_db_connection_drop, close_db_connections
-from products.signals.backend.models import SignalReportArtefact
from products.signals.backend.report_generation.select_repo import (
RepoSelectionResult,
+ persisted_repo_selection,
resolve_team_github_integration,
select_repository_for_report,
)
@@ -85,21 +85,6 @@ def _capture_repo_research_event(
)
-def _load_previous_repo_selection(report_id: str) -> RepoSelectionResult | None:
- """Load a previous repo_selection artefact for this report, if one exists."""
- artefact = (
- SignalReportArtefact.objects.filter(
- report_id=report_id,
- type=SignalReportArtefact.ArtefactType.REPO_SELECTION,
- )
- .order_by("-created_at")
- .first()
- )
- if artefact is None:
- return None
- return RepoSelectionResult.model_validate_json(artefact.content)
-
-
@temporalio.activity.defn
@scoped_temporal()
@close_db_connections
@@ -126,7 +111,7 @@ async def select_repository_activity(input: SelectRepositoryInput) -> RepoSelect
async with Heartbeater():
# Check for a previous selection from an earlier run, if any
previous = await aretry_on_db_connection_drop(
- lambda: database_sync_to_async(_load_previous_repo_selection, thread_sensitive=False)(input.report_id)
+ lambda: database_sync_to_async(persisted_repo_selection, thread_sensitive=False)(input.report_id)
)
if previous is not None and previous.repository is not None:
logger.info(
diff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.py
index 551ee912e759..c7530952f268 100644
--- a/products/signals/backend/test/test_agentic_report_activity.py
+++ b/products/signals/backend/test/test_agentic_report_activity.py
@@ -187,7 +187,7 @@ def _build_signals() -> list[SignalData]:
@pytest.mark.django_db
async def test_select_repository_activity_returns_repo(monkeypatch, ateam):
monkeypatch.setattr(
- "products.signals.backend.temporal.agentic.select_repository._load_previous_repo_selection",
+ "products.signals.backend.temporal.agentic.select_repository.persisted_repo_selection",
lambda report_id: None,
)
monkeypatch.setattr(
@@ -218,7 +218,7 @@ async def test_select_repository_activity_reuses_previous_selection(monkeypatch,
previous = RepoSelectionResult(repository="posthog/posthog", reason="Previously selected")
monkeypatch.setattr(
- "products.signals.backend.temporal.agentic.select_repository._load_previous_repo_selection",
+ "products.signals.backend.temporal.agentic.select_repository.persisted_repo_selection",
lambda report_id: previous,
)
@@ -259,7 +259,7 @@ async def test_select_repository_activity_retries_transient_db_drop(monkeypatch,
return previous
monkeypatch.setattr(
- "products.signals.backend.temporal.agentic.select_repository._load_previous_repo_selection",
+ "products.signals.backend.temporal.agentic.select_repository.persisted_repo_selection",
flaky_load,
)
@@ -276,7 +276,7 @@ async def test_select_repository_activity_retries_transient_db_drop(monkeypatch,
@pytest.mark.django_db
async def test_select_repository_activity_no_repo(monkeypatch, ateam):
monkeypatch.setattr(
- "products.signals.backend.temporal.agentic.select_repository._load_previous_repo_selection",
+ "products.signals.backend.temporal.agentic.select_repository.persisted_repo_selection",
lambda report_id: None,
)
monkeypatch.setattr(
@@ -320,7 +320,7 @@ async def test_select_repository_activity_does_not_raise_with_only_user_integrat
)
monkeypatch.setattr(
- "products.signals.backend.temporal.agentic.select_repository._load_previous_repo_selection",
+ "products.signals.backend.temporal.agentic.select_repository.persisted_repo_selection",
lambda report_id: None,
)
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index b49f702b0c3f..74c3ede6f38e 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -4077,6 +4077,39 @@ def create_task(team_id: int, user_id: int | None, *, validated_data: dict) -> c
if default_integration:
validated_data["github_integration"] = default_integration
+ # Inbox "Create PR" / "Discuss" don't pre-select a repo, so resolve one here rather than
+ # creating a report-linked task that can never open a PR.
+ signal_report = validated_data.get("signal_report")
+ if (
+ signal_report is not None
+ and not validated_data.get("repository")
+ and validated_data.get("origin_product") == Task.OriginProduct.SIGNAL_REPORT
+ ):
+ from products.signals.backend.facade.api import ( # noqa: PLC0415 — cross-product read kept off the api import path
+ persisted_repo_selection,
+ )
+ from products.tasks.backend.logic.repo_selection.cascade import ( # noqa: PLC0415 — keeps repo-selection agent imports lazy
+ cascade_select_repository,
+ )
+
+ # The report's own selection is authoritative — including a scout's deliberate no-repo
+ # (`repository=None`), which must not fall through to the cascade.
+ selection = persisted_repo_selection(str(signal_report.id))
+ resolved_repository = (
+ selection.repository
+ if selection is not None
+ else cascade_select_repository(
+ team_id,
+ user_id,
+ validated_data.get("description") or "",
+ team=team,
+ single_repo_wins=True,
+ allow_refresh=False,
+ )
+ )
+ if resolved_repository:
+ validated_data["repository"] = resolved_repository
+
if (
validated_data.get("repository")
and validated_data.get("origin_product", Task.OriginProduct.USER_CREATED) == Task.OriginProduct.USER_CREATED
diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.py
index e34bb8246d58..83e9c2aa281a 100644
--- a/products/tasks/backend/logic/repo_selection/agent.py
+++ b/products/tasks/backend/logic/repo_selection/agent.py
@@ -168,10 +168,10 @@ async def _github_reconnect_required(team_id: int) -> bool:
).aexists()
-def _list_candidate_repos(github: GitHubIntegrationBase, team_id: int) -> list[str]:
+def _list_candidate_repos(github: GitHubIntegrationBase, team_id: int, *, allow_refresh: bool = True) -> list[str]:
"""Fetch all repositories accessible via the resolved GitHub source."""
repos: set[str] = set()
- for repo in github.list_all_cached_repositories(max_repos=_MAX_GITHUB_REPOS):
+ for repo in github.list_all_cached_repositories(max_repos=_MAX_GITHUB_REPOS, allow_refresh=allow_refresh):
full_name = repo.get("full_name")
if not full_name:
continue
diff --git a/products/tasks/backend/logic/repo_selection/cascade.py b/products/tasks/backend/logic/repo_selection/cascade.py
index 2cafea7a75c2..7078d2c56df0 100644
--- a/products/tasks/backend/logic/repo_selection/cascade.py
+++ b/products/tasks/backend/logic/repo_selection/cascade.py
@@ -1,6 +1,7 @@
import logging
from posthog.git import extract_explicit_repo
+from posthog.models.team import Team
from posthog.sync import database_sync_to_async
from products.tasks.backend.logic.repo_selection.agent import _list_candidate_repos, resolve_team_github_integration
@@ -9,35 +10,54 @@ from products.tasks.backend.models import Task
logger = logging.getLogger(__name__)
-async def select_repository_for_message(
+def cascade_select_repository(
team_id: int,
- user_id: int,
+ user_id: int | None,
message: str,
*,
- origin_product: Task.OriginProduct,
+ team: Team | None = None,
+ single_repo_wins: bool = False,
+ allow_refresh: bool = True,
) -> str | None:
- """Pick a connected repository only when the message names it explicitly.
-
- The sandbox conversation open path must stay fast: it runs before the Run is created, so we
- avoid the repo-selection LLM agent here. Messages without an explicit connected `owner/repo`
- mention return `None`, which starts a repo-less sandbox. Selection must never block the
- conversation from starting, so this never raises — every failure degrades to "no repo".
-
- This is the user-initiated path, so we pass `user_id` as the requester: their own connected
- GitHub is a valid source even if they aren't an org owner (it's their own credentials, not a
- cross-account leak), letting them reference repos only they have connected.
+ """Pick a connected repository without the sandbox-backed selection agent.
+
+ Resolves only the trivial cases: with ``single_repo_wins``, a lone connected repo is taken
+ directly; otherwise the message has to name a connected ``owner/repo`` explicitly. Anything
+ ambiguous returns `None` and the caller starts a repo-less run rather than paying for agentic
+ discovery. Selection must never block that run from starting, so this never raises — every
+ failure degrades to "no repo".
+
+ ``user_id`` is passed as the requester, so their own connected GitHub stands in when the team
+ has no team-level integration (their own credentials, not a cross-account leak), letting them
+ reference repos only they have connected. ``allow_refresh=False`` reads only the cached repo
+ list, so a caller on the request path never blocks on a live GitHub sync.
"""
try:
- github = await database_sync_to_async(resolve_team_github_integration, thread_sensitive=False)(
- team_id, requester_user_id=user_id
- )
+ github = resolve_team_github_integration(team_id, team=team, requester_user_id=user_id)
if github is None:
return None
- candidates = await database_sync_to_async(_list_candidate_repos, thread_sensitive=False)(github, team_id)
+ candidates = _list_candidate_repos(github, team_id, allow_refresh=allow_refresh)
if not candidates:
return None
-
+ if single_repo_wins and len(candidates) == 1:
+ return candidates[0]
return extract_explicit_repo(message, candidates)
except Exception:
- logger.warning("repo_selection_for_message.failed team_id=%s", team_id, exc_info=True)
+ logger.warning("cascade_select_repository.failed team_id=%s", team_id, exc_info=True)
return None
+
+
+async def select_repository_for_message(
+ team_id: int,
+ user_id: int,
+ message: str,
+ *,
+ origin_product: Task.OriginProduct,
+) -> str | None:
+ """Pick a connected repository only when the message names it explicitly.
+
+ The sandbox conversation open path must stay fast: it runs before the Run is created, so we
+ avoid the repo-selection LLM agent here. A lone connected repo is deliberately *not* assumed —
+ an unprompted mention shouldn't pin a sandbox to a repo the user never named.
+ """
+ return await database_sync_to_async(cascade_select_repository, thread_sensitive=False)(team_id, user_id, message)
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 4fa9dffbe986..333f974d21e8 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -32,6 +32,7 @@ from posthog.storage import object_storage
from products.slack_app.backend.models import SlackThreadTaskMapping
from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.repo_selection import RepoSelectionResult
from products.tasks.backend.logic.services.code_usage_gate import (
CodeUsageStatus,
_gateway_usage_url,
@@ -1452,6 +1453,54 @@ class TestTaskAPI(BaseTaskAPITest):
).exists()
)
+ @parameterized.expand(
+ [
+ # no artefact yet → cascade picks the team's only connected repo, so "Create PR" works
+ # without the client pre-selecting one
+ ("no_selection", False, None, "acme/web"),
+ # a persisted selection wins over the cascade, even when it names another repo
+ ("persisted_repo", True, "acme/api", "acme/api"),
+ # a scout's deliberate no-repo must not fall through to the cascade
+ ("persisted_no_repo", True, None, None),
+ ]
+ )
+ def test_create_signal_report_task_resolves_repository_when_none_provided(
+ self, _name, has_artefact, persisted_repository, expected_repository
+ ):
+ from products.signals.backend.models import SignalReport, SignalReportArtefact
+
+ Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="gh-cascade",
+ config={"installation_id": "gh-cascade"},
+ sensitive_config={},
+ repository_cache=[{"full_name": "acme/web", "name": "web", "id": 1}],
+ repository_cache_updated_at=django_timezone.now(),
+ )
+ report = SignalReport.objects.create(team=self.team)
+ if has_artefact:
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.REPO_SELECTION,
+ content=RepoSelectionResult(repository=persisted_repository, reason="test").model_dump_json(),
+ )
+
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {
+ "title": "Signal Task",
+ "description": "From a signal report",
+ "origin_product": "signal_report",
+ "signal_report": str(report.id),
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.json()["repository"], expected_repository)
+
def test_create_task_with_signal_report_discussion_records_artefact_without_gate_row(self):
from products.signals.backend.models import SignalReport, SignalReportTask
from products.signals.backend.task_run_artefacts import (
diff --git a/products/tasks/backend/tests/test_repo_selection_cascade.py b/products/tasks/backend/tests/test_repo_selection_cascade.py
index 04590f00685f..32fcf65433d9 100644
--- a/products/tasks/backend/tests/test_repo_selection_cascade.py
+++ b/products/tasks/backend/tests/test_repo_selection_cascade.py
@@ -1,6 +1,9 @@
+import pytest
from unittest.mock import MagicMock, patch
-from products.tasks.backend.logic.repo_selection.cascade import select_repository_for_message
+from posthog.models.integration import Integration
+
+from products.tasks.backend.logic.repo_selection.cascade import cascade_select_repository, select_repository_for_message
from products.tasks.backend.models import Task
_CASCADE = "products.tasks.backend.logic.repo_selection.cascade"
@@ -37,3 +40,30 @@ class TestSelectRepositoryForMessage:
resolve, list_repos = _patch_candidates(MagicMock(), ["posthog/posthog", "posthog/posthog-js"])
with resolve, list_repos:
assert await _run("the dashboards are slow") is None
+
+
+class TestCascadeSelectRepository:
+ @pytest.mark.parametrize("single_repo_wins,expected", [(True, "posthog/posthog"), (False, None)])
+ def test_lone_repo_only_taken_when_opted_in(self, single_repo_wins, expected):
+ # Inbox report actions opt in (a single-repo team has no ambiguity to resolve); an unprompted
+ # sandbox message doesn't, so it never pins itself to a repo the user never named.
+ resolve, list_repos = _patch_candidates(MagicMock(), ["posthog/posthog"])
+ with resolve, list_repos:
+ assert cascade_select_repository(1, 2, "", single_repo_wins=single_repo_wins) == expected
+
+ @pytest.mark.django_db
+ def test_unsynced_cache_is_read_without_a_live_sync(self, team):
+ # Request-path callers pass allow_refresh=False, so a never-synced cache
+ # (repository_cache_updated_at is null) is still read rather than triggering a GitHub sync.
+ Integration.objects.create(
+ team=team,
+ kind="github",
+ integration_id="gh-1",
+ config={"installation_id": "gh-1"},
+ sensitive_config={},
+ repository_cache=[{"full_name": "PostHog/PostHog", "name": "PostHog", "id": 1}],
+ )
+
+ assert cascade_select_repository(team.id, None, "", single_repo_wins=True, allow_refresh=False) == (
+ "posthog/posthog"
+ )