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): prefer recently-active area owners when suggesting reviewers (#71029)

Dawid Karasiewicz8231c1df839f
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 5fe56dac8c93..1e1afe965987 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -256,6 +256,7 @@ rules:
|SignalReportArtefact
|SignalReportRefund
|SignalReportTask
+ |SignalRepositoryAreaActivity
|SignalTeamConfig
|SignalSourceConfig
|SignalScoutConfig
@@ -566,6 +567,7 @@ rules:
|SignalReportArtefact
|SignalReportRefund
|SignalReportTask
+ |SignalRepositoryAreaActivity
|SignalTeamConfig
|SignalSourceConfig
|SignalScoutConfig
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index b72daddfcf93..f55f7a152c89 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -53,6 +53,20 @@ class GitHubCommitAuthor:
login: str
name: str | None
commit_url: str
+ # GitHub caps the file listing at 300 entries.
+ file_paths: tuple[str, ...] = ()
+ is_bot: bool = False
+
+
+@dataclass(frozen=True)
+class GitHubCommitAttribution:
+ """GitHub's own commit→account attribution, from the commits listing."""
+
+ sha: str
+ login: str
+ is_bot: bool
+ # Git author display name — untrusted free text, for display only, never parse it.
+ name: str | None = None
class GitHubIntegrationError(Exception):
@@ -669,7 +683,97 @@ class GitHubIntegrationBase:
git_author = data.get("commit", {}).get("author", {})
name = git_author.get("name") or author.get("login")
commit_url = data.get("html_url", f"https://github.com/{repository}/commit/{sha}")
- return GitHubCommitAuthor(login=author["login"], name=name, commit_url=commit_url)
+ files = data.get("files")
+ file_paths = (
+ tuple(f["filename"] for f in files if isinstance(f, dict) and isinstance(f.get("filename"), str))
+ if isinstance(files, list)
+ else ()
+ )
+ return GitHubCommitAuthor(
+ login=author["login"],
+ name=name,
+ commit_url=commit_url,
+ file_paths=file_paths,
+ is_bot=author.get("type") == "Bot",
+ )
+
+ def list_commit_attributions(
+ self,
+ repository: str,
+ *,
+ since: datetime,
+ # The listing includes merge commits, so it must run deeper than the non-merge
+ # git log it joins against (posthog/posthog: ~11k listed entries per 90 days).
+ max_pages: int = 150,
+ ) -> list[GitHubCommitAttribution]:
+ """GitHub's commit→login attribution for default-branch commits since ``since``.
+
+ The listing endpoint carries no file data — callers join on sha against their own
+ source of changed paths (e.g. a local ``git log``). Commits GitHub cannot attribute
+ to an account (unrecognized author emails) are skipped. The first page failing
+ raises; later pages are best-effort so a long history returns what was fetched.
+ Rate limits raise ``GitHubRateLimitError`` (from ``api_request``).
+ """
+ params: dict[str, str | int] = {
+ "per_page": 100,
+ "since": since.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ }
+ attributions: list[GitHubCommitAttribution] = []
+ for page in range(1, max(1, max_pages) + 1):
+ response = self.api_request(
+ "GET",
+ f"/repos/{repository}/commits",
+ endpoint="/repos/{owner}/{repo}/commits",
+ params={**params, "page": page},
+ )
+ if response.status_code != 200:
+ if page == 1:
+ raise GitHubIntegrationError(
+ f"GitHubIntegration: commit listing failed for {repository}",
+ status_code=response.status_code,
+ )
+ logger.info(
+ "GitHub API non-200 during commit listing pagination",
+ status_code=response.status_code,
+ repository=repository,
+ page=page,
+ )
+ break
+ try:
+ body = response.json()
+ if not isinstance(body, list):
+ raise ValueError(f"expected a list, got {type(body).__name__}")
+ except Exception as exc:
+ # Page 1 must raise like the non-200 branch — an empty result here would
+ # let callers write an empty attribution map as if it were real data.
+ if page == 1:
+ raise GitHubIntegrationError(
+ f"GitHubIntegration: malformed commit listing for {repository}",
+ status_code=response.status_code,
+ ) from exc
+ logger.warning(
+ "GitHubIntegration: malformed commit listing page", repository=repository, page=page, exc_info=True
+ )
+ break
+ for entry in body:
+ if not isinstance(entry, dict):
+ continue
+ sha = entry.get("sha")
+ author = entry.get("author")
+ if not isinstance(sha, str) or not isinstance(author, dict) or not author.get("login"):
+ continue
+ git_author = (entry.get("commit") or {}).get("author") or {}
+ attributions.append(
+ GitHubCommitAttribution(
+ sha=sha,
+ login=author["login"],
+ is_bot=author.get("type") == "Bot",
+ name=git_author.get("name") if isinstance(git_author.get("name"), str) else None,
+ )
+ )
+ if len(body) < 100:
+ break
+ return attributions
@staticmethod
def parse_pull_request_url(pr_url: str) -> tuple[str, str, int] | None:
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index dc0204f4c8cd..e92b2f5cf30e 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -96,7 +96,7 @@ from products.feature_flags.backend.tasks import (
from products.logs.backend.facade.tasks import logs_alert_events_cleanup_task
from products.pulse.backend.tasks import mark_stale_pulse_briefs_failed
from products.reminders.backend.tasks import process_due_reminders
-from products.signals.backend.tasks import sync_pending_signals_refund_credits
+from products.signals.backend.tasks import refresh_signal_repository_activity, sync_pending_signals_refund_credits
from products.stamphog.backend.facade.tasks import DAILY_DIGEST_CRONTAB, send_daily_digests
from products.streamlit_apps.backend.facade.api import (
auto_restart_crashed_streamlit_sandboxes,
@@ -285,6 +285,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="sync pending signals refund credits",
)
+ # Keep the signals repository area-activity cache warm - weekly, Monday early morning
+ sender.add_periodic_task(
+ crontab(day_of_week="mon", hour="5", minute="35"),
+ refresh_signal_repository_activity.s(),
+ name="refresh signals repository activity",
+ )
+
# Loop task retention sweep - daily at 4:30 AM
add_periodic_task_with_expiry(
sender,
diff --git a/products/signals/backend/custom_agent/base.py b/products/signals/backend/custom_agent/base.py
index 64471f5cdba9..2d13d8e7d840 100644
--- a/products/signals/backend/custom_agent/base.py
+++ b/products/signals/backend/custom_agent/base.py
@@ -23,6 +23,7 @@ from products.signals.backend.report_generation.research import (
ActionabilityChoice,
PriorityAssessment,
)
+from products.signals.backend.report_generation.resolve_reviewers import rank_assignee_candidates
from products.signals.backend.report_generation.select_repo import RepoSelectionResult, select_repository_for_team
from products.signals.backend.temporal.agentic import (
SIGNALS_REPO_DISCOVERY_ENV_NAME,
@@ -90,6 +91,13 @@ class _AssigneesResolution(BaseModel):
default_factory=list,
description="Suggested GitHub assignees/reviewers. Return [] when no clear owner is supported by evidence.",
)
+ relevant_paths: list[str] = Field(
+ default_factory=list,
+ description=(
+ "Repo-relative file paths most relevant to this report (the code the report is about). "
+ "Used to rank assignees by recent activity in those areas."
+ ),
+ )
class CustomSignalAgent:
@@ -336,8 +344,13 @@ Explain the impact/scope, not just the implementation size."""
Rules:
- Use GitHub logins only.
-- Prefer owners/authors supported by code paths, blame/commit evidence, or obvious domain ownership.
-- Return an empty list when no clear assignee is supported.
+- Suggest people supported by evidence (blame/commit history, obvious domain ownership),
+ordered by strength of evidence. Blame can be stale — your suggestions are re-ranked
+against recent commit activity in the affected areas, so focus on relevance, not recency.
+- Always fill `relevant_paths` with the repo-relative file paths this report is about;
+they drive the recency ranking. Return assignees even if you are unsure of their current
+involvement — the ranking handles that.
+- Return an empty assignees list when no clear candidate is supported by evidence.
- Do not include placeholder users."""
# ------------------------------------------------------------------
@@ -366,7 +379,48 @@ Rules:
_AssigneesResolution,
label="resolve_assignees",
)
- self.register_assignees(result.assignees)
+ assignees = await self._rank_assignees_by_area_activity(result)
+ self.register_assignees(assignees)
+
+ async def _rank_assignees_by_area_activity(self, result: _AssigneesResolution) -> list[CustomAgentAssignee]:
+ """Re-rank agent-proposed assignees through the recency-aware activity system.
+
+ Same scoring as the deterministic reviewer path: the agent's order supplies the
+ evidence weights, cached area activity supplies recency, and active-in-area
+ contributors enter as capped fallbacks. The agent's own list is the fallback when
+ there is no repository or the ranking yields nothing (e.g. no activity map yet).
+ """
+ if self.repository is None or not (result.assignees or result.relevant_paths):
+ return result.assignees
+ try:
+ ranked = await database_sync_to_async(rank_assignee_candidates, thread_sensitive=False)(
+ team_id=self.team_id,
+ repository=self.repository,
+ candidate_logins=[assignee.github_login for assignee in result.assignees],
+ touched_paths=result.relevant_paths,
+ )
+ except Exception:
+ logger.warning("custom agent assignee re-ranking failed, keeping agent order", exc_info=True)
+ return result.assignees
+ if not ranked:
+ return result.assignees
+
+ agent_by_login = {assignee.github_login: assignee for assignee in result.assignees}
+ assignees: list[CustomAgentAssignee] = []
+ for candidate in ranked:
+ agent_entry = agent_by_login.get(candidate.login)
+ assignees.append(
+ CustomAgentAssignee(
+ github_login=candidate.login,
+ github_name=(agent_entry.github_name if agent_entry else None) or candidate.name,
+ relevant_commits=(
+ agent_entry.relevant_commits
+ if agent_entry and agent_entry.relevant_commits
+ else candidate.commits
+ ),
+ )
+ )
+ return assignees
# ------------------------------------------------------------------
# 6. Internal — framework entry point + private helpers (do not override)
diff --git a/products/signals/backend/migrations/0069_signalrepositoryareaactivity.py b/products/signals/backend/migrations/0069_signalrepositoryareaactivity.py
new file mode 100644
index 000000000000..0eea5e55347e
--- /dev/null
+++ b/products/signals/backend/migrations/0069_signalrepositoryareaactivity.py
@@ -0,0 +1,52 @@
+# Generated by Django 5.2.14 on 2026-07-16 10:51
+
+import django.utils.timezone
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1255_wizard_runs_rate_limit_and_provisioned_onboarding_reason"),
+ ("signals", "0068_signalscoutrun_metadata"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="SignalRepositoryAreaActivity",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ ("repository", models.CharField(max_length=400)),
+ ("area", models.CharField(blank=True, max_length=400)),
+ ("contributors", models.JSONField(blank=True, default=list)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("refreshed_at", models.DateTimeField(blank=True, null=True)),
+ ("last_used_at", models.DateTimeField(default=django.utils.timezone.now)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="signal_repo_area_activities",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Signal repository area activity",
+ "verbose_name_plural": "Signal repository area activities",
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("team", "repository", "area"), name="signal_repo_area_activity_uniq"
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index e66f751fb339..d9cd85d88ecb 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0068_signalscoutrun_metadata
+0069_signalrepositoryareaactivity
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 3298e89e02d9..f7a7e6c2e182 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1427,3 +1427,39 @@ class SignalProjectProfile(TeamScopedRootMixin, UUIDModel):
# ORDER BY computed_at DESC LIMIT 1 lookup pattern.
models.Index(fields=["team", "-computed_at"], name="signal_proj_profile_recent_idx"),
]
+
+
+class SignalRepositoryAreaActivity(TeamScopedRootMixin, UUIDModel):
+ """Cached recent-contributor map for one (repository, area) pair.
+
+ Backs recency-aware reviewer suggestion (`report_generation/repo_activity.py`). An
+ *area* is a path prefix (see `area_for_path`); `""` means the repository root. Rows are
+ created on demand, refreshed lazily when stale, and kept warm by the weekly
+ `refresh_signal_repository_activity` task — which only re-fetches rows read recently
+ (`last_used_at`), so abandoned areas age out of the warm set.
+ """
+
+ # db_constraint=False: creating an FK constraint locks the hot posthog_team table and
+ # has blocked deploys — app-level enforcement only (same as SignalReportRefund).
+ team = models.ForeignKey(
+ "posthog.Team",
+ on_delete=models.CASCADE,
+ related_name="signal_repo_area_activities",
+ db_constraint=False,
+ )
+ # Normalized "owner/repo", lowercase.
+ repository = models.CharField(max_length=400)
+ area = models.CharField(max_length=400, blank=True)
+ # [{login, name, commit_count, last_commit_at, last_commit_sha, last_commit_url}]
+ contributors = models.JSONField(default=list, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ # Null until the first successful GitHub fetch.
+ refreshed_at = models.DateTimeField(null=True, blank=True)
+ last_used_at = models.DateTimeField(default=timezone.now)
+
+ class Meta:
+ verbose_name = "Signal repository area activity"
+ verbose_name_plural = "Signal repository area activities"
+ constraints = [
+ models.UniqueConstraint(fields=["team", "repository", "area"], name="signal_repo_area_activity_uniq"),
+ ]
diff --git a/products/signals/backend/report_generation/repo_activity.py b/products/signals/backend/report_generation/repo_activity.py
new file mode 100644
index 000000000000..e0dea6676f40
--- /dev/null
+++ b/products/signals/backend/report_generation/repo_activity.py
@@ -0,0 +1,272 @@
+"""Recent-contributor activity per repository area, cached for reviewer routing.
+
+Supplies the recency signal blame resolution lacks: for each *area* (a path prefix like
+``products/signals``) it knows who actually committed there in the last
+``ACTIVITY_WINDOW_DAYS`` days. Two sources joined on commit sha: a local
+``git log --name-only`` pass in a short-lived sandbox (sha → changed paths, via the tasks
+facade) and GitHub's commits listing (sha → login — git author emails are unverified free
+text, so identity comes only from GitHub's own attribution). Cached in
+``SignalRepositoryAreaActivity`` — reviewer resolution only ever reads the cache; rebuilds
+run async (on cache miss and weekly).
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+
+from django.db import transaction
+from django.utils import timezone
+
+from posthog.egress.limiter.policies import Priority
+from posthog.models.github_integration_base import GitHubCommitAttribution
+from posthog.models.integration import GitHubIntegration
+from posthog.models.scoping import team_scope
+
+from products.tasks.backend.facade.repo_activity import (
+ RepositoryCommitActivityError,
+ collect_repository_commit_activity,
+)
+
+from ..models import SignalRepositoryAreaActivity
+
+logger = logging.getLogger(__name__)
+
+ACTIVITY_WINDOW_DAYS = 90
+ACTIVITY_STALE_AFTER = timedelta(days=7)
+# The weekly refresh only rebuilds repositories whose rows were read this recently.
+ACTIVITY_KEEP_WARM_WINDOW = timedelta(days=45)
+AREA_PATH_DEPTH = 2
+MAX_AREAS_PER_RESOLUTION = 6
+MAX_CONTRIBUTORS_PER_AREA = 50
+# Synthetic area holding every contributor to the repository; the last fallback level.
+# Distinct from "" (files at the repository root).
+REPO_WIDE_AREA = "*"
+
+
+@dataclass(frozen=True)
+class ContributorActivity:
+ login: str
+ name: str | None
+ commit_count: int
+ last_commit_at: datetime
+ last_commit_sha: str
+ last_commit_url: str
+
+
+def area_for_path(path: str) -> str:
+ """Map a repo-relative file path to its area (first ``AREA_PATH_DEPTH`` directories).
+
+ ``products/signals/backend/models.py`` → ``products/signals``;
+ ``posthog/models.py`` → ``posthog``; a root-level file → ``""`` (repository root).
+ """
+ directories = [p for p in path.strip("/").split("/") if p][:-1]
+ return "/".join(directories[:AREA_PATH_DEPTH])
+
+
+def areas_for_paths(paths: list[str]) -> list[str]:
+ """Distinct areas for a set of file paths, most-touched first, capped."""
+ counts: dict[str, int] = {}
+ for path in paths:
+ area = area_for_path(path)
+ counts[area] = counts.get(area, 0) + 1
+ ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
+ return [area for area, _count in ranked[:MAX_AREAS_PER_RESOLUTION]]
+
+
+def area_fallback_chain(area: str) -> list[str]:
+ """Lookup order when an area has no active contributors: itself, its parent, repo-wide.
+
+ ``products/signals`` → ``["products/signals", "products", "*"]``; the rebuild indexes
+ every commit at all of these levels, so walking up never invents data.
+ """
+ chain = [area]
+ if "/" in area:
+ chain.append(area.rsplit("/", 1)[0])
+ if area != REPO_WIDE_AREA:
+ chain.append(REPO_WIDE_AREA)
+ return chain
+
+
+def get_area_activity(team_id: int, repository: str, areas: list[str]) -> dict[str, list[ContributorActivity]]:
+ """Recent contributors per area, read from the ``SignalRepositoryAreaActivity`` cache.
+
+ Cache-only — never hits git or GitHub. Missing areas get a placeholder row (so rebuilds
+ know they are wanted) and are absent from the result; callers must treat absence as
+ "no signal", not "nobody is active".
+ """
+ if not areas:
+ return {}
+
+ repository = repository.strip().lower()
+ now = timezone.now()
+ result: dict[str, list[ContributorActivity]] = {}
+
+ with team_scope(team_id):
+ rows = {
+ row.area: row
+ for row in SignalRepositoryAreaActivity.objects.filter(
+ team_id=team_id, repository=repository, area__in=areas
+ )
+ }
+ missing = [area for area in areas if area not in rows]
+ if missing:
+ # Placeholder rows so rebuilds know these areas are wanted; ignore_conflicts
+ # covers a concurrent resolution creating the same row.
+ SignalRepositoryAreaActivity.objects.bulk_create(
+ [
+ SignalRepositoryAreaActivity(team_id=team_id, repository=repository, area=area, last_used_at=now)
+ for area in missing
+ ],
+ ignore_conflicts=True,
+ )
+ if rows:
+ SignalRepositoryAreaActivity.objects.filter(
+ team_id=team_id, id__in=[row.id for row in rows.values()]
+ ).update(last_used_at=now)
+ for area, row in rows.items():
+ if row.refreshed_at is not None:
+ result[area] = _parse_contributors(row.contributors)
+
+ return result
+
+
+def repository_activity_needs_rebuild(team_id: int, repository: str) -> bool:
+ """Whether the repository's cached map is missing or older than ``ACTIVITY_STALE_AFTER``."""
+ repository = repository.strip().lower()
+ with team_scope(team_id):
+ return not SignalRepositoryAreaActivity.objects.filter(
+ team_id=team_id,
+ repository=repository,
+ refreshed_at__gte=timezone.now() - ACTIVITY_STALE_AFTER,
+ ).exists()
+
+
+def rebuild_repository_activity(team_id: int, repository: str) -> int:
+ """Rebuild the repository's whole area-activity map from its git history.
+
+ One facade call collects the recent commits with their touched paths (sandbox git log);
+ one paginated GitHub commits listing supplies sha→login attribution — the two join on
+ sha, so identity never depends on author emails. Commits GitHub can't attribute, and
+ bot accounts, are dropped. Each commit is indexed at every fallback level (its areas,
+ their parents, and ``REPO_WIDE_AREA``) so lookups can walk up when an area has no
+ active contributors. Every area row for the repository is replaced in one transaction —
+ areas with no recent commits are stamped refreshed with no contributors, which scoring
+ reads as "nobody is active here", distinct from a never-built row.
+
+ Returns the number of areas with at least one contributor. Raises
+ ``RepositoryCommitActivityError`` when collection fails; attribution failures
+ (including rate limits) propagate so a rebuild never writes a half-attributed map.
+ """
+ repository = repository.strip().lower()
+ commits = collect_repository_commit_activity(team_id, repository, since_days=ACTIVITY_WINDOW_DAYS)
+ attribution_by_sha = _commit_attributions_by_sha(team_id, repository) if commits else {}
+
+ per_area: dict[str, dict[str, dict]] = {}
+ for commit in commits: # newest-first, so the first commit seen per login is their latest
+ attribution = attribution_by_sha.get(commit.sha)
+ if attribution is None or attribution.is_bot:
+ continue
+ login = attribution.login.lower()
+ commit_areas: set[str] = set()
+ for path in commit.paths:
+ commit_areas.update(area_fallback_chain(area_for_path(path)))
+ for area in commit_areas:
+ entry = per_area.setdefault(area, {}).get(login)
+ if entry is None:
+ per_area[area][login] = {
+ "login": login,
+ "name": attribution.name or login,
+ "commit_count": 1,
+ "last_commit_at": commit.committed_at,
+ "last_commit_sha": commit.sha,
+ "last_commit_url": f"https://github.com/{repository}/commit/{commit.sha}",
+ }
+ else:
+ entry["commit_count"] += 1
+
+ def contributors_for(area: str) -> list[dict]:
+ by_login = per_area.get(area, {})
+ return sorted(by_login.values(), key=lambda c: -c["commit_count"])[:MAX_CONTRIBUTORS_PER_AREA]
+
+ now = timezone.now()
+ with team_scope(team_id), transaction.atomic():
+ existing = {
+ row.area: row for row in SignalRepositoryAreaActivity.objects.filter(team_id=team_id, repository=repository)
+ }
+ to_update = []
+ for area, row in existing.items():
+ row.contributors = contributors_for(area)
+ row.refreshed_at = now
+ to_update.append(row)
+ if to_update:
+ SignalRepositoryAreaActivity.objects.bulk_update(to_update, ["contributors", "refreshed_at"])
+ to_create = [
+ SignalRepositoryAreaActivity(
+ team_id=team_id,
+ repository=repository,
+ area=area,
+ contributors=contributors_for(area),
+ refreshed_at=now,
+ last_used_at=now,
+ )
+ for area in per_area
+ if area not in existing
+ ]
+ if to_create:
+ # ignore_conflicts: the live read path may create a placeholder for the same
+ # area concurrently — that row is then refreshed by the next rebuild.
+ SignalRepositoryAreaActivity.objects.bulk_create(to_create, ignore_conflicts=True)
+
+ logger.info(
+ "rebuilt signal repository activity for team %d %s: %d commits, %d areas",
+ team_id,
+ repository,
+ len(commits),
+ len(per_area),
+ )
+ return len(per_area)
+
+
+def _commit_attributions_by_sha(team_id: int, repository: str) -> dict[str, GitHubCommitAttribution]:
+ """GitHub's sha→login attribution for the activity window, keyed for the sha join."""
+ github = GitHubIntegration.first_for_team_repository(team_id, repository, source="signals_activity_rebuild")
+ if github is None:
+ # Same expected-deferral type the collector raises — the rebuild task logs it
+ # instead of capturing an exception.
+ raise RepositoryCommitActivityError(f"No GitHub integration for team {team_id} can access {repository}")
+ # Sheddable: rebuilds are deferrable background work — the egress limiter drops BATCH
+ # calls first when the installation's shared budget runs hot, and a denied listing
+ # aborts the rebuild rather than writing a half-attributed map.
+ github.priority = Priority.BATCH
+ since = timezone.now() - timedelta(days=ACTIVITY_WINDOW_DAYS)
+ return {attribution.sha: attribution for attribution in github.list_commit_attributions(repository, since=since)}
+
+
+def _parse_contributors(raw: object) -> list[ContributorActivity]:
+ if not isinstance(raw, list):
+ return []
+ parsed: list[ContributorActivity] = []
+ for entry in raw:
+ if not isinstance(entry, dict):
+ continue
+ login = entry.get("login")
+ last_commit_at_raw = entry.get("last_commit_at")
+ if not isinstance(login, str) or not isinstance(last_commit_at_raw, str):
+ continue
+ try:
+ last_commit_at = datetime.fromisoformat(last_commit_at_raw.replace("Z", "+00:00"))
+ except ValueError:
+ continue
+ parsed.append(
+ ContributorActivity(
+ login=login,
+ name=entry.get("name") if isinstance(entry.get("name"), str) else None,
+ commit_count=int(entry.get("commit_count") or 0),
+ last_commit_at=last_commit_at,
+ last_commit_sha=str(entry.get("last_commit_sha") or ""),
+ last_commit_url=str(entry.get("last_commit_url") or ""),
+ )
+ )
+ return parsed
diff --git a/products/signals/backend/report_generation/resolve_reviewers.py b/products/signals/backend/report_generation/resolve_reviewers.py
index 84e18702453c..45e7a45b22b6 100644
--- a/products/signals/backend/report_generation/resolve_reviewers.py
+++ b/products/signals/backend/report_generation/resolve_reviewers.py
@@ -6,11 +6,13 @@ from collections import Counter
from collections.abc import Iterable, Mapping
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
+from datetime import datetime
from typing import Any, Literal
from django.db.models import Expression, Prefetch, Q, QuerySet, Subquery, Value
from django.db.models.fields.json import KeyTextTransform, KeyTransform
from django.db.models.functions import Concat, Lower
+from django.utils import timezone
from social_django.models import UserSocialAuth
@@ -22,6 +24,15 @@ from posthog.models.user import User
from posthog.models.user_integration import UserIntegration
from products.signals.backend.contracts import RelevantCommit
+from products.signals.backend.report_generation.repo_activity import (
+ ACTIVITY_WINDOW_DAYS,
+ REPO_WIDE_AREA,
+ ContributorActivity,
+ area_fallback_chain,
+ areas_for_paths,
+ get_area_activity,
+ repository_activity_needs_rebuild,
+)
from ..models import SignalReportArtefact
@@ -29,6 +40,13 @@ logger = logging.getLogger(__name__)
MAX_SUGGESTED_REVIEWERS = 3
MAX_COMMIT_LOOKUPS = 15
+
+RECENCY_FULL_WEIGHT_DAYS = 30
+RECENCY_DECAY_FLOOR = 0.3
+STALE_BLAME_MULTIPLIER = 0.15
+# Caps activity-only fallbacks below blame candidates: they only win when every blame author is stale.
+ACTIVITY_ONLY_SCORE_CAP = 0.25
+ACTIVITY_BONUS_SATURATION_COMMITS = 10
GitHubLoginFieldLookup = Literal[
"extra_data__login",
"config__github_user__login",
@@ -115,10 +133,12 @@ def resolve_suggested_reviewers(
repository: str,
commit_hashes_with_reasons: dict[str, str],
) -> list[_ResolvedReviewer]:
- """Resolve commit hashes to up to 3 reviewers with their relevant commits.
+ """Resolve commit hashes to up to 3 reviewers, preferring recently-active owners.
- Commits earlier in the dict are weighted more heavily (they come from
- higher-priority findings and more critical code paths).
+ Blame candidates (commit authors, weighted by finding position) are recency-shaped
+ against cached area activity, and recently-active area contributors enter as capped
+ fallbacks — see ``_score_candidates``. With no activity data available at all, scoring
+ degrades to blame-only.
"""
if not commit_hashes_with_reasons or not repository:
return []
@@ -161,8 +181,9 @@ def resolve_suggested_reviewers(
for i, (sha, reason) in enumerate(items):
author_info = author_results.get(i)
- if author_info:
- login = author_info.login
+ if author_info and not author_info.is_bot:
+ # Lowercased to match the activity map's keys (and the persisted artefact shape).
+ login = author_info.login.lower()
weight = total - i
login_weights[login] += weight
login_commits.setdefault(login, []).append(
@@ -171,16 +192,213 @@ def resolve_suggested_reviewers(
if login not in login_names:
login_names[login] = author_info.name
- # Return top reviewers by weighted score
- return [
- _ResolvedReviewer(
- login=login,
- name=login_names.get(login),
- commits=login_commits.get(login, []),
- weight=weight,
+ touched_paths = [path for info in author_results.values() if info is not None for path in info.file_paths]
+ activity_by_login = _relevant_area_activity(team_id, repository, touched_paths)
+
+ return _rank_scored_candidates(login_weights, activity_by_login, login_commits, login_names)
+
+
+def rank_assignee_candidates(
+ team_id: int,
+ repository: str,
+ candidate_logins: list[str],
+ touched_paths: list[str],
+) -> list[_ResolvedReviewer]:
+ """Rank agent-proposed assignees through the area-activity system.
+
+ The ordered candidate list is position-weighted like blame commits, blended with
+ cached recent activity for the touched paths, and topped up with active-in-area
+ fallbacks — the same scoring the deterministic reviewer path uses. Returns an empty
+ list when nothing is known (no candidates and no activity data), so callers keep
+ their own ordering as the fallback.
+ """
+ deduped = list(dict.fromkeys(login.strip().lower() for login in candidate_logins if login.strip()))
+ login_weights: Counter[str] = Counter()
+ total = len(deduped)
+ for i, login in enumerate(deduped):
+ login_weights[login] = total - i
+
+ activity_by_login = _relevant_area_activity(team_id, repository, touched_paths)
+ if not activity_by_login and not login_weights:
+ return []
+ return _rank_scored_candidates(login_weights, activity_by_login, login_commits={}, login_names={})
+
+
+def _rank_scored_candidates(
+ login_weights: Counter[str],
+ activity_by_login: dict[str, _AreaContributor],
+ login_commits: dict[str, list[RelevantCommit]],
+ login_names: dict[str, str | None],
+) -> list[_ResolvedReviewer]:
+ scores = _score_candidates(login_weights, activity_by_login)
+
+ def rank_key(item: tuple[str, float]) -> tuple[float, int, str]:
+ login, score = item
+ activity = activity_by_login.get(login)
+ return (-score, -(activity.commit_count if activity else 0), login)
+
+ ranked = sorted(scores.items(), key=rank_key)[:MAX_SUGGESTED_REVIEWERS]
+ reviewers: list[_ResolvedReviewer] = []
+ for login, score in ranked:
+ commits = list(login_commits.get(login, []))
+ activity = activity_by_login.get(login)
+ if not commits and activity is not None:
+ commits = [
+ RelevantCommit(
+ sha=activity.last_commit_sha,
+ url=activity.last_commit_url,
+ reason=(
+ f"Recently active in {_area_label(activity.area)} "
+ f"({activity.commit_count} commit(s) in the last {ACTIVITY_WINDOW_DAYS} days)."
+ ),
+ )
+ ]
+ name = login_names.get(login)
+ if name is None and activity is not None:
+ name = activity.name
+ reviewers.append(_ResolvedReviewer(login=login, name=name, commits=commits, weight=score))
+ return reviewers
+
+
+def _area_label(area: str) -> str:
+ if area == REPO_WIDE_AREA:
+ return "this repository"
+ if area == "":
+ return "the repository root"
+ return f"`{area}`"
+
+
+@dataclass(frozen=True)
+class _AreaContributor:
+ """A login's activity aggregated across the report's relevant areas."""
+
+ name: str | None
+ commit_count: int
+ days_since_last_commit: float
+ last_commit_sha: str
+ last_commit_url: str
+ area: str # the area of the evidence (freshest) commit, for evidence wording
+
+
+def _relevant_area_activity(
+ team_id: int,
+ repository: str,
+ touched_paths: list[str],
+) -> dict[str, _AreaContributor]:
+ """Aggregate cached area activity across the areas the finding commits touched.
+
+ Cache-only; a missing or stale map schedules an async rebuild and this report falls
+ back to whatever is cached (possibly nothing). An area with no active contributors
+ falls back up its chain (parent directory, then repo-wide) — someone active nearby
+ beats nobody. Returns an empty dict when nothing is known — callers must treat that
+ as "no signal", not "nobody is active".
+ """
+ areas = areas_for_paths(touched_paths)
+ if not areas:
+ return {}
+ chains = [area_fallback_chain(area) for area in areas]
+ lookup_areas = list(dict.fromkeys(area for chain in chains for area in chain))
+ activity_by_area = get_area_activity(team_id, repository, lookup_areas)
+ if repository_activity_needs_rebuild(team_id, repository):
+ _schedule_activity_rebuild(team_id, repository)
+
+ now = timezone.now()
+ merged: dict[str, _AreaContributor] = {}
+ used_levels: set[str] = set()
+ for chain in chains:
+ level = next((area for area in chain if activity_by_area.get(area)), None)
+ if level is None or level in used_levels:
+ continue
+ used_levels.add(level)
+ for contributor in activity_by_area[level]:
+ existing = merged.get(contributor.login)
+ merged[contributor.login] = _merge_contributor(existing, contributor, level, now)
+ return merged
+
+
+def _schedule_activity_rebuild(team_id: int, repository: str) -> None:
+ # Local import: tasks.py imports repo_activity at load time.
+ from products.signals.backend.tasks import rebuild_signal_repository_activity
+
+ try:
+ rebuild_signal_repository_activity.delay(team_id=team_id, repository=repository)
+ except Exception:
+ logger.warning("Failed to schedule activity rebuild for %s", repository, exc_info=True)
+
+
+def _merge_contributor(
+ existing: _AreaContributor | None,
+ incoming: ContributorActivity,
+ area: str,
+ now: datetime,
+) -> _AreaContributor:
+ days_since = max(0.0, (now - incoming.last_commit_at).total_seconds() / 86400)
+ if existing is None:
+ return _AreaContributor(
+ name=incoming.name,
+ commit_count=incoming.commit_count,
+ days_since_last_commit=days_since,
+ last_commit_sha=incoming.last_commit_sha,
+ last_commit_url=incoming.last_commit_url,
+ area=area,
)
- for login, weight in login_weights.most_common(MAX_SUGGESTED_REVIEWERS)
- ]
+ # Evidence follows the freshest commit, so sha/url/area always agree with
+ # days_since_last_commit.
+ keep_incoming_evidence = days_since < existing.days_since_last_commit
+ return _AreaContributor(
+ name=existing.name or incoming.name,
+ commit_count=existing.commit_count + incoming.commit_count,
+ days_since_last_commit=min(existing.days_since_last_commit, days_since),
+ last_commit_sha=incoming.last_commit_sha if keep_incoming_evidence else existing.last_commit_sha,
+ last_commit_url=incoming.last_commit_url if keep_incoming_evidence else existing.last_commit_url,
+ area=area if keep_incoming_evidence else existing.area,
+ )
+
+
+def _recency_multiplier(days_since_last_commit: float | None) -> float:
+ """How much of a blame weight survives, given the author's latest area commit."""
+ if days_since_last_commit is None:
+ return STALE_BLAME_MULTIPLIER
+ if days_since_last_commit <= RECENCY_FULL_WEIGHT_DAYS:
+ return 1.0
+ if days_since_last_commit >= ACTIVITY_WINDOW_DAYS:
+ return STALE_BLAME_MULTIPLIER
+ span = ACTIVITY_WINDOW_DAYS - RECENCY_FULL_WEIGHT_DAYS
+ progress = (days_since_last_commit - RECENCY_FULL_WEIGHT_DAYS) / span
+ return 1.0 - progress * (1.0 - RECENCY_DECAY_FLOOR)
+
+
+def _score_candidates(
+ login_weights: Counter[str],
+ activity_by_login: dict[str, _AreaContributor],
+) -> dict[str, float]:
+ """Blend blame weights with area recency; add capped activity-only fallbacks.
+
+ Invariants: a freshly-active area contributor always outranks a blame author who is
+ gone from the area (their base starts above the stale floor), and never outranks the
+ *top-weighted* blame author while that author is active in the window (the cap sits
+ below the decay floor). Lower-weighted active blame authors can still be outranked by
+ a very active area owner — deliberate: weight-1 blame is one marginal commit, not a
+ stronger claim than sustained area ownership. With no activity data at all, blame
+ weights pass through unchanged (legacy behavior).
+ """
+ if not activity_by_login:
+ return {login: float(weight) for login, weight in login_weights.items()}
+
+ max_blame_weight = float(max(login_weights.values(), default=0)) or 1.0
+ scores: dict[str, float] = {}
+ for login, weight in login_weights.items():
+ activity = activity_by_login.get(login)
+ multiplier = _recency_multiplier(activity.days_since_last_commit if activity else None)
+ scores[login] = float(weight) * multiplier
+
+ for login, activity in activity_by_login.items():
+ if login in scores:
+ continue
+ saturation = min(activity.commit_count, ACTIVITY_BONUS_SATURATION_COMMITS) / ACTIVITY_BONUS_SATURATION_COMMITS
+ base = STALE_BLAME_MULTIPLIER + (ACTIVITY_ONLY_SCORE_CAP - STALE_BLAME_MULTIPLIER) * saturation
+ scores[login] = max_blame_weight * base * _recency_multiplier(activity.days_since_last_commit)
+ return scores
@dataclass
@@ -190,7 +408,7 @@ class _ResolvedReviewer:
login: str
name: str | None
commits: list[RelevantCommit]
- weight: int
+ weight: float
def get_org_member_github_login_to_user_map(team_id: int) -> dict[str, User] | None:
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 81a097c2279b..35c241d35760 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -1,12 +1,14 @@
from datetime import timedelta
from decimal import Decimal
+from django.core.cache import cache
from django.utils import timezone
import structlog
from celery import shared_task
from posthog.cloud_utils import get_cached_instance_license
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
from posthog.models import Team
@@ -16,8 +18,14 @@ from posthog.scoping_audit import skip_team_scope_audit
from products.signals.backend.billing import current_billing_period_bounds
from products.signals.backend.implementation_pr import PrCloseReason, close_implementation_pr_for_report
-from products.signals.backend.models import SignalReportRefund
+from products.signals.backend.models import SignalReportRefund, SignalRepositoryAreaActivity
+from products.signals.backend.report_generation.repo_activity import (
+ ACTIVITY_KEEP_WARM_WINDOW,
+ rebuild_repository_activity,
+ repository_activity_needs_rebuild,
+)
from products.signals.backend.slack_inbox_notifications import dispatch_reviewer_added_notifications
+from products.tasks.backend.facade.repo_activity import RepositoryCommitActivityError
logger = structlog.get_logger(__name__)
@@ -261,3 +269,78 @@ def sync_pending_signals_refund_credits() -> None:
sync_signals_refund_credit.delay(str(refund_id))
if pending_ids:
logger.info("signals refund credit sweeper re-enqueued pending refunds", count=len(pending_ids))
+
+
+_ACTIVITY_ROW_MAX_IDLE = timedelta(days=90)
+# Backstop for a worker dying without releasing the rebuild lock; above the task's
+# time_limit so a live rebuild is never treated as abandoned.
+_REBUILD_LOCK_TTL_SECONDS = 30 * 60
+
+
+@shared_task(
+ name="products.signals.backend.tasks.rebuild_signal_repository_activity",
+ ignore_result=True,
+ max_retries=0,
+ # Sandbox clone (10m cap) + git log (3m cap) + attribution listing; the hard limit
+ # backstops a hung sandbox call.
+ soft_time_limit=20 * 60,
+ time_limit=22 * 60,
+)
+@with_team_scope()
+def rebuild_signal_repository_activity(team_id: int, repository: str, force: bool = False) -> None:
+ """Rebuild one repository's area-activity map from its git history (sandbox clone + git log).
+
+ Enqueued on cache miss by reviewer resolution and weekly by the sweeper (which passes
+ ``force`` — its rows sit exactly at the staleness boundary). A failed rebuild leaves
+ the cached rows untouched; the next enqueue retries.
+ """
+ # Concurrent enqueues for the same (team, repository) are common — several reports can
+ # hit the same stale map before the first rebuild lands. The staleness re-check debounces
+ # re-triggers over the freshness window; the atomic cache lock closes the remaining race
+ # where several queued workers all pass the check before the first rebuild writes.
+ if not force and not repository_activity_needs_rebuild(team_id, repository):
+ return
+ lock_key = f"signals_repo_activity_rebuild/{team_id}/{repository.strip().lower()}"
+ if not cache.add(lock_key, "1", timeout=_REBUILD_LOCK_TTL_SECONDS):
+ return
+ try:
+ rebuild_repository_activity(team_id, repository)
+ except (RepositoryCommitActivityError, GitHubRateLimitError, GitHubEgressBudgetExhausted) as exc:
+ # Expected deferrals (integration gone, rate limit, shed by the egress limiter) —
+ # the map stays stale and the next enqueue retries.
+ logger.warning(
+ "signals repository activity rebuild deferred",
+ team_id=team_id,
+ repository=repository,
+ error=str(exc),
+ )
+ except Exception as exc:
+ capture_exception(exc, {"team_id": team_id, "repository": repository})
+ finally:
+ cache.delete(lock_key)
+
+
+@shared_task(
+ name="products.signals.backend.tasks.refresh_signal_repository_activity",
+ ignore_result=True,
+ max_retries=0,
+)
+@skip_team_scope_audit
+def refresh_signal_repository_activity() -> None:
+ """Weekly (Monday) warm-up: enqueue a rebuild for every recently-used repository map."""
+ now = timezone.now()
+ SignalRepositoryAreaActivity.objects.unscoped().filter(
+ last_used_at__lt=now - _ACTIVITY_ROW_MAX_IDLE
+ ).delete() # nosemgrep: idor-lookup-without-team (system Celery sweeper, no user input; unscoped is the sanctioned cross-team access)
+
+ repositories = list(
+ SignalRepositoryAreaActivity.objects.unscoped() # nosemgrep: idor-lookup-without-team (system Celery sweeper, no user input; unscoped is the sanctioned cross-team access)
+ .filter(last_used_at__gte=now - ACTIVITY_KEEP_WARM_WINDOW)
+ .values_list("team_id", "repository")
+ .distinct()
+ .order_by("team_id", "repository")
+ )
+ for team_id, repository in repositories:
+ rebuild_signal_repository_activity.delay(team_id=team_id, repository=repository, force=True)
+ if repositories:
+ logger.info("signals repository activity refresh enqueued rebuilds", count=len(repositories))
diff --git a/products/signals/backend/test/test_repo_activity.py b/products/signals/backend/test/test_repo_activity.py
new file mode 100644
index 000000000000..d4aac1502603
--- /dev/null
+++ b/products/signals/backend/test/test_repo_activity.py
@@ -0,0 +1,244 @@
+from datetime import timedelta
+
+import pytest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from posthog.models import Organization, Team
+from posthog.models.github_integration_base import GitHubCommitAttribution
+from posthog.models.scoping import team_scope
+
+from products.signals.backend.models import SignalRepositoryAreaActivity
+from products.signals.backend.report_generation.repo_activity import (
+ MAX_AREAS_PER_RESOLUTION,
+ REPO_WIDE_AREA,
+ area_fallback_chain,
+ area_for_path,
+ areas_for_paths,
+ get_area_activity,
+ rebuild_repository_activity,
+ repository_activity_needs_rebuild,
+)
+from products.signals.backend.tasks import refresh_signal_repository_activity
+from products.tasks.backend.facade.repo_activity import RepositoryCommitActivity
+
+_COLLECT_PATCH_TARGET = "products.signals.backend.report_generation.repo_activity.collect_repository_commit_activity"
+
+
+def organization():
+ org = Organization.objects.create(name="test-repo-activity-org")
+ yield org
+ org.delete()
+
+
+def team(organization):
+ return Team.objects.create(organization=organization, name="test-repo-activity-team")
+
+
+def _commit(sha: str, _email: str, days_ago: int, paths: list[str]) -> RepositoryCommitActivity:
+ # _email kept in call sites as narrative: identity comes from the attribution join,
+ # never from commit metadata.
+ return RepositoryCommitActivity(
+ sha=sha,
+ committed_at=(timezone.now() - timedelta(days=days_ago)).isoformat(),
+ paths=paths,
+ )
+
+
+def _fresh_row(team, area: str, contributors: list[dict] | None = None, **kwargs):
+ with team_scope(team.id, canonical=True):
+ return SignalRepositoryAreaActivity.objects.create(
+ team=team,
+ repository="acme/app",
+ area=area,
+ contributors=contributors
+ or [
+ {
+ "login": "alice",
+ "name": "Alice",
+ "commit_count": 5,
+ "last_commit_at": timezone.now().isoformat(),
+ "last_commit_sha": "e" * 7,
+ "last_commit_url": "https://github.com/acme/app/commit/eeeeeee",
+ }
+ ],
+ refreshed_at=kwargs.pop("refreshed_at", timezone.now()),
+ **kwargs,
+ )
+
+
+class TestAreaForPath:
+ def test_root_file_maps_to_empty_area(self):
+ assert area_for_path("README.md") == ""
+
+ def test_single_directory(self):
+ assert area_for_path("posthog/models.py") == "posthog"
+
+ def test_deep_path_capped_at_two_directories(self):
+ assert area_for_path("products/signals/backend/models.py") == "products/signals"
+ assert area_for_path("products/signals/backend/temporal/agentic/report.py") == "products/signals"
+
+ def test_leading_slash_normalized(self):
+ assert area_for_path("/products/signals/x.py") == "products/signals"
+
+ def test_areas_ranked_by_touch_count_and_capped(self):
+ paths = ["a/b/one.py", "a/b/two.py", "c/d/one.py"]
+ assert areas_for_paths(paths) == ["a/b", "c/d"]
+
+ many = [f"dir{i}/sub/file.py" for i in range(MAX_AREAS_PER_RESOLUTION + 3)]
+ assert len(areas_for_paths(many)) == MAX_AREAS_PER_RESOLUTION
+
+ def test_fallback_chain_walks_up_to_repo_wide(self):
+ assert area_fallback_chain("products/signals") == ["products/signals", "products", REPO_WIDE_AREA]
+ assert area_fallback_chain("posthog") == ["posthog", REPO_WIDE_AREA]
+ assert area_fallback_chain("") == ["", REPO_WIDE_AREA]
+
+
+class FakeAttributionGitHub:
+ """Stub of the commits-listing surface the rebuild joins against."""
+
+ def __init__(self, by_sha: dict[str, tuple[str, bool]]):
+ self.by_sha = by_sha
+
+ def list_commit_attributions(self, repository, *, since, max_pages=60):
+ return [
+ GitHubCommitAttribution(sha=sha, login=login, is_bot=is_bot) for sha, (login, is_bot) in self.by_sha.items()
+ ]
+
+
+def _patch_attributions(by_sha: dict[str, tuple[str, bool]]):
+ return patch(
+ "products.signals.backend.report_generation.repo_activity.GitHubIntegration.first_for_team_repository",
+ return_value=FakeAttributionGitHub(by_sha),
+ )
+
+
+class TestRebuildRepositoryActivity:
+ def test_builds_area_map_joining_git_history_with_github_attribution(self, team):
+ commits = [
+ _commit("a" * 7, "[email protected]", 2, ["products/signals/backend/models.py"]),
+ _commit("b" * 7, "[email protected]", 9, ["products/signals/frontend/App.tsx"]),
+ _commit("c" * 7, "[email protected]", 30, ["products/signals/backend/tasks.py", "posthog/models/user.py"]),
+ _commit("d" * 7, "[email protected]", 1, ["products/signals/backend/views.py"]),
+ ]
+ attributions = {
+ # identity comes from GitHub's sha attribution — the git emails above are noise
+ "a" * 7: ("alice", False),
+ "b" * 7: ("alice", False),
+ "c" * 7: ("BobDev", False),
+ # "d" is absent: GitHub couldn't attribute it, so it drops
+ }
+
+ with patch(_COLLECT_PATCH_TARGET, return_value=commits), _patch_attributions(attributions):
+ rebuild_repository_activity(team.id, "acme/app")
+
+ activity = get_area_activity(team.id, "acme/app", ["products/signals", "posthog/models"])
+
+ signals_area = {c.login: c for c in activity["products/signals"]}
+ # alice: both commits, latest one kept as evidence
+ assert signals_area["alice"].commit_count == 2
+ assert signals_area["alice"].last_commit_sha == "a" * 7
+ # login lowercased
+ assert signals_area["bobdev"].commit_count == 1
+ assert [c.login for c in activity["posthog/models"]] == ["bobdev"]
+ assert "nobody" not in signals_area
+
+ # commits are also indexed at the parent and repo-wide levels for walk-up
+ parents = get_area_activity(team.id, "acme/app", ["products", REPO_WIDE_AREA])
+ assert {c.login for c in parents["products"]} == {"alice", "bobdev"}
+ repo_wide = {c.login: c for c in parents[REPO_WIDE_AREA]}
+ assert repo_wide["alice"].commit_count == 2
+ assert repo_wide["bobdev"].commit_count == 1
+
+ def test_bot_commits_are_excluded(self, team):
+ commits = [
+ _commit("a" * 7, "[email protected]", 3, ["frontend/src/notebooks/Notebook.tsx"]),
+ _commit("b" * 7, "[email protected]", 1, ["frontend/src/generated.ts"]),
+ ]
+ attributions = {
+ "a" * 7: ("MariusAndra", False),
+ "b" * 7: ("posthog[bot]", True),
+ }
+
+ with patch(_COLLECT_PATCH_TARGET, return_value=commits), _patch_attributions(attributions):
+ rebuild_repository_activity(team.id, "acme/app")
+
+ activity = get_area_activity(team.id, "acme/app", ["frontend/src"])
+ assert [c.login for c in activity["frontend/src"]] == ["mariusandra"]
+
+ def test_replaces_previous_map_and_empties_dead_areas(self, team):
+ _fresh_row(team, "products/old", refreshed_at=timezone.now() - timedelta(days=30))
+
+ commits = [_commit("a" * 7, "[email protected]", 1, ["products/new/x.py"])]
+ with patch(_COLLECT_PATCH_TARGET, return_value=commits), _patch_attributions({"a" * 7: ("alice", False)}):
+ rebuild_repository_activity(team.id, "acme/app")
+
+ with team_scope(team.id, canonical=True):
+ old_row = SignalRepositoryAreaActivity.objects.get(repository="acme/app", area="products/old")
+ new_row = SignalRepositoryAreaActivity.objects.get(repository="acme/app", area="products/new")
+ # the dead area is refreshed-but-empty: "nobody is active", not "unknown"
+ assert old_row.contributors == []
+ assert old_row.refreshed_at is not None
+ assert old_row.refreshed_at > timezone.now() - timedelta(minutes=1)
+ assert [c["login"] for c in new_row.contributors] == ["alice"]
+
+
+class TestGetAreaActivity:
+ def test_reads_fresh_cache(self, team):
+ _fresh_row(team, "products/signals")
+
+ result = get_area_activity(team.id, "acme/app", ["products/signals"])
+
+ assert [c.login for c in result["products/signals"]] == ["alice"]
+
+ def test_missing_area_gets_placeholder_row_and_is_absent(self, team):
+ result = get_area_activity(team.id, "acme/app", ["products/signals"])
+
+ assert result == {}
+ with team_scope(team.id, canonical=True):
+ row = SignalRepositoryAreaActivity.objects.get(repository="acme/app", area="products/signals")
+ assert row.refreshed_at is None
+
+ def test_needs_rebuild_transitions(self, team):
+ assert repository_activity_needs_rebuild(team.id, "acme/app") is True
+
+ row = _fresh_row(team, "products/signals")
+ assert repository_activity_needs_rebuild(team.id, "acme/app") is False
+
+ with team_scope(team.id, canonical=True):
+ SignalRepositoryAreaActivity.objects.filter(id=row.id).update(
+ refreshed_at=timezone.now() - timedelta(days=30)
+ )
+ assert repository_activity_needs_rebuild(team.id, "acme/app") is True
+
+
+class TestWeeklyRefreshTask:
+ def test_enqueues_one_rebuild_per_repository_and_drops_idle_rows(self, team):
+ now = timezone.now()
+ with team_scope(team.id, canonical=True):
+ SignalRepositoryAreaActivity.objects.create(
+ team=team, repository="acme/app", area="a/one", last_used_at=now
+ )
+ SignalRepositoryAreaActivity.objects.create(
+ team=team, repository="acme/app", area="a/two", last_used_at=now
+ )
+ SignalRepositoryAreaActivity.objects.create(
+ team=team, repository="acme/other", area="b/one", last_used_at=now
+ )
+ idle = SignalRepositoryAreaActivity.objects.create(
+ team=team, repository="acme/dead", area="c/one", last_used_at=now - timedelta(days=120)
+ )
+
+ with patch("products.signals.backend.tasks.rebuild_signal_repository_activity.delay") as delay:
+ refresh_signal_repository_activity()
+
+ enqueued = {(call.kwargs["team_id"], call.kwargs["repository"]) for call in delay.call_args_list}
+ assert enqueued == {(team.id, "acme/app"), (team.id, "acme/other")}
+ with team_scope(team.id, canonical=True):
+ assert not SignalRepositoryAreaActivity.objects.filter(id=idle.id).exists()
diff --git a/products/signals/backend/test/test_resolve_reviewers.py b/products/signals/backend/test/test_resolve_reviewers.py
index 066b006ba27b..b8131a948800 100644
--- a/products/signals/backend/test/test_resolve_reviewers.py
+++ b/products/signals/backend/test/test_resolve_reviewers.py
@@ -1,13 +1,34 @@
+from collections import Counter
+from datetime import timedelta
+
import pytest
+from unittest.mock import patch
+
+from django.utils import timezone
from social_django.models import UserSocialAuth
from posthog.models import Organization, Team, User
+from posthog.models.github_integration_base import GitHubCommitAuthor
from posthog.models.integration import Integration
from posthog.models.organization import OrganizationMembership
+from posthog.models.scoping import team_scope
from posthog.models.user_integration import UserIntegration
-from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
+from products.signals.backend.models import SignalRepositoryAreaActivity
+from products.signals.backend.report_generation.repo_activity import ACTIVITY_WINDOW_DAYS, ContributorActivity
+from products.signals.backend.report_generation.resolve_reviewers import (
+ RECENCY_DECAY_FLOOR,
+ RECENCY_FULL_WEIGHT_DAYS,
+ STALE_BLAME_MULTIPLIER,
+ _AreaContributor,
+ _recency_multiplier,
+ _relevant_area_activity,
+ _score_candidates,
+ rank_assignee_candidates,
+ resolve_org_github_login_to_users,
+ resolve_suggested_reviewers,
+)
@pytest.fixture
@@ -106,3 +127,252 @@ def test_skips_users_outside_organization(organization, team):
assert result == {}
finally:
other_org.delete()
+
+
+# ── recency-aware scoring ─────────────────────────────────────────────────────
+
+
+class TestRecencyScoring:
+ def test_recency_multiplier_shape(self):
+ assert _recency_multiplier(None) == STALE_BLAME_MULTIPLIER
+ assert _recency_multiplier(0) == 1.0
+ assert _recency_multiplier(RECENCY_FULL_WEIGHT_DAYS) == 1.0
+ assert _recency_multiplier(ACTIVITY_WINDOW_DAYS) == STALE_BLAME_MULTIPLIER
+ assert _recency_multiplier(ACTIVITY_WINDOW_DAYS + 100) == STALE_BLAME_MULTIPLIER
+ midpoint = (RECENCY_FULL_WEIGHT_DAYS + ACTIVITY_WINDOW_DAYS) / 2
+ assert _recency_multiplier(midpoint) == pytest.approx((1.0 + RECENCY_DECAY_FLOOR) / 2)
+
+ def test_no_activity_data_keeps_blame_weights(self):
+ weights = Counter({"old-timer": 10, "runner-up": 4})
+
+ scores = _score_candidates(weights, {})
+
+ assert scores == {"old-timer": 10.0, "runner-up": 4.0}
+
+ def test_stale_blame_author_loses_to_active_area_contributor(self):
+ weights = Counter({"old-timer": 10})
+ activity = {
+ "active-owner": _AreaContributor(
+ name="Active Owner",
+ commit_count=12,
+ days_since_last_commit=2,
+ last_commit_sha="a" * 7,
+ last_commit_url="https://github.com/acme/app/commit/aaaaaaa",
+ area="products/signals",
+ ),
+ }
+
+ scores = _score_candidates(weights, activity)
+
+ # old-timer authored the blame commits but has no recent commits in the area.
+ assert scores["active-owner"] > scores["old-timer"]
+
+ def test_recently_active_blame_author_beats_activity_only_contributor(self):
+ def contributor(days_since: float) -> _AreaContributor:
+ return _AreaContributor(
+ name=None,
+ commit_count=12,
+ days_since_last_commit=days_since,
+ last_commit_sha="b" * 7,
+ last_commit_url="https://github.com/acme/app/commit/bbbbbbb",
+ area="products/signals",
+ )
+
+ weights = Counter({"active-author": 10})
+ activity = {
+ "active-author": contributor(days_since=5),
+ "bystander": contributor(days_since=1),
+ }
+
+ scores = _score_candidates(weights, activity)
+
+ assert scores["active-author"] > scores["bystander"]
+
+ def test_lightly_active_contributor_beats_stale_blame_even_with_tiny_blame_weight(self):
+ # Regression: a single old blame commit (weight 1) used to crush activity-only
+ # candidates via the cap, so the long-gone author still won the assign.
+ weights = Counter({"long-gone": 1})
+ activity = {
+ "light-owner": _AreaContributor(
+ name=None,
+ commit_count=3,
+ days_since_last_commit=1,
+ last_commit_sha="c" * 7,
+ last_commit_url="",
+ area="posthog/migrations",
+ ),
+ }
+
+ scores = _score_candidates(weights, activity)
+
+ assert scores["light-owner"] > scores["long-gone"]
+
+ def test_half_stale_bystander_does_not_beat_stale_blame(self):
+ weights = Counter({"long-gone": 1})
+ activity = {
+ "half-stale": _AreaContributor(
+ name=None,
+ commit_count=3,
+ days_since_last_commit=70,
+ last_commit_sha="c" * 7,
+ last_commit_url="",
+ area="posthog/migrations",
+ ),
+ }
+
+ scores = _score_candidates(weights, activity)
+
+ assert scores["long-gone"] >= scores["half-stale"]
+
+
+class TestAreaWalkUp:
+ def test_empty_area_falls_back_to_parent_then_repo_wide(self, team):
+ def _row(area: str, logins: list[str]) -> None:
+ SignalRepositoryAreaActivity.objects.create(
+ team=team,
+ repository="acme/app",
+ area=area,
+ contributors=[
+ {
+ "login": login,
+ "name": login.title(),
+ "commit_count": 3,
+ "last_commit_at": timezone.now().isoformat(),
+ "last_commit_sha": "a" * 7,
+ "last_commit_url": "https://github.com/acme/app/commit/aaaaaaa",
+ }
+ for login in logins
+ ],
+ refreshed_at=timezone.now(),
+ )
+
+ with team_scope(team.id, canonical=True):
+ _row("products/dead", []) # refreshed, nobody active
+ _row("products", ["parent-owner"])
+ _row("*", ["repo-regular"])
+
+ with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
+ merged = _relevant_area_activity(team.id, "acme/app", ["products/dead/models.py"])
+
+ # the dead area walks up to its parent; repo-wide stays in reserve
+ assert set(merged) == {"parent-owner"}
+ assert merged["parent-owner"].area == "products"
+
+ with team_scope(team.id, canonical=True):
+ SignalRepositoryAreaActivity.objects.filter(area="products").update(contributors=[])
+ with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
+ merged = _relevant_area_activity(team.id, "acme/app", ["products/dead/models.py"])
+
+ assert set(merged) == {"repo-regular"}
+
+
+class TestRankAssigneeCandidates:
+ def _seed_area(self, team, area: str, entries: list[tuple[str, int, int]]) -> None:
+ with team_scope(team.id, canonical=True):
+ SignalRepositoryAreaActivity.objects.create(
+ team=team,
+ repository="acme/app",
+ area=area,
+ contributors=[
+ {
+ "login": login,
+ "name": login.title(),
+ "commit_count": count,
+ "last_commit_at": (timezone.now() - timedelta(days=days_ago)).isoformat(),
+ "last_commit_sha": "a" * 7,
+ "last_commit_url": "https://github.com/acme/app/commit/aaaaaaa",
+ }
+ for login, count, days_ago in entries
+ ],
+ refreshed_at=timezone.now(),
+ )
+
+ def test_stale_agent_candidate_demoted_below_active_area_owner(self, team):
+ self._seed_area(team, "products/signals", [("active-owner", 12, 2)])
+
+ with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
+ ranked = rank_assignee_candidates(
+ team.id, "acme/app", ["old-timer"], ["products/signals/backend/models.py"]
+ )
+
+ assert [candidate.login for candidate in ranked] == ["active-owner", "old-timer"]
+ # activity-only candidate carries generated evidence; the agent candidate keeps none
+ assert "Recently active in `products/signals`" in ranked[0].commits[0].reason
+ assert ranked[1].commits == []
+
+ def test_active_agent_candidate_keeps_top_spot(self, team):
+ self._seed_area(team, "products/signals", [("agent-pick", 5, 3), ("bystander", 12, 1)])
+
+ with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
+ ranked = rank_assignee_candidates(
+ team.id, "acme/app", ["agent-pick"], ["products/signals/backend/models.py"]
+ )
+
+ assert ranked[0].login == "agent-pick"
+
+ def test_paths_alone_yield_activity_candidates(self, team):
+ self._seed_area(team, "products/signals", [("area-owner", 8, 1)])
+
+ with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
+ ranked = rank_assignee_candidates(team.id, "acme/app", [], ["products/signals/backend/models.py"])
+
+ assert [candidate.login for candidate in ranked] == ["area-owner"]
+
+ def test_no_activity_data_returns_agent_order(self, team):
+ with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
+ ranked = rank_assignee_candidates(
+ team.id, "acme/app", ["first-pick", "second-pick"], ["products/signals/backend/models.py"]
+ )
+
+ assert [candidate.login for candidate in ranked] == ["first-pick", "second-pick"]
+
+
+class TestResolveSuggestedReviewersEndToEnd:
+ def test_stale_blame_author_demoted_and_active_owner_suggested(self, team):
+ class FakeGitHub:
+ def get_commit_author_info(self, repository, sha):
+ return GitHubCommitAuthor(
+ login="old-timer",
+ name="Old Timer",
+ commit_url=f"https://github.com/acme/app/commit/{sha}",
+ file_paths=("products/signals/backend/models.py",),
+ )
+
+ activity = {
+ "products/signals": [
+ ContributorActivity(
+ login="active-owner",
+ name="Active Owner",
+ commit_count=15,
+ last_commit_at=timezone.now() - timedelta(days=2),
+ last_commit_sha="c" * 7,
+ last_commit_url="https://github.com/acme/app/commit/ccccccc",
+ ),
+ ]
+ }
+
+ with (
+ patch(
+ "products.signals.backend.report_generation.resolve_reviewers.GitHubIntegration.first_for_team_repository",
+ return_value=FakeGitHub(),
+ ),
+ patch(
+ "products.signals.backend.report_generation.resolve_reviewers.get_area_activity",
+ return_value=activity,
+ ),
+ patch(
+ "products.signals.backend.report_generation.resolve_reviewers.repository_activity_needs_rebuild",
+ return_value=False,
+ ),
+ ):
+ reviewers = resolve_suggested_reviewers(team.id, "acme/app", {"d" * 7: "introduced the bug"})
+
+ assert [r.login for r in reviewers] == ["active-owner", "old-timer"]
+ # The activity-only candidate carries their latest area commit as evidence.
+ assert reviewers[0].commits[0].sha == "c" * 7
+ assert "Recently active in `products/signals`" in reviewers[0].commits[0].reason
+ # The blame author keeps their blame commit evidence, just demoted.
+ assert reviewers[1].commits[0].sha == "d" * 7
diff --git a/products/signals/backend/test/test_reviewer_scenarios.py b/products/signals/backend/test/test_reviewer_scenarios.py
new file mode 100644
index 000000000000..c27281bfeb0f
--- /dev/null
+++ b/products/signals/backend/test/test_reviewer_scenarios.py
@@ -0,0 +1,187 @@
+"""Scenario tests for reviewer assignment: seeded history in, suggested reviewers out.
+
+Unlike the single-invariant unit tests, these run the full path a report takes — the cache
+is seeded through the real ``rebuild_repository_activity`` join (fake git log + fake GitHub
+attribution, GitHub-realistic mixed-case logins), then ``resolve_suggested_reviewers`` runs
+against blame commits. Assertions are ordinal (who outranks whom), never score values, so
+constant retuning doesn't break them. The persona cast doubles as executable documentation
+of the intended assignment behaviour.
+"""
+
+from datetime import timedelta
+
+import pytest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from posthog.models import Organization, Team
+from posthog.models.github_integration_base import GitHubCommitAttribution, GitHubCommitAuthor
+
+from products.signals.backend.report_generation.repo_activity import rebuild_repository_activity
+from products.signals.backend.report_generation.resolve_reviewers import (
+ MAX_SUGGESTED_REVIEWERS,
+ resolve_suggested_reviewers,
+)
+from products.tasks.backend.facade.repo_activity import RepositoryCommitActivity
+
+REPOSITORY = "acme/app"
+
+# The cast. Logins carry GitHub's canonical casing on purpose — the activity map lowercases
+# them at rebuild, and blame lookups must survive that mismatch (a real bug the all-lowercase
+# fixtures used to hide).
+FOUNDER = ("DepartedFounder", "[email protected]") # heavy blame, no commits in the window
+MAINTAINER = ("MariusAndra", "[email protected]") # active in the area, some blame
+NEW_JOINER = ("new-joiner", "[email protected]") # active in the area, no blame
+BOT = ("posthog[bot]", "[email protected]") # busiest committer of all, never suggestable
+NEIGHBOUR = ("SiblingDev", "[email protected]") # active in a sibling area only
+
+AREA_PATH = "products/signals/backend/models.py" # -> area products/signals
+SIBLING_PATH = "products/replay/backend/models.py" # -> area products/replay
+
+
+def _history() -> tuple[list[RepositoryCommitActivity], dict[str, tuple[str, bool]]]:
+ """~40 synthetic commits over the window, newest-first, plus GitHub's sha→login map."""
+ commits: list[RepositoryCommitActivity] = []
+ attributions: dict[str, tuple[str, bool]] = {}
+ plan = [
+ # (login, email, is_bot, path, commit_count, newest_days_ago)
+ (*MAINTAINER, False, AREA_PATH, 12, 1),
+ (*NEW_JOINER, False, AREA_PATH, 8, 2),
+ (*BOT, True, AREA_PATH, 15, 0),
+ (*NEIGHBOUR, False, SIBLING_PATH, 6, 1),
+ # The founder's window activity is zero — their blame commits below predate it.
+ ]
+ serial = 0
+ for login, _email, is_bot, path, count, newest in plan:
+ for i in range(count):
+ serial += 1
+ sha = f"{serial:07d}" + "a" * 33
+ commits.append(
+ RepositoryCommitActivity(
+ sha=sha,
+ committed_at=(timezone.now() - timedelta(days=newest + i * 2)).isoformat(),
+ paths=[path],
+ )
+ )
+ attributions[sha] = (login, is_bot)
+ commits.sort(key=lambda c: c.committed_at, reverse=True)
+ return commits, attributions
+
+
+# Blame commits: SHAs the research findings would carry, resolved via the commit API.
+# The founder authored the two most-relevant ones long ago; the maintainer one recent one.
+BLAME = {
+ "f" * 40: FOUNDER,
+ "e" * 40: FOUNDER,
+ "d" * 40: MAINTAINER,
+ "b" * 40: BOT,
+}
+
+
+class FakeBlameGitHub:
+ def get_commit_author_info(self, repository, sha):
+ login, _email = BLAME[sha]
+ return GitHubCommitAuthor(
+ login=login, # canonical casing, as the API returns it
+ name=login,
+ commit_url=f"https://github.com/{REPOSITORY}/commit/{sha}",
+ file_paths=(AREA_PATH,),
+ is_bot=login.endswith("[bot]"),
+ )
+
+
+def organization():
+ org = Organization.objects.create(name="test-reviewer-scenarios-org")
+ yield org
+ org.delete()
+
+
+def team(organization):
+ return Team.objects.create(organization=organization, name="test-reviewer-scenarios-team")
+
+
+def seeded_team(team):
+ """Seed the activity cache through the real rebuild join, not hand-built rows."""
+ commits, attributions = _history()
+
+ class FakeAttributionGitHub:
+ def list_commit_attributions(self, repository, *, since, max_pages=150):
+ return [
+ GitHubCommitAttribution(sha=sha, login=login, is_bot=is_bot)
+ for sha, (login, is_bot) in attributions.items()
+ ]
+
+ with (
+ patch(
+ "products.signals.backend.report_generation.repo_activity.collect_repository_commit_activity",
+ return_value=commits,
+ ),
+ patch(
+ "products.signals.backend.report_generation.repo_activity.GitHubIntegration.first_for_team_repository",
+ return_value=FakeAttributionGitHub(),
+ ),
+ ):
+ rebuild_repository_activity(team.id, REPOSITORY)
+ return team
+
+
+def _resolve(team, blame_shas: list[str]):
+ with patch(
+ "products.signals.backend.report_generation.resolve_reviewers.GitHubIntegration.first_for_team_repository",
+ return_value=FakeBlameGitHub(),
+ ):
+ return resolve_suggested_reviewers(team.id, REPOSITORY, dict.fromkeys(blame_shas, "relevant"))
+
+
+class TestReviewerScenarios:
+ def test_active_maintainer_outranks_departed_founder(self, seeded_team):
+ reviewers = _resolve(seeded_team, ["f" * 40, "e" * 40, "d" * 40])
+
+ logins = [r.login for r in reviewers]
+ # The founder owns the two strongest blame commits but left months ago; the
+ # maintainer holds weaker blame and current area activity.
+ assert logins.index("mariusandra") < logins.index("departedfounder")
+
+ def test_mixed_case_blame_login_is_one_active_candidate(self, seeded_team):
+ reviewers = _resolve(seeded_team, ["d" * 40])
+
+ # The API returned MariusAndra, the map stores mariusandra — one entry, top-ranked
+ # (active blame author), never a stale-scored duplicate pair.
+ assert reviewers[0].login == "mariusandra"
+ lowered = [r.login.lower() for r in reviewers]
+ assert len(lowered) == len(set(lowered))
+
+ def test_new_joiner_surfaces_when_all_blame_is_stale(self, seeded_team):
+ reviewers = _resolve(seeded_team, ["f" * 40, "e" * 40])
+
+ logins = [r.login for r in reviewers]
+ # Everyone in blame is gone; the area's actual current contributors fill in.
+ assert "mariusandra" in logins
+ assert "new-joiner" in logins
+ if "departedfounder" in logins:
+ assert logins.index("mariusandra") < logins.index("departedfounder")
+
+ def test_bots_never_suggested(self, seeded_team):
+ # The bot is both the busiest area committer and a blame author.
+ reviewers = _resolve(seeded_team, ["b" * 40, "f" * 40])
+
+ assert all("[bot]" not in r.login for r in reviewers)
+
+ def test_sibling_area_contributor_stays_out_of_a_healthy_area(self, seeded_team):
+ reviewers = _resolve(seeded_team, ["d" * 40])
+
+ assert "siblingdev" not in [r.login for r in reviewers]
+
+ def test_at_most_three_and_deterministic(self, seeded_team):
+ first = _resolve(seeded_team, ["f" * 40, "e" * 40, "d" * 40])
+ second = _resolve(seeded_team, ["f" * 40, "e" * 40, "d" * 40])
+
+ assert len(first) <= MAX_SUGGESTED_REVIEWERS
+ assert [(r.login, [c.sha for c in r.commits]) for r in first] == [
+ (r.login, [c.sha for c in r.commits]) for r in second
+ ]
diff --git a/products/tasks/backend/facade/repo_activity.py b/products/tasks/backend/facade/repo_activity.py
new file mode 100644
index 000000000000..4b4cbcdb482e
--- /dev/null
+++ b/products/tasks/backend/facade/repo_activity.py
@@ -0,0 +1,19 @@
+"""Facade re-export for repository commit-activity collection.
+
+Runs one deterministic ``git log`` pass against a history-only clone in a
+short-lived sandbox and returns plain data — no agent, no ORM models. Kept out
+of ``facade/api.py`` so the heavy sandbox dependencies stay off the light
+data-surface import path.
+"""
+
+from products.tasks.backend.logic.services.repo_commit_activity import (
+ RepositoryCommitActivity,
+ RepositoryCommitActivityError,
+ collect_repository_commit_activity,
+)
+
+__all__ = [
+ "RepositoryCommitActivity",
+ "RepositoryCommitActivityError",
+ "collect_repository_commit_activity",
+]
diff --git a/products/tasks/backend/logic/services/repo_commit_activity.py b/products/tasks/backend/logic/services/repo_commit_activity.py
new file mode 100644
index 000000000000..704888a268ef
--- /dev/null
+++ b/products/tasks/backend/logic/services/repo_commit_activity.py
@@ -0,0 +1,182 @@
+"""Collect recent commit activity from a repository's git history.
+
+Boots a short-lived sandbox, makes a minimal history-only clone
+(``--shallow-since --filter=blob:none --no-checkout``), runs one
+``git log --name-only`` pass, parses it, and destroys the sandbox. No agent
+runs; callers get plain data.
+"""
+
+import re
+import shlex
+from dataclasses import dataclass
+
+import structlog
+
+from posthog.models.integration import GitHubIntegration
+
+# Import names only — pulling `Sandbox` at module level would trigger the module's lazy
+# resolver and drag the modal/temporal runtime onto the Django startup path.
+from products.tasks.backend.logic.services.sandbox import (
+ WORKING_DIR,
+ SandboxBase,
+ SandboxConfig,
+ SandboxTemplate,
+ get_sandbox_class,
+ sandbox_repo_path,
+)
+
+logger = structlog.get_logger(__name__)
+
+_RECORD_SEP = "\x01"
+_FIELD_SEP = "\x1f"
+
+_CLONE_TIMEOUT_SECONDS = 10 * 60
+_LOG_TIMEOUT_SECONDS = 3 * 60
+# Hard byte cap on git log output: sandbox.execute reads all stdout into the worker, and
+# --max-count bounds commits, not paths — one pathological tree-wide commit could otherwise
+# balloon the transfer. ~3x a very active monorepo's real 90-day output (~20MB).
+_MAX_LOG_BYTES = 64 * 1024 * 1024
+
+DEFAULT_SINCE_DAYS = 90
+# Runaway backstop only — sized well above a very active monorepo's 90-day non-merge count
+# (posthog/posthog ≈ 8k). Truncating newest-first would silently drop the window's older
+# half, making its contributors look fully stale instead of decayed.
+DEFAULT_MAX_COMMITS = 20_000
+
+
+class RepositoryCommitActivityError(Exception):
+ pass
+
+
+@dataclass(frozen=True)
+class RepositoryCommitActivity:
+ """One commit from the repository's recent default-branch history, newest-first.
+
+ Deliberately no author name/email: commit metadata is attacker-controlled free text
+ that could embed the parser's delimiters and forge records. Identity comes from
+ GitHub's sha→login attribution; the parsed format contains only sha and date.
+ """
+
+ sha: str
+ committed_at: str # ISO 8601 committer date — same axis the --since filter selects on
+ paths: list[str]
+
+
+def collect_repository_commit_activity(
+ team_id: int,
+ repository: str,
+ *,
+ since_days: int = DEFAULT_SINCE_DAYS,
+ max_commits: int = DEFAULT_MAX_COMMITS,
+) -> list[RepositoryCommitActivity]:
+ """Return the repository's commits from the last ``since_days`` days, newest-first.
+
+ Raises :class:`RepositoryCommitActivityError` when no GitHub integration can access
+ the repository or the clone/log fails.
+ """
+ repository = repository.strip().lower()
+ github = GitHubIntegration.first_for_team_repository(team_id, repository, source="repo_commit_activity")
+ if github is None:
+ raise RepositoryCommitActivityError(f"No GitHub integration for team {team_id} can access {repository}")
+ github_token = github.get_access_token()
+
+ sandbox = get_sandbox_class().create(
+ SandboxConfig(
+ name=f"repo-activity-{team_id}",
+ # Git-only job, no agent server — the slim image boots faster (stamphog precedent).
+ template=SandboxTemplate.SLIM_BASE,
+ # The token reaches the clone URL via ${GITHUB_TOKEN} expansion inside the
+ # sandbox — never in the command string, which sandbox provider/timeout
+ # exceptions carry into logs and exception capture unredacted.
+ environment_variables={"GITHUB_TOKEN": github_token},
+ snapshot_id=None,
+ metadata={"purpose": "repo_commit_activity"},
+ )
+ )
+ try:
+ _clone_history(sandbox, repository, github_token, since_days)
+ return _read_log(sandbox, repository, since_days, max_commits)
+ finally:
+ try:
+ sandbox.destroy()
+ except Exception:
+ logger.warning("repo_commit_activity: sandbox destroy failed", sandbox_id=sandbox.id, exc_info=True)
+
+
+def _clone_history(sandbox: SandboxBase, repository: str, github_token: str, since_days: int) -> None:
+ # `repository` passed first_for_team_repository's safe-path check, so it's plain
+ # owner/repo and safe inside double quotes. The token placeholder expands from the
+ # sandbox environment; the command string itself never contains the credential.
+ org, repo = repository.split("/")
+ repo_url = f'"https://x-access-token:${{GITHUB_TOKEN}}@github.com/{org}/{repo}.git"'
+ target_path = sandbox_repo_path(repository)
+ org_path = f"{WORKING_DIR}/repos/{org}"
+ command = (
+ f"rm -rf {shlex.quote(target_path)} && "
+ f"mkdir -p {shlex.quote(org_path)} && "
+ f"cd {shlex.quote(org_path)} && "
+ f"git clone --single-branch --no-checkout --filter=blob:none "
+ f"--shallow-since={shlex.quote(f'{since_days} days')} {repo_url} {shlex.quote(repo)}"
+ )
+ result = sandbox.execute(command, timeout_seconds=_CLONE_TIMEOUT_SECONDS)
+ if result.exit_code != 0:
+ # Git argv sees the expanded URL, so fatal messages can still echo the token.
+ stderr = result.stderr.replace(github_token, "<redacted>") if github_token else result.stderr
+ raise RepositoryCommitActivityError(
+ f"History clone of {repository} failed with exit code {result.exit_code}: {stderr[:300]}"
+ )
+
+
+def _read_log(
+ sandbox: SandboxBase, repository: str, since_days: int, max_commits: int
+) -> list[RepositoryCommitActivity]:
+ target_path = sandbox_repo_path(repository)
+ # %cd (committer date): the same axis --since filters on, and when the change landed.
+ # No free-form fields (%an/%ae): commit metadata can embed the delimiters and forge
+ # records; sha and date are further shape-validated in _parse_log.
+ pretty = f"{_RECORD_SEP}%H{_FIELD_SEP}%cd"
+ log_command = (
+ f"git -C {shlex.quote(target_path)} log "
+ # --no-renames: inexact rename detection compares blob contents, which a blobless
+ # clone fetches over the network per candidate pair; a rename crediting both the
+ # old and new path's areas is also better data for activity mapping.
+ f"--since={shlex.quote(f'{since_days} days')} --no-merges --no-renames --max-count={max_commits} "
+ f"--date=iso-strict --pretty=format:{shlex.quote(pretty)} --name-only"
+ )
+ # Stage to a file and ship at most _MAX_LOG_BYTES+1 back: the worker reads all stdout
+ # into memory, so the byte cap is enforced sandbox-side. The sentinel extra byte
+ # distinguishes "exactly at the limit" from "truncated"; && preserves git's exit code.
+ command = f"{log_command} > /tmp/repo-activity.log && head -c {_MAX_LOG_BYTES + 1} /tmp/repo-activity.log"
+ result = sandbox.execute(command, timeout_seconds=_LOG_TIMEOUT_SECONDS)
+ if result.exit_code != 0:
+ raise RepositoryCommitActivityError(
+ f"git log of {repository} failed with exit code {result.exit_code}: {result.stderr[:300]}"
+ )
+ if len(result.stdout.encode()) > _MAX_LOG_BYTES:
+ raise RepositoryCommitActivityError(
+ f"git log of {repository} exceeded {_MAX_LOG_BYTES} bytes; refusing to build a truncated map"
+ )
+ return _parse_log(result.stdout)
+
+
+_SHA_RE = re.compile(r"^[0-9a-f]{40}$")
+_ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[+-]\d{2}:\d{2}|Z)$")
+
+
+def _parse_log(stdout: str) -> list[RepositoryCommitActivity]:
+ commits: list[RepositoryCommitActivity] = []
+ for record in stdout.split(_RECORD_SEP):
+ if not record.strip():
+ continue
+ header, _, body = record.partition("\n")
+ fields = header.split(_FIELD_SEP)
+ if len(fields) != 2:
+ continue
+ sha, committed_at = (field.strip() for field in fields)
+ # Strict shape validation: only records that look exactly like git's own output
+ # join against GitHub attribution.
+ if not _SHA_RE.match(sha) or not _ISO_DATE_RE.match(committed_at):
+ continue
+ paths = [line.strip() for line in body.splitlines() if line.strip()]
+ commits.append(RepositoryCommitActivity(sha=sha, committed_at=committed_at, paths=paths))
+ return commits
diff --git a/products/tasks/backend/logic/services/test_repo_commit_activity.py b/products/tasks/backend/logic/services/test_repo_commit_activity.py
new file mode 100644
index 000000000000..7e60d6197fce
--- /dev/null
+++ b/products/tasks/backend/logic/services/test_repo_commit_activity.py
@@ -0,0 +1,37 @@
+from products.tasks.backend.logic.services.repo_commit_activity import _parse_log
+
+_SHA_A = "a" * 40
+_SHA_B = "b" * 40
+_SHA_C = "c" * 40
+
+
+def test_parse_log_extracts_commits_with_paths():
+ stdout = (
+ f"\x01{_SHA_A}\x1f2026-07-10T10:00:00+00:00\n"
+ "products/signals/backend/models.py\n"
+ "products/signals/backend/tasks.py\n"
+ f"\x01{_SHA_B}\x1f2026-07-01T09:00:00+00:00\n"
+ "posthog/models/user.py\n"
+ )
+
+ commits = _parse_log(stdout)
+
+ assert [c.sha for c in commits] == [_SHA_A, _SHA_B]
+ assert commits[0].paths == [
+ "products/signals/backend/models.py",
+ "products/signals/backend/tasks.py",
+ ]
+ assert commits[1].committed_at == "2026-07-01T09:00:00+00:00"
+
+
+def test_parse_log_skips_malformed_records_and_handles_empty_output():
+ assert _parse_log("") == []
+ assert _parse_log("\x01broken-header-without-separators\nsome/path.py\n") == []
+ # Shape validation: non-hex sha and non-ISO date records are dropped, so free-text
+ # fields can't forge a record even if they smuggle the delimiters in.
+ assert _parse_log("\x01not-a-sha\x1f2026-07-05T08:00:00+00:00\npath.py\n") == []
+ assert _parse_log(f"\x01{_SHA_C}\x1fyesterday\npath.py\n") == []
+
+ commits = _parse_log(f"\x01{_SHA_C}\x1f2026-07-05T08:00:00+00:00\n")
+ assert len(commits) == 1
+ assert commits[0].paths == []