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.

chore(review-hog): route the config views through the facade (#115691)

Julian Bez3f92c6186a56
diff --git a/products/review_hog/backend/facade/api.py b/products/review_hog/backend/facade/api.py
new file mode 100644
index 000000000000..262f8cd3b974
--- /dev/null
+++ b/products/review_hog/backend/facade/api.py
@@ -0,0 +1,108 @@
+"""PostHog Review's data surface for its own views and for other products.
+
+Takes plain values and contracts, returns contracts. Keep heavy imports (Temporal, HogQL) off this
+module: they go in their own facade submodule.
+"""
+
+import logging
+from collections.abc import Mapping
+
+from posthog.models.scoping.manager import resolve_effective_team_id
+
+from products.review_hog.backend.facade.contracts import (
+ ReviewProjectPreferenceDefaults,
+ ReviewSkill,
+ ReviewSkillChoice,
+ ReviewUserPreferences,
+)
+from products.review_hog.backend.facade.enums import ReviewSkillKind
+from products.review_hog.backend.models import ReviewUserSettings
+from products.review_hog.backend.preferences import ReviewPreferences
+from products.review_hog.backend.reviewer.lazy_seed import seed_canonicals_tolerantly, sync_canonical_authoring
+from products.review_hog.backend.skill_configs import ReviewSkillMenu
+from products.stamphog.backend.facade.api import has_reviewable_repo_config
+
+logger = logging.getLogger(__name__)
+
+
+def list_review_skill_choices(team_id: int, user_id: int, kind: ReviewSkillKind) -> list[ReviewSkillChoice]:
+ """The review skills of `kind` the user can see, by name, with the user's state for each.
+
+ Seeds the canonical skills and the user's canonical config rows first, so a cold team or user
+ sees the defaults.
+ """
+ return ReviewSkillMenu(team_id, user_id, kind).choices()
+
+
+def get_review_skill(team_id: int, user_id: int, kind: ReviewSkillKind, skill_name: str) -> ReviewSkill:
+ """The live review skill of `kind` called `skill_name`, when the user can see it.
+
+ Raises `ReviewSkillNameError` when the name does not carry the prefix of `kind`, and
+ `ReviewSkillNotFoundError` when no such skill is visible to the user.
+ """
+ return ReviewSkillMenu(team_id, user_id, kind).get(skill_name)
+
+
+def set_review_perspective_enabled(
+ team_id: int, user_id: int, perspective: ReviewSkill, enabled: bool
+) -> ReviewSkillChoice:
+ """Enable or disable one perspective for the user.
+
+ Raises `LastEnabledPerspectiveError` when the user would have no enabled perspective left.
+ """
+ return ReviewSkillMenu(team_id, user_id, ReviewSkillKind.PERSPECTIVE).set_enabled(perspective, enabled)
+
+
+def select_review_skill(team_id: int, user_id: int, kind: ReviewSkillKind, skill: ReviewSkill) -> ReviewSkillChoice:
+ """Make `skill` the user's single active skill of a single-active `kind`."""
+ return ReviewSkillMenu(team_id, user_id, kind).select(skill)
+
+
+def _stamphog_connected(team_id: int) -> bool:
+ # This reads the stamphog product DB, which can fail fast on its own circuit breaker. An
+ # informational UI flag must not fail the settings endpoint, so fall back to False.
+ try:
+ return has_reviewable_repo_config(team_id)
+ except Exception:
+ logger.exception("review_hog_stamphog_connected_check_failed")
+ return False
+
+
+def _user_preferences(team_id: int, preferences: ReviewPreferences) -> ReviewUserPreferences:
+ return ReviewUserPreferences(
+ default_review_mode=preferences.default_review_mode,
+ review_drafts=preferences.review_drafts,
+ resolve_comments=preferences.resolve_comments,
+ urgency_threshold=preferences.urgency_threshold,
+ celebrate_clean_reviews=preferences.celebrate_clean_reviews,
+ review_inbox_prs=preferences.review_inbox_prs,
+ stamphog_review_inbox_prs=preferences.stamphog_review_inbox_prs,
+ sources=preferences.sources,
+ project_defaults=ReviewProjectPreferenceDefaults(
+ urgency_threshold=preferences.project.urgency_threshold,
+ celebrate_clean_reviews=preferences.project.celebrate_clean_reviews,
+ ),
+ stamphog_connected=_stamphog_connected(team_id),
+ )
+
+
+def get_review_user_preferences(team_id: int, user_id: int) -> ReviewUserPreferences:
+ """The user's effective review preferences on the project. Reading never creates a row."""
+ team_id = resolve_effective_team_id(team_id)
+ # Seed the authoring companion before any review has run: the "Create your own …" tasks
+ # `skill-get` it over MCP, and this settings read backs the Code review tab's always-called
+ # endpoint. `team_id` is already the effective (root) team, the same team the review runs
+ # under, so the skill lands where the sandbox agent's `skill-get` will look.
+ seed_canonicals_tolerantly(team_id, sync_canonical_authoring)
+ return _user_preferences(team_id, ReviewUserSettings.load_preferences(team_id, user_id))
+
+
+def update_review_user_preferences(team_id: int, user_id: int, changes: Mapping[str, object]) -> ReviewUserPreferences:
+ """Apply `changes` to the user's preferences. A value equal to the inherited one clears the user's own value.
+
+ Raises `InvalidPreference` for an unknown key or an invalid value.
+ """
+ # Resolve a raw environment URL id to its root team once: `for_team` canonicalizes its filter
+ # but not the create kwargs, and mismatched ids mean a never-matching get plus 500s on re-read.
+ team_id = resolve_effective_team_id(team_id)
+ return _user_preferences(team_id, ReviewUserSettings.save_preference_changes(team_id, user_id, changes))
diff --git a/products/review_hog/backend/facade/contracts.py b/products/review_hog/backend/facade/contracts.py
index 41fbf4befade..300d700824c0 100644
--- a/products/review_hog/backend/facade/contracts.py
+++ b/products/review_hog/backend/facade/contracts.py
@@ -1,8 +1,17 @@
"""What PostHog Review hands to other products and to its own views. No Django here."""
+from collections.abc import Mapping
+
from posthog.dataclasses import frozen
-from products.review_hog.backend.facade.enums import PRReviewRequestStatus, ResolveSkipReason, ReviewRequestRefusal
+from products.review_hog.backend.facade.enums import (
+ DefaultReviewMode,
+ PreferenceSource,
+ PRReviewRequestStatus,
+ ResolveSkipReason,
+ ReviewRequestRefusal,
+ UrgencyThreshold,
+)
# What the trigger runs. The default 'review' includes the resolution stage when the pull request
# owner's `resolve_comments` setting is on; the others are the split button's explicit variants.
@@ -40,3 +49,59 @@ class PRReviewRequestOutcome:
@property
def resolve_will_run(self) -> bool:
return self.started and self.resolve_skip_reason is None
+
+
+class ReviewSkillNameError(ValueError):
+ """The skill name does not carry the prefix of the requested review skill kind."""
+
+
+class ReviewSkillNotFoundError(LookupError):
+ """No live review skill with this name is visible to the user on the project."""
+
+
+class LastEnabledPerspectiveError(ValueError):
+ """The change would leave the user with no enabled review perspective."""
+
+
+@frozen
+class ReviewSkill:
+ """A live review skill the user can see, without the user's state for it."""
+
+ skill_name: str
+ description: str
+ body: str
+
+
+@frozen
+class ReviewSkillChoice:
+ """One review skill in a user's config menu, with the user's state for it.
+
+ `enabled` is "runs on the user's reviews": enabled for a perspective, active for a single-active kind.
+ """
+
+ skill_name: str
+ enabled: bool
+ description: str
+ body: str
+
+
+@frozen
+class ReviewProjectPreferenceDefaults:
+ urgency_threshold: UrgencyThreshold
+ celebrate_clean_reviews: bool
+
+
+@frozen
+class ReviewUserPreferences:
+ """A user's effective review preferences, where each value comes from, and the project defaults."""
+
+ default_review_mode: DefaultReviewMode
+ review_drafts: bool
+ resolve_comments: bool
+ urgency_threshold: UrgencyThreshold
+ celebrate_clean_reviews: bool
+ review_inbox_prs: bool
+ stamphog_review_inbox_prs: bool
+ sources: Mapping[str, PreferenceSource]
+ project_defaults: ReviewProjectPreferenceDefaults
+ stamphog_connected: bool
diff --git a/products/review_hog/backend/facade/enums.py b/products/review_hog/backend/facade/enums.py
index 522bf4cfc4f2..b4275b01df4e 100644
--- a/products/review_hog/backend/facade/enums.py
+++ b/products/review_hog/backend/facade/enums.py
@@ -1,4 +1,4 @@
-"""Choices the review request contracts carry. No Django here, so clients and other products can read them."""
+"""Choices the review contracts carry. No Django here, so clients and other products can read them."""
from enum import StrEnum
@@ -32,3 +32,33 @@ class ReviewRequestRefusal(LabeledStrEnum):
FLASH_AFTER_FULL = "flash_after_full", "Standard after a published Deep review"
RESOLUTION_NOT_OPTED_IN = "resolution_not_opted_in", "The pull request owner has not opted in to resolution"
+
+
+class DefaultReviewMode(LabeledStrEnum):
+ FOLLOW = "follow", "Let each repository decide"
+ FLASH = "flash", "On everywhere"
+ OFF = "off", "Off everywhere"
+
+
+class UrgencyThreshold(LabeledStrEnum):
+ # Values mirror `IssuePriority`, so the threshold compares directly against finding priorities.
+ CONSIDER = "consider", "Consider (all)"
+ SHOULD_FIX = "should_fix", "Should fix"
+ MUST_FIX = "must_fix", "Must fix"
+
+
+class PreferenceSource(LabeledStrEnum):
+ USER = "user", "Set by the user"
+ PROJECT = "project", "Project default"
+ DEFAULT = "default", "Built-in default"
+
+
+class ReviewSkillKind(StrEnum):
+ """The review skill families a user configures. Each family is one skill-name prefix."""
+
+ # Multi-enable: several run on one review, and at least one must stay enabled.
+ PERSPECTIVE = "perspective"
+ # Single-active: exactly one runs, and selecting one switches the others off.
+ VALIDATION = "validation"
+ BLIND_SPOTS = "blind_spots"
+ RESOLUTION = "resolution"
diff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.py
index 5fc7a973091f..4197c7e9c8e5 100644
--- a/products/review_hog/backend/models.py
+++ b/products/review_hog/backend/models.py
@@ -1,4 +1,6 @@
-from django.db import models
+from collections.abc import Mapping
+
+from django.db import models, transaction
from django.db.models.functions import Lower
from django.utils.functional import Promise
@@ -488,7 +490,7 @@ class ReviewUserSettings(UUIDModel, TeamScopedRootMixin):
urgency_threshold = models.CharField(
max_length=20,
choices=UrgencyThreshold.choices,
- default=UrgencyThreshold.CONSIDER,
+ default=UrgencyThreshold.CONSIDER.value,
db_default=UrgencyThreshold.CONSIDER.value,
)
created_at = models.DateTimeField(auto_now_add=True)
@@ -522,6 +524,22 @@ class ReviewUserSettings(UUIDModel, TeamScopedRootMixin):
rows = cls.load_many(team_id, user_ids)
return {user_id: ReviewPreferences.resolve(row.preferences, project) for user_id, row in rows.items()}
+ @classmethod
+ def save_preference_changes(cls, team_id: int, user_id: int, changes: Mapping[str, object]) -> ReviewPreferences:
+ """Apply `changes` to the user's stored preferences and return the effective result.
+
+ Raises `InvalidPreference` for an unknown key or an invalid value.
+ """
+ rows = cls.objects.for_team(team_id, canonical=True)
+ with transaction.atomic():
+ row, _created = rows.get_or_create(team_id=team_id, user_id=user_id)
+ # The lock keeps two concurrent edits of different keys from losing one of them.
+ row = rows.select_for_update().get(id=row.id)
+ current = ReviewPreferences.resolve(row.preferences, ReviewProjectSettings.load(team_id).defaults)
+ row.preferences = current.with_changes(changes)
+ row.save(update_fields=["preferences", "updated_at"])
+ return cls.load_preferences(team_id, user_id)
+
class ReviewInstallationClaim(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):
"""Which repositories of a GitHub installation this project reviews, like GitHub's install picker.
diff --git a/products/review_hog/backend/preferences.py b/products/review_hog/backend/preferences.py
index 4bb535d58f1d..924941f7720f 100644
--- a/products/review_hog/backend/preferences.py
+++ b/products/review_hog/backend/preferences.py
@@ -12,30 +12,11 @@ This module is pure. `ReviewUserSettings` and `ReviewProjectSettings` store the
from collections.abc import Mapping
from typing import cast
-from django.db import models
-
from posthog.dataclasses import frozen
-PreferenceValue = str | bool
-
-
-class DefaultReviewMode(models.TextChoices):
- FOLLOW = "follow", "Let each repository decide"
- FLASH = "flash", "On everywhere"
- OFF = "off", "Off everywhere"
+from products.review_hog.backend.facade.enums import DefaultReviewMode, PreferenceSource, UrgencyThreshold
-
-class UrgencyThreshold(models.TextChoices):
- # Values mirror `IssuePriority`, so the threshold compares directly against finding priorities.
- CONSIDER = "consider", "Consider (all)"
- SHOULD_FIX = "should_fix", "Should fix"
- MUST_FIX = "must_fix", "Must fix"
-
-
-class PreferenceSource(models.TextChoices):
- USER = "user", "Set by the user"
- PROJECT = "project", "Project default"
- DEFAULT = "default", "Built-in default"
+PreferenceValue = str | bool
class InvalidPreference(ValueError):
diff --git a/products/review_hog/backend/presentation/views/blind_spots.py b/products/review_hog/backend/presentation/views/blind_spots.py
index a34e94cfd111..9028a309a831 100644
--- a/products/review_hog/backend/presentation/views/blind_spots.py
+++ b/products/review_hog/backend/presentation/views/blind_spots.py
@@ -1,9 +1,6 @@
import logging
from typing import cast
-from django.db import transaction
-from django.utils import timezone
-
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import serializers, viewsets
from rest_framework.exceptions import NotFound, ValidationError
@@ -11,18 +8,11 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.permissions import PostHogFeatureFlagPermission
-from products.review_hog.backend.models import ReviewSkillConfig
-from products.review_hog.backend.reviewer.lazy_seed import seed_canonicals_tolerantly, sync_canonical_blind_spots
-from products.review_hog.backend.reviewer.skill_loader import (
- CANONICAL_BLIND_SPOTS_SKILL_NAMES,
- REVIEW_HOG_BLIND_SPOTS_PREFIX,
- register_missing_blind_spots_config,
- visible_skill_names,
-)
-from products.skills.backend.models.skills import LLMSkill
+from products.review_hog.backend.facade.api import get_review_skill, list_review_skill_choices, select_review_skill
+from products.review_hog.backend.facade.contracts import ReviewSkillNameError, ReviewSkillNotFoundError
+from products.review_hog.backend.facade.enums import ReviewSkillKind
logger = logging.getLogger(__name__)
@@ -32,7 +22,8 @@ class ReviewBlindSpotsConfigSerializer(serializers.Serializer):
help_text="Name of the `review-hog-blind-spots-*` skill this row represents (the sweep's identity)."
)
active = serializers.BooleanField(
- help_text="Whether this blind-spots skill runs the sweep on the requesting user's PR reviews on this project."
+ source="enabled",
+ help_text="Whether this blind-spots skill runs the sweep on the requesting user's PR reviews on this project.",
)
description = serializers.CharField(
allow_blank=True, help_text="The blind-spots skill's description, for display in the config UI."
@@ -73,8 +64,6 @@ class ReviewBlindSpotsConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericView
scope_object = "llm_skill"
permission_classes = [PostHogFeatureFlagPermission]
posthog_feature_flag = "review-hog"
- # Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.
- queryset = ReviewSkillConfig.objects.unscoped()
serializer_class = ReviewBlindSpotsConfigSerializer
lookup_field = "skill_name"
pagination_class = None
@@ -95,37 +84,9 @@ class ReviewBlindSpotsConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericView
),
)
def list(self, request: Request, **kwargs) -> Response:
- # Resolve a raw environment URL id to its root team once — the skills and config rows all
- # live on the canonical team, so an unresolved id would render an empty menu.
- team_id = resolve_effective_team_id(self.team_id)
user_id = cast(int, request.user.id) # authenticated via the viewset mixin
- # A team that never ran a review has no LLMSkill rows yet — seed the canonical or the
- # menu renders empty until the first run.
- seed_canonicals_tolerantly(team_id, sync_canonical_blind_spots)
- register_missing_blind_spots_config(team_id, user_id)
- active_by_name = dict(
- ReviewSkillConfig.objects.for_team(team_id, canonical=True)
- .filter(user_id=user_id, skill_name__startswith=REVIEW_HOG_BLIND_SPOTS_PREFIX)
- .values_list("skill_name", "enabled")
- )
- # Per-user visibility: the menu advertises the canonical plus this user's own customs —
- # never a teammate's.
- visible = visible_skill_names(
- team_id, user_id, prefix=REVIEW_HOG_BLIND_SPOTS_PREFIX, canonical_names=CANONICAL_BLIND_SPOTS_SKILL_NAMES
- )
- skills = LLMSkill.objects.filter(team_id=team_id, name__in=visible, is_latest=True, deleted=False).order_by(
- "name"
- )
- items = [
- {
- "skill_name": s.name,
- "active": active_by_name.get(s.name, False),
- "description": s.description,
- "body": s.body,
- }
- for s in skills
- ]
- return Response(ReviewBlindSpotsConfigSerializer(items, many=True).data)
+ choices = list_review_skill_choices(self.team_id, user_id, ReviewSkillKind.BLIND_SPOTS)
+ return Response(ReviewBlindSpotsConfigSerializer(choices, many=True).data)
@extend_schema(
request=ReviewBlindSpotsConfigSelectSerializer,
@@ -147,22 +108,12 @@ class ReviewBlindSpotsConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericView
),
)
def partial_update(self, request: Request, skill_name: str, **kwargs) -> Response:
- if not skill_name.startswith(REVIEW_HOG_BLIND_SPOTS_PREFIX):
- raise ValidationError(f"'{skill_name}' is not a review blind-spots skill")
- # Resolve a raw environment URL id to its root team once: `for_team` canonicalizes its
- # filter but not the create kwargs, and mismatched ids mean a never-matching get plus
- # 500s on the unique constraint from the second call on.
- team_id = resolve_effective_team_id(self.team_id)
user_id = cast(int, request.user.id) # authenticated via the viewset mixin
- # Same cold-team seed as list(): selecting the canonical before the team's first review
- # would 404 without it.
- seed_canonicals_tolerantly(team_id, sync_canonical_blind_spots)
- skill = LLMSkill.objects.filter(team_id=team_id, name=skill_name, is_latest=True, deleted=False).first()
- # A teammate's custom 404s exactly like a missing skill — visibility is author-only, and a
- # distinct error would leak that the name exists.
- if skill is None or skill_name not in visible_skill_names(
- team_id, user_id, prefix=REVIEW_HOG_BLIND_SPOTS_PREFIX, canonical_names=CANONICAL_BLIND_SPOTS_SKILL_NAMES
- ):
+ try:
+ skill = get_review_skill(self.team_id, user_id, ReviewSkillKind.BLIND_SPOTS, skill_name)
+ except ReviewSkillNameError:
+ raise ValidationError(f"'{skill_name}' is not a review blind-spots skill")
+ except ReviewSkillNotFoundError:
raise NotFound(f"No blind-spots skill '{skill_name}' on this project")
select = ReviewBlindSpotsConfigSelectSerializer(data=request.data)
@@ -172,23 +123,5 @@ class ReviewBlindSpotsConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericView
"The blind-spot check is single-active — select a different skill instead of deactivating"
)
- register_missing_blind_spots_config(team_id, user_id)
- configs = ReviewSkillConfig.objects.for_team(team_id, canonical=True)
- # Single-active: deactivate-others + activate-this must land together, or a crash between them
- # leaves the user with no active skill (the loader's canonical fallback would heal it).
- with transaction.atomic():
- configs.filter(user_id=user_id, skill_name__startswith=REVIEW_HOG_BLIND_SPOTS_PREFIX, enabled=True).exclude(
- skill_name=skill_name
- ).update(enabled=False, updated_at=timezone.now())
- # `team_id` / `user_id` stay in the create kwargs — the fail-closed filter doesn't propagate.
- config, _created = configs.get_or_create(
- team_id=team_id, user_id=user_id, skill_name=skill_name, defaults={"enabled": True}
- )
- if not config.enabled:
- config.enabled = True
- config.save(update_fields=["enabled", "updated_at"])
- return Response(
- ReviewBlindSpotsConfigSerializer(
- {"skill_name": skill_name, "active": True, "description": skill.description, "body": skill.body}
- ).data
- )
+ choice = select_review_skill(self.team_id, user_id, ReviewSkillKind.BLIND_SPOTS, skill)
+ return Response(ReviewBlindSpotsConfigSerializer(choice).data)
diff --git a/products/review_hog/backend/presentation/views/perspectives.py b/products/review_hog/backend/presentation/views/perspectives.py
index e23d4eecc9f0..a5db51c52e0e 100644
--- a/products/review_hog/backend/presentation/views/perspectives.py
+++ b/products/review_hog/backend/presentation/views/perspectives.py
@@ -8,18 +8,19 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.permissions import PostHogFeatureFlagPermission
-from products.review_hog.backend.models import ReviewSkillConfig
-from products.review_hog.backend.reviewer.lazy_seed import seed_canonicals_tolerantly, sync_canonical_perspectives
-from products.review_hog.backend.reviewer.skill_loader import (
- CANONICAL_PERSPECTIVE_SKILL_NAMES,
- REVIEW_HOG_PERSPECTIVE_PREFIX,
- register_missing_perspective_configs,
- visible_skill_names,
+from products.review_hog.backend.facade.api import (
+ get_review_skill,
+ list_review_skill_choices,
+ set_review_perspective_enabled,
)
-from products.skills.backend.models.skills import LLMSkill
+from products.review_hog.backend.facade.contracts import (
+ LastEnabledPerspectiveError,
+ ReviewSkillNameError,
+ ReviewSkillNotFoundError,
+)
+from products.review_hog.backend.facade.enums import ReviewSkillKind
logger = logging.getLogger(__name__)
@@ -63,8 +64,6 @@ class ReviewPerspectiveConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericVie
scope_object = "llm_skill"
permission_classes = [PostHogFeatureFlagPermission]
posthog_feature_flag = "review-hog"
- # Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.
- queryset = ReviewSkillConfig.objects.unscoped()
serializer_class = ReviewPerspectiveConfigSerializer
lookup_field = "skill_name"
pagination_class = None
@@ -85,38 +84,9 @@ class ReviewPerspectiveConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericVie
),
)
def list(self, request: Request, **kwargs) -> Response:
- # Resolve a raw environment URL id to its root team once — the skills and config rows all
- # live on the canonical team, so an unresolved id would render an empty menu.
- team_id = resolve_effective_team_id(self.team_id)
user_id = cast(int, request.user.id) # authenticated via the viewset mixin
- # A team that never ran a review has no LLMSkill rows yet — seed the canonicals or the
- # menu renders empty until the first run.
- seed_canonicals_tolerantly(team_id, sync_canonical_perspectives)
- register_missing_perspective_configs(team_id, user_id)
- # Prefix-scope: validators share this table, so only join perspective rows to the menu.
- enabled_by_name = dict(
- ReviewSkillConfig.objects.for_team(team_id, canonical=True)
- .filter(user_id=user_id, skill_name__startswith=REVIEW_HOG_PERSPECTIVE_PREFIX)
- .values_list("skill_name", "enabled")
- )
- # Per-user visibility: the menu advertises the canonicals plus this user's own customs —
- # never a teammate's.
- visible = visible_skill_names(
- team_id, user_id, prefix=REVIEW_HOG_PERSPECTIVE_PREFIX, canonical_names=CANONICAL_PERSPECTIVE_SKILL_NAMES
- )
- skills = LLMSkill.objects.filter(team_id=team_id, name__in=visible, is_latest=True, deleted=False).order_by(
- "name"
- )
- items = [
- {
- "skill_name": s.name,
- "enabled": enabled_by_name.get(s.name, False),
- "description": s.description,
- "body": s.body,
- }
- for s in skills
- ]
- return Response(ReviewPerspectiveConfigSerializer(items, many=True).data)
+ choices = list_review_skill_choices(self.team_id, user_id, ReviewSkillKind.PERSPECTIVE)
+ return Response(ReviewPerspectiveConfigSerializer(choices, many=True).data)
@extend_schema(
request=ReviewPerspectiveConfigUpdateSerializer,
@@ -137,53 +107,20 @@ class ReviewPerspectiveConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericVie
),
)
def partial_update(self, request: Request, skill_name: str, **kwargs) -> Response:
- if not skill_name.startswith(REVIEW_HOG_PERSPECTIVE_PREFIX):
- raise ValidationError(f"'{skill_name}' is not a review perspective skill")
- # Resolve a raw environment URL id to its root team once: `for_team` canonicalizes its
- # filter but not the create kwargs, and mismatched ids mean a never-matching get plus
- # 500s on the unique constraint from the second call on.
- team_id = resolve_effective_team_id(self.team_id)
user_id = cast(int, request.user.id) # authenticated via the viewset mixin
- # Same cold-team seed as list(): a canonical toggled before the team's first review would
- # 404 without it.
- seed_canonicals_tolerantly(team_id, sync_canonical_perspectives)
- skill = LLMSkill.objects.filter(team_id=team_id, name=skill_name, is_latest=True, deleted=False).first()
- # A teammate's custom 404s exactly like a missing skill — visibility is author-only, and a
- # distinct error would leak that the name exists.
- if skill is None or skill_name not in visible_skill_names(
- team_id, user_id, prefix=REVIEW_HOG_PERSPECTIVE_PREFIX, canonical_names=CANONICAL_PERSPECTIVE_SKILL_NAMES
- ):
+ try:
+ perspective = get_review_skill(self.team_id, user_id, ReviewSkillKind.PERSPECTIVE, skill_name)
+ except ReviewSkillNameError:
+ raise ValidationError(f"'{skill_name}' is not a review perspective skill")
+ except ReviewSkillNotFoundError:
raise NotFound(f"No perspective skill '{skill_name}' on this project")
update = ReviewPerspectiveConfigUpdateSerializer(data=request.data)
update.is_valid(raise_exception=True)
enabled: bool = update.validated_data["enabled"]
- # Seed the canonicals first so the min-1 floor counts a cold user's defaults, not zero.
- register_missing_perspective_configs(team_id, user_id)
- if not enabled:
- # Best-effort floor (count + write, no lock) — same as scouts. The loader's
- # NoEnabledPerspectivesError is the backstop if a rare concurrent double-disable slips through.
- # Prefix-scope: the floor counts only perspectives — an enabled validator (same table)
- # must not let a user disable their last perspective.
- others_enabled = (
- ReviewSkillConfig.objects.for_team(team_id, canonical=True)
- .filter(user_id=user_id, enabled=True, skill_name__startswith=REVIEW_HOG_PERSPECTIVE_PREFIX)
- .exclude(skill_name=skill_name)
- .count()
- )
- if others_enabled == 0:
- raise ValidationError("Cannot disable your last enabled perspective — at least one must stay on")
-
- # `team_id` / `user_id` stay in the create kwargs — the fail-closed filter doesn't propagate.
- config, _created = ReviewSkillConfig.objects.for_team(team_id, canonical=True).get_or_create(
- team_id=team_id, user_id=user_id, skill_name=skill_name, defaults={"enabled": enabled}
- )
- if config.enabled != enabled:
- config.enabled = enabled
- config.save(update_fields=["enabled", "updated_at"])
- return Response(
- ReviewPerspectiveConfigSerializer(
- {"skill_name": skill_name, "enabled": enabled, "description": skill.description, "body": skill.body}
- ).data
- )
+ try:
+ choice = set_review_perspective_enabled(self.team_id, user_id, perspective, enabled)
+ except LastEnabledPerspectiveError:
+ raise ValidationError("Cannot disable your last enabled perspective — at least one must stay on")
+ return Response(ReviewPerspectiveConfigSerializer(choice).data)
diff --git a/products/review_hog/backend/presentation/views/resolution.py b/products/review_hog/backend/presentation/views/resolution.py
index 05ba03b46ee2..752ca369cb66 100644
--- a/products/review_hog/backend/presentation/views/resolution.py
+++ b/products/review_hog/backend/presentation/views/resolution.py
@@ -1,9 +1,6 @@
import logging
from typing import cast
-from django.db import transaction
-from django.utils import timezone
-
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import serializers, viewsets
from rest_framework.exceptions import NotFound, ValidationError
@@ -11,18 +8,11 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.permissions import PostHogFeatureFlagPermission
-from products.review_hog.backend.models import ReviewSkillConfig
-from products.review_hog.backend.reviewer.lazy_seed import seed_canonicals_tolerantly, sync_canonical_resolution
-from products.review_hog.backend.reviewer.skill_loader import (
- CANONICAL_RESOLUTION_SKILL_NAMES,
- REVIEW_HOG_RESOLUTION_PREFIX,
- register_missing_resolution_config,
- visible_skill_names,
-)
-from products.skills.backend.models.skills import LLMSkill
+from products.review_hog.backend.facade.api import get_review_skill, list_review_skill_choices, select_review_skill
+from products.review_hog.backend.facade.contracts import ReviewSkillNameError, ReviewSkillNotFoundError
+from products.review_hog.backend.facade.enums import ReviewSkillKind
logger = logging.getLogger(__name__)
@@ -32,7 +22,8 @@ class ReviewResolutionConfigSerializer(serializers.Serializer):
help_text="Name of the `review-hog-resolution-*` skill this row represents (the criteria's identity)."
)
active = serializers.BooleanField(
- help_text="Whether these criteria drive the resolution stage on the requesting user's PRs on this project."
+ source="enabled",
+ help_text="Whether these criteria drive the resolution stage on the requesting user's PRs on this project.",
)
description = serializers.CharField(
allow_blank=True, help_text="The resolution skill's description, for display in the config UI."
@@ -73,8 +64,6 @@ class ReviewResolutionConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericView
scope_object = "llm_skill"
permission_classes = [PostHogFeatureFlagPermission]
posthog_feature_flag = "review-hog"
- # Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.
- queryset = ReviewSkillConfig.objects.unscoped()
serializer_class = ReviewResolutionConfigSerializer
lookup_field = "skill_name"
pagination_class = None
@@ -95,37 +84,9 @@ class ReviewResolutionConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericView
),
)
def list(self, request: Request, **kwargs) -> Response:
- # Resolve a raw environment URL id to its root team once — the skills and config rows all
- # live on the canonical team, so an unresolved id would render an empty menu.
- team_id = resolve_effective_team_id(self.team_id)
user_id = cast(int, request.user.id) # authenticated via the viewset mixin
- # A team that never ran a review has no LLMSkill rows yet — seed the canonical or the
- # menu renders empty until the first run.
- seed_canonicals_tolerantly(team_id, sync_canonical_resolution)
- register_missing_resolution_config(team_id, user_id)
- active_by_name = dict(
- ReviewSkillConfig.objects.for_team(team_id, canonical=True)
- .filter(user_id=user_id, skill_name__startswith=REVIEW_HOG_RESOLUTION_PREFIX)
- .values_list("skill_name", "enabled")
- )
- # Per-user visibility: the menu advertises the canonical plus this user's own customs —
- # never a teammate's.
- visible = visible_skill_names(
- team_id, user_id, prefix=REVIEW_HOG_RESOLUTION_PREFIX, canonical_names=CANONICAL_RESOLUTION_SKILL_NAMES
- )
- skills = LLMSkill.objects.filter(team_id=team_id, name__in=visible, is_latest=True, deleted=False).order_by(
- "name"
- )
- items = [
- {
- "skill_name": s.name,
- "active": active_by_name.get(s.name, False),
- "description": s.description,
- "body": s.body,
- }
- for s in skills
- ]
- return Response(ReviewResolutionConfigSerializer(items, many=True).data)
+ choices = list_review_skill_choices(self.team_id, user_id, ReviewSkillKind.RESOLUTION)
+ return Response(ReviewResolutionConfigSerializer(choices, many=True).data)
@extend_schema(
request=ReviewResolutionConfigSelectSerializer,
@@ -147,22 +108,12 @@ class ReviewResolutionConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericView
),
)
def partial_update(self, request: Request, skill_name: str, **kwargs) -> Response:
- if not skill_name.startswith(REVIEW_HOG_RESOLUTION_PREFIX):
- raise ValidationError(f"'{skill_name}' is not a review resolution skill")
- # Resolve a raw environment URL id to its root team once: `for_team` canonicalizes its
- # filter but not the create kwargs, and mismatched ids mean a never-matching get plus
- # 500s on the unique constraint from the second call on.
- team_id = resolve_effective_team_id(self.team_id)
user_id = cast(int, request.user.id) # authenticated via the viewset mixin
- # Same cold-team seed as list(): selecting the canonical before the team's first review
- # would 404 without it.
- seed_canonicals_tolerantly(team_id, sync_canonical_resolution)
- skill = LLMSkill.objects.filter(team_id=team_id, name=skill_name, is_latest=True, deleted=False).first()
- # A teammate's custom 404s exactly like a missing skill — visibility is author-only, and a
- # distinct error would leak that the name exists.
- if skill is None or skill_name not in visible_skill_names(
- team_id, user_id, prefix=REVIEW_HOG_RESOLUTION_PREFIX, canonical_names=CANONICAL_RESOLUTION_SKILL_NAMES
- ):
+ try:
+ skill = get_review_skill(self.team_id, user_id, ReviewSkillKind.RESOLUTION, skill_name)
+ except ReviewSkillNameError:
+ raise ValidationError(f"'{skill_name}' is not a review resolution skill")
+ except ReviewSkillNotFoundError:
raise NotFound(f"No resolution skill '{skill_name}' on this project")
select = ReviewResolutionConfigSelectSerializer(data=request.data)
@@ -172,23 +123,5 @@ class ReviewResolutionConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericView
"Resolution criteria are single-active — select a different skill instead of deactivating"
)
- register_missing_resolution_config(team_id, user_id)
- configs = ReviewSkillConfig.objects.for_team(team_id, canonical=True)
- # Single-active: deactivate-others + activate-this must land together, or a crash between them
- # leaves the user with no active skill (the loader's canonical fallback would heal it).
- with transaction.atomic():
- configs.filter(user_id=user_id, skill_name__startswith=REVIEW_HOG_RESOLUTION_PREFIX, enabled=True).exclude(
- skill_name=skill_name
- ).update(enabled=False, updated_at=timezone.now())
- # `team_id` / `user_id` stay in the create kwargs — the fail-closed filter doesn't propagate.
- config, _created = configs.get_or_create(
- team_id=team_id, user_id=user_id, skill_name=skill_name, defaults={"enabled": True}
- )
- if not config.enabled:
- config.enabled = True
- config.save(update_fields=["enabled", "updated_at"])
- return Response(
- ReviewResolutionConfigSerializer(
- {"skill_name": skill_name, "active": True, "description": skill.description, "body": skill.body}
- ).data
- )
+ choice = select_review_skill(self.team_id, user_id, ReviewSkillKind.RESOLUTION, skill)
+ return Response(ReviewResolutionConfigSerializer(choice).data)
diff --git a/products/review_hog/backend/presentation/views/settings.py b/products/review_hog/backend/presentation/views/settings.py
index 7a19ffa1a562..c1bc06d98449 100644
--- a/products/review_hog/backend/presentation/views/settings.py
+++ b/products/review_hog/backend/presentation/views/settings.py
@@ -1,31 +1,18 @@
-import logging
from typing import cast
-from django.db import transaction
-
-from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
+from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.models.user import User
from posthog.permissions import PostHogFeatureFlagPermission
-from products.review_hog.backend.models import ReviewProjectSettings, ReviewUserSettings
-from products.review_hog.backend.preferences import (
- PREFERENCE_KEYS,
- DefaultReviewMode,
- PreferenceSource,
- ReviewPreferences,
- UrgencyThreshold,
-)
-from products.review_hog.backend.reviewer.lazy_seed import seed_canonicals_tolerantly, sync_canonical_authoring
-from products.stamphog.backend.facade.api import has_reviewable_repo_config
-
-logger = logging.getLogger(__name__)
+from products.review_hog.backend.facade.api import get_review_user_preferences, update_review_user_preferences
+from products.review_hog.backend.facade.contracts import ReviewUserPreferences
+from products.review_hog.backend.facade.enums import DefaultReviewMode, PreferenceSource, UrgencyThreshold
def _source_field(key: str) -> serializers.ChoiceField:
@@ -107,28 +94,15 @@ class ReviewUserSettingsSerializer(serializers.Serializer):
)
project_defaults = ReviewProjectDefaultsSerializer(
read_only=True,
- source="project",
help_text="The project defaults the Deep review preferences fall back to.",
)
- stamphog_connected = serializers.SerializerMethodField(
+ stamphog_connected = serializers.BooleanField(
+ read_only=True,
help_text="Whether this project has at least one synced, enabled Stamphog repository. When "
"false, the stamphog_review_inbox_prs toggle has nothing to act on and the UI renders it "
"disabled with a pointer to connect the Stamphog GitHub App.",
)
- def _team_id(self) -> int:
- return self.context["team_id"]
-
- @extend_schema_field(serializers.BooleanField())
- def get_stamphog_connected(self, instance: ReviewPreferences) -> bool:
- # This reads the stamphog product DB, which can fail fast on its own circuit breaker. An
- # informational UI flag must not fail the settings endpoint, so fall back to False.
- try:
- return has_reviewable_repo_config(self._team_id())
- except Exception:
- logger.exception("review_hog_stamphog_connected_check_failed")
- return False
-
class ReviewUserSettingsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""The requesting user's PostHog Review preferences for a project.
@@ -142,28 +116,13 @@ class ReviewUserSettingsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)
scope_object = "INTERNAL"
permission_classes = [PostHogFeatureFlagPermission]
posthog_feature_flag = "review-hog"
- # Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.
- queryset = ReviewUserSettings.objects.unscoped()
serializer_class = ReviewUserSettingsSerializer
def _user_id(self) -> int:
return cast(User, self.request.user).id
- def _save_changes(self, team_id: int, changes: dict) -> ReviewPreferences:
- # Resolve a raw environment URL id to its root team once: `for_team` canonicalizes its filter
- # but not the create kwargs, and mismatched ids mean a never-matching get plus 500s on re-read.
- rows = ReviewUserSettings.objects.for_team(team_id, canonical=True)
- with transaction.atomic():
- row, _created = rows.get_or_create(team_id=team_id, user_id=self._user_id())
- # The lock keeps two concurrent edits of different keys from losing one of them.
- row = rows.select_for_update().get(id=row.id)
- current = ReviewPreferences.resolve(row.preferences, ReviewProjectSettings.load(team_id).defaults)
- row.preferences = current.with_changes(changes)
- row.save(update_fields=["preferences", "updated_at"])
- return ReviewUserSettings.load_preferences(team_id, self._user_id())
-
- def _response(self, team_id: int, preferences: ReviewPreferences) -> Response:
- return Response(ReviewUserSettingsSerializer(preferences, context={"team_id": team_id}).data)
+ def _response(self, preferences: ReviewUserPreferences) -> Response:
+ return Response(ReviewUserSettingsSerializer(preferences).data)
@extend_schema(
methods=["GET"],
@@ -190,17 +149,10 @@ class ReviewUserSettingsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)
# Not named `settings` — that would shadow DRF's `APIView.settings` (its APISettings object).
@action(detail=False, methods=["GET", "PATCH"], url_path="settings", url_name="settings")
def user_settings(self, request: Request, **kwargs) -> Response:
- team_id = resolve_effective_team_id(self.team_id)
if request.method == "PATCH":
- serializer = ReviewUserSettingsSerializer(data=request.data, partial=True, context={"team_id": team_id})
+ serializer = ReviewUserSettingsSerializer(data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
- changes = {
- key: serializer.validated_data[key] for key in PREFERENCE_KEYS if key in serializer.validated_data
- }
- return self._response(team_id, self._save_changes(team_id, changes))
- # Seed the authoring companion before any review has run: the "Create your own …" tasks
- # `skill-get` it over MCP, and this settings GET is the Code review tab's always-called
- # endpoint. `team_id` is already the effective (root) team, the same team the review runs
- # under, so the skill lands where the sandbox agent's `skill-get` will look.
- seed_canonicals_tolerantly(team_id, sync_canonical_authoring)
- return self._response(team_id, ReviewUserSettings.load_preferences(team_id, self._user_id()))
+ return self._response(
+ update_review_user_preferences(self.team_id, self._user_id(), serializer.validated_data)
+ )
+ return self._response(get_review_user_preferences(self.team_id, self._user_id()))
diff --git a/products/review_hog/backend/presentation/views/validators.py b/products/review_hog/backend/presentation/views/validators.py
index d255f09e6020..0b94105345f7 100644
--- a/products/review_hog/backend/presentation/views/validators.py
+++ b/products/review_hog/backend/presentation/views/validators.py
@@ -1,9 +1,6 @@
import logging
from typing import cast
-from django.db import transaction
-from django.utils import timezone
-
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import serializers, viewsets
from rest_framework.exceptions import NotFound, ValidationError
@@ -11,18 +8,11 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.permissions import PostHogFeatureFlagPermission
-from products.review_hog.backend.models import ReviewSkillConfig
-from products.review_hog.backend.reviewer.lazy_seed import seed_canonicals_tolerantly, sync_canonical_validation
-from products.review_hog.backend.reviewer.skill_loader import (
- CANONICAL_VALIDATION_SKILL_NAMES,
- REVIEW_HOG_VALIDATION_PREFIX,
- register_missing_validation_config,
- visible_skill_names,
-)
-from products.skills.backend.models.skills import LLMSkill
+from products.review_hog.backend.facade.api import get_review_skill, list_review_skill_choices, select_review_skill
+from products.review_hog.backend.facade.contracts import ReviewSkillNameError, ReviewSkillNotFoundError
+from products.review_hog.backend.facade.enums import ReviewSkillKind
logger = logging.getLogger(__name__)
@@ -32,7 +22,8 @@ class ReviewValidatorConfigSerializer(serializers.Serializer):
help_text="Name of the `review-hog-validation-*` skill this row represents (the validator's identity)."
)
active = serializers.BooleanField(
- help_text="Whether this validator is the one that validates the requesting user's PR reviews on this project."
+ source="enabled",
+ help_text="Whether this validator is the one that validates the requesting user's PR reviews on this project.",
)
description = serializers.CharField(
allow_blank=True, help_text="The validator skill's description, for display in the config UI."
@@ -71,8 +62,6 @@ class ReviewValidatorConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
scope_object = "llm_skill"
permission_classes = [PostHogFeatureFlagPermission]
posthog_feature_flag = "review-hog"
- # Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.
- queryset = ReviewSkillConfig.objects.unscoped()
serializer_class = ReviewValidatorConfigSerializer
lookup_field = "skill_name"
pagination_class = None
@@ -93,37 +82,9 @@ class ReviewValidatorConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
),
)
def list(self, request: Request, **kwargs) -> Response:
- # Resolve a raw environment URL id to its root team once — the skills and config rows all
- # live on the canonical team, so an unresolved id would render an empty menu.
- team_id = resolve_effective_team_id(self.team_id)
user_id = cast(int, request.user.id) # authenticated via the viewset mixin
- # A team that never ran a review has no LLMSkill rows yet — seed the canonical or the
- # menu renders empty until the first run.
- seed_canonicals_tolerantly(team_id, sync_canonical_validation)
- register_missing_validation_config(team_id, user_id)
- active_by_name = dict(
- ReviewSkillConfig.objects.for_team(team_id, canonical=True)
- .filter(user_id=user_id, skill_name__startswith=REVIEW_HOG_VALIDATION_PREFIX)
- .values_list("skill_name", "enabled")
- )
- # Per-user visibility: the menu advertises the canonical plus this user's own customs —
- # never a teammate's.
- visible = visible_skill_names(
- team_id, user_id, prefix=REVIEW_HOG_VALIDATION_PREFIX, canonical_names=CANONICAL_VALIDATION_SKILL_NAMES
- )
- skills = LLMSkill.objects.filter(team_id=team_id, name__in=visible, is_latest=True, deleted=False).order_by(
- "name"
- )
- items = [
- {
- "skill_name": s.name,
- "active": active_by_name.get(s.name, False),
- "description": s.description,
- "body": s.body,
- }
- for s in skills
- ]
- return Response(ReviewValidatorConfigSerializer(items, many=True).data)
+ choices = list_review_skill_choices(self.team_id, user_id, ReviewSkillKind.VALIDATION)
+ return Response(ReviewValidatorConfigSerializer(choices, many=True).data)
@extend_schema(
request=ReviewValidatorConfigSelectSerializer,
@@ -144,22 +105,12 @@ class ReviewValidatorConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
),
)
def partial_update(self, request: Request, skill_name: str, **kwargs) -> Response:
- if not skill_name.startswith(REVIEW_HOG_VALIDATION_PREFIX):
- raise ValidationError(f"'{skill_name}' is not a review validator skill")
- # Resolve a raw environment URL id to its root team once: `for_team` canonicalizes its
- # filter but not the create kwargs, and mismatched ids mean a never-matching get plus
- # 500s on the unique constraint from the second call on.
- team_id = resolve_effective_team_id(self.team_id)
user_id = cast(int, request.user.id) # authenticated via the viewset mixin
- # Same cold-team seed as list(): selecting the canonical before the team's first review
- # would 404 without it.
- seed_canonicals_tolerantly(team_id, sync_canonical_validation)
- skill = LLMSkill.objects.filter(team_id=team_id, name=skill_name, is_latest=True, deleted=False).first()
- # A teammate's custom 404s exactly like a missing skill — visibility is author-only, and a
- # distinct error would leak that the name exists.
- if skill is None or skill_name not in visible_skill_names(
- team_id, user_id, prefix=REVIEW_HOG_VALIDATION_PREFIX, canonical_names=CANONICAL_VALIDATION_SKILL_NAMES
- ):
+ try:
+ skill = get_review_skill(self.team_id, user_id, ReviewSkillKind.VALIDATION, skill_name)
+ except ReviewSkillNameError:
+ raise ValidationError(f"'{skill_name}' is not a review validator skill")
+ except ReviewSkillNotFoundError:
raise NotFound(f"No validator skill '{skill_name}' on this project")
select = ReviewValidatorConfigSelectSerializer(data=request.data)
@@ -167,23 +118,5 @@ class ReviewValidatorConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
if not select.validated_data["active"]:
raise ValidationError("Validators are single-active — select a different validator instead of deactivating")
- register_missing_validation_config(team_id, user_id)
- configs = ReviewSkillConfig.objects.for_team(team_id, canonical=True)
- # Single-active: deactivate-others + activate-this must land together, or a crash between them
- # leaves the user with no active validator (the loader's canonical fallback would heal it).
- with transaction.atomic():
- configs.filter(user_id=user_id, skill_name__startswith=REVIEW_HOG_VALIDATION_PREFIX, enabled=True).exclude(
- skill_name=skill_name
- ).update(enabled=False, updated_at=timezone.now())
- # `team_id` / `user_id` stay in the create kwargs — the fail-closed filter doesn't propagate.
- config, _created = configs.get_or_create(
- team_id=team_id, user_id=user_id, skill_name=skill_name, defaults={"enabled": True}
- )
- if not config.enabled:
- config.enabled = True
- config.save(update_fields=["enabled", "updated_at"])
- return Response(
- ReviewValidatorConfigSerializer(
- {"skill_name": skill_name, "active": True, "description": skill.description, "body": skill.body}
- ).data
- )
+ choice = select_review_skill(self.team_id, user_id, ReviewSkillKind.VALIDATION, skill)
+ return Response(ReviewValidatorConfigSerializer(choice).data)
diff --git a/products/review_hog/backend/skill_configs.py b/products/review_hog/backend/skill_configs.py
new file mode 100644
index 000000000000..e289e8498420
--- /dev/null
+++ b/products/review_hog/backend/skill_configs.py
@@ -0,0 +1,208 @@
+"""Per-user review skill menus: which team review skills a user sees, and which run on their reviews.
+
+A review skill is any team `LLMSkill` whose name carries the prefix of its kind (canonical or custom,
+handled identically at run time). The skill itself is team-level; a `ReviewSkillConfig` row per
+(team, user, skill name) controls whether it runs on that user's PR reviews. Visibility is per-user:
+a menu shows the canonicals plus the customs the user authored, never a teammate's custom
+(`visible_skill_names`).
+
+Perspectives are multi-enable with a floor of one. The other kinds are single-active: a review runs
+exactly one, and there is always a default (the canonical), so no floor is needed.
+"""
+
+from collections.abc import Callable
+
+from django.db import transaction
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+from posthog.models.scoping.manager import resolve_effective_team_id
+from posthog.models.team.team import Team
+
+from products.review_hog.backend.facade.contracts import (
+ LastEnabledPerspectiveError,
+ ReviewSkill,
+ ReviewSkillChoice,
+ ReviewSkillNameError,
+ ReviewSkillNotFoundError,
+)
+from products.review_hog.backend.facade.enums import ReviewSkillKind
+from products.review_hog.backend.models import ReviewSkillConfig
+from products.review_hog.backend.reviewer.lazy_seed import (
+ SyncResult,
+ seed_canonicals_tolerantly,
+ sync_canonical_blind_spots,
+ sync_canonical_perspectives,
+ sync_canonical_resolution,
+ sync_canonical_validation,
+)
+from products.review_hog.backend.reviewer.skill_loader import (
+ CANONICAL_BLIND_SPOTS_SKILL_NAMES,
+ CANONICAL_PERSPECTIVE_SKILL_NAMES,
+ CANONICAL_RESOLUTION_SKILL_NAMES,
+ CANONICAL_VALIDATION_SKILL_NAMES,
+ REVIEW_HOG_BLIND_SPOTS_PREFIX,
+ REVIEW_HOG_PERSPECTIVE_PREFIX,
+ REVIEW_HOG_RESOLUTION_PREFIX,
+ REVIEW_HOG_VALIDATION_PREFIX,
+ register_missing_blind_spots_config,
+ register_missing_perspective_configs,
+ register_missing_resolution_config,
+ register_missing_validation_config,
+ visible_skill_names,
+)
+from products.skills.backend.models.skills import LLMSkill
+
+
+@frozen
+class ReviewSkillFamily:
+ prefix: str
+ canonical_names: tuple[str, ...]
+ sync_canonicals: Callable[[Team], SyncResult]
+ register_missing_configs: Callable[[int, int], None]
+
+
+REVIEW_SKILL_FAMILIES: dict[ReviewSkillKind, ReviewSkillFamily] = {
+ ReviewSkillKind.PERSPECTIVE: ReviewSkillFamily(
+ prefix=REVIEW_HOG_PERSPECTIVE_PREFIX,
+ canonical_names=CANONICAL_PERSPECTIVE_SKILL_NAMES,
+ sync_canonicals=sync_canonical_perspectives,
+ register_missing_configs=register_missing_perspective_configs,
+ ),
+ ReviewSkillKind.VALIDATION: ReviewSkillFamily(
+ prefix=REVIEW_HOG_VALIDATION_PREFIX,
+ canonical_names=CANONICAL_VALIDATION_SKILL_NAMES,
+ sync_canonicals=sync_canonical_validation,
+ register_missing_configs=register_missing_validation_config,
+ ),
+ ReviewSkillKind.BLIND_SPOTS: ReviewSkillFamily(
+ prefix=REVIEW_HOG_BLIND_SPOTS_PREFIX,
+ canonical_names=CANONICAL_BLIND_SPOTS_SKILL_NAMES,
+ sync_canonicals=sync_canonical_blind_spots,
+ register_missing_configs=register_missing_blind_spots_config,
+ ),
+ ReviewSkillKind.RESOLUTION: ReviewSkillFamily(
+ prefix=REVIEW_HOG_RESOLUTION_PREFIX,
+ canonical_names=CANONICAL_RESOLUTION_SKILL_NAMES,
+ sync_canonicals=sync_canonical_resolution,
+ register_missing_configs=register_missing_resolution_config,
+ ),
+}
+
+
+class ReviewSkillMenu:
+ """One user's menu of one kind of review skill on a project."""
+
+ def __init__(self, team_id: int, user_id: int, kind: ReviewSkillKind) -> None:
+ # Resolve a raw environment URL id to its root team once: the skills and config rows all live
+ # on the canonical team, so an unresolved id would render an empty menu. `for_team`
+ # canonicalizes its filter but not the create kwargs, and mismatched ids mean a never-matching
+ # get plus 500s on the unique constraint from the second call on.
+ self.team_id = resolve_effective_team_id(team_id)
+ self.user_id = user_id
+ self.kind = kind
+ self.family = REVIEW_SKILL_FAMILIES[kind]
+
+ def _seed_canonical_skills(self) -> None:
+ # A team that never ran a review has no LLMSkill rows yet. Without the seed the menu renders
+ # empty until the first run, and a canonical selected before that run 404s.
+ seed_canonicals_tolerantly(self.team_id, self.family.sync_canonicals)
+
+ def _visible_names(self) -> set[str]:
+ return visible_skill_names(
+ self.team_id, self.user_id, prefix=self.family.prefix, canonical_names=self.family.canonical_names
+ )
+
+ def _check_name(self, skill_name: str) -> None:
+ if not skill_name.startswith(self.family.prefix):
+ raise ReviewSkillNameError(skill_name)
+
+ def choices(self) -> list[ReviewSkillChoice]:
+ """The visible skills of this kind, by name, with the user's state for each."""
+ self._seed_canonical_skills()
+ self.family.register_missing_configs(self.team_id, self.user_id)
+ # Prefix-scope: all kinds share this table, so only join this kind's rows to the menu.
+ enabled_by_name = dict(
+ ReviewSkillConfig.objects.for_team(self.team_id, canonical=True)
+ .filter(user_id=self.user_id, skill_name__startswith=self.family.prefix)
+ .values_list("skill_name", "enabled")
+ )
+ skills = LLMSkill.objects.filter(
+ team_id=self.team_id, name__in=self._visible_names(), is_latest=True, deleted=False
+ ).order_by("name")
+ return [
+ ReviewSkillChoice(
+ skill_name=skill.name,
+ enabled=enabled_by_name.get(skill.name, False),
+ description=skill.description,
+ body=skill.body,
+ )
+ for skill in skills
+ ]
+
+ def get(self, skill_name: str) -> ReviewSkill:
+ """The live skill of this kind with this name, when the user can see it."""
+ self._check_name(skill_name)
+ self._seed_canonical_skills()
+ skill = LLMSkill.objects.filter(team_id=self.team_id, name=skill_name, is_latest=True, deleted=False).first()
+ # A teammate's custom 404s exactly like a missing skill — visibility is author-only, and a
+ # distinct error would leak that the name exists.
+ if skill is None or skill_name not in self._visible_names():
+ raise ReviewSkillNotFoundError(skill_name)
+ return ReviewSkill(skill_name=skill.name, description=skill.description, body=skill.body)
+
+ def set_enabled(self, skill: ReviewSkill, enabled: bool) -> ReviewSkillChoice:
+ """Enable or disable one perspective. Upserts the config row, so a fresh custom needs one call."""
+ if self.kind != ReviewSkillKind.PERSPECTIVE:
+ raise ValueError(f"{self.kind} skills are single-active; select one instead")
+ self._check_name(skill.skill_name)
+ # Seed the canonicals first so the min-1 floor counts a cold user's defaults, not zero.
+ self.family.register_missing_configs(self.team_id, self.user_id)
+ configs = ReviewSkillConfig.objects.for_team(self.team_id, canonical=True)
+ if not enabled:
+ # Best-effort floor (count + write, no lock) — same as scouts. The loader's
+ # NoEnabledPerspectivesError is the backstop if a rare concurrent double-disable slips through.
+ # Prefix-scope: the floor counts only perspectives — an enabled validator (same table)
+ # must not let a user disable their last perspective.
+ others_enabled = (
+ configs.filter(user_id=self.user_id, enabled=True, skill_name__startswith=self.family.prefix)
+ .exclude(skill_name=skill.skill_name)
+ .count()
+ )
+ if others_enabled == 0:
+ raise LastEnabledPerspectiveError(skill.skill_name)
+
+ # `team_id` / `user_id` stay in the create kwargs — the fail-closed filter doesn't propagate.
+ config, _created = configs.get_or_create(
+ team_id=self.team_id, user_id=self.user_id, skill_name=skill.skill_name, defaults={"enabled": enabled}
+ )
+ if config.enabled != enabled:
+ config.enabled = enabled
+ config.save(update_fields=["enabled", "updated_at"])
+ return ReviewSkillChoice(
+ skill_name=skill.skill_name, enabled=enabled, description=skill.description, body=skill.body
+ )
+
+ def select(self, skill: ReviewSkill) -> ReviewSkillChoice:
+ """Make one skill the user's single active skill of this kind, and switch the others off."""
+ if self.kind == ReviewSkillKind.PERSPECTIVE:
+ raise ValueError("perspectives are multi-enable; enable or disable them instead")
+ self._check_name(skill.skill_name)
+ self.family.register_missing_configs(self.team_id, self.user_id)
+ configs = ReviewSkillConfig.objects.for_team(self.team_id, canonical=True)
+ # Single-active: deactivate-others + activate-this must land together, or a crash between them
+ # leaves the user with no active skill (the loader's canonical fallback would heal it).
+ with transaction.atomic():
+ configs.filter(user_id=self.user_id, skill_name__startswith=self.family.prefix, enabled=True).exclude(
+ skill_name=skill.skill_name
+ ).update(enabled=False, updated_at=timezone.now())
+ # `team_id` / `user_id` stay in the create kwargs — the fail-closed filter doesn't propagate.
+ config, _created = configs.get_or_create(
+ team_id=self.team_id, user_id=self.user_id, skill_name=skill.skill_name, defaults={"enabled": True}
+ )
+ if not config.enabled:
+ config.enabled = True
+ config.save(update_fields=["enabled", "updated_at"])
+ return ReviewSkillChoice(
+ skill_name=skill.skill_name, enabled=True, description=skill.description, body=skill.body
+ )
diff --git a/pyproject.toml b/pyproject.toml
index cd779f88dcdc..06bfdc6324ac 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -644,14 +644,6 @@ ignore_imports = [
"products.mcp_store.backend.presentation.views -> products.mcp_store.backend.tools",
"products.notifications.backend.presentation.views -> products.notifications.backend.cache",
"products.notifications.backend.presentation.views -> products.notifications.backend.models",
- "products.review_hog.backend.presentation.views.blind_spots -> products.review_hog.backend.models",
- "products.review_hog.backend.presentation.views.blind_spots -> products.review_hog.backend.reviewer.lazy_seed",
- "products.review_hog.backend.presentation.views.blind_spots -> products.review_hog.backend.reviewer.skill_loader",
- "products.review_hog.backend.presentation.views.blind_spots -> products.skills.backend.models.skills",
- "products.review_hog.backend.presentation.views.perspectives -> products.review_hog.backend.models",
- "products.review_hog.backend.presentation.views.perspectives -> products.review_hog.backend.reviewer.lazy_seed",
- "products.review_hog.backend.presentation.views.perspectives -> products.review_hog.backend.reviewer.skill_loader",
- "products.review_hog.backend.presentation.views.perspectives -> products.skills.backend.models.skills",
"products.review_hog.backend.presentation.views.project_settings -> products.review_hog.backend.automatic_review_rules",
"products.review_hog.backend.presentation.views.project_settings -> products.review_hog.backend.models",
"products.review_hog.backend.presentation.views.project_settings -> products.review_hog.backend.preferences",
@@ -661,10 +653,6 @@ ignore_imports = [
"products.review_hog.backend.presentation.views.repositories -> products.review_hog.backend.models",
"products.review_hog.backend.presentation.views.repositories -> products.review_hog.backend.ownership",
"products.review_hog.backend.presentation.views.repositories -> products.review_hog.backend.repository_settings",
- "products.review_hog.backend.presentation.views.resolution -> products.review_hog.backend.models",
- "products.review_hog.backend.presentation.views.resolution -> products.review_hog.backend.reviewer.lazy_seed",
- "products.review_hog.backend.presentation.views.resolution -> products.review_hog.backend.reviewer.skill_loader",
- "products.review_hog.backend.presentation.views.resolution -> products.skills.backend.models.skills",
"products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.models",
"products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.pr_status",
"products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.preferences",
@@ -678,13 +666,6 @@ ignore_imports = [
"products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.review_design",
"products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.review_state",
"products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.reviewer.tools.github_meta",
- "products.review_hog.backend.presentation.views.settings -> products.review_hog.backend.models",
- "products.review_hog.backend.presentation.views.settings -> products.review_hog.backend.preferences",
- "products.review_hog.backend.presentation.views.settings -> products.review_hog.backend.reviewer.lazy_seed",
- "products.review_hog.backend.presentation.views.validators -> products.review_hog.backend.models",
- "products.review_hog.backend.presentation.views.validators -> products.review_hog.backend.reviewer.lazy_seed",
- "products.review_hog.backend.presentation.views.validators -> products.review_hog.backend.reviewer.skill_loader",
- "products.review_hog.backend.presentation.views.validators -> products.skills.backend.models.skills",
"products.tracing.backend.presentation.views -> products.tracing.backend.logic",
"products.tracing.backend.presentation.views -> products.tracing.backend.sparkline_query_runner",
"products.tracing.backend.presentation.views -> products.tracing.backend.has_spans_query_runner",