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): expose PUT API for suggested-reviewer artefacts (#59357)

Oliver Browne810b6eaccabb
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index 969eb0c27b27..5b3e8f28a1cb 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -1161,6 +1161,12 @@ signal_reports_router.register(
"environment_signal_report_tasks",
["team_id", "report_id"],
)
+signal_reports_router.register(
+ r"artefacts",
+ signals.SignalReportArtefactViewSet,
+ "environment_signal_report_artefacts",
+ ["team_id", "report_id"],
+)
projects_router.register(
r"signals/source_configs",
signals.SignalSourceConfigViewSet,
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 642dfdbfd0f4..a42bc9698a0b 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -361,3 +361,60 @@ class SignalReportArtefactSerializer(serializers.ModelSerializer):
)
return parsed
+
+
+class SuggestedReviewerEntryWriteSerializer(serializers.Serializer):
+ """Single entry in a PUT body for a `suggested_reviewers` artefact.
+
+ Each entry must identify a reviewer by at least one of `github_login` or `user_uuid`.
+ The server canonicalizes to a lowercase `github_login` — if `user_uuid` is supplied,
+ it must map to an org member on this team with a linked GitHub login.
+ """
+
+ github_login = serializers.CharField(
+ required=False,
+ allow_blank=False,
+ max_length=200,
+ help_text="GitHub login (case-insensitive). Stored lowercased.",
+ )
+ user_uuid = serializers.UUIDField(
+ required=False,
+ help_text=(
+ "PostHog user UUID. Must be an org member on this team with a linked GitHub identity. "
+ "If supplied together with `github_login`, the server-resolved login from the user wins."
+ ),
+ )
+ github_name = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=200,
+ help_text="Optional human-readable display name. Not backfilled from GitHub by the server.",
+ )
+
+ def validate(self, attrs: dict) -> dict:
+ if not attrs.get("github_login") and not attrs.get("user_uuid"):
+ raise serializers.ValidationError("Each entry must include `github_login` or `user_uuid` (or both).")
+ return attrs
+
+
+class SignalReportArtefactWriteSerializer(serializers.Serializer):
+ """PUT body for replacing a `suggested_reviewers` artefact's content.
+
+ Only `suggested_reviewers` artefacts may be modified via this endpoint;
+ the viewset enforces the type check before validation runs.
+ """
+
+ MAX_ENTRIES = 10
+
+ content = SuggestedReviewerEntryWriteSerializer(
+ many=True,
+ allow_empty=True,
+ help_text=(
+ f"Full replacement list of reviewers. Empty list clears the artefact. At most {MAX_ENTRIES} entries."
+ ),
+ )
+
+ def validate_content(self, value: list[dict]) -> list[dict]:
+ if len(value) > self.MAX_ENTRIES:
+ raise serializers.ValidationError(f"At most {self.MAX_ENTRIES} reviewers may be supplied.")
+ return value
diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.py
new file mode 100644
index 000000000000..43fd7a19b2dd
--- /dev/null
+++ b/products/signals/backend/test/test_signal_report_artefact_api.py
@@ -0,0 +1,504 @@
+import json
+import uuid
+
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+from rest_framework import status
+from social_django.models import UserSocialAuth
+
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.signals.backend.models import SignalReport, SignalReportArtefact
+
+
+def _attach_github_login(user: User, login: str, *, uid: str | None = None) -> None:
+ UserSocialAuth.objects.create(
+ user=user,
+ provider="github",
+ uid=uid or f"gh-{login}",
+ extra_data={"login": login},
+ )
+
+
+class TestSignalReportArtefactViewSet(APIBaseTest):
+ def _list_url(self, report_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/artefacts/"
+
+ def _detail_url(self, report_id: str, artefact_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/artefacts/{artefact_id}/"
+
+ def _create_report(self, team: Team | None = None) -> SignalReport:
+ return SignalReport.objects.create(
+ team=team or self.team,
+ status=SignalReport.Status.READY,
+ title="Test report",
+ summary="Test summary",
+ signal_count=1,
+ total_weight=1.0,
+ )
+
+ def _create_artefact(
+ self,
+ report: SignalReport,
+ *,
+ artefact_type: str = SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content: list | dict | None = None,
+ ) -> SignalReportArtefact:
+ if content is None:
+ content = []
+ return SignalReportArtefact.objects.create(
+ team=report.team,
+ report=report,
+ type=artefact_type,
+ content=json.dumps(content),
+ )
+
+ def _create_org_member(self, email: str, *, github_login: str | None = None) -> User:
+ user = User.objects.create(email=email)
+ OrganizationMembership.objects.create(user=user, organization=self.organization)
+ if github_login is not None:
+ _attach_github_login(user, github_login, uid=f"gh-{email}")
+ return user
+
+ # --- GET list ---
+
+ def test_list_returns_results_envelope(self):
+ report = self._create_report()
+ self._create_artefact(report, content=[{"github_login": "alice"}])
+ self._create_artefact(
+ report,
+ artefact_type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
+ content={"priority": "P1"},
+ )
+
+ response = self.client.get(self._list_url(str(report.id)))
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["count"] == 2
+ assert len(data["results"]) == 2
+ types = {row["type"] for row in data["results"]}
+ assert types == {"suggested_reviewers", "priority_judgment"}
+
+ def test_list_enriches_suggested_reviewers_with_user(self):
+ member = self._create_org_member("[email protected]", github_login="Alice")
+ report = self._create_report()
+ self._create_artefact(report, content=[{"github_login": "alice", "github_name": "Alice"}])
+
+ response = self.client.get(self._list_url(str(report.id)))
+ assert response.status_code == status.HTTP_200_OK
+ rows = response.json()["results"]
+ reviewer = rows[0]["content"][0]
+ assert reviewer["github_login"] == "alice"
+ assert reviewer["user"] is not None
+ assert reviewer["user"]["uuid"] == str(member.uuid)
+ assert reviewer["user"]["email"] == "[email protected]"
+
+ def test_list_unknown_login_returns_null_user(self):
+ report = self._create_report()
+ self._create_artefact(report, content=[{"github_login": "nobody"}])
+
+ response = self.client.get(self._list_url(str(report.id)))
+ assert response.status_code == status.HTTP_200_OK
+ rows = response.json()["results"]
+ assert rows[0]["content"][0]["user"] is None
+
+ def test_list_scoped_to_report_and_team(self):
+ report = self._create_report()
+ other_report = self._create_report()
+ self._create_artefact(report, content=[{"github_login": "alice"}])
+ self._create_artefact(other_report, content=[{"github_login": "bob"}])
+
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ other_team_report = self._create_report(team=other_team)
+ self._create_artefact(other_team_report, content=[{"github_login": "carol"}])
+
+ response = self.client.get(self._list_url(str(report.id)))
+ assert response.status_code == status.HTTP_200_OK
+ results = response.json()["results"]
+ assert len(results) == 1
+ assert results[0]["content"][0]["github_login"] == "alice"
+
+ # --- GET retrieve ---
+
+ def test_retrieve_returns_single_enriched_artefact(self):
+ member = self._create_org_member("[email protected]", github_login="bob")
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[{"github_login": "bob"}])
+
+ response = self.client.get(self._detail_url(str(report.id), str(artefact.id)))
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["id"] == str(artefact.id)
+ assert body["content"][0]["user"]["uuid"] == str(member.uuid)
+
+ def test_retrieve_artefact_from_other_team_returns_404(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ other_report = self._create_report(team=other_team)
+ artefact = self._create_artefact(other_report, content=[{"github_login": "alice"}])
+
+ response = self.client.get(self._detail_url(str(other_report.id), str(artefact.id)))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ # --- PUT (update) ---
+
+ def test_put_replaces_full_list(self):
+ report = self._create_report()
+ artefact = self._create_artefact(
+ report,
+ content=[{"github_login": "alice", "github_name": "Alice", "relevant_commits": []}],
+ )
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"github_login": "Bob"}, {"github_login": "Carol"}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ artefact.refresh_from_db()
+ stored = json.loads(artefact.content)
+ assert [r["github_login"] for r in stored] == ["bob", "carol"]
+ assert all(r["relevant_commits"] == [] for r in stored)
+
+ def test_put_empty_list_clears_content(self):
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[{"github_login": "alice"}])
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": []}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ artefact.refresh_from_db()
+ assert json.loads(artefact.content) == []
+
+ def test_put_preserves_relevant_commits_for_kept_entries(self):
+ report = self._create_report()
+ artefact = self._create_artefact(
+ report,
+ content=[
+ {
+ "github_login": "alice",
+ "github_name": "Alice A.",
+ "relevant_commits": [{"sha": "abc123", "url": "u", "reason": "r"}],
+ },
+ {
+ "github_login": "bob",
+ "github_name": "Bob B.",
+ "relevant_commits": [{"sha": "def456", "url": "u2", "reason": "r2"}],
+ },
+ ],
+ )
+
+ # Keep alice (existing commits should survive), add a new reviewer dave (commits empty).
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"github_login": "alice"}, {"github_login": "dave"}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ artefact.refresh_from_db()
+ stored = {r["github_login"]: r for r in json.loads(artefact.content)}
+ assert stored["alice"]["relevant_commits"] == [{"sha": "abc123", "url": "u", "reason": "r"}]
+ assert stored["alice"]["github_name"] == "Alice A." # carried over from prior
+ assert stored["dave"]["relevant_commits"] == []
+ assert "bob" not in stored
+
+ def test_put_resolves_user_uuid_to_github_login(self):
+ member = self._create_org_member("[email protected]", github_login="AliceCase")
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"user_uuid": str(member.uuid)}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ artefact.refresh_from_db()
+ stored = json.loads(artefact.content)
+ assert len(stored) == 1
+ assert stored[0]["github_login"] == "alicecase"
+
+ def test_put_user_uuid_wins_over_supplied_github_login(self):
+ member = self._create_org_member("[email protected]", github_login="AliceCase")
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+
+ # Client supplies both; server canonicalizes to the user's actual GitHub login.
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"user_uuid": str(member.uuid), "github_login": "totally-different"}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ artefact.refresh_from_db()
+ stored = json.loads(artefact.content)
+ assert stored[0]["github_login"] == "alicecase"
+
+ def test_put_user_uuid_without_github_login_returns_400(self):
+ # Org member without any linked GitHub identity.
+ member = self._create_org_member("[email protected]", github_login=None)
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"user_uuid": str(member.uuid)}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "not an org member" in response.json()["error"]
+
+ def test_put_user_uuid_not_in_org_returns_400(self):
+ # Random UUID not tied to anyone in this org.
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"user_uuid": str(uuid.uuid4())}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_put_entry_missing_both_login_and_uuid_returns_400(self):
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"github_name": "orphan"}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_put_content_must_be_a_list(self):
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": "not-a-list"}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_put_dedupes_by_canonical_login_preserving_order(self):
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps(
+ {
+ "content": [
+ {"github_login": "Alice"},
+ {"github_login": "BOB"},
+ {"github_login": "alice"}, # duplicate after lowercase
+ ]
+ }
+ ),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ artefact.refresh_from_db()
+ stored = json.loads(artefact.content)
+ assert [r["github_login"] for r in stored] == ["alice", "bob"]
+
+ def test_put_is_idempotent(self):
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+ body = json.dumps({"content": [{"github_login": "alice"}, {"github_login": "bob"}]})
+
+ first = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=body,
+ content_type="application/json",
+ )
+ assert first.status_code == status.HTTP_200_OK
+ artefact.refresh_from_db()
+ first_content = artefact.content
+
+ second = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=body,
+ content_type="application/json",
+ )
+ assert second.status_code == status.HTTP_200_OK
+ artefact.refresh_from_db()
+ assert artefact.content == first_content
+
+ def test_put_response_is_enriched_with_user(self):
+ member = self._create_org_member("[email protected]", github_login="alice")
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"github_login": "alice"}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["content"][0]["user"]["uuid"] == str(member.uuid)
+
+ @parameterized.expand(
+ [
+ ("video_segment", SignalReportArtefact.ArtefactType.VIDEO_SEGMENT),
+ ("safety_judgment", SignalReportArtefact.ArtefactType.SAFETY_JUDGMENT),
+ ("actionability_judgment", SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT),
+ ("priority_judgment", SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT),
+ ("signal_finding", SignalReportArtefact.ArtefactType.SIGNAL_FINDING),
+ ("repo_selection", SignalReportArtefact.ArtefactType.REPO_SELECTION),
+ ("dismissal", SignalReportArtefact.ArtefactType.DISMISSAL),
+ ]
+ )
+ def test_put_rejects_non_suggested_reviewers_types(self, _name, artefact_type):
+ report = self._create_report()
+ artefact = self._create_artefact(report, artefact_type=artefact_type, content={})
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": []}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Only suggested_reviewers" in response.json()["error"]
+
+ def test_put_other_team_returns_404(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ other_report = self._create_report(team=other_team)
+ artefact = self._create_artefact(other_report, content=[])
+
+ response = self.client.put(
+ self._detail_url(str(other_report.id), str(artefact.id)),
+ data=json.dumps({"content": []}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_put_max_entries_enforced(self):
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+
+ too_many = [{"github_login": f"user{i}"} for i in range(11)]
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": too_many}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_patch_not_allowed(self):
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+
+ response = self.client.patch(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": []}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
+
+ def test_post_not_allowed(self):
+ report = self._create_report()
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"content": []}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
+
+ def test_delete_not_allowed(self):
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+ response = self.client.delete(self._detail_url(str(report.id), str(artefact.id)))
+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
+
+ def test_list_excludes_artefacts_when_parent_report_deleted(self):
+ report = self._create_report()
+ self._create_artefact(report, content=[{"github_login": "alice"}])
+ report.status = SignalReport.Status.DELETED
+ report.save(update_fields=["status"])
+
+ response = self.client.get(self._list_url(str(report.id)))
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["results"] == []
+
+ def test_put_on_deleted_report_artefact_returns_404(self):
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+ report.status = SignalReport.Status.DELETED
+ report.save(update_fields=["status"])
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"github_login": "alice"}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_put_empty_github_name_clears_prior_value(self):
+ # The pipeline stored a name; the client wants to clear it.
+ report = self._create_report()
+ artefact = self._create_artefact(
+ report,
+ content=[{"github_login": "alice", "github_name": "Alice A.", "relevant_commits": []}],
+ )
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"github_login": "alice", "github_name": ""}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ artefact.refresh_from_db()
+ stored = json.loads(artefact.content)
+ assert stored[0]["github_name"] == ""
+
+ def test_put_omitted_github_name_carries_over_prior_value(self):
+ # When the client doesn't mention github_name, keep what the pipeline had.
+ report = self._create_report()
+ artefact = self._create_artefact(
+ report,
+ content=[{"github_login": "alice", "github_name": "Alice A.", "relevant_commits": []}],
+ )
+
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"github_login": "alice"}]}),
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ artefact.refresh_from_db()
+ stored = json.loads(artefact.content)
+ assert stored[0]["github_name"] == "Alice A."
+
+ def test_put_after_update_preserves_filter_jsonb_containment(self):
+ """The list filter `?suggested_reviewers=<user-uuid>` reads the same field.
+
+ Ensure that after a PUT, the canonical stored shape still matches the
+ jsonb containment query the report list uses.
+ """
+ member = self._create_org_member("[email protected]", github_login="alice")
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[])
+
+ put_response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"github_login": "alice"}]}),
+ content_type="application/json",
+ )
+ assert put_response.status_code == status.HTTP_200_OK
+
+ list_url = f"/api/projects/{self.team.id}/signals/reports/?suggested_reviewers={member.uuid}"
+ list_response = self.client.get(list_url)
+ assert list_response.status_code == status.HTTP_200_OK
+ ids = {r["id"] for r in list_response.json()["results"]}
+ assert str(report.id) in ids
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 65e418d2071b..f0a70c4c89d0 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -69,6 +69,7 @@ from products.signals.backend.report_generation.resolve_reviewers import (
)
from products.signals.backend.serializers import (
SignalReportArtefactSerializer,
+ SignalReportArtefactWriteSerializer,
SignalReportSerializer,
SignalReportTaskSerializer,
SignalSourceConfigSerializer,
@@ -752,24 +753,6 @@ class SignalReportViewSet(
return Response({"status": "deletion_started", "report_id": report_id}, status=status.HTTP_202_ACCEPTED)
- @extend_schema(exclude=True)
- @action(detail=True, methods=["get"], url_path="artefacts", required_scopes=["task:read"])
- def artefacts(self, request, pk=None, **kwargs):
- report = cast(SignalReport, self.get_object())
- artefacts = list(report.artefacts.all().order_by("-created_at"))
- logins_union = normalized_github_logins_from_suggested_reviewer_artefacts(artefacts)
- login_map = resolve_org_github_login_to_users(self.team.id, logins_union) if logins_union else {}
- serializer = SignalReportArtefactSerializer(
- artefacts,
- many=True,
- context={
- **self.get_serializer_context(),
- "signals_github_login_to_user_map": login_map,
- },
- )
- results = serializer.data
- return Response({"results": results, "count": len(results)})
-
@extend_schema(exclude=True)
@action(detail=True, methods=["get"], url_path="signals", required_scopes=["task:read"])
def signals(self, request, pk=None, **kwargs):
@@ -901,6 +884,169 @@ class SignalReportViewSet(
return Response({"status": "reingestion_started", "report_id": report_id}, status=status.HTTP_202_ACCEPTED)
+@extend_schema_view(
+ list=extend_schema(exclude=True),
+ retrieve=extend_schema(exclude=True),
+ update=extend_schema(exclude=True),
+)
+class SignalReportArtefactViewSet(
+ TeamAndOrgViewSetMixin,
+ mixins.ListModelMixin,
+ mixins.RetrieveModelMixin,
+ mixins.UpdateModelMixin,
+ viewsets.GenericViewSet,
+):
+ """Artefacts attached to a signal report. PUT replaces the content of a
+ `suggested_reviewers` artefact; other types return 400."""
+
+ serializer_class = SignalReportArtefactSerializer
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ scope_object = "task"
+ queryset = SignalReportArtefact.objects.all().order_by("-created_at")
+ # No POST / PATCH / DELETE
+ http_method_names = ["get", "put", "head", "options"]
+
+ def safely_get_queryset(self, queryset):
+ # Mirror SignalReportViewSet: a deleted parent report is unreachable, so
+ # its artefacts must be too (otherwise a known UUID would bypass deletion).
+ return queryset.filter(
+ report_id=self.parents_query_dict["report_id"],
+ team=self.team,
+ ).exclude(report__status=SignalReport.Status.DELETED)
+
+ def list(self, request, *args, **kwargs):
+ queryset = self.filter_queryset(self.get_queryset())
+ page = self.paginate_queryset(queryset)
+ artefacts = list(page if page is not None else queryset)
+ logins_union = normalized_github_logins_from_suggested_reviewer_artefacts(artefacts)
+ login_map = resolve_org_github_login_to_users(self.team.id, logins_union) if logins_union else {}
+ serializer = SignalReportArtefactSerializer(
+ artefacts,
+ many=True,
+ context={
+ **self.get_serializer_context(),
+ "signals_github_login_to_user_map": login_map,
+ },
+ )
+ if page is not None:
+ return self.get_paginated_response(serializer.data)
+ return Response(serializer.data)
+
+ def update(self, request, *args, **kwargs):
+ artefact = cast(SignalReportArtefact, self.get_object())
+
+ # Generic endpoint, single-type allow-list: any other artefact type is
+ # part of the agentic pipeline contract and must not be hand-edited.
+ if artefact.type != SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS:
+ return Response(
+ {
+ "error": (
+ "Only suggested_reviewers artefacts may be modified via this endpoint. "
+ f"This artefact has type '{artefact.type}'."
+ )
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ write_serializer = SignalReportArtefactWriteSerializer(data=request.data)
+ write_serializer.is_valid(raise_exception=True)
+ entries = write_serializer.validated_data["content"]
+
+ # Resolve any user_uuid → canonical github_login via team org membership.
+ uuids_to_resolve = [str(e["user_uuid"]) for e in entries if e.get("user_uuid")]
+ uuid_to_login: dict[str, str] = (
+ get_org_member_github_logins_by_user_uuid(self.team.id, uuids_to_resolve) if uuids_to_resolve else {}
+ )
+
+ # Resolve canonical login per entry. Fail loudly if a user_uuid does not
+ # map to an org member with a GitHub identity on this team.
+ # The third tuple element distinguishes "github_name explicitly supplied
+ # (incl. empty string to clear)" from "field absent" — the merge step below
+ # only falls back to the prior name when the field is absent.
+ resolved_entries: list[tuple[str, str | None, bool]] = []
+ for idx, entry in enumerate(entries):
+ user_uuid = entry.get("user_uuid")
+ if user_uuid is not None:
+ resolved_login = uuid_to_login.get(str(user_uuid))
+ if not resolved_login:
+ return Response(
+ {
+ "error": (
+ f"content[{idx}]: user_uuid '{user_uuid}' is not an org member of this team "
+ "with a linked GitHub identity."
+ )
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ login_lc = resolved_login.lower()
+ else:
+ raw_login = entry.get("github_login") or ""
+ login_lc = raw_login.strip().lower()
+ if not login_lc:
+ return Response(
+ {"error": f"content[{idx}]: github_login resolved to empty after normalization."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ explicit_name = "github_name" in entry
+ github_name = entry.get("github_name") if explicit_name else None
+ resolved_entries.append((login_lc, github_name, explicit_name))
+
+ # Preserve relevant_commits for entries that survive the replace, keyed by login.
+ try:
+ prior_content = json.loads(artefact.content)
+ except (json.JSONDecodeError, ValueError):
+ prior_content = []
+ prior_commits_by_login: dict[str, list] = {}
+ prior_name_by_login: dict[str, str | None] = {}
+ if isinstance(prior_content, list):
+ for prior in prior_content:
+ if not isinstance(prior, dict):
+ continue
+ login = (prior.get("github_login") or "").strip().lower()
+ if not login:
+ continue
+ commits = prior.get("relevant_commits")
+ if isinstance(commits, list):
+ prior_commits_by_login[login] = commits
+ prior_name = prior.get("github_name")
+ if isinstance(prior_name, str):
+ prior_name_by_login[login] = prior_name
+
+ # Dedupe by canonical login, preserve first-seen order.
+ seen: set[str] = set()
+ new_content: list[dict] = []
+ for login_lc, github_name, explicit_name in resolved_entries:
+ if login_lc in seen:
+ continue
+ seen.add(login_lc)
+ # If the client supplied github_name (incl. ""), honour it. Otherwise
+ # carry over the prior one so kept reviewers don't lose their name.
+ effective_name = github_name if explicit_name else prior_name_by_login.get(login_lc)
+ new_content.append(
+ {
+ "github_login": login_lc,
+ "github_name": effective_name,
+ "relevant_commits": prior_commits_by_login.get(login_lc, []),
+ }
+ )
+
+ artefact.content = json.dumps(new_content)
+ artefact.save(update_fields=["content"])
+
+ # Return the read-shape (enriched) so the client sees the canonical result.
+ login_map = resolve_org_github_login_to_users(self.team.id, list(seen)) if seen else {}
+ read_serializer = SignalReportArtefactSerializer(
+ artefact,
+ context={
+ **self.get_serializer_context(),
+ "signals_github_login_to_user_map": login_map,
+ },
+ )
+ return Response(read_serializer.data)
+
+
@extend_schema_view(list=extend_schema(exclude=True))
class SignalReportTaskViewSet(
TeamAndOrgViewSetMixin,