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): let scouts own report reviewer routing, owners are context (#73515)

Andrew Maguire6d18b39d74ab
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index 01de720437c1..6a6cdcff4390 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -54,8 +54,8 @@ class ReviewerContent(TypedDict):
github_name: str | None
relevant_commits: list[dict]
reason: str | None
- # True for entries injected by the scout owner guardrail (editor-controlled `LLMSkillOwner`).
- # These route the report but are never eligible to select the autostart task identity.
+ # True when a scout's own reviewer pick matches a current `LLMSkillOwner` (editor-controlled) and
+ # was stamped for it. These route the report but are never eligible to select the autostart task identity.
is_skill_owner: bool
@@ -297,18 +297,19 @@ def _resolve_autostart_assignee(
reviewer at all — it runs as the triggering user (see `_resolve_triggering_user`), so a user
can't name a colleague and have the agent run under that colleague's identity.
- Owner-provenance entries (``is_skill_owner``) are excluded from identity selection: the scout
- owner guardrail injects them from an editor-controlled `LLMSkillOwner`, so treating them as a
- trusted commit-authorship signal would let a skill editor name a privileged teammate as owner
- and have the implementation agent mint an OAuth session under that teammate. They still route
- the report (they remain in the artefact); they just can't be the runner.
+ Owner-provenance entries (``is_skill_owner``) are excluded from identity selection: a scout is
+ steered by its editor-controlled skill body, so a picked reviewer who is a current `LLMSkillOwner`
+ is stamped on the way in — treating that pick as a trusted commit-authorship signal would let a
+ skill editor name a privileged teammate as owner, steer the scout to pick them, and have the
+ implementation agent mint an OAuth session under that teammate. They still route the report (they
+ remain in the artefact); they just can't be the runner.
Walks *reviewers_content* in order (most relevant first). A reviewer's effective threshold is
their personal autonomy setting when present, otherwise the team default (itself "all
priorities"/P4 when the team has no config row). A lower rank means higher priority. Returns
the first matching ``User``, or ``None`` if no reviewer maps to an org member.
"""
- # Owner-injected entries never select the task identity (see docstring). Filter before resolving
+ # Owner-stamped entries never select the task identity (see docstring). Filter before resolving
# so their logins aren't even looked up as candidates.
identity_candidates = [r for r in reviewers_content if not r.get("is_skill_owner")]
login_to_user = resolve_org_github_login_to_users(
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 31e3b17f14dd..0d708cada5fa 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -64,9 +64,13 @@ it is exercised via the `run_signals_scout` management command (see `../manageme
resolved server-side), which the escalation guidance points `suggested_reviewers` at (owner
first, via `scout-members-list`) — without it a scout only sees its pinned version's
`created_by`, i.e. the last editor, and would route ownership to whoever most recently touched
- the skill. This prompt line is advisory; the deterministic backstop is the owner guardrail in
- `tools/report.py._build_suggested_reviewers`, which places the skill's owners ahead of the
- model's picks regardless of what it wrote. The line is gated on the report channel: a
+ the skill. The scout owns routing: this line is context, not a rule, so a skill body can steer
+ `suggested_reviewers` elsewhere (a named reviewer, a team convention) or say "don't route to me"
+ and be honoured — `tools/report.py._build_suggested_reviewers` injects nothing, it only takes
+ the scout's picks. Owners feed exactly one code rule there — a picked reviewer who is a current
+ owner is stamped `is_skill_owner=True` so autostart never mints its session under an
+ editor-controlled owner (`auto_start._resolve_autostart_assignee`); the stamp changes identity
+ eligibility, never who reviews. The line is gated on the report channel: a
signal-channel scout has no `suggested_reviewers` field, so member names/emails (PII) must not
reach its prompt.
- `skill_loader.py`
@@ -81,7 +85,7 @@ it is exercised via the `run_signals_scout` management command (see `../manageme
then editors by last-edit recency, capped). Both paths are restricted to
`team.all_users_with_access()` so a revoked user's profile stops flowing into a privileged prompt.
`resolve_skill_owner_user_uuids` exposes the owner set (seed-creator first) to the report tools'
- reviewer guardrail. Author resolution is opt-in via `load_skill_for_run(..., include_authors=True)`
+ reviewer provenance stamp (`is_skill_owner`). Author resolution is opt-in via `load_skill_for_run(..., include_authors=True)`
— only the runner's prompt-building path pays for it; the report-authorization gate in `views.py`
loads the skill per report write just to check `allowed_tools` and skips it.
- `lazy_seed.py`
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index 33b77148be6f..f98506310965 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -246,40 +246,17 @@ def _build_priority(priority: str | None, explanation: str | None) -> PriorityAs
return PriorityAssessment(priority=priority_level, explanation=explanation)
-def _owner_reviewer_entries(team: Team, skill_name: str) -> list[SuggestedReviewerEntry]:
- """The running scout's owners as reviewer entries (GitHub logins), seed-creator first.
+def _owner_logins(team: Team, skill_name: str) -> set[str]:
+ """The running scout's owner GitHub logins (lowercased), for stamping reviewer provenance.
- This is the deterministic half of the guardrail: owners come from `LLMSkillOwner`, not the model's
- prose, so ownership is always represented regardless of what the LLM picked. Owners with no linked
- GitHub identity are skipped — a `suggested_reviewers` artefact is GitHub-login-keyed, so there's no
- one to route to (the prompt still names them by email)."""
+ Owners come from `LLMSkillOwner`. Owners with no linked GitHub identity aren't included — they
+ can't be a routable reviewer, and provenance only matters for a login that could appear in the
+ artefact. Used to mark, not to inject: routing is the scout's call (see `_build_suggested_reviewers`)."""
owner_uuids = resolve_skill_owner_user_uuids(team, skill_name)
if not owner_uuids:
- return []
+ return set()
uuid_to_login = get_org_member_github_logins_by_user_uuid(team.id, owner_uuids)
- entries: list[SuggestedReviewerEntry] = []
- seen: set[str] = set()
- for owner_uuid in owner_uuids:
- login = uuid_to_login.get(owner_uuid) # already lowercased by the resolver
- if not login or login in seen:
- continue
- seen.add(login)
- # `is_skill_owner=True` is the provenance flag autostart uses to keep these editor-controlled
- # entries out of task-identity selection — they route the report but never mint a session.
- entries.append(SuggestedReviewerEntry(github_login=login, reason="skill owner", is_skill_owner=True))
- return entries
-
-
-def _skill_authored_report(team: Team, skill_name: str, report_id: str) -> bool:
- """Whether any run of this (team, skill) emitted the report. Reports carry no skill column — the
- run-side `emitted_report_ids` tally is the authorship record, so the check is a containment query
- across the skill's runs. `for_team` (not the ambient-context manager) so it works on the async
- harness path too, where no request scope is set and the fail-closed manager would raise."""
- return (
- SignalScoutRun.objects.for_team(team.id)
- .filter(skill_name=skill_name, emitted_report_ids__contains=report_id)
- .exists()
- )
+ return {login for login in uuid_to_login.values() if login} # already lowercased by the resolver
def _build_suggested_reviewers(
@@ -287,7 +264,6 @@ def _build_suggested_reviewers(
reviewers: list[ReviewerInput] | None,
*,
skill_name: str | None = None,
- enforce_owners: bool = False,
) -> SuggestedReviewers | None:
"""Resolve reviewer entries to a canonical, lowercased, deduped `suggested_reviewers` artefact
(GitHub logins), or None to omit it.
@@ -300,84 +276,75 @@ def _build_suggested_reviewers(
rather than silently dropping the reviewer, since a quietly-lost reviewer is what leaves a report
routed to no one.
- **Owner guardrail:** with `enforce_owners` and a `skill_name`, the running scout's owners
- (`LLMSkillOwner`) are resolved deterministically and placed *first*, ahead of the model's picks —
- so a report about a scout always routes to whoever owns it, even if the model picked the wrong
- person or none at all. This is a code rule the LLM can't prose past; it replaces the old reliance
- on the model reading a prompt line correctly. Owners and the model's picks are then deduped by
- login and capped, owners never dropped; an owner the scout also names keeps owner provenance
- (`is_skill_owner=True`), since a steerable scout repeating an owner is not independent evidence.
+ **The scout owns routing.** Owners are *not* injected here — they're surfaced to the scout as
+ context (the run prompt's skill-owners line) so it can decide, and a skill body that says "route
+ to X" or "don't route to me" is honoured because nothing overrides the scout's picks. When the
+ scout picks no one, the report routes to no one; when it picks someone, that's the routing.
+
+ **Owner provenance (an identity guardrail, not a routing one).** With a `skill_name`, a picked
+ reviewer whose login is a current skill owner is stamped `is_skill_owner=True`. This never changes
+ *who* reviews — it only marks the entry so autostart can't mint its session under that login
+ (`_resolve_autostart_assignee`). A scout is steered by its editor-controlled skill body, so a pick
+ that happens to match an owner is not independent commit-authorship evidence; without the stamp a
+ skill editor could name a privileged member as owner, steer the scout to pick that login, and have
+ the implementation agent run as them. The owner still routes the report (they stay in the
+ artefact); they just can't be the runner.
Does DB reads (UUID + owner resolution), so callers on the async path must bridge it off the event
loop."""
- owner_entries = _owner_reviewer_entries(team, skill_name) if enforce_owners and skill_name else []
-
- if not reviewers and not owner_entries:
+ if not reviewers:
return None
- scout_entries: list[SuggestedReviewerEntry] = []
- if reviewers:
- # Cap the input list *before* resolving — otherwise a malformed call with hundreds of uuid
- # entries would fire one unbounded `IN` query (parameter/timeout risk) just to be rejected
- # afterwards. The DRF ListField enforces the same bound at the API boundary; this guards the
- # direct callers too.
- if len(reviewers) > MAX_SUGGESTED_REVIEWERS:
- raise InvalidScoutReportError(
- f"at most {MAX_SUGGESTED_REVIEWERS} suggested reviewers, got {len(reviewers)}"
- )
+ # Cap the input list *before* resolving — otherwise a malformed call with hundreds of uuid
+ # entries would fire one unbounded `IN` query (parameter/timeout risk) just to be rejected
+ # afterwards. The DRF ListField enforces the same bound at the API boundary; this guards the
+ # direct callers too.
+ if len(reviewers) > MAX_SUGGESTED_REVIEWERS:
+ raise InvalidScoutReportError(f"at most {MAX_SUGGESTED_REVIEWERS} suggested reviewers, got {len(reviewers)}")
- for entry in reviewers:
- has_login = bool(entry.github_login and entry.github_login.strip())
- if not has_login and not entry.user_uuid:
- raise InvalidScoutReportError("each suggested reviewer needs a github_login or a user_uuid")
-
- uuids_to_resolve = [str(entry.user_uuid) for entry in reviewers if entry.user_uuid]
- uuid_to_login = get_org_member_github_logins_by_user_uuid(team.id, uuids_to_resolve) if uuids_to_resolve else {}
-
- for entry in reviewers:
- if entry.user_uuid:
- resolved = uuid_to_login.get(str(entry.user_uuid))
- if not resolved:
- raise InvalidScoutReportError(
- f"user_uuid '{entry.user_uuid}' is not an org member of this team with a linked GitHub identity"
- )
- login = resolved.lower()
- else:
- login = (entry.github_login or "").strip().lower()
- if not login:
- raise InvalidScoutReportError("github_login resolved to empty after normalization")
- reason = entry.reason.strip() if entry.reason and entry.reason.strip() else None
- scout_entries.append(SuggestedReviewerEntry(github_login=login, reason=reason))
-
- # Owners first (guardrail), then the scout's picks; dedupe by login so an owner the scout also
- # named isn't listed twice, and cap — owners lead, so they're never the ones truncated. An owner
- # the scout *also* picked keeps `is_skill_owner=True` (only the scout's reason merges in): the
- # skill body is the run's steering layer, so a scout repeating an owner's login is not
- # independent commit-authorship evidence — clearing the flag would let a skill editor name a
- # privileged member as owner, steer the scout to repeat that login, and mint the autostart
- # session as them. The invariant is that an owner row never adds identity eligibility; an
- # owner-picked reviewer still routes the report, and autostart falls to the next non-owner
- # reviewer or the team fallback.
- entries_by_login: dict[str, SuggestedReviewerEntry] = {e.github_login: e for e in owner_entries}
+ for entry in reviewers:
+ has_login = bool(entry.github_login and entry.github_login.strip())
+ if not has_login and not entry.user_uuid:
+ raise InvalidScoutReportError("each suggested reviewer needs a github_login or a user_uuid")
+
+ uuids_to_resolve = [str(entry.user_uuid) for entry in reviewers if entry.user_uuid]
+ uuid_to_login = get_org_member_github_logins_by_user_uuid(team.id, uuids_to_resolve) if uuids_to_resolve else {}
+
+ scout_entries: list[SuggestedReviewerEntry] = []
+ for entry in reviewers:
+ if entry.user_uuid:
+ resolved = uuid_to_login.get(str(entry.user_uuid))
+ if not resolved:
+ raise InvalidScoutReportError(
+ f"user_uuid '{entry.user_uuid}' is not an org member of this team with a linked GitHub identity"
+ )
+ login = resolved.lower()
+ else:
+ login = (entry.github_login or "").strip().lower()
+ if not login:
+ raise InvalidScoutReportError("github_login resolved to empty after normalization")
+ reason = entry.reason.strip() if entry.reason and entry.reason.strip() else None
+ scout_entries.append(SuggestedReviewerEntry(github_login=login, reason=reason))
+
+ # Dedupe by login (a login + its uuid can resolve to the same person), preserving the scout's
+ # order — there's no reordering, so the scout's ranking is the routing order.
+ entries_by_login: dict[str, SuggestedReviewerEntry] = {}
for scout_entry in scout_entries:
- existing = entries_by_login.get(scout_entry.github_login)
- if existing is None:
- entries_by_login[scout_entry.github_login] = scout_entry
- elif existing.is_skill_owner and scout_entry.reason:
- entries_by_login[scout_entry.github_login] = SuggestedReviewerEntry(
- github_login=scout_entry.github_login,
- reason=scout_entry.reason,
- is_skill_owner=True,
- )
- merged = list(entries_by_login.values())
- entries = merged[:MAX_SUGGESTED_REVIEWERS]
- # A skill can have more routable owners than the reviewer cap (MAX_SKILL_OWNERS exceeds it), and
- # owner entries never carry PR intent — so an owner-only capped list would silently discard the
- # scout's explicit picks and with them the `_wants_repo_selection` signal. Reserve the last slot
- # for the first non-owner pick so routing keeps owners first but intent survives the cap.
- non_owner_picks = [e for e in merged if not e.is_skill_owner]
- if non_owner_picks and all(e.is_skill_owner for e in entries):
- entries = [*merged[: MAX_SUGGESTED_REVIEWERS - 1], non_owner_picks[0]]
+ entries_by_login.setdefault(scout_entry.github_login, scout_entry)
+ entries = list(entries_by_login.values())[:MAX_SUGGESTED_REVIEWERS]
+
+ # Stamp owner provenance on picks that match a current owner. Recomputed from the live owner set
+ # every call, so a former owner picked as a plain reviewer isn't left flagged (which would keep
+ # excluding them from autostart identity). This marks identity eligibility only; it never adds,
+ # removes, or reorders a reviewer.
+ owners = _owner_logins(team, skill_name) if skill_name else set()
+ if owners:
+ entries = [
+ e
+ if e.github_login not in owners
+ else SuggestedReviewerEntry(github_login=e.github_login, reason=e.reason, is_skill_owner=True)
+ for e in entries
+ ]
if not entries:
return None
@@ -392,12 +359,20 @@ def _wants_repo_selection(
report that supplies none of these skips selection entirely, so it never pays for the (free-form)
selection sandbox just to surface in the inbox.
- Owner-guardrail entries don't count as PR intent: they're injected on every emit for routing, so
- counting them would run free-form repo selection — and later autostart under the team fallback
- runner — for a prioritized report whose scout supplied neither a repo nor a reviewer."""
+ Every reviewer here is a scout pick (nothing is injected), so any reviewer counts as intent — even
+ one who happens to be a skill owner, since the scout chose to route to them. `is_skill_owner` only
+ governs autostart identity, not intent.
+
+ So an owner-only pick now counts as intent and can reach autostart — but never as the owner:
+ `auto_start._resolve_autostart_assignee` still excludes `is_skill_owner` picks from identity, so an
+ owner-only pick resolves the runner through the reviewer-less fallback
+ (`_resolve_autostart_fallback_user`) — the team's signals-enabler or org admin, derived from
+ team/org config a skill editor can't control. A steered owner-only pick can at most trigger that
+ same trusted fallback an editor could already trigger with any non-resolving pick; it never lets the
+ editor-controlled owner become the runner."""
if repository is not None:
return True
- scout_picked_reviewer = reviewers is not None and any(not entry.is_skill_owner for entry in reviewers.root)
+ scout_picked_reviewer = reviewers is not None and bool(reviewers.root)
return priority is not None and scout_picked_reviewer
@@ -806,7 +781,7 @@ async def emit_report(
# Resolves user_uuid → github_login (a DB read), so bridge it off the event loop. Runs before the
# safety judge so an unresolvable reviewer fails fast rather than after paying for the LLM call.
reviewers = await database_sync_to_async(_build_suggested_reviewers, thread_sensitive=False)(
- team, suggested_reviewers, skill_name=run.skill_name, enforce_owners=True
+ team, suggested_reviewers, skill_name=run.skill_name
)
preflight = await database_sync_to_async(_preflight_emit_gates, thread_sensitive=False)(team, run)
@@ -914,7 +889,7 @@ def emit_report_sync(
explanation=actionability_explanation, choice=actionability, already_addressed=already_addressed
)
priority_assessment = _build_priority(priority, priority_explanation)
- reviewers = _build_suggested_reviewers(team, suggested_reviewers, skill_name=run.skill_name, enforce_owners=True)
+ reviewers = _build_suggested_reviewers(team, suggested_reviewers, skill_name=run.skill_name)
preflight = _preflight_emit_gates(team, run)
if preflight is not None:
@@ -1015,15 +990,11 @@ def _do_edit_report(
# first means a combined edit (title/summary + a bad reviewer) fails before the content write
# commits, rather than leaving the report partially mutated behind a failed call.
#
- # Enforce owners only when this edit actually sets reviewers — otherwise a title-only edit would
- # inject owners over a routing a human may have already chosen — and only on a report this skill
- # authored: `edit_report` can target any inbox report, and the guardrail exists to make a scout's
- # own reports route to its owners, not to stamp the editing skill's owners onto unrelated reports.
# When no reviewers are supplied, this resolves to None and existing reviewers are left untouched.
- enforce_owners = bool(suggested_reviewers) and _skill_authored_report(team, run.skill_name, report_id)
- reviewers = _build_suggested_reviewers(
- team, suggested_reviewers, skill_name=run.skill_name, enforce_owners=enforce_owners
- )
+ # When reviewers are supplied, the scout's picks replace them verbatim (nothing injected); owner
+ # provenance is stamped so a picked owner still can't become the autostart identity, regardless of
+ # which report the edit targets.
+ reviewers = _build_suggested_reviewers(team, suggested_reviewers, skill_name=run.skill_name)
updated_fields: list[str] = []
if title is not None or summary is not None:
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index f4ff81adb619..351d28fcefe1 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -27,7 +27,6 @@ from products.signals.backend.scout_harness.tools.report import (
_build_suggested_reviewers,
_capture_report_edited,
_report_classification_props,
- _skill_authored_report,
_wants_repo_selection,
)
from products.signals.backend.temporal.report_safety_judge import SafetyJudgeResponse
@@ -415,39 +414,29 @@ class TestScoutReportAPI(APIBaseTest):
assert stored["alice"]["reason"] == "confirmed owner via human correction"
assert stored["dave"]["relevant_commits"] == []
- def test_edit_report_injects_owners_only_into_reports_the_skill_authored(self) -> None:
- # The owner guardrail on edit is scoped to reports the skill authored: `edit_report` can
- # target any inbox report, and stamping the editing skill's owners onto an unrelated
- # (e.g. pipeline-authored) report would rewrite that report's routing on no evidence.
+ def test_edit_uses_scout_picks_verbatim_and_stamps_owners_on_any_report(self) -> None:
+ # No injection: an edit replaces reviewers with the scout's picks in order, even on a report
+ # the skill didn't author. But a picked *owner* is stamped `is_skill_owner=True` on any report
+ # the scout edits, so a steered scout can't launder autostart identity through a foreign one.
self._seed_skill_owner("scoutowner")
run = _make_run(self.team)
- with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
- authored = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
foreign = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title="pipeline report")
-
with patch(AUTOSTART_PATH, new=AsyncMock()):
- for report_id in (authored["report_id"], str(foreign.id)):
- response = self.client.post(
- self._edit_url(str(run.id)),
- data={"report_id": report_id, "suggested_reviewers": [{"github_login": "picked"}]},
- format="json",
- )
- assert response.status_code == status.HTTP_200_OK, response.json()
-
- assert self._reviewer_logins(authored["report_id"]) == ["scoutowner", "picked"]
- assert self._reviewer_logins(str(foreign.id)) == ["picked"]
-
- def test_skill_authored_report_resolves_without_ambient_team_scope(self) -> None:
- # `SignalScoutRun` is on a fail-closed manager; the async harness path (temporal runner) has
- # no ambient request scope, so the helper must query via `for_team` — the ambient-context
- # manager would raise TeamScopeError there. This direct call runs with no request scope,
- # exactly like the runner.
- run = _make_run(self.team)
- with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
- created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
- foreign = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title="pipeline")
- assert _skill_authored_report(self.team, "signals-scout-general", created["report_id"]) is True
- assert _skill_authored_report(self.team, "signals-scout-general", str(foreign.id)) is False
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={
+ "report_id": str(foreign.id),
+ "suggested_reviewers": [{"github_login": "scoutowner"}, {"github_login": "picked"}],
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ artefact = self._latest_artefact(str(foreign.id), SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS)
+ assert artefact is not None
+ stored = {e["github_login"]: e for e in json.loads(artefact.content)}
+ assert self._reviewer_logins(str(foreign.id)) == ["scoutowner", "picked"]
+ assert stored["scoutowner"]["is_skill_owner"] is True
+ assert stored["picked"]["is_skill_owner"] is False
def test_edit_readding_former_owner_clears_owner_provenance(self) -> None:
# A former owner re-added as a normal reviewer must lose `is_skill_owner`: provenance is
@@ -455,8 +444,13 @@ class TestScoutReportAPI(APIBaseTest):
# flag forward would keep excluding them from autostart identity selection.
self._seed_skill_owner("formerowner")
run = _make_run(self.team)
+ # The scout picks the (then-)owner as reviewer; the pick is stamped as owner provenance.
with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):
- created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ created = self.client.post(
+ self._emit_url(str(run.id)),
+ data=self._payload(suggested_reviewers=[{"github_login": "formerowner"}]),
+ format="json",
+ ).json()
report_id = created["report_id"]
artefact = self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS)
assert artefact is not None
@@ -799,113 +793,60 @@ class TestBuildSuggestedReviewers(APIBaseTest):
def _seed_owner(self, skill_name: str, user: User) -> None:
LLMSkillOwner.objects.for_team(self.team.id).create(team=self.team, skill_name=skill_name, user=user)
- def test_owners_enforced_first_and_deduped(self) -> None:
- # The guardrail: the running scout's owners are routed first, ahead of the model's picks, so a
- # report about a scout always reaches whoever owns it — even if the model also names the owner
- # (deduped) or picks someone else too. A regression that drops the guardrail routes to the
- # model's pick alone.
- self._seed_owner("signals-scout-x", self._github_member("ownerlogin"))
- result = _build_suggested_reviewers(
- self.team,
- [ReviewerInput(github_login="ownerlogin"), ReviewerInput(github_login="other")],
- skill_name="signals-scout-x",
- enforce_owners=True,
- )
- assert result is not None
- assert [e.github_login for e in result.root] == ["ownerlogin", "other"]
- assert result.root[0].reason == "skill owner"
-
- def test_owner_injected_when_scout_supplies_no_reviewers(self) -> None:
- # Foolproof routing: a report authored with no reviewers still routes to the owner, rather
- # than to no one.
+ def test_no_reviewers_yields_none_even_with_owners(self) -> None:
+ # The scout owns routing: with no picks the report routes to no one. A regression that
+ # re-adds owner injection would route a picked-nobody report to the owner instead.
self._seed_owner("signals-scout-y", self._github_member("soleowner"))
- result = _build_suggested_reviewers(self.team, None, skill_name="signals-scout-y", enforce_owners=True)
- assert result is not None
- assert [e.github_login for e in result.root] == ["soleowner"]
+ assert _build_suggested_reviewers(self.team, None, skill_name="signals-scout-y") is None
- def test_owners_not_injected_without_enforce_flag(self) -> None:
- # The edit path leaves enforcement off when the caller isn't setting reviewers, so an
- # unrelated edit never injects owners over a routing a human may have chosen.
- self._seed_owner("signals-scout-z", self._github_member("ignoredowner"))
+ def test_owner_pick_stamped_in_place_without_reordering(self) -> None:
+ # A picked reviewer who is a current owner is stamped `is_skill_owner=True` (the autostart
+ # identity guardrail) — but stamping must not inject, drop, or reorder: the scout's order is
+ # the routing order, and a non-owner pick stays unstamped.
+ self._seed_owner("signals-scout-x", self._github_member("ownerlogin"))
result = _build_suggested_reviewers(
self.team,
- [ReviewerInput(github_login="picked")],
- skill_name="signals-scout-z",
- enforce_owners=False,
+ [ReviewerInput(github_login="other"), ReviewerInput(github_login="ownerlogin")],
+ skill_name="signals-scout-x",
)
assert result is not None
- assert [e.github_login for e in result.root] == ["picked"]
+ assert [(e.github_login, e.is_skill_owner) for e in result.root] == [("other", False), ("ownerlogin", True)]
- def test_scout_repeating_an_owner_keeps_owner_provenance(self) -> None:
- # The skill body steers the scout, so a scout repeating an owner's login is not independent
- # commit-authorship evidence: clearing `is_skill_owner` here would let a skill editor name a
- # privileged member as owner, steer the scout to repeat that login, and mint the autostart
- # session as them. The flag must survive the dedupe; only the scout's reason merges in.
+ def test_scout_picked_owner_keeps_its_reason(self) -> None:
+ # Stamping rebuilds the owner entry, so it must carry the scout's reason forward — a report's
+ # reviewer routing is only as useful as the reason behind it. This is also the security case:
+ # a skill editor could name a privileged member as owner and steer the scout to pick them, so
+ # the pick is stamped (kept out of autostart identity) rather than trusted as authorship.
self._seed_owner("signals-scout-v", self._github_member("pickedowner"))
result = _build_suggested_reviewers(
self.team,
[ReviewerInput(github_login="PickedOwner", reason="top author on the surface")],
skill_name="signals-scout-v",
- enforce_owners=True,
)
assert result is not None
assert [(e.github_login, e.is_skill_owner, e.reason) for e in result.root] == [
("pickedowner", True, "top author on the surface")
]
- def test_scout_pick_survives_owner_overflow_at_the_cap(self) -> None:
- # A skill can hold more GitHub-routable owners than MAX_SUGGESTED_REVIEWERS
- # (MAX_SKILL_OWNERS exceeds it). Plain head-truncation would return an owner-only list,
- # silently discarding the scout's explicit pick — and with it the only entry
- # `_wants_repo_selection` counts as PR intent. The last slot is reserved for the pick.
- for i in range(MAX_SUGGESTED_REVIEWERS + 2):
- self._seed_owner("signals-scout-full", self._github_member(f"owner{i}"))
- result = _build_suggested_reviewers(
- self.team,
- [ReviewerInput(github_login="scoutpick", reason="top author on the surface")],
- skill_name="signals-scout-full",
- enforce_owners=True,
- )
- assert result is not None
- assert len(result.root) == MAX_SUGGESTED_REVIEWERS
- assert result.root[-1].github_login == "scoutpick"
- assert result.root[-1].is_skill_owner is False
- assert all(e.is_skill_owner for e in result.root[:-1])
-
- def test_owner_without_github_identity_is_skipped(self) -> None:
- # A `suggested_reviewers` artefact is GitHub-login-keyed, so an owner with no linked identity
- # can't be routed — skip them without failing the whole resolution.
- orphan = User.objects.create(email="[email protected]")
- OrganizationMembership.objects.create(user=orphan, organization=self.organization)
- self._seed_owner("signals-scout-w", orphan)
- result = _build_suggested_reviewers(
- self.team,
- [ReviewerInput(github_login="picked")],
- skill_name="signals-scout-w",
- enforce_owners=True,
- )
- assert result is not None
- assert [e.github_login for e in result.root] == ["picked"]
-
_P1 = PriorityAssessment(priority=Priority.P1, explanation="big blast radius")
-_OWNER_ONLY_REVIEWERS = SuggestedReviewers.model_validate([{"github_login": "owner", "is_skill_owner": True}])
-_OWNER_PLUS_SCOUT_PICK = SuggestedReviewers.model_validate(
- [{"github_login": "owner", "is_skill_owner": True}, {"github_login": "picked"}]
-)
+_PICKED_REVIEWER = SuggestedReviewers.model_validate([{"github_login": "picked"}])
+# An owner-flagged reviewer only exists because the scout picked an owner, so it carries PR intent
+# like any other pick — `is_skill_owner` governs autostart identity, not intent.
+_OWNER_FLAGGED_REVIEWER = SuggestedReviewers.model_validate([{"github_login": "owner", "is_skill_owner": True}])
class TestWantsRepoSelection(SimpleTestCase):
- """The PR-intent gate for repo selection. The load-bearing case: owner-guardrail entries land on
- every emit, so counting them as reviewers would run free-form repo selection (and later autostart
- under the team fallback runner) for a prioritized report whose scout supplied neither a repo nor
- a reviewer."""
+ """The PR-intent gate for repo selection. The load-bearing case: an owner-flagged reviewer is a
+ scout pick (nothing is injected), so it counts as intent — re-excluding it would skip repo
+ selection for a prioritized report whose scout deliberately routed to an owner."""
@parameterized.expand(
[
- ("owner_only_reviewers_are_not_pr_intent", None, _P1, _OWNER_ONLY_REVIEWERS, False),
- ("scout_pick_with_priority_is_pr_intent", None, _P1, _OWNER_PLUS_SCOUT_PICK, True),
- ("explicit_repository_always_selects", "posthog/posthog", None, _OWNER_ONLY_REVIEWERS, True),
+ ("picked_reviewer_with_priority_is_pr_intent", None, _P1, _PICKED_REVIEWER, True),
+ ("owner_flagged_reviewer_with_priority_is_pr_intent", None, _P1, _OWNER_FLAGGED_REVIEWER, True),
+ ("reviewer_without_priority_is_not_pr_intent", None, None, _PICKED_REVIEWER, False),
+ ("explicit_repository_always_selects", "posthog/posthog", None, None, True),
("priority_without_reviewers_is_not_pr_intent", None, _P1, None, False),
]
)