:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): forward report claims to scouts as routing notes (#125190)
Dylan Martinfec28cdc139e
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 5461576566e3..008cfdda89a2 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -3844,7 +3844,8 @@ class SignalScoutNote(TeamScopedRootMixin, UUIDModel):another path (the report's reviewers artefact, and the project profile's recent corrections), sothe key scopes aren't required on top. It is the only derived kind addressed to more than theauthoring scout: a removed login is also sent to every scout whose `reviewer:` memory names it,- because those are the scouts still routing on it.+ because those are the scouts still routing on it. A claim by a person or their agent uses the+ same kind as positive evidence, and reaches the holders of the claimant's memory the same way.`origin` keeps the kinds apart so the run prompt can frame a dismissal as one reviewer's verdicton one report, a discussion as a question to weigh, feedback as a reader's rating, and a reviewercorrection as a trigger to revisit routing memory — rather than fleet-level steering.diff --git a/products/signals/backend/report_assignments.py b/products/signals/backend/report_assignments.pyindex ecc1f522450a..483e63d9f646 100644--- a/products/signals/backend/report_assignments.py+++ b/products/signals/backend/report_assignments.py@@ -2,7 +2,9 @@from __future__ import annotations+from collections.abc import Callablefrom datetime import datetime+from functools import partialfrom typing import TypedDictfrom django.db import transaction@@ -415,8 +417,13 @@ def claim_report(claim_id: str | None = None,takeover: bool = False,takeover_claim_id: str | None = None,+ on_new_claim: Callable[..., None] | None = None,) -> ReportClaim | None:- """Claim, release, or attach a PR to one report and return the current assignment."""+ """Claim, release, or attach a PR to one report and return the current assignment.++ `on_new_claim` runs after commit, only when this call started a claim, with `takeover` set when+ it replaced someone else's claim.+ """if release and (pr_url or pull_requests or takeover):raise ReportClaimConflict("Release cannot be combined with pull requests or takeover.")urls = list(dict.fromkeys(([pr_url] if pr_url else []) + (pull_requests or [])))@@ -461,6 +468,7 @@ def claim_report():return assignmentraise ReportClaimConflict(f"Reports with status '{report_status}' cannot be claimed.")+ took_over = Falseif assignment is not None and not actor_works_under_claim(assignment, actor):if takeover_claim_id and str(assignment.claim_id) != takeover_claim_id:raise ReportClaimConflict("The report's claim changed. Reload the report and try again.")@@ -470,8 +478,11 @@ def claim_report()release_claim(assignment, actor, takeover=True)assignment = None+ took_over = Trueif assignment is None:assignment = create_claim(locked_report, actor)+ if on_new_claim is not None:+ transaction.on_commit(partial(on_new_claim, takeover=took_over))for pr_details in details:link_pull_request(diff --git a/products/signals/backend/report_claim_follow_up.py b/products/signals/backend/report_claim_follow_up.pynew file mode 100644index 000000000000..9f53c52369f7--- /dev/null+++ b/products/signals/backend/report_claim_follow_up.py@@ -0,0 +1,111 @@+"""What happens after a report claim commits: tell the scouts, then record what the claim did.++Kept out of `report_assignments`, which the scout harness imports, so the claim path does not+import the harness back.+"""++from __future__ import annotations++import logging+import dataclasses++import posthoganalytics++from posthog.dataclasses import frozen+from posthog.event_usage import groups+from posthog.models import Team, User++from products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.reviewer_correction_notes import (+ ReviewerClaim,+ claim_scout_notes_enabled,+ forward_reviewer_claim_note,+)+from products.signals.backend.scout_note_actor import actor_github_login+from products.signals.backend.suggested_reviewer_index import match_reviewer_set++logger = logging.getLogger(__name__)+++@frozen+class ClaimantOutcome:+ """What a claim by a person or their agent said about routing, and what forwarding it achieved."""++ claimant_was_suggested: bool+ suggested_count: int+ claim_notes_enabled: bool+ claim_notes_written: int+ claim_note_targets: int+++def record_report_claimed(+ *,+ team_id: int,+ report_id: str,+ actor: ArtefactAttribution,+ scoped_team_ids: tuple[int, ...] | None,+ was_impersonated: bool,+ takeover: bool,+) -> None:+ """Forward a new claim to the scouts, then emit `signals_report_claimed`.++ Only a person or their agent chose the work, so task and system claims are recorded but never+ forwarded. An impersonated claim is a support action, not routing evidence, the same rule the+ reviewer correction notes follow.+ """+ try:+ team = Team.objects.select_related("organization").get(id=team_id)+ claimant: ClaimantOutcome | None = None+ user = User.objects.filter(pk=actor.user_id).first() if actor.kind in ("user", "agent") else None+ if user is not None:+ match = match_reviewer_set(+ team_id=team_id,+ report_id=report_id,+ user_uuid=str(user.uuid),+ github_login=actor_github_login(team_id, user),+ )+ notes_enabled = claim_scout_notes_enabled(team)+ forwarded = (+ forward_reviewer_claim_note(+ team=team,+ claim=ReviewerClaim(+ report_id=report_id,+ actor_user_id=user.id,+ scoped_team_ids=scoped_team_ids,+ claimant_was_suggested=match.names_identity,+ via_agent=actor.agent_name if actor.kind == "agent" else None,+ ),+ )+ if notes_enabled and not was_impersonated+ else None+ )+ claimant = ClaimantOutcome(+ claimant_was_suggested=match.names_identity,+ suggested_count=match.reviewer_count,+ claim_notes_enabled=notes_enabled,+ claim_notes_written=len(forwarded.note_ids) if forwarded else 0,+ claim_note_targets=forwarded.targets_resolved if forwarded else 0,+ )+ _capture_report_claimed(team=team, report_id=report_id, actor=actor, takeover=takeover, claimant=claimant)+ except Exception:+ # The claim and its activity row already committed. Nothing here may turn it into a 5xx.+ logger.exception("Failed to record a report claim", extra={"team_id": team_id, "report_id": report_id})+++def _capture_report_claimed(+ *, team: Team, report_id: str, actor: ArtefactAttribution, takeover: bool, claimant: ClaimantOutcome | None+) -> None:+ # For a person or their agent, the share of claims with `claimant_was_suggested` is the routing hit+ # rate the claim notes try to raise. Compare it by `claim_notes_enabled`.+ posthoganalytics.capture(+ event="signals_report_claimed",+ distinct_id=str(team.uuid),+ properties={+ "team_id": team.id,+ "report_id": report_id,+ "actor_kind": actor.kind,+ "takeover": takeover,+ **(dataclasses.asdict(claimant) if claimant else {}),+ },+ groups=groups(team.organization, team),+ )diff --git a/products/signals/backend/report_generation/reviewer_telemetry.py b/products/signals/backend/report_generation/reviewer_telemetry.pyindex de53548f481a..a57ce63ed4c0 100644--- a/products/signals/backend/report_generation/reviewer_telemetry.py+++ b/products/signals/backend/report_generation/reviewer_telemetry.py@@ -75,6 +75,7 @@ def capture_suggested_reviewers_resolved(after_inbox_notification: bool | None = None,removal_reason: str | None = None,has_removal_note: bool | None = None,+ self_removal: bool | None = None,) -> None:"""Emit `signals_suggested_reviewers_resolved` when a report's suggested reviewers are persisted.@@ -94,6 +95,7 @@ def capture_suggested_reviewers_resolved(`correction_note_targets` report what that forwarding did — notes written, and scouts thecorrection was addressed to, which is the larger number when the suppression window swallowed atarget's logins. Both are absent on every other path, so absence reads as "no correction".+ `self_removal` marks the "Remove yourself" path, the negative counterpart of `signals_report_claimed`.Best-effort: never raises, so analytics can't break report generation."""@@ -133,6 +135,7 @@ def capture_suggested_reviewers_resolved("all_unlinkable": bool(linkability.unlinkable_count) and not linkability.linkable_count,**({"removal_reason": removal_reason} if removal_reason else {}),**({"has_removal_note": has_removal_note} if has_removal_note is not None else {}),+ **({"self_removal": True} if self_removal else {}),**({}if correction_notes_written is Nonediff --git a/products/signals/backend/reviewer_correction_notes.py b/products/signals/backend/reviewer_correction_notes.pyindex 1cc86d7912f7..6b4c97e924f8 100644--- a/products/signals/backend/reviewer_correction_notes.py+++ b/products/signals/backend/reviewer_correction_notes.py@@ -1,9 +1,12 @@-"""Send scoped reviewer edits to the scouts that produced the report or hold its routing memory.+"""Send scoped reviewer edits and claims to the scouts that produced the report or hold its routing memory.Notes use the same GitHub logins or PostHog user UUIDs as the correction activity log.They are searchable by other scouts and research through the existing notes tools.Forwarding is best effort after commit, with the editor's steering permissions. A noteasks agents to check the source report; it does not establish a standing ownership rule.++A removal is negative routing evidence. A claim is the positive counterpart: a person, or their+agent, took the work, so the scouts can suggest that person for similar reports."""from __future__ import annotations@@ -11,11 +14,13 @@ from __future__ import annotationsimport reimport loggingfrom collections.abc import Sequence-from datetime import timedelta+from datetime import datetime, timedeltafrom uuid import UUIDfrom django.utils import timezone+import posthoganalytics+from posthog.dataclasses import frozenfrom posthog.models import Team, User@@ -68,6 +73,14 @@ _MAX_LOGIN_CHARS = 39# added login never suppresses a later removal of the same login (a reversal the scout needs to hear)._ADDED_SECTION_PREFIX = "Added: "_REMOVED_SECTION_PREFIX = "Removed: "+_CLAIMED_SECTION_PREFIX = "Claimed: "++# Org-keyed kill switch for claim notes. Teams outside the rollout are the comparison group for+# `signals_report_claimed.claimant_was_suggested`.+CLAIM_SCOUT_NOTES_FLAG = "signals-claim-scout-notes"++# The agent name on a claim is caller-supplied text, so it is bounded and kept to one line.+_MAX_AGENT_CHARS = 60@frozen@@ -89,6 +102,21 @@ class ReviewerCorrection:removal_note: str | None = None+@frozen+class ReviewerClaim:+ """One new claim on a report by a person or by their agent.++ `actor_user_id` is the person in both cases. `via_agent` names the agent when the agent made the+ claim for them. Task and system claims are never a `ReviewerClaim`, because no person chose the work.+ """++ report_id: str+ actor_user_id: int+ scoped_team_ids: tuple[int, ...] | None+ claimant_was_suggested: bool+ via_agent: str | None = None++@frozenclass ForwardedCorrectionNotes:"""What forwarding achieved, for the reviewer-edit analytics event.@@ -107,6 +135,28 @@ class _ReviewersAlreadyTold:added: set[str]removed: set[str]+ claimed: set[str]+++@frozen+class _NoteAuthor:+ """The person a note is attributed to, after the steering gate passed, and the report it names."""++ canonical_team: Team+ actor: User+ actor_login: str | None+ report: SignalReport++ @property+ def rendered(self) -> str:+ return render_actor(self.actor, github_login=self.actor_login)++ @property+ def identities(self) -> set[str]:+ identities = {str(self.actor.uuid)}+ if self.actor_login:+ identities.add(self.actor_login)+ return identities_NOTHING_FORWARDED = ForwardedCorrectionNotes(note_ids=(), targets_resolved=0)@@ -132,52 +182,103 @@ def forward_reviewer_correction_note(*, team: Team, correction: ReviewerCorrectireturn _NOTHING_FORWARDED-def _forward(*, team: Team, correction: ReviewerCorrection) -> ForwardedCorrectionNotes:+def forward_reviewer_claim_note(*, team: Team, claim: ReviewerClaim) -> ForwardedCorrectionNotes:+ """Leave a claim as a scout note, one per scout that touched the report or holds the claimant's memory.++ Best-effort by the same contract as `forward_reviewer_correction_note`: the claim already stands.+ """+ try:+ return _forward_claim(team=team, claim=claim)+ except Exception:+ logger.exception(+ "Failed to forward a report claim to a scout note",+ extra={"team_id": team.id, "report_id": claim.report_id},+ )+ return _NOTHING_FORWARDED+++def claim_scout_notes_enabled(team: Team) -> bool:+ """Whether claims on this team's reports reach the scouts. Fails closed on a flag-read error."""+ try:+ org_id = str(team.organization_id)+ return (+ posthoganalytics.feature_enabled(+ CLAIM_SCOUT_NOTES_FLAG,+ org_id,+ groups={"organization": org_id},+ group_properties={"organization": {"id": org_id}},+ send_feature_flag_events=False,+ )+ is True+ )+ except Exception:+ logger.warning("Failed to read the claim scout notes flag", exc_info=True)+ return False+++def _note_author(+ *, team: Team, actor_user_id: int, scoped_team_ids: tuple[int, ...] | None, report_id: str+) -> _NoteAuthor | None:# Scout rows and their notes live under the canonical parent team, and a note is readable by# everyone with access to that project. Forwarding a child environment's correction would hand# its report id and title to an audience that may have no access to that environment, so those# corrections stay on the report and the activity log only.canonical_team = team.parent_team or teamif team.id != canonical_team.id:- return _NOTHING_FORWARDED+ return None- actor = User.objects.filter(pk=correction.actor_user_id).first()+ actor = User.objects.filter(pk=actor_user_id).first()if actor is None:- return _NOTHING_FORWARDED+ return Noneif not principal_may_steer_scouts(user=actor,- scoped_team_ids=correction.scoped_team_ids,+ scoped_team_ids=scoped_team_ids,canonical_team=canonical_team,):- return _NOTHING_FORWARDED+ return None+ report = SignalReport.objects.filter(team_id=canonical_team.id, id=report_id).first()+ if report is None:+ return None+ return _NoteAuthor(+ canonical_team=canonical_team,+ actor=actor,+ actor_login=actor_github_login(canonical_team.id, actor),+ report=report,+ )+++def _forward(*, team: Team, correction: ReviewerCorrection) -> ForwardedCorrectionNotes:added_reviewers = _renderable(correction.added_reviewers)removed_reviewers = _renderable(correction.removed_reviewers)if not added_reviewers and not removed_reviewers:return _NOTHING_FORWARDED- report = SignalReport.objects.filter(team_id=canonical_team.id, id=correction.report_id).first()- if report is None:+ author = _note_author(+ team=team,+ actor_user_id=correction.actor_user_id,+ scoped_team_ids=correction.scoped_team_ids,+ report_id=correction.report_id,+ )+ if author is None:return _NOTHING_FORWARDED- targets = _resolve_targets(canonical_team.id, correction.report_id, removed_reviewers)+ team_id = author.canonical_team.id+ targets = _resolve_targets(team_id, correction.report_id, removed_reviewers)# One lookup serves the editor's name in every note and the self-removal split below, which keeps# an editor taking their own login off from reading as a teammate's verdict.- actor_login = actor_github_login(canonical_team.id, actor)- editor = render_actor(actor, github_login=actor_login)- actor_identities = {str(actor.uuid)}- if actor_login:- actor_identities.add(actor_login)+ editor = author.rendered+ actor_identities = author.identitiesexpires_at = timezone.now() + DERIVED_NOTE_TTLnote_ids: list[str] = []for skill_name in targets:- already_told = _reviewers_already_told(canonical_team.id, skill_name, correction.report_id)+ already_told = _reviewers_already_told(team_id, skill_name, correction.report_id)added = tuple(login for login in added_reviewers if login not in already_told.added)removed = tuple(login for login in removed_reviewers if login not in already_told.removed)if not added and not removed:continuecontent = _build_note_content(- report=report,+ report=author.report,editor=editor,added_reviewers=added,# Split per note rather than per edit: the caveat belongs to the logins this scout is@@ -188,27 +289,69 @@ def _forward(*, team: Team, correction: ReviewerCorrection) -> ForwardedCorrectiremoval_reason=correction.removal_reason,removal_note=correction.removal_note,)- try:- created = leave_note(- team_id=canonical_team.id,- content=content,- skill_name=skill_name,- created_by_id=actor.id,- expires_at=expires_at,- origin=SignalScoutNote.Origin.REPORT_REVIEWER_CORRECTION,- )- except Exception:- # Per-note guard on top of the outer boundary, so one unwritable target (a skill deleted- # mid-request, say) doesn't cost the other scouts their notes.- logger.exception(- "Failed to forward a reviewer correction to one scout",- extra={"team_id": canonical_team.id, "skill_name": skill_name},- )+ note_id = _leave_note(author=author, skill_name=skill_name, content=content, expires_at=expires_at)+ if note_id is not None:+ note_ids.append(note_id)+ return ForwardedCorrectionNotes(note_ids=tuple(note_ids), targets_resolved=len(targets))+++def _forward_claim(*, team: Team, claim: ReviewerClaim) -> ForwardedCorrectionNotes:+ author = _note_author(+ team=team,+ actor_user_id=claim.actor_user_id,+ scoped_team_ids=claim.scoped_team_ids,+ report_id=claim.report_id,+ )+ if author is None:+ return _NOTHING_FORWARDED+ # The login is what scouts route on, so the note names it first. A memory can still name the+ # PostHog user UUID, from before the login was linked, so holders are searched on both.+ claimant = _renderable([identity for identity in (author.actor_login, str(author.actor.uuid)) if identity])+ if not claimant:+ return _NOTHING_FORWARDED++ team_id = author.canonical_team.id+ targets = _resolve_targets(team_id, claim.report_id, claimant)+ content = _build_claim_note_content(+ report=author.report,+ claimant=author.rendered,+ identity=claimant[0],+ via_agent=claim.via_agent,+ claimant_was_suggested=claim.claimant_was_suggested,+ )+ expires_at = timezone.now() + DERIVED_NOTE_TTL+ note_ids: list[str] = []+ for skill_name in targets:+ # A claim, a release, and a claim again on one report is one piece of evidence.+ if _reviewers_already_told(team_id, skill_name, claim.report_id).claimed.intersection(claimant):continue- note_ids.append(created.id)+ note_id = _leave_note(author=author, skill_name=skill_name, content=content, expires_at=expires_at)+ if note_id is not None:+ note_ids.append(note_id)return ForwardedCorrectionNotes(note_ids=tuple(note_ids), targets_resolved=len(targets))+def _leave_note(*, author: _NoteAuthor, skill_name: str, content: str, expires_at: datetime) -> str | None:+ try:+ created = leave_note(+ team_id=author.canonical_team.id,+ content=content,+ skill_name=skill_name,+ created_by_id=author.actor.id,+ expires_at=expires_at,+ origin=SignalScoutNote.Origin.REPORT_REVIEWER_CORRECTION,+ )+ except Exception:+ # Per-note guard on top of the outer boundary, so one unwritable target (a skill deleted+ # mid-request, say) doesn't cost the other scouts their notes.+ logger.exception(+ "Failed to forward a reviewer note to one scout",+ extra={"team_id": author.canonical_team.id, "skill_name": skill_name},+ )+ return None+ return created.id++def _renderable(logins: Sequence[str]) -> tuple[str, ...]:"""Bound and sanitize GitHub logins or canonical user UUIDs before prompt rendering."""kept: list[str] = []@@ -236,8 +379,10 @@ def _renderable(logins: Sequence[str]) -> tuple[str, ...]:return tuple(kept[:MAX_CORRECTION_REVIEWERS])-def _resolve_targets(team_id: int, report_id: str, removed_reviewers: Sequence[str]) -> list[str]:- """Who to tell: every scout that touched the report, plus every holder of the removed logins.+def _resolve_targets(team_id: int, report_id: str, holder_identities: Sequence[str]) -> list[str]:+ """Who to tell: every scout that touched the report, plus every holder of the given identities.++ The identities are the removed logins for a correction, and the claimant for a claim.Touching means emitted or edited, because a scout that set the reviewers through an edit did therouting a human has just corrected, and it is better to tell it once too often than to leave it@@ -249,12 +394,12 @@ def _resolve_targets(team_id: int, report_id: str, removed_reviewers: Sequence[sreads the fleet-wide notes alongside its own and a holder would hear the same edit twice."""touching = _live_skills(team_id, resolve_touching_scout_skills(team_id, report_id))- holders = _memory_holders(team_id, removed_reviewers)+ holders = _memory_holders(team_id, holder_identities)targets = [*touching, *(name for name in holders if name not in touching)]return targets[:MAX_NOTE_TARGETS] if targets else [""]-def _memory_holders(team_id: int, removed_reviewers: Sequence[str]) -> list[str]:+def _memory_holders(team_id: int, identities: Sequence[str]) -> list[str]:"""The live scouts whose `reviewer:` memory names one of these identities.One query for the whole login list, matching each as a whole token. A substring search would@@ -266,14 +411,14 @@ def _memory_holders(team_id: int, removed_reviewers: Sequence[str]) -> list[str]audience. So is one written by a scout whose skill is gone, because a note addressed to a namethat no longer exists steers no one (and `leave_note` rejects the target)."""- if not removed_reviewers:+ if not identities:return []named = {entry.created_by_skillfor entry in search_scratchpad_naming(team_id=team_id,key_prefix=REVIEWER_MEMORY_KEY_PREFIX,- terms=removed_reviewers,+ terms=identities,limit=_MEMORY_SEARCH_LIMIT,)if entry.created_by_skill@@ -296,7 +441,7 @@ def _reviewers_already_told(team_id: int, skill_name: str, report_id: str) -> _R"""The reviewer identities this target was already told about inside the window, split by direction.Suppression is per action, not per login: an added login must not suppress a later removal of the- same reviewer. Only notes about the same report can suppress a repeat: another report can+ same reviewer, and a claim must not suppress a later removal. Only notes about the same report can suppress a repeat: another report canconcern a different area or provide independent evidence of a repeated mistake."""contents = (@@ -315,14 +460,19 @@ def _reviewers_already_told(team_id: int, skill_name: str, report_id: str) -> _R# enough to recognize direction without a second table to track what was sent.added_told: set[str] = set()removed_told: set[str] = set()+ claimed_told: set[str] = set()for content in contents:- already_seen = added_told | removed_told+ already_seen = added_told | removed_told | claimed_toldfor paragraph in content.split("\n\n"):if paragraph.startswith(_ADDED_SECTION_PREFIX):added_told |= _quoted_reviewers(paragraph) - already_seenelif paragraph.startswith(_REMOVED_SECTION_PREFIX):removed_told |= _quoted_reviewers(paragraph) - already_seen- return _ReviewersAlreadyTold(added=added_told, removed=removed_told)+ elif paragraph.startswith(_CLAIMED_SECTION_PREFIX):+ # Only the first sentence names the claimant. Identities cannot contain a period.+ # No reviewer edit reverses a claim, so a newer edit does not unsuppress an older claim.+ claimed_told |= _quoted_reviewers(paragraph.split(".", 1)[0])+ return _ReviewersAlreadyTold(added=added_told, removed=removed_told, claimed=claimed_told)def _quoted_reviewers(content: str) -> set[str]:@@ -366,8 +516,7 @@ def _build_note_content(sections.append(f"The editor's note on the removal:\n\n{quoted_note}")sections.append(_removal_guidance(by_a_teammate=bool(teammate_removed), reason=removal_reason))sections.append(- "Reviewers are identified by GitHub login or PostHog user UUID. Check current project membership "- "with `scout-members-list`; a GitHub account is not required for Inbox assignment. "+ f"{_IDENTITY_FOOTER} ""This edit is binding on the source report. For another report, check its scope and reason with ""`inbox-reports-retrieve` before applying it. Record only supported ownership evidence in your ""`reviewer:` memory, with the source report, date, and scope. This note expires."@@ -375,6 +524,43 @@ def _build_note_content(return "\n\n".join(sections)+def _build_claim_note_content(+ *,+ report: SignalReport,+ claimant: str,+ identity: str,+ via_agent: str | None,+ claimant_was_suggested: bool,+) -> str:+ agent = " ".join((via_agent or "").replace("`", "").split())[:_MAX_AGENT_CHARS]+ by = f"Their agent ({agent}) claimed it for them." if agent else "They claimed it themselves."+ # Positive evidence is weaker than a removal reason: a person can pick up work outside their+ # area. The guidance asks for a scoped memory entry, not a routing rule.+ fit = (+ "They were already a suggested reviewer, so the claim confirms that routing."+ if claimant_was_suggested+ else "They were not a suggested reviewer. Consider them for similar work in the same area."+ )+ return "\n\n".join(+ [+ f"Inbox routing correction: {claimant} claimed the work on {_subject(report)}",+ f"{_CLAIMED_SECTION_PREFIX}`{identity}`. {by} {fit}",+ "A claim is positive evidence that this person works in this area. It is not proof of ownership, "+ "and one claim is not a standing rule. Search your `reviewer:` memory for this identity and area. "+ "Record that they claimed the work, with the source report and date. Several claims in one area "+ "are stronger evidence than one. Do not extend this to unrelated areas.",+ f"{_IDENTITY_FOOTER} For another report, check its scope with `inbox-reports-retrieve` before "+ "applying this. This note expires.",+ ]+ )+++_IDENTITY_FOOTER = (+ "Reviewers are identified by GitHub login or PostHog user UUID. Check current project membership "+ "with `scout-members-list`; a GitHub account is not required for Inbox assignment."+)++# A stated reason replaces the generic caution: it tells the scout which of the meanings a removal# can have applies, and each leads to a different memory update._REASON_GUIDANCE = {diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex 3c30b842f6d8..4b91e888f847 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -284,7 +284,7 @@ Each note's `origin` says how to read it, and each names the report ids it conce- `human`: steering someone wrote for you directly.- `report_dismissal`: a reviewer's verdict on one or more of your reports, forwarded so it reaches you without you re-finding them. One note covers one verdict, so when a reviewer acted on several reports at once read it as their view of that batch, never as a fleet-wide rule. **Dismissed** is the only kind that should make you stop filing something, and the reason code decides whether it even means that: `analysis_wrong` and `report_unclear` speak to your precision, while `wontfix_*` say the report was not useful in this project's context, so fold a reason that generalizes into a `noise:`/`pattern:` entry; `wrong_assignee` says the report reached the wrong owner, not that the finding was wrong, so correct the matching `reviewer:` memory and keep watching the topic; `wrong_repo` says the report targeted the wrong repository, not that the finding was wrong — keep watching the topic, record the repository the note says was wrong so you do not pick it again for that kind of work, and record the corrected repository when the note names one; `already_fixed` means the issue was real and someone fixed it, so record that a fix shipped and keep watching for a recurrence. **Snoozed or restored** is about timing, not correctness: the report is still live, so keep watching what it describes.- `report_discussion`: a question a user asked when they opened a discussion on one of your reports. Not a verdict and not a directive, but often carrying a preference, a correction, or context you couldn't have known ("this is expected, it's the approval flow"): fold the durable part into a `noise:`/`pattern:`/`watch:` entry, and leave one-off asks and unrelated chatter be.-- `report_reviewer_correction`: someone changed a report's suggested reviewers. Identities can be GitHub logins or PostHog user UUIDs. The edit is binding on that report; elsewhere it is scoped evidence to check. Read the source report and its ownership context before changing your `reviewer:` memory. Preserve the source, date, area, and reason where available. Self-removal alone does not establish an ownership change or a standing exclusion, but a stated removal reason does: follow the guidance the note gives for it. Repeated corrections on related reports can show stale memory; retain evidence that still applies and do not extend a correction to unrelated areas.+- `report_reviewer_correction`: someone changed a report's suggested reviewers. Identities can be GitHub logins or PostHog user UUIDs. The edit is binding on that report; elsewhere it is scoped evidence to check. Read the source report and its ownership context before changing your `reviewer:` memory. Preserve the source, date, area, and reason where available. Self-removal alone does not establish an ownership change or a standing exclusion, but a stated removal reason does: follow the guidance the note gives for it. Repeated corrections on related reports can show stale memory; retain evidence that still applies and do not extend a correction to unrelated areas. A note with a `Claimed:` section means a person, or their agent, claimed the report. That is positive evidence that the person works in that area: record it with the source and date, and consider them for similar reports. One claim is not proof of ownership.A resolved report never reaches you this way, because resolving means the report did its job rather than that filing it was wrong. Its note stays on the report, so read `dismissal_note` there when your inbox search turns it up, and record that a fix shipped and when, so you can tell a later recurrence from the original.diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 1d26de20909c..3c70104cf35d 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -1252,8 +1252,9 @@ class ScoutNoteSerializer(serializers.Serializer):"a directive. `report_feedback` for the note someone left when rating a report useful or ""not: one reader's rating of the named report, context to weigh rather than a directive. ""`report_reviewer_correction` for a suggested reviewer someone added or removed on a "- "report: evidence about who owns that surface, and a prompt to revisit the routing "- "memory it corrects, rather than a directive."+ "report, or for a report a person or their agent claimed: evidence about who owns that "+ "surface, and a prompt to revisit the routing memory it corrects or supports, rather "+ "than a directive."),)diff --git a/products/signals/backend/scout_harness/tools/notes.py b/products/signals/backend/scout_harness/tools/notes.pyindex bc70477aa1d9..b205b9a984b1 100644--- a/products/signals/backend/scout_harness/tools/notes.py+++ b/products/signals/backend/scout_harness/tools/notes.py@@ -14,7 +14,8 @@ typed when they dismissed, snoozed, or restored an inbox report (seeasked when they opened a discussion on a report (see `discussion_notes.py`);`report_feedback`, forwarded from the note someone left when rating a report usefulor not (see `feedback_notes.py`); and `report_reviewer_correction`, forwarded when-someone added or removed a suggested reviewer (see `reviewer_correction_notes.py`).+someone added or removed a suggested reviewer, or claimed a report (see+`reviewer_correction_notes.py`)."""from __future__ import annotations@@ -131,7 +132,7 @@ def leave_note(writes `HUMAN`. `REPORT_DISMISSAL` belongs to `dismissal_notes.forward_dismissal_note`,`REPORT_DISCUSSION` to `discussion_notes.forward_discussion_note`, `REPORT_FEEDBACK` to`feedback_notes.forward_feedback_note`, and `REPORT_REVIEWER_CORRECTION` to- `reviewer_correction_notes.forward_reviewer_correction_note`.+ `reviewer_correction_notes.forward_reviewer_correction_note` and `forward_reviewer_claim_note`."""_validate_note(team_id=team_id, skill_name=skill_name, content=content)row = SignalScoutNote.objects.create(diff --git a/products/signals/backend/suggested_reviewer_index.py b/products/signals/backend/suggested_reviewer_index.pyindex baf901441c0e..b1cf14856615 100644--- a/products/signals/backend/suggested_reviewer_index.py+++ b/products/signals/backend/suggested_reviewer_index.py@@ -15,6 +15,8 @@ from django.db.models import Q, QuerySetimport structlogfrom pydantic import ValidationError+from posthog.dataclasses import frozen+from products.signals.backend.artefact_schemas import SuggestedReviewersfrom products.signals.backend.models import SignalReportArtefact, SignalReportSuggestedReviewer@@ -108,3 +110,18 @@ def report_ids_naming_reviewers(user_uuids, github_logins, logins_match_unidentified_only=logins_match_unidentified_only)return SignalReportSuggestedReviewer.objects.for_team(team_id).filter(identity).values("report_id")+++@frozen+class ReviewerSetMatch:+ reviewer_count: int+ names_identity: bool+++def match_reviewer_set(*, team_id: int, report_id: str, user_uuid: str, github_login: str | None) -> ReviewerSetMatch:+ """Whether a report's current reviewer set names this person, with the "is this me?" login rule."""+ rows = SignalReportSuggestedReviewer.objects.for_team(team_id).filter(report_id=report_id)+ identity = _identity_filter(+ [user_uuid], [github_login] if github_login else [], logins_match_unidentified_only=False+ )+ return ReviewerSetMatch(reviewer_count=rows.count(), names_identity=rows.filter(identity).exists())diff --git a/products/signals/backend/test/test_reviewer_correction_scout_notes.py b/products/signals/backend/test/test_reviewer_correction_scout_notes.pyindex b244f1abe158..338d4348d3b3 100644--- a/products/signals/backend/test/test_reviewer_correction_scout_notes.py+++ b/products/signals/backend/test/test_reviewer_correction_scout_notes.py@@ -19,10 +19,13 @@ from products.signals.backend.models import ()from products.signals.backend.reviewer_correction_notes import (MAX_CORRECTION_REVIEWERS,+ ReviewerClaim,ReviewerCorrection,+ _build_claim_note_content,_build_note_content,_renderable,_reviewers_already_told,+ forward_reviewer_claim_note,forward_reviewer_correction_note,)from products.signals.backend.scout_harness.tools.notes import list_notes@@ -169,6 +172,30 @@ class TestReviewerCorrectionNoteContent(SimpleTestCase):# which is the only part of a note the run prompt renders.assert content.startswith("Inbox routing correction: Ada Lovelace changed the suggested reviewers")+ @parameterized.expand(+ [+ ("suggested_by_hand", True, None, "They claimed it themselves.", "confirms that routing"),+ ("unsuggested_by_agent", False, "codex", "Their agent (codex) claimed it", "Consider them for similar"),+ ]+ )+ def test_a_claim_note_says_who_claimed_and_whether_routing_was_right(+ self, _name: str, suggested: bool, via_agent: str | None, by: str, fit: str+ ) -> None:+ report = SignalReport(id="0198e7f0-0000-7000-8000-000000000001", title="Checkout errors")++ content = _build_claim_note_content(+ report=report,+ claimant="Ada ([email protected])",+ identity="octocat",+ via_agent=via_agent,+ claimant_was_suggested=suggested,+ )++ assert content.startswith("Inbox routing correction: Ada ([email protected]) claimed the work on report `")+ assert "Claimed: `octocat`." in content+ assert by in content+ assert fit in content+class TestReviewerCorrectionScoutNotes(APIBaseTest):def _create_report(self, title: str = "Checkout errors spiked") -> SignalReport:@@ -220,6 +247,51 @@ class TestReviewerCorrectionScoutNotes(APIBaseTest):),)+ def _claim(self, report: SignalReport) -> None:+ forward_reviewer_claim_note(+ team=self.team,+ claim=ReviewerClaim(+ report_id=str(report.id),+ actor_user_id=self.user.id,+ scoped_team_ids=None,+ claimant_was_suggested=False,+ ),+ )++ @parameterized.expand([("no_linked_login", None), ("linked_login", "octocat")])+ def test_a_claim_reaches_the_authoring_scout_and_the_claimants_memory_holder(+ self, _name: str, github_login: str | None+ ) -> None:+ self._create_skill()+ self._create_skill(OTHER_SCOUT_SKILL)+ report = self._create_report()+ self._create_run(emitted_report_ids=[str(report.id)])+ self._remember(+ key="reviewer:products/logs",+ content=f"{self.user.uuid} fixed the logs ingestion path",+ skill_name=OTHER_SCOUT_SKILL,+ )++ with patch("products.signals.backend.reviewer_correction_notes.actor_github_login", return_value=github_login):+ self._claim(report)++ notes = self._correction_notes()+ assert sorted(note.skill_name for note in notes) == [SCOUT_SKILL, OTHER_SCOUT_SKILL]+ assert f"Claimed: `{github_login or self.user.uuid}`." in notes[0].content++ def test_a_repeat_claim_is_coalesced_across_a_removal_and_does_not_hide_it(self) -> None:+ report = self._create_report()+ identity = str(self.user.uuid)++ self._claim(report)+ self._forward(report, removed=(identity,))+ self._claim(report)++ notes = self._correction_notes()+ assert len(notes) == 2+ assert f"Claimed: `{identity}`." in notes[0].content+ assert f"Removed: `{identity}`." in notes[1].content+def test_reversal_within_window_still_forwards(self) -> None:# Suppression is per direction: an addition must not swallow a later removal of the same login# inside the window — that reversal is exactly the stale-routing correction the channel existsdiff --git a/products/signals/backend/test/test_signal_report_assignment_api.py b/products/signals/backend/test/test_signal_report_assignment_api.pyindex b3c2a26673b9..a0fce43f27f0 100644--- a/products/signals/backend/test/test_signal_report_assignment_api.py+++ b/products/signals/backend/test/test_signal_report_assignment_api.py@@ -27,6 +27,7 @@ from products.signals.backend.models import (SignalReportCheck,SignalReportMonitoringAttempt,SignalReportPullRequest,+ SignalScoutNote,)from products.signals.backend.report_assignments import (sync_task_pull_request_to_assignments,@@ -34,6 +35,7 @@ from products.signals.backend.report_assignments import ()from products.signals.backend.report_claims import get_active_claim, get_active_claims, responsible_usersfrom products.signals.backend.report_monitoring_attempts import complete_implementation+from products.signals.backend.suggested_reviewer_index import sync_suggested_reviewer_indexclass TestPrimaryPullRequest(SimpleTestCase):@@ -122,6 +124,82 @@ class TestSignalReportAssignmentAPI(APIBaseTest):assert log.detail["changes"][0]["before"] is Noneassert log.detail["changes"][0]["after"]["kind"] == SignalActorKind.USER+ @parameterized.expand(+ [+ # name, actor, impersonated, flag on, suggested, notes written+ ("person", "user", False, True, False, 1),+ ("suggested_person", "user", False, True, True, 1),+ ("their_agent", "agent", False, True, False, 1),+ ("flag_off", "user", False, False, False, 0),+ ("impersonated", "user", True, True, False, 0),+ ("task", "task", False, True, False, None),+ ]+ )+ def test_a_new_claim_steers_scouts_only_for_a_person_and_records_the_outcome(+ self,+ _name: str,+ actor: str,+ impersonated: bool,+ flag_on: bool,+ suggested: bool,+ notes_written: int | None,+ ) -> None:+ report = self._create_report()+ if suggested:+ SignalReportArtefact.objects.create(+ team=self.team,+ report=report,+ type="suggested_reviewers",+ content=json.dumps([{"user_uuid": str(self.user.uuid), "github_login": None}]),+ )+ sync_suggested_reviewer_index(team_id=self.team.id, report_id=str(report.id))+ headers: dict[str, str] = {}+ if actor == "agent":+ headers = self._agent_headers("codex")+ elif actor == "task":+ Task = apps.get_model("tasks", "Task")+ task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ title="Signal task",+ description="Implement the report",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ )+ headers = {"X-PostHog-Task-Id": str(task.id)}++ with (+ patch(+ "products.signals.backend.reviewer_correction_notes.posthoganalytics.feature_enabled",+ return_value=flag_on,+ ),+ patch("products.signals.backend.views.is_impersonated_session", return_value=impersonated),+ patch("products.signals.backend.report_claim_follow_up.posthoganalytics.capture") as capture,+ ):+ with self.captureOnCommitCallbacks(execute=True):+ first = self.client.post(self._claim_url(report), data={}, format="json", headers=headers)+ with self.captureOnCommitCallbacks(execute=True):+ repeat = self.client.post(self._claim_url(report), data={}, format="json", headers=headers)++ assert first.status_code == repeat.status_code == status.HTTP_200_OK+ notes = list(+ SignalScoutNote.objects.filter(team=self.team, origin=SignalScoutNote.Origin.REPORT_REVIEWER_CORRECTION)+ )+ assert len(notes) == (notes_written or 0)+ if actor == "agent":+ assert "Their agent (codex) claimed it for them." in notes[0].content+ claimed_events = [c for c in capture.call_args_list if c.kwargs["event"] == "signals_report_claimed"]+ # Re-claiming under the same claim is not a new claim, so it records nothing.+ assert len(claimed_events) == 1+ properties = claimed_events[0].kwargs["properties"]+ assert properties["actor_kind"] == actor+ if notes_written is None:+ assert "claimant_was_suggested" not in properties+ else:+ assert properties["claimant_was_suggested"] is suggested+ assert properties["suggested_count"] == int(suggested)+ assert properties["claim_notes_enabled"] is flag_on+ assert properties["claim_notes_written"] == notes_written+def test_identical_claim_is_idempotent(self):report = self._create_report()self.client.post(self._claim_url(report), data={}, format="json")diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 17d2d3490e5c..3325880cab5c 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -184,6 +184,7 @@ from products.signals.backend.report_check_authoring import (cancel_check,replace_metric_check,)+from products.signals.backend.report_claim_follow_up import record_report_claimedfrom products.signals.backend.report_claims import (ReportClaim,actor_works_under_claim,@@ -2985,18 +2986,29 @@ class SignalReportViewSet(request_serializer.is_valid(raise_exception=True)report = cast(SignalReport, self.get_object())data = request_serializer.validated_data+ actor = self._request_attribution()+ was_impersonated = is_impersonated_session(request)+ scoped_team_ids = get_authenticator_scoped_team_ids(request.successful_authenticator)try:claim_report(report=report,- actor=self._request_attribution(),+ actor=actor,user=cast(User, request.user),- was_impersonated=is_impersonated_session(request),+ was_impersonated=was_impersonated,pr_url=data.get("pr_url"),release=data["release"],pull_requests=data.get("pull_requests"),claim_id=str(data["claim_id"]) if data.get("claim_id") else None,takeover=data["takeover"],takeover_claim_id=str(data["takeover_claim_id"]) if data.get("takeover_claim_id") else None,+ on_new_claim=partial(+ record_report_claimed,+ team_id=self.team.id,+ report_id=str(report.id),+ actor=actor,+ scoped_team_ids=tuple(scoped_team_ids) if scoped_team_ids is not None else None,+ was_impersonated=was_impersonated,+ ),)except InvalidPullRequestUrl as err:raise serializers.ValidationError({"pr_url": str(err)})@@ -6229,6 +6241,7 @@ def remove_suggested_reviewer(],correction=correction,forward_note=forward_note,+ self_removal=True,))return True@@ -6242,6 +6255,7 @@ def _record_reviewer_edit(user_uuids: list[str],correction: ReviewerCorrection | None,forward_note: bool = True,+ self_removal: bool = False,) -> None:"""The post-commit tail of a reviewer edit: steer the scouts, then record what the edit did.@@ -6261,6 +6275,7 @@ def _record_reviewer_edit(correction_note_targets=forwarded.targets_resolved if forwarded else None,removal_reason=correction.removal_reason if correction else None,has_removal_note=bool(correction.removal_note) if correction and correction.removed_reviewers else None,+ self_removal=self_removal,)diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 7db77faa885b..f95553a02a63 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -8757,7 +8757,7 @@ export interface ScoutNoteApi {* @nullable*/created_by_name: string | null- /** Where the note came from. `human` for one left directly through this API. `report_dismissal` for one forwarded from the note someone typed when they dismissed, snoozed, or restored one or more inbox reports: one reviewer's verdict on the reports its content names, so weigh it as evidence about those reports rather than as fleet-level steering. `report_discussion` for the question someone asked when they opened a discussion on a report: context to weigh, neither a verdict on the report nor a directive. `report_feedback` for the note someone left when rating a report useful or not: one reader's rating of the named report, context to weigh rather than a directive. `report_reviewer_correction` for a suggested reviewer someone added or removed on a report: evidence about who owns that surface, and a prompt to revisit the routing memory it corrects, rather than a directive. */+ /** Where the note came from. `human` for one left directly through this API. `report_dismissal` for one forwarded from the note someone typed when they dismissed, snoozed, or restored one or more inbox reports: one reviewer's verdict on the reports its content names, so weigh it as evidence about those reports rather than as fleet-level steering. `report_discussion` for the question someone asked when they opened a discussion on a report: context to weigh, neither a verdict on the report nor a directive. `report_feedback` for the note someone left when rating a report useful or not: one reader's rating of the named report, context to weigh rather than a directive. `report_reviewer_correction` for a suggested reviewer someone added or removed on a report, or for a report a person or their agent claimed: evidence about who owns that surface, and a prompt to revisit the routing memory it corrects or supports, rather than a directive. */origin: string}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b41f1885c923..b40831c21121 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -102876,7 +102876,7 @@ export namespace Schemas {* @nullable*/created_by_name: string | null;- /** Where the note came from. `human` for one left directly through this API. `report_dismissal` for one forwarded from the note someone typed when they dismissed, snoozed, or restored one or more inbox reports: one reviewer's verdict on the reports its content names, so weigh it as evidence about those reports rather than as fleet-level steering. `report_discussion` for the question someone asked when they opened a discussion on a report: context to weigh, neither a verdict on the report nor a directive. `report_feedback` for the note someone left when rating a report useful or not: one reader's rating of the named report, context to weigh rather than a directive. `report_reviewer_correction` for a suggested reviewer someone added or removed on a report: evidence about who owns that surface, and a prompt to revisit the routing memory it corrects, rather than a directive. */+ /** Where the note came from. `human` for one left directly through this API. `report_dismissal` for one forwarded from the note someone typed when they dismissed, snoozed, or restored one or more inbox reports: one reviewer's verdict on the reports its content names, so weigh it as evidence about those reports rather than as fleet-level steering. `report_discussion` for the question someone asked when they opened a discussion on a report: context to weigh, neither a verdict on the report nor a directive. `report_feedback` for the note someone left when rating a report useful or not: one reader's rating of the named report, context to weigh rather than a directive. `report_reviewer_correction` for a suggested reviewer someone added or removed on a report, or for a report a person or their agent claimed: evidence about who owns that surface, and a prompt to revisit the routing memory it corrects or supports, rather than a directive. */origin: string;}