: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): use issue repositories as routing defaults (#124298)
Alex Lebedev380a835f5e01
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.mdindex 24a6cf5290f3..e101bae8004a 100644--- a/docs/internal/signals-pr-lifecycle.md+++ b/docs/internal/signals-pr-lifecycle.md@@ -179,10 +179,24 @@ New metric checks validate numeric goals and baselines against their metric kind## Repository selection-The shared repository selection prompt asks the agent to check the sources in the supplied context before choosing a repository.+For reports built from GitHub issues, the issue repository is a default when it is an eligible candidate.+With multiple permitted candidates, selection can choose another repository based on code ownership, applicable routing rules, or past wrong-repository corrections.+Matching paths can be vendored, generated, or mirrored copies; ownership evidence takes precedence over the source default.+If the evidence otherwise leaves candidates equally plausible, selection prefers the issue repository.+Selection sandboxes use read-only GitHub credentials and read-only PostHog scopes to inspect repositories and query the cache.++The selector checks cached source visibility before the single-candidate shortcut or the agent runs, including when the source is not eligible.+If the source is not confirmed public, the permitted destinations are the eligible source itself and eligible repositories confirmed private.+Missing or non-boolean visibility metadata is unconfirmed.+If no permitted destination remains, selection returns no repository.+A confirmed public source does not restrict destination visibility, so an unavailable public source can still route to another eligible repository.+The restricted candidate list governs both the prompt and validation of the agent's result.+A single permitted repository is selected without running the agent, and re-research reuses a stored non-null repository selection.++The shared repository selection prompt also asks the agent to check other sources in the supplied context before choosing a repository.For information from a private repository or another explicitly private source, it prefers a relevant private candidate and returns no repository if none is suitable or its visibility cannot be confirmed.Each candidate carries a private, public, or unknown label from the cached GitHub repository list, so the agent does not query GitHub for visibility.-This is prompt guidance, not an enforced access control, and it does not validate repositories selected outside the agent.+These broader context checks remain prompt guidance; the source-repository restriction does not validate selections made outside the shared selector.## Reviewer notificationsdiff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.mdindex ae50dd7ddce0..ae8b65aaf50d 100644--- a/products/signals/backend/report_generation/AGENTS.md+++ b/products/signals/backend/report_generation/AGENTS.md@@ -7,15 +7,16 @@ It is exercised locally via management commands, and it is also used by the prod- `select_repo.py`Selects the most relevant GitHub repository for a set of signals.- - If the team has 0 repos: returns `None` (report goes to `pending_input`).- - If the team has 1 repo: returns it directly (no sandbox needed).- - If the team has N repos: spawns a sandbox agent that uses `gh` CLI to explore candidates and pick the best match. Uses `PostHog/.github` as a small dummy repo for the sandbox clone, since the agent only needs `gh` CLI access (not the repo itself).+ - If no eligible repo passes the source-visibility check: returns `None` (report goes to `pending_input`).+ - If 1 eligible repo passes the source-visibility check: returns it directly (no sandbox needed).+ - If multiple eligible repos pass the source-visibility check: spawns a sandbox agent that uses `gh` CLI to explore candidates and pick the best match. Uses `PostHog/.github` as a small dummy repo for the sandbox clone, since the agent only needs `gh` CLI access (not the repo itself).- 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`.+ - A source repository is the agent's default when eligible. Code ownership, applicable routing rules, and past corrections can override it; matching paths alone do not establish ownership. Equally plausible candidates favor the source. See `source_repository.py`.+ - Before the shortcut or agent runs, a source not confirmed public restricts destinations to itself when eligible or to confirmed-private candidates. Missing or non-boolean visibility is unconfirmed. The restricted candidates also govern result validation.- `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.+ The repository a report's signals were filed against. A single unambiguous GitHub issue repository supplies a selection default; issues from two repositories supply none. An unavailable source can still route to an eligible confirmed-private repository, or to any eligible repository when the source is confirmed public.- `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 8a82d57e3101..d4e7975556c2 100644--- a/products/signals/backend/report_generation/select_repo.py+++ b/products/signals/backend/report_generation/select_repo.py@@ -77,7 +77,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,+ source_repository: str | None = None,) -> RepoSelectionResult:"""Select the most relevant repository for a free-form request against the team's repos.@@ -87,26 +87,17 @@ async def select_repository_for_team(— 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+ ``source_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.+ makes it the agent's default when the team can reach it; the agent can still select another."""- # 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)+ agent_runtime = 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)- )+ 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,@@ -120,12 +111,12 @@ async def select_repository_for_team(sandbox_environment_id=sandbox_environment_id,verbose=verbose,output_fn=output_fn,- 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,+ model=agent_runtime.model,+ runtime_adapter=agent_runtime.runtime_adapter,+ reasoning_effort=agent_runtime.reasoning_effort,+ service_tier=agent_runtime.service_tier,past_corrections=past_corrections,- pinned_repository=pinned_repository,+ source_repository=source_repository,)except RepoSelectionRejectedError as exc:# Preserve legacy behavior: surface validation reject as null with reason so callers'@@ -159,8 +150,9 @@ async def select_repository_for_report() -> RepoSelectionResult:"""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.+ Signals that name their own repository make it the default, so a report built from a GitHub+ issue targets the repository the issue was filed against unless the agent finds the code+ elsewhere."""from products.signals.backend.temporal.types import render_signals_to_text # noqa: PLC0415@@ -174,5 +166,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),+ source_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.pyindex 549a77f4bfe2..aefc7138f09e 100644--- a/products/signals/backend/report_generation/source_repository.py+++ b/products/signals/backend/report_generation/source_repository.py@@ -1,8 +1,9 @@"""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.+Repository selection makes it the agent's default (see `select_repo.py`). It is not the answer on+its own, because an issue filed in one repository often asks for a change in another, such as an+SDK, so the agent still checks where the code lives.Only a single unambiguous repository counts. A report that merges issues from two repositoriesnames neither, and guessing between them is the failure this module exists to prevent.diff --git a/products/signals/backend/test/test_repo_corrections.py b/products/signals/backend/test/test_repo_corrections.pyindex 7865b2641cca..efabbeeff616 100644--- a/products/signals/backend/test/test_repo_corrections.py+++ b/products/signals/backend/test/test_repo_corrections.py@@ -116,9 +116,12 @@ class TestSelectRepositoryPassesCorrections(BaseTest):patch.object(select_repo, "select_repository", new=select),patch.object(select_repo, "resolve_agent_runtime", return_value=runtime),):- result = async_to_sync(select_repo.select_repository_for_team)(self.team.id, self.user.id, "context")+ result = async_to_sync(select_repo.select_repository_for_team)(+ self.team.id, self.user.id, "context", source_repository="acme/website"+ )assert result.repository == "acme/checkout"block.assert_called_once_with(self.team.id)assert select.await_args is not Noneassert select.await_args.kwargs["past_corrections"] == "- entry"+ assert select.await_args.kwargs["source_repository"] == "acme/website"diff --git a/products/signals/backend/test/test_source_repository.py b/products/signals/backend/test/test_source_repository.pyindex 4b2eefafc61f..d55bccac0e47 100644--- a/products/signals/backend/test/test_source_repository.py+++ b/products/signals/backend/test/test_source_repository.py@@ -52,9 +52,9 @@ def test_source_repository_from_signals(signals: list[SignalData], expected: strassert 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"))+class TestSelectRepositoryDefaultsToTheSourceRepository(BaseTest):+ def test_report_selection_passes_the_repository_its_issue_was_filed_against(self):+ select = AsyncMock(return_value=RepoSelectionResult(repository="posthog/posthog", reason="selected"))with (patch.object(select_repo, "select_repository", new=select),patch.object(select_repo, "resolve_agent_runtime", return_value=DEFAULT_RUNTIME),@@ -63,4 +63,4 @@ class TestSelectRepositoryPinsTheSourceRepository(BaseTest):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"+ assert select.await_args.kwargs["source_repository"] == "posthog/posthog"diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.pyindex c0b7ce4b1add..c7998865625a 100644--- a/products/tasks/backend/logic/repo_selection/agent.py+++ b/products/tasks/backend/logic/repo_selection/agent.py@@ -286,8 +286,8 @@ def _visibility_label(private: bool | None) -> str:return "private" if private else "public"-def _candidate_visibility(github: GitHubIntegrationBase, candidate_repos: list[str]) -> dict[str, bool | None]:- """The `private` flag of each candidate from the light cache, or None when the cached entry lacks it.+def _candidate_visibility(github: GitHubIntegrationBase, repositories: list[str]) -> dict[str, bool | None]:+ """The `private` flag of each requested repository, including an ineligible source, from the light cache.A pure cache read: `_list_candidate_repos` already refreshed the cache when it was stale, so asecond refresh would only cost another GitHub round trip. Entries synced before the flag was@@ -300,7 +300,16 @@ def _candidate_visibility(github: GitHubIntegrationBase, candidate_repos: list[scontinueprivate = repo.get("private")cached[full_name.lower()] = private if isinstance(private, bool) else None- return {repo: cached.get(repo) for repo in candidate_repos}+ return {repo: cached.get(repo) for repo in repositories}+++def _filter_candidates_by_source_visibility(+ source_repository: str | None, candidate_repos: list[str], visibility: Mapping[str, bool | None]+) -> list[str]:+ """Unknown source visibility cannot justify moving issue content to a public repository."""+ if source_repository is None or visibility.get(source_repository) is False:+ return candidate_repos+ return [repo for repo in candidate_repos if repo == source_repository or visibility.get(repo) is True]def _build_repo_selection_prompt(@@ -310,6 +319,7 @@ def _build_repo_selection_prompt(past_corrections: str | None = None,routing_rules: str | None = None,visibility: Mapping[str, bool | None] | None = None,+ source_repository: str | None = None,) -> str:"""Build the prompt for the sandbox agent to select the most relevant repository.@@ -330,6 +340,10 @@ def _build_repo_selection_prompt(`visibility` maps each candidate to its GitHub `private` flag (see `_candidate_visibility`).A candidate missing from it, or the whole argument left None, renders as unknown visibility,which the source privacy rule treats as unconfirmed.++ `source_repository` is a candidate the request was filed against (e.g. a GitHub issue's+ repository). It is the default answer, not the only one: an issue filed in one repository+ often asks for a change in another, such as an SDK."""schema = RepoSelectionResult.model_json_schema()# `task_id` is system-set after the run — keep it out of the agent's output contract.@@ -343,6 +357,23 @@ def _build_repo_selection_prompt(f"{i + 1}. `{repo}` ({_visibility_label(visibility.get(repo))})" for i, repo in enumerate(candidate_repos))+ source_section = (+ f"""+## Source repository++The request was filed as an issue in `{source_repository}`. Select it by default. Select a different+candidate only on specific evidence that the code the request describes lives there: cache paths+or README content, a matching team routing rule, or a past correction below. An issue filed in one+repository often asks for a change in an SDK or another sibling repository. When the evidence+otherwise leaves two candidates equally plausible, prefer `{source_repository}`. Matching file+paths alone do not establish equal ownership: distinguish canonical code from vendored or mirrored+copies. Applicable routing rules, past corrections, and specific ownership evidence override the+source default.+"""+ if source_repository+ else ""+ )+rules_section = (f"""## Team routing rules (this project)@@ -403,7 +434,7 @@ If no relevant private candidate exists, or the relevant candidate's visibility## Candidate repositories (lowercased; full_name format is `owner/repo`; visibility in parentheses){repo_list}-{rules_section}{corrections_section}+{source_section}{rules_section}{corrections_section}## The cache (your source of truth — query it before answering)A Postgres-backed cache of every candidate repo's README, full file-tree paths, and metadata lives@@ -574,30 +605,15 @@ def _salvage_repo_selection(text: str, candidate_repos: list[str]) -> RepoSelect)-# 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.+def _eligible_source_repository(source_repository: str | None, candidate_repos: list[str]) -> str | None:+ """The source repository when it is a candidate, lowercased like the candidates, else None.- 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.+ A default the agent may not select would only steer it toward a rejected answer."""- 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."- ),- )+ if source_repository is None:+ return None+ source = source_repository.strip().lower()+ return source if source in candidate_repos else Noneasync def select_repository(@@ -620,7 +636,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,+ source_repository: str | None = None,) -> RepoSelectionResult:"""Select the most relevant repository for a free-form request context.@@ -630,11 +646,11 @@ 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.+ `source_repository` is a repository the request itself names — a GitHub issue says which+ repository it was filed against. When it is an eligible candidate the prompt makes it the+ default, and the agent still decides: the code an issue describes can live in another+ repository. Its visibility constrains destinations even when it is not an eligible candidate:+ a source that is not confirmed public can only stay in place or move to a confirmed private repo.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 redundant@@ -682,8 +698,20 @@ 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)++ source_repository = (source_repository or "").strip().lower() or None+ visibility = await database_sync_to_async(_candidate_visibility, thread_sensitive=False)(+ github, [*candidate_repos, source_repository] if source_repository else candidate_repos+ )+ candidate_repos = _filter_candidates_by_source_visibility(source_repository, candidate_repos, visibility)+ if not candidate_repos:+ return RepoSelectionResult(+ repository=None,+ reason=(+ "The source repository is private or its visibility is unknown, "+ "and no eligible private destination is available."+ ),+ )if len(candidate_repos) == 1:return RepoSelectionResult(repository=candidate_repos[0],@@ -693,13 +721,13 @@ async def select_repository(if output_fn:output_fn(f"Selecting repository from {len(candidate_repos)} candidates...")routing_rules = await database_sync_to_async(_routing_rules_block, thread_sensitive=False)(team_id, candidate_repos)- visibility = await database_sync_to_async(_candidate_visibility, thread_sensitive=False)(github, candidate_repos)prompt = _build_repo_selection_prompt(context,candidate_repos,past_corrections=past_corrections,routing_rules=routing_rules,visibility=visibility,+ source_repository=_eligible_source_repository(source_repository, candidate_repos),)sandbox_context = CustomPromptSandboxContext(team_id=team_id,@@ -708,6 +736,7 @@ async def select_repository(sandbox_environment_id=sandbox_environment_id,# Read-only PostHog scopes so the agent can call `execute-sql` against `system.integration_repository_cache`.posthog_mcp_scopes="read_only",+ github_read_access=True,sandbox_resources=SandboxResources(cpu_cores=2, memory_gb=8),# Optional agent runtime/model override (e.g. the Codex runtime + gpt-5.5). All-None keeps# the agent-server default; threaded through from the caller's per-step resolution.diff --git a/products/tasks/backend/tests/test_repo_selection_prompt.py b/products/tasks/backend/tests/test_repo_selection_prompt.pyindex a1748037fd69..e0cf35cd62d8 100644--- a/products/tasks/backend/tests/test_repo_selection_prompt.py+++ b/products/tasks/backend/tests/test_repo_selection_prompt.py@@ -8,7 +8,7 @@ from posthog.egress.limiter.policies import Priorityfrom posthog.models.repo_routing_rule import RepoRoutingRulefrom products.tasks.backend.logic.repo_selection.agent import (- PINNED_REPOSITORY_REASON,+ RepoSelectionRejectedError,RepoSelectionUsageLimitError,_build_repo_selection_prompt,_routing_rules_block,@@ -240,18 +240,50 @@ def test_select_repository_reports_a_usage_limit_refusal() -> None:)+def test_source_repository_section_included_only_when_given() -> None:+ base = _build_repo_selection_prompt("ctx", ["acme/a", "acme/b"])+ assert "## Source repository" not in base++ with_source = _build_repo_selection_prompt(+ "ctx",+ ["acme/a", "acme/b"],+ routing_rules="1. Support app asks → `acme/b`",+ source_repository="acme/b",+ )+ assert "filed as an issue in `acme/b`" in with_source+ assert (+ with_source.index("`acme/b`")+ < with_source.index("## Source repository")+ < with_source.index("Team routing rules")+ )++@pytest.mark.parametrize(- "pinned,expected_repository",- [("Acme/B", "acme/b"), (" acme/b ", "acme/b"), ("acme/gone", None)],+ "source,expected_in_prompt,routing_rules,past_corrections",+ [+ ("Acme/B", "acme/b", "1. Client library bugs belong in `acme/a`", None),+ (" acme/b ", "acme/b", None, "A reviewer corrected a client library report from `acme/b` to `acme/a`."),+ ("acme/gone", None, None, None),+ ],)-def test_pinned_repository_answers_without_running_the_agent(pinned: str, expected_repository: str | None) -> None:- start = AsyncMock()+def test_source_repository_is_a_default_for_the_agent_not_an_answer(+ source: str, expected_in_prompt: str | None, routing_rules: str | None, past_corrections: str | None+) -> None:+ result = RepoSelectionResult(repository="acme/a", reason="the code lives in acme/a")+ session = MagicMock()+ session.end = AsyncMock()+ start = AsyncMock(return_value=(session, result))github = MagicMock()- github.list_all_cached_repositories.return_value = [{"full_name": "acme/a"}, {"full_name": "acme/b"}]+ github.list_all_cached_repositories.return_value = [+ {"full_name": "acme/a", "private": False},+ {"full_name": "acme/b", "private": False},+ {"full_name": "acme/gone", "private": False},+ ]with (patch(f"{_AGENT}.GitHubRepositoryFullCache") as cache,patch(f"{_AGENT}._list_eligible_full_names", return_value={"acme/a", "acme/b"}),+ patch(f"{_AGENT}._routing_rules_block", return_value=routing_rules),patch(f"{_AGENT}.MultiTurnSession.start", start),):cache.return_value.sync_full_cache = AsyncMock()@@ -263,35 +295,138 @@ def test_pinned_repository_answers_without_running_the_agent(pinned: str, expectpriority=Priority.NORMAL,github=github,candidate_repos=["acme/a", "acme/b"],- pinned_repository=pinned,+ source_repository=source,+ past_corrections=past_corrections,)- assert selected.repository == expected_repository- if expected_repository:- assert selected.reason == PINNED_REPOSITORY_REASON+ assert selected.repository == "acme/a"+ assert start.call_args.kwargs["context"].github_read_access is True+ prompt = start.call_args.kwargs["prompt"]+ if expected_in_prompt:+ assert f"filed as an issue in `{expected_in_prompt}`" in promptelse:- assert "acme/gone" in selected.reason+ assert "## Source repository" not in prompt+ if routing_rules:+ assert routing_rules in prompt+ if past_corrections:+ assert past_corrections in prompt+++ "source_metadata,target_private,expected",+ [+ ({"private": True}, False, None),+ ({"private": True}, None, None),+ ({"private": True}, True, "acme/b"),+ ({"private": False}, False, "acme/b"),+ ({"private": False}, True, "acme/b"),+ ({}, False, None),+ (None, False, None),+ ({"private": "false"}, False, None),+ (None, True, "acme/b"),+ ],+)+def test_source_visibility_constrains_single_eligible_repository(+ source_metadata: dict[str, bool | str] | None, target_private: bool | None, expected: str | None+) -> None:+ github = MagicMock()+ cached_repositories = [{"full_name": "acme/b", "private": target_private}]+ if source_metadata is not None:+ cached_repositories.append({"full_name": "acme/a", **source_metadata})+ github.list_all_cached_repositories.return_value = cached_repositories+ start = AsyncMock()++ with (+ patch(f"{_AGENT}.GitHubRepositoryFullCache") as cache,+ patch(f"{_AGENT}._list_eligible_full_names", return_value={"acme/b"}),+ patch(f"{_AGENT}.MultiTurnSession.start", start),+ ):+ cache.return_value.sync_full_cache = AsyncMock()+ selected = async_to_sync(select_repository)(+ 1,+ 1,+ "Find the repository for this issue.",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ priority=Priority.NORMAL,+ github=github,+ candidate_repos=["acme/a", "acme/b"],+ source_repository=" Acme/A ",+ )++ assert selected.repository == expected+ assert "acme/a" not in selected.reasonstart.assert_not_awaited()-def test_pinned_repository_beats_the_single_candidate_shortcut() -> None:[email protected]("source_private", [None, True])+def test_nonpublic_source_can_keep_its_repository(source_private: bool | None) -> None:github = MagicMock()- github.list_all_cached_repositories.return_value = [{"full_name": "acme/a"}]+ github.list_all_cached_repositories.return_value = [+ {"full_name": "acme/a", "private": source_private},+ {"full_name": "acme/b", "private": False},+ ]with (patch(f"{_AGENT}.GitHubRepositoryFullCache") as cache,- patch(f"{_AGENT}._list_eligible_full_names", return_value={"acme/a"}),+ patch(f"{_AGENT}._list_eligible_full_names", return_value={"acme/a", "acme/b"}),):cache.return_value.sync_full_cache = AsyncMock()selected = async_to_sync(select_repository)(1,1,- "which repo?",- origin_product=Task.OriginProduct.SLACK,+ "Find the repository for this issue.",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,priority=Priority.NORMAL,github=github,- candidate_repos=["acme/a"],- pinned_repository="acme/b",+ candidate_repos=["acme/a", "acme/b"],+ source_repository="acme/a",)- assert selected.repository is None+ assert selected.repository == "acme/a"++[email protected]("selected_repository", ["acme/b", "acme/c"])+def test_source_visibility_constrains_agent_selection(selected_repository: str) -> None:+ result = RepoSelectionResult(repository=selected_repository, reason="Matching code.")+ session = MagicMock()+ session.end = AsyncMock()+ start = AsyncMock(return_value=(session, result))+ github = MagicMock()+ github.list_all_cached_repositories.return_value = [+ {"full_name": "acme/a", "private": True},+ {"full_name": "acme/b", "private": True},+ {"full_name": "acme/c", "private": False},+ {"full_name": "acme/d", "private": True},+ ]++ with (+ patch(f"{_AGENT}.GitHubRepositoryFullCache") as cache,+ patch(f"{_AGENT}._list_eligible_full_names", return_value={"acme/b", "acme/c", "acme/d"}),+ patch(f"{_AGENT}._routing_rules_block", return_value=None),+ patch(f"{_AGENT}.MultiTurnSession.start", start),+ ):+ cache.return_value.sync_full_cache = AsyncMock()++ def select() -> RepoSelectionResult:+ return async_to_sync(select_repository)(+ 1,+ 1,+ "Find the repository for this issue.",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ priority=Priority.NORMAL,+ github=github,+ candidate_repos=["acme/b", "acme/c", "acme/d"],+ source_repository="acme/a",+ )++ if selected_repository == "acme/c":+ with pytest.raises(RepoSelectionRejectedError):+ select()+ else:+ assert select().repository == "acme/b"++ prompt = start.call_args.kwargs["prompt"]+ assert "1. `acme/b` (private)" in prompt+ assert "2. `acme/d` (private)" in prompt+ assert "`acme/c`" not in prompt+ session.end.assert_awaited_once()