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): suggest code owners for inbox reports (#105268)

Mikayla Thompson76f8b8d19773
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index 99b8822d7e3d..5ba87a68a20b 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -17,6 +17,8 @@ This is prompt guidance, not an enforced access control, and it does not validat
## Reviewer notifications
+Research suggests reviewers from relevant commit authors and recent code activity. It also checks the finding's relevant paths against `owners.yaml` and the connected repository's CODEOWNERS. When they disagree, the `owners.yaml` owner comes first and a routable CODEOWNERS owner follows. A human edit to the report's reviewer list stays in place on later research runs. Missing ownership files or paths leave the existing author-based suggestions unchanged. Scout-authored reports use their own reviewer selection guidance.
+
Slack notifications for a ready report include only reviewers who have access to the report's project when delivery starts.
The same access rule applies when a reviewer is added later.
If no suggested reviewer has access, the ready report still goes to the configured team channel without reviewer mentions.
diff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.md
index c4dd8ea08238..3d3648650708 100644
--- a/products/signals/backend/report_generation/AGENTS.md
+++ b/products/signals/backend/report_generation/AGENTS.md
@@ -27,6 +27,9 @@ It is exercised locally via management commands, and it is also used by the prod
The repository used for research is tracked separately via the `repo_selection` artefact.
+- `ownership_reviewers.py`
+ Matches a finding's relevant code paths against the repository's `owners.yaml` and CODEOWNERS on the connected GitHub repository. When both name different project members, it suggests the `owners.yaml` owner first and the CODEOWNERS owner second. A human reviewer edit prevents subsequent research runs from replacing the selection.
+
- `team_membership.py`
Resolves which teams a person belongs to, so a report can be routed at a team slug rather than at a name. Provider-neutral by design (a membership is a slug, a display name, and whether the person maintains the team); the synced GitHub org roster read through the engineering_analytics facade is the only source behind it today.
- Backs the `team` filter and the `teams` field on `scout-members-list` (`resolve_reviewers.list_project_members`).
diff --git a/products/signals/backend/report_generation/ownership_reviewers.py b/products/signals/backend/report_generation/ownership_reviewers.py
new file mode 100644
index 000000000000..6221752a9b30
--- /dev/null
+++ b/products/signals/backend/report_generation/ownership_reviewers.py
@@ -0,0 +1,168 @@
+"""Find project members who own the code named by a report finding."""
+
+import re
+import logging
+from dataclasses import dataclass
+
+from django.db.models.functions import Lower
+
+from owners_yaml.matcher import compile_pattern, normalize_path
+
+from posthog.models.integration import GitHubIntegration
+from posthog.models.team.team import Team
+
+from products.engineering_analytics.backend.facade.api import resolve_path_owners
+from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM
+from products.signals.backend.report_generation.resolve_reviewers import (
+ bounded_reviewer_reason,
+ resolve_org_github_login_to_users,
+)
+
+logger = logging.getLogger(__name__)
+
+_CODEOWNERS_LOCATIONS = (".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS")
+_MAX_CODEOWNERS_BYTES = 3 * 1024 * 1024
+_MAX_PATHS = 12
+_TEAM_SLUG = re.compile(r"[A-Za-z0-9._-]+\Z")
+
+
+@dataclass(frozen=True)
+class OwnershipReviewer:
+ login: str
+ reason: str
+
+
+def _codeowners_for_paths(github: GitHubIntegration, repository: str, paths: list[str]) -> dict[str, tuple[str, ...]]:
+ for location in _CODEOWNERS_LOCATIONS:
+ try:
+ file = github.get_file_contents(repository, location)
+ except Exception:
+ logger.exception("Could not read CODEOWNERS from %s", repository)
+ return {}
+ if file is not None:
+ break
+ else:
+ return {}
+
+ content = file["content"]
+ if len(content.encode("utf-8")) >= _MAX_CODEOWNERS_BYTES:
+ return {}
+ rules = []
+ for line in content.splitlines():
+ parts = line.split()
+ if not parts or parts[0].startswith("#") or parts[0].startswith("!") or "[" in parts[0]:
+ continue
+ try:
+ matcher = compile_pattern(parts[0])
+ except ValueError:
+ continue
+ rules.append((matcher, tuple(parts[1:])))
+
+ return {path: next((owners for matcher, owners in reversed(rules) if matcher.test(path)), ()) for path in paths}
+
+
+def suggest_repository_owners(
+ team_id: int, repository: str, relevant_paths: list[str], preferred_logins: list[str]
+) -> list[OwnershipReviewer]:
+ """Add one routable member per owning source, preferring recent relevant authors."""
+ paths = list(dict.fromkeys(normalize_path(path) for path in relevant_paths if path))[:_MAX_PATHS]
+ paths = [path for path in paths if path and ".." not in path.split("/")]
+ if not repository or not paths or "/" not in repository:
+ return []
+
+ try:
+ team = Team.objects.get(id=team_id)
+ github = GitHubIntegration.first_for_team_repository(team_id, repository)
+ if github is None:
+ return []
+ codeowners = _codeowners_for_paths(github, repository, paths)
+ ownership = resolve_path_owners(repository, paths)
+ except Exception:
+ logger.exception("Could not resolve repository owners for %s", repository)
+ return []
+
+ org = repository.split("/", 1)[0]
+ groups: list[tuple[list[str], str]] = []
+ seen_owners: set[tuple[str, ...]] = set()
+ if ownership.resolved:
+ for path in paths:
+ slug = ownership.team_by_path.get(path, UNOWNED_TEAM)
+ if slug != UNOWNED_TEAM and _TEAM_SLUG.fullmatch(slug):
+ handles = (f"@{org}/{slug}".lower(),)
+ if handles not in seen_owners:
+ groups.append((list(handles), bounded_reviewer_reason(f"owners.yaml: {path}") or "owners.yaml"))
+ seen_owners.add(handles)
+ for path in paths:
+ owners = codeowners.get(path, ())
+ codeowner_handles = tuple(owner.lower() for owner in owners)
+ if codeowner_handles and codeowner_handles not in seen_owners:
+ groups.append((list(codeowner_handles), bounded_reviewer_reason(f"CODEOWNERS: {path}") or "CODEOWNERS"))
+ seen_owners.add(codeowner_handles)
+
+ email_logins: dict[str, str] = {}
+ email_owners = {owner for owners, _ in groups for owner in owners if "@" in owner[1:]}
+ if email_owners:
+ try:
+ email_logins = {
+ member.email.lower(): login
+ for member in team.all_users_with_access()
+ .annotate(normalized_email=Lower("email"))
+ .filter(normalized_email__in=email_owners)
+ if (login := member.get_github_login())
+ }
+ except Exception:
+ logger.exception("Could not match code owner emails for %s", repository)
+ team_logins: dict[str, list[str]] = {}
+ candidates: list[tuple[list[str], str]] = []
+ for owner_handles, reason in groups:
+ logins: list[str] = []
+ for owner in owner_handles:
+ if not owner.startswith("@"):
+ if login := email_logins.get(owner):
+ logins.append(login.lower())
+ continue
+ handle = owner[1:]
+ if "/" not in handle:
+ if _TEAM_SLUG.fullmatch(handle):
+ logins.append(handle.lower())
+ continue
+ owner_org, slug = handle.split("/", 1)
+ if owner_org.lower() != org.lower() or not _TEAM_SLUG.fullmatch(slug):
+ continue
+ if slug not in team_logins:
+ try:
+ response = github.list_team_members(org, slug)
+ team_logins[slug] = response.get("logins", []) if response.get("success") else []
+ except Exception:
+ logger.exception("Could not list code owner team members for %s", repository)
+ team_logins[slug] = []
+ logins.extend(login.lower() for login in team_logins[slug])
+ if logins:
+ candidates.append((list(dict.fromkeys(logins)), reason))
+
+ try:
+ members = resolve_org_github_login_to_users(team_id, (login for logins, _ in candidates for login in logins))
+ accessible_ids = set(
+ team.all_users_with_access()
+ .filter(id__in=[member.id for member in members.values()])
+ .values_list("id", flat=True)
+ )
+ members = {login: member for login, member in members.items() if member.id in accessible_ids}
+ except Exception:
+ logger.exception("Could not match code owners to project members for %s", repository)
+ return []
+ reviewers: list[OwnershipReviewer] = []
+ covered: set[str] = set()
+ selected_sources: set[str] = set()
+ for logins, reason in candidates:
+ source = reason.split(":", 1)[0]
+ if source in selected_sources:
+ continue
+ available = (set(logins) & members.keys()) - covered
+ if not available:
+ continue
+ login = next((login for login in preferred_logins if login in available), min(available))
+ covered.update(logins)
+ selected_sources.add(source)
+ reviewers.append(OwnershipReviewer(login=login, reason=reason))
+ return reviewers
diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.py
index fbea2444ee91..bb1a75891883 100644
--- a/products/signals/backend/scout_harness/prompt.py
+++ b/products/signals/backend/scout_harness/prompt.py
@@ -533,6 +533,7 @@ _GITHUB_EVIDENCE_HEAD = """# Code-derived reviewer evidence (`gh`, read-only)
This sandbox has the GitHub CLI (`gh`) authenticated with a **read-only** token for this project's connected repositories. Its one job here: turn "who owns the affected surface?" into commit evidence before you set `suggested_reviewers`, instead of inheriting precedent. `gh` has no repository to infer, so every example below passes `--repo` and so must every call you make.
- **Query recent authors of the affected path** once you know which files or dirs the issue touches (from the entity, the error, or a comparable report's `repository`): `gh api 'repos/<owner>/<repo>/commits?path=<dir-or-file>&per_page=30' --jq '[.[].author.login] | group_by(.) | map({login: .[0], commits: length}) | sort_by(-.commits)'`. Two or three such calls (the specific file, its directory, the product root) triangulate ownership. This is evidence-gathering, not archaeology, so don't page through history beyond that.
+- **Check repository ownership when you know the affected paths.** Look for `CODEOWNERS` in `.github/`, then the repository root, then `docs/`; use the first file found and the last rule that matches each path. Also check `owners.yaml` when present. Human reviewer corrections take precedence; if the files name different owners, keep the `owners.yaml` owner first and add a CODEOWNERS owner as a second suggested reviewer only when each resolves to a project member. A GitHub team handle is not a reviewer: resolve its members before suggesting one person. Missing files or unclear paths are not evidence of ownership.
- **Check whether the work is already in flight** before you file something autostart could open a PR for: `gh pr list --repo <owner>/<repo> --state open --search '<keywords>'` (then `gh pr view <n> --repo <owner>/<repo> --json files,title,url` on a plausible hit), `gh api 'repos/<owner>/<repo>/branches?per_page=100'` for a recently pushed branch, and `gh issue list --repo <owner>/<repo> --state open --assignee '*' --search '<keywords>'` for a ticket someone is on. Search by the paths a fix would touch as well as by wording, since concurrent work is easier to recognize by its files. An *open, unassigned* backlog ticket doesn't count: the issue is known, not started. """
_GITHUB_EVIDENCE_TAIL = """
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index 6f0041ef0bcf..1f015696db01 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -25,12 +25,13 @@ from products.signals.backend.agent_runtime import STEP_RESEARCH, resolve_agent_
from products.signals.backend.artefact_schemas import ArtefactContent, RelatedTo, ReportLink, SuggestedReviewers
from products.signals.backend.auto_start import ReviewerContent
from products.signals.backend.enums import ReportLinkKind
-from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
+from products.signals.backend.models import ArtefactAttribution, SignalActorKind, SignalReport, SignalReportArtefact
from products.signals.backend.receivers import _is_safety_suppressed
from products.signals.backend.recurrence import fixed_dismissal_at
from products.signals.backend.repo_corrections import SCOUT_REPOSITORY_CONTENT_NEEDLE, WRONG_REPO_CONTENT_NEEDLE
from products.signals.backend.report_charts import ReportChart, chart_batch_error
from products.signals.backend.report_content_gates import team_report_metrics_enabled
+from products.signals.backend.report_generation.ownership_reviewers import suggest_repository_owners
from products.signals.backend.report_generation.research import (
ActionabilityAssessment,
ActionabilityChoice,
@@ -41,6 +42,7 @@ from products.signals.backend.report_generation.research import (
run_multi_turn_research,
)
from products.signals.backend.report_generation.resolve_reviewers import (
+ MAX_SUGGESTED_REVIEWERS,
ReviewerResolutionDiagnostics,
resolve_suggested_reviewers_with_diagnostics,
)
@@ -322,19 +324,40 @@ def _build_reviewers_content(
commit_hashes_with_reasons[sha] = str(reason) if reason else ""
resolution = resolve_suggested_reviewers_with_diagnostics(team_id, repository, commit_hashes_with_reasons)
+ paths = [path for finding in findings for path in finding.relevant_code_paths]
+ owner_reviewers = suggest_repository_owners(
+ team_id, repository, paths, [reviewer.login.lower() for reviewer in resolution.reviewers]
+ )
reviewers_content: list[ReviewerContent] = []
+ reviewers_by_login = {reviewer.login.lower(): reviewer for reviewer in resolution.reviewers}
+ for owner in owner_reviewers:
+ reviewer = reviewers_by_login.get(owner.login)
+ reviewers_content.append(
+ ReviewerContent(
+ github_login=owner.login,
+ user_uuid=None,
+ github_name=reviewer.name if reviewer else None,
+ relevant_commits=[dict(commit.model_dump()) for commit in reviewer.commits] if reviewer else [],
+ reason=owner.reason,
+ is_skill_owner=False,
+ source_skill=None,
+ )
+ )
+ if len(reviewers_content) == MAX_SUGGESTED_REVIEWERS:
+ break
for reviewer in resolution.reviewers:
+ if len(reviewers_content) == MAX_SUGGESTED_REVIEWERS:
+ break
+ if reviewer.login.lower() in {entry["github_login"] for entry in reviewers_content}:
+ continue
reviewers_content.append(
ReviewerContent(
github_login=reviewer.login.lower(),
- # Commit authorship only ever names a GitHub account, so this path stores no uuid;
- # read-time enrichment resolves the login to a member as it always has.
user_uuid=None,
github_name=reviewer.name,
relevant_commits=[dict(commit.model_dump()) for commit in reviewer.commits],
reason=None,
- # Pipeline reviewers are commit-authorship-derived, never owner-injected.
is_skill_owner=False,
source_skill=None,
)
@@ -410,7 +433,7 @@ def _reviewer_selection_written_since(team_id: int, report_id: str, since: datet
).exists()
-def _append_agentic_report_artefacts(*, team_id: int, report_id: str, artefacts: list[ArtefactDraft]) -> None:
+def _append_agentic_report_artefacts(*, team_id: int, report_id: str, artefacts: list[ArtefactDraft]) -> bool:
# Append-only: each (re-promotion) run adds a new version of its artefacts rather than
# replacing the previous ones. The report's current judgments / repo selection / reviewers are
# the latest row of each type; findings are keyed by `signal_id` (latest per signal wins).
@@ -426,7 +449,20 @@ def _append_agentic_report_artefacts(*, team_id: int, report_id: str, artefacts:
# `mark_report_pending_input`). The research activity only resolves the payload; see
# `_resolve_report_charts_payload` and `RunAgenticReportOutput.charts`.
with transaction.atomic():
+ if any(isinstance(draft.content, SuggestedReviewers) for draft in artefacts):
+ SignalReport.objects.select_for_update().get(id=report_id, team_id=team_id)
+ human_selected_reviewers = SignalReportArtefact.objects.filter(
+ team_id=team_id,
+ report_id=report_id,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ actor_kind=SignalActorKind.USER,
+ ).exists()
+ else:
+ human_selected_reviewers = False
+ wrote_reviewers = False
for draft in artefacts:
+ if human_selected_reviewers and isinstance(draft.content, SuggestedReviewers):
+ continue
SignalReportArtefact.append(
team_id=team_id,
report_id=report_id,
@@ -434,6 +470,8 @@ def _append_agentic_report_artefacts(*, team_id: int, report_id: str, artefacts:
attribution=draft.attribution,
reevaluate_autostart=False,
)
+ wrote_reviewers |= isinstance(draft.content, SuggestedReviewers)
+ return wrote_reviewers
def _resolve_report_charts_payload(
@@ -558,7 +596,7 @@ async def _persist_agentic_report_artefacts(
)
)
- await database_sync_to_async(_append_agentic_report_artefacts, thread_sensitive=False)(
+ wrote_reviewers = await database_sync_to_async(_append_agentic_report_artefacts, thread_sensitive=False)(
team_id=team_id,
report_id=report_id,
artefacts=artefacts,
@@ -568,7 +606,7 @@ async def _persist_agentic_report_artefacts(
# above, so re-promotions without new findings don't re-fire. Delivery is at-least-once
# (a retry of this activity re-captures an identical payload), so consumers read report
# state as the latest event per report_id rather than counting raw events.
- if reviewers_content and has_new_finding:
+ if wrote_reviewers:
await database_sync_to_async(capture_suggested_reviewers_resolved, thread_sensitive=False)(
team_id=team_id,
report_id=report_id,
diff --git a/products/signals/backend/test/test_ownership_reviewers.py b/products/signals/backend/test/test_ownership_reviewers.py
new file mode 100644
index 000000000000..198f299fde36
--- /dev/null
+++ b/products/signals/backend/test/test_ownership_reviewers.py
@@ -0,0 +1,231 @@
+from types import SimpleNamespace
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.models import User
+from posthog.models.organization import OrganizationMembership
+
+from products.engineering_analytics.backend.facade.contracts import PathOwnership
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.artefact_schemas import SignalFinding, SuggestedReviewers
+from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.signals.backend.report_generation.ownership_reviewers import (
+ OwnershipReviewer,
+ _codeowners_for_paths,
+ suggest_repository_owners,
+)
+from products.signals.backend.report_generation.resolve_reviewers import _ResolvedReviewer
+from products.signals.backend.temporal.agentic.report import (
+ ArtefactDraft,
+ _append_agentic_report_artefacts,
+ _build_reviewers_content,
+)
+
+
+def test_codeowners_uses_first_file_and_last_matching_rule():
+ github = MagicMock()
+ github.get_file_contents.side_effect = lambda _repo, location: (
+ {"content": "*.py @example/old\n/src/ @example/current\n/src/generated.py\n*** @example/invalid\n"}
+ if location == ".github/CODEOWNERS"
+ else {"content": "* @example/ignored"}
+ )
+
+ matches = _codeowners_for_paths(github, "example/app", ["src/app.py", "src/generated.py", "lib/app.py"])
+
+ assert matches == {
+ "src/app.py": ("@example/current",),
+ "src/generated.py": (),
+ "lib/app.py": ("@example/old",),
+ }
+ github.get_file_contents.assert_called_once_with("example/app", ".github/CODEOWNERS")
+
+
+def test_codeowners_uses_root_when_github_file_is_absent():
+ github = MagicMock()
+ github.get_file_contents.side_effect = [None, {"content": "*.py @author"}]
+
+ assert _codeowners_for_paths(github, "example/app", ["src/app.py"]) == {"src/app.py": ("@author",)}
+
+
+def test_owners_yaml_precedes_a_different_codeowner(team):
+ project_members = {}
+ for login in ("primary", "backup", "secondary"):
+ member = User.objects.create(email=f"{login}@example.com")
+ OrganizationMembership.objects.create(organization=team.organization, user=member)
+ project_members[login] = member
+ github = MagicMock()
+ github.get_file_contents.side_effect = [{"content": "/src/ @example/main @example/other\n"}]
+ github.list_team_members.side_effect = lambda _org, slug: {
+ "success": True,
+ "logins": ["primary", "backup"] if slug == "main" else ["secondary", "outside"],
+ }
+ with (
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ),
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.resolve_path_owners",
+ return_value=PathOwnership(team_by_path={"src/app.py": "main"}, registry={}, resolved=True),
+ ),
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.resolve_org_github_login_to_users",
+ return_value=project_members,
+ ),
+ ):
+ reviewers = suggest_repository_owners(team.id, "example/app", ["src/app.py"], ["secondary"])
+
+ assert reviewers == [
+ OwnershipReviewer(login="backup", reason="owners.yaml: src/app.py"),
+ OwnershipReviewer(login="secondary", reason="CODEOWNERS: src/app.py"),
+ ]
+
+
+def test_only_one_reviewer_per_ownership_source_across_paths(team):
+ members = {}
+ for login in ("first", "second", "third", "fourth"):
+ member = User.objects.create(email=f"{login}@example.com")
+ OrganizationMembership.objects.create(organization=team.organization, user=member)
+ members[login] = member
+ github = MagicMock()
+ github.get_file_contents.return_value = {"content": "/src/a.py @third\n/src/b.py @fourth\n"}
+ github.list_team_members.side_effect = lambda _org, slug: {
+ "success": True,
+ "logins": ["first"] if slug == "one" else ["second"],
+ }
+ with (
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ),
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.resolve_path_owners",
+ return_value=PathOwnership(team_by_path={"src/a.py": "one", "src/b.py": "two"}, registry={}, resolved=True),
+ ),
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.resolve_org_github_login_to_users",
+ return_value=members,
+ ),
+ ):
+ reviewers = suggest_repository_owners(team.id, "example/app", ["src/a.py", "src/b.py"], [])
+
+ assert reviewers == [
+ OwnershipReviewer(login="first", reason="owners.yaml: src/a.py"),
+ OwnershipReviewer(login="third", reason="CODEOWNERS: src/a.py"),
+ ]
+
+
+def test_codeowners_email_matches_a_project_member_with_a_github_identity(team):
+ member = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(organization=team.organization, user=member)
+ github = MagicMock()
+ github.get_file_contents.return_value = {"content": "*.py [email protected]\n"}
+ with (
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ),
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.resolve_path_owners",
+ return_value=PathOwnership(team_by_path={}, registry={}, resolved=False),
+ ),
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.resolve_org_github_login_to_users",
+ return_value={"linked": member},
+ ),
+ patch.object(User, "get_github_login", return_value="linked"),
+ ):
+ reviewers = suggest_repository_owners(team.id, "example/app", ["src/app.py"], [])
+
+ assert reviewers == [OwnershipReviewer(login="linked", reason="CODEOWNERS: src/app.py")]
+
+
+def test_codeowners_routes_without_owners_yaml_only_to_a_project_member(team):
+ member = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(organization=team.organization, user=member)
+ github = MagicMock()
+ github.get_file_contents.return_value = {"content": "/src/ @example/other @external\n"}
+ github.list_team_members.return_value = {"success": True, "logins": ["outside", "inside"]}
+ with (
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ),
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.resolve_path_owners",
+ return_value=PathOwnership(team_by_path={}, registry={}, resolved=False),
+ ),
+ patch(
+ "products.signals.backend.report_generation.ownership_reviewers.resolve_org_github_login_to_users",
+ return_value={"inside": member},
+ ),
+ ):
+ reviewers = suggest_repository_owners(team.id, "example/app", ["src/app.py"], [])
+
+ assert reviewers == [OwnershipReviewer(login="inside", reason="CODEOWNERS: src/app.py")]
+
+
+def test_ownership_suggestions_follow_repository_owners_then_commit_authors():
+ author = _ResolvedReviewer(login="author", name=None, commits=[], weight=1.0)
+ resolution = SimpleNamespace(reviewers=[author], diagnostics=SimpleNamespace(outcome="resolved"))
+ finding = SignalFinding(
+ signal_id="sig-1",
+ relevant_commit_hashes={"abcdef0": "fix"},
+ relevant_code_paths=["src/app.py"],
+ data_queried="",
+ verified=True,
+ )
+ with (
+ patch(
+ "products.signals.backend.temporal.agentic.report.resolve_suggested_reviewers_with_diagnostics",
+ return_value=resolution,
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.report.suggest_repository_owners",
+ return_value=[
+ OwnershipReviewer(login="primary", reason="owners.yaml: src/app.py"),
+ OwnershipReviewer(login="secondary", reason="CODEOWNERS: src/app.py"),
+ ],
+ ),
+ ):
+ reviewers = _build_reviewers_content(1, "example/app", [finding]).reviewers
+
+ assert [entry["github_login"] for entry in reviewers] == ["primary", "secondary", "author"]
+ assert reviewers[1]["reason"] == "CODEOWNERS: src/app.py"
+
+
+def test_later_research_does_not_replace_a_human_reviewer_edit(team, user):
+ report = SignalReport.objects.create(team=team, status=SignalReport.Status.IN_PROGRESS)
+ manually_selected = SuggestedReviewers.model_validate([{"github_login": "chosen"}])
+ SignalReportArtefact.append_status(
+ team_id=team.id,
+ report_id=str(report.id),
+ content=manually_selected,
+ attribution=ArtefactAttribution.from_user(user.id),
+ reevaluate_autostart=False,
+ )
+
+ wrote_reviewers = _append_agentic_report_artefacts(
+ team_id=team.id,
+ report_id=str(report.id),
+ artefacts=[
+ ArtefactDraft(
+ content=SuggestedReviewers.model_validate([{"github_login": "automatic"}]),
+ attribution=ArtefactAttribution.system(),
+ )
+ ],
+ )
+
+ assert not wrote_reviewers
+ assert (
+ SignalReportArtefact.objects.filter(
+ report=report, type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS
+ ).count()
+ == 1
+ )