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.

38.0 KB
Raw Blame
from collections.abc import Mapping

from django.db import models, transaction
from django.db.models.functions import Lower
from django.utils.functional import Promise

from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import UUIDModel

from products.review_hog.backend.facade.enums import (
    AutomaticFlashFor,
    ReviewInstallationClaimScope,
    ReviewProjectSettingsBotPullRequests,
    ReviewRepositoryPersonKind,
    ReviewUserRepositoryChoiceMode,
)
from products.review_hog.backend.preferences import ReviewPreferences, ReviewProjectDefaults, UrgencyThreshold
from products.review_hog.backend.reviewer.artefact_content import (
    ArtefactContentValidationError,
    DroppedFindingArtefact,
    FindingOutcomeArtefact,
    ResolutionRunArtefact,
    ReviewArtefactContent,
    ReviewIssueFinding,
    ReviewLogArtefactContent,
    ReviewWorkingStateContent,
    TaskRunArtefact,
    ThreadVerdictArtefact,
    TurnMarkerArtefact,
    ValidationVerdict,
    artefact_type_for,
)
from products.signals.backend.facade.taxonomy import ArtefactAttribution


class ReviewReport(UUIDModel, TeamScopedRootMixin):
    """The living per-target review document.

    One row per `(team, repository, pr_number)` — or per `(team, repository, head_branch)` for a
    PR-less branch target (`pr_number` NULL), which upgrades in place once its PR exists. ReviewHog
    is loop-y — after the first pass it re-checks the target for new commits/comments and takes
    another turn — so the report is updated in place across turns and the watermark records what the
    latest turn already reviewed.
    """

    class Status(models.TextChoices):
        ACTIVE = "active"
        IDLE = "idle"
        CLOSED = "closed"

    # db_constraint=False keeps the migration lock-free on hot posthog_team.
    team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    repository = models.CharField(max_length=255)  # owner/repo
    # NULL = a branch target with no PR yet; backfilled by the fetch stage once a PR opens.
    pr_number = models.IntegerField(null=True, blank=True)
    pr_url = models.TextField(blank=True)
    head_branch = models.CharField(max_length=255)
    base_branch = models.CharField(max_length=255)
    # Whose configuration drives this report's reviews (the PR author on the label path) — stamped at
    # acting-user resolve on every run, so it works for future non-PR triggers too. Powers "your
    # recent reviews"; db_constraint=False keeps the migration lock-free on hot posthog_user.
    acting_user = models.ForeignKey(
        "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False
    )
    # The PR author's GitHub login, refreshed from the fetched metadata every turn. Powers the
    # "For you" scope's authored-PRs match (compared case-insensitively against the viewer's linked
    # GitHub login) — a teammate-triggered review of your PR lands under THEIR acting_user, so
    # without this the findings would be invisible to you. Null until a post-column turn stamps it.
    author_login = models.CharField(max_length=255, null=True, blank=True)
    status = models.CharField(max_length=20, choices=Status, default=Status.ACTIVE)
    run_count = models.IntegerField(default=0)
    last_run_at = models.DateTimeField(null=True, blank=True)
    # Watermark — what the latest turn already reviewed, so a re-run knows what changed.
    head_sha = models.CharField(max_length=64, null=True, blank=True)
    # The head the latest COMPLETED turn reviewed — stamped at finalize, while `head_sha` advances at
    # turn START. Read paths pairing stats/links with the completed turn's findings anchor here, so an
    # in-flight or crashed turn's metadata never splices onto the previous turn's findings.
    completed_head_sha = models.CharField(max_length=64, null=True, blank=True)
    # Only a successful publish or no-findings turn suppresses automatic retries.
    automatic_reviewed_head_sha = models.CharField(max_length=64, null=True, blank=True)
    # The urgency threshold the last COMPLETED turn's body/publish gated on — stamped at finalize
    # (alongside `run_count` / `completed_head_sha`) from the same resolve snapshot both consumed,
    # so the detail view buckets published vs held-back findings truthfully even when the acting
    # user's settings later change. Null for pre-column turns (readers fall back to the viewer's
    # own setting as an approximation).
    run_urgency_threshold = models.CharField(max_length=20, null=True, blank=True)
    # Latest published head for outcome tracking and compatibility reads.
    published_head_sha = models.CharField(max_length=64, null=True, blank=True)
    # Each mode has its own marker so a Flash review cannot suppress Full publication.
    published_heads_by_mode = models.JSONField(null=True, blank=True)
    # The urgency threshold in force at each publish, keyed by the `run_index` that published, as
    # `{"1": "consider", "2": "must_fix"}`. Outcome classification reconstructs the published finding
    # set from this, since the user's live setting can change after publish. Keyed per turn rather
    # than held as one scalar because a report republishes as new commits land and the acting user
    # may change their threshold in between: each turn posts only its own findings, so a later
    # tightened threshold must not retroactively hide what an earlier, looser turn already posted.
    published_urgency_thresholds = models.JSONField(null=True, blank=True)
    # The head each turn published at, keyed by `run_index` like the thresholds above, as
    # `{"1": "abc123", "2": "def456"}`. Outcome classification compares a finding against the head its
    # own turn was published at: a fix can land between two turns, and comparing every finding against
    # only the latest published head hides those commits entirely, marking a finding that was fixed as
    # ignored. Kept beside the thresholds rather than merged into one map because that one already
    # shipped; both are written together at publish.
    published_head_shas = models.JSONField(null=True, blank=True)
    # Set once this report's finding-outcome events have been flushed to capture — the outcome
    # sweep's completion marker. Distinct from the `finding_outcome` artefacts (the decided
    # classification, persisted first): a crash between persist and flush leaves this NULL, so the
    # next sweep re-emits from the stored artefacts instead of re-deciding the outcomes.
    outcomes_emitted_at = models.DateTimeField(null=True, blank=True)
    last_seen_comment_id = models.BigIntegerField(null=True, blank=True)
    # The PR's live "review in progress" status comment (publish path only): the GitHub comment id we
    # edit in place, and the last-edit watermark that debounces refreshes across concurrent activities.
    status_comment_id = models.BigIntegerField(null=True, blank=True)
    status_comment_edited_at = models.DateTimeField(null=True, blank=True)
    report_markdown = models.TextField(default="", blank=True)
    # Provenance for inbox-triggered reviews: the signals report whose implementation this review
    # targets. A plain UUID, not an FK — the link must survive report deletion/reingestion on the
    # signals side (the signals-side `code_review` artefact is API-deletable; this row is the durable
    # link). Filled once, never overwritten by later turns from another trigger.
    signal_report_id = models.UUIDField(null=True, blank=True)
    # Which trigger created this report ("stamphog" / "inbox" / "manual" / "ui" / "comment", or "label" from
    # before labels stopped starting reviews); stamped on create only.
    trigger_source = models.CharField(max_length=20, default="manual")
    # The reviewer arm, chosen once at creation from the report's tier (see `REVIEW_ARMS_BY_TIER`)
    # and sticky for the report's life. Adapter/model/effort/permission-mode persist as one bundle
    # because a model without its adapter can't be routed. NULL on rows created before arms were
    # persisted; reads resolve through `resolve_review_arm`, which falls back to the REVIEW_* pins.
    review_runtime_adapter = models.CharField(max_length=32, null=True, blank=True)
    review_model = models.CharField(max_length=128, null=True, blank=True)
    review_reasoning_effort = models.CharField(max_length=32, null=True, blank=True)
    review_initial_permission_mode = models.CharField(max_length=32, null=True, blank=True)
    # The routing bucket the arm was chosen from (a `ReviewTier` value) and, for agent PRs, the
    # Signals priority ("P0".."P4") that placed it there. Stamped with the arm at creation; a
    # person's trigger can lift the tier later, never lower it. The priority is the value the
    # decision used, kept because the report's judgment can change afterwards. NULL on pre-tier rows.
    review_tier = models.CharField(max_length=32, null=True, blank=True)
    review_signal_priority = models.CharField(max_length=4, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["team", "repository", "pr_number"],
                name="unique_review_report_per_pr",
                condition=models.Q(pr_number__isnull=False),
            ),
            models.UniqueConstraint(
                fields=["team", "repository", "head_branch"],
                name="unique_review_report_per_branch",
                condition=models.Q(pr_number__isnull=True),
            ),
        ]
        indexes = [
            models.Index(fields=["team", "status"], name="reviewhog_rpt_team_status_idx"),
            models.Index(fields=["signal_report_id"], name="reviewhog_rpt_signal_rpt_idx"),
            # Serves the "recent reviews" API: one user's reports, newest completed turn first.
            models.Index(fields=["team", "acting_user", "-last_run_at"], name="reviewhog_rpt_recent_idx"),
            # Same API's everyone scope: the whole project's reports, newest completed turn first.
            models.Index(fields=["team", "-last_run_at"], name="reviewhog_rpt_team_recent_idx"),
            # The outcome sweep's backlog: published, PR-bound, not yet stamped emitted. The whole
            # predicate lives in the condition, so the index holds only the working set and shrinks
            # as reports are classified; `team` leads it because the cross-team discovery reads
            # DISTINCT team_id off this index and the per-team read filters on team first.
            # `-updated_at` trails it so the per-team read's newest-first slice is an index scan
            # rather than a sort over every pending row.
            models.Index(
                fields=["team", "-updated_at"],
                name="reviewhog_rpt_unclassified_idx",
                condition=models.Q(
                    published_head_sha__isnull=False, pr_number__isnull=False, outcomes_emitted_at__isnull=True
                ),
            ),
        ]


def review_report_artefact_type_choices() -> list[tuple[str, str | Promise]]:
    # Callable so growing the enum doesn't generate a no-op migration.
    return list(ReviewReportArtefact.ArtefactType.choices)


class ReviewReportArtefact(UUIDModel, TeamScopedRootMixin):
    """Work log for a `ReviewReport`, with append-only completed turns.

    Mirrors Signals' `SignalReportArtefact` funnel — the row's type is derived from the content
    model's class and attribution maps to `created_by` / `task` columns — but owns its own types
    and has no auto-start side effects.
    Deduplication can retire superseded findings and verdicts from an unfinished turn.
    """

    class ArtefactType(models.TextChoices):
        ISSUE_FINDING = "issue_finding"
        # A single-agent finding the turn did not keep, with the reason. Only analysis reads it.
        DROPPED_FINDING = "dropped_finding"
        VALIDATION_VERDICT = "validation_verdict"
        # The classified fate of a published finding, written by the outcome-telemetry batch after
        # the PR merged (one per finding); its presence marks the finding already classified.
        FINDING_OUTCOME = "finding_outcome"
        # The resolution stage's per-thread ruling (latest row per thread_id wins).
        THREAD_VERDICT = "thread_verdict"
        # One resolution run's opening work-list; the newest row is the report's latest run.
        RESOLUTION_RUN = "resolution_run"
        TASK_RUN = "task_run"
        COMMIT = "commit"
        CODE_REFERENCE = "code_reference"
        NOTE = "note"
        # Per-turn pipeline working state, read back by the DB-driven resume (head_sha-scoped).
        CHUNK_SET = "chunk_set"
        PERSPECTIVE_SELECTION = "perspective_selection"
        PERSPECTIVE_RESULT = "perspective_result"
        # The turn's fetched PR inputs, stored by reference so stage activities reload them from the
        # DB instead of crossing the Temporal workflow boundary with the big pr_files payload.
        PR_SNAPSHOT = "pr_snapshot"
        # One per executed turn: the ReviewHog version and input fingerprint the turn ran with.
        TURN_MARKER = "turn_marker"

    # Log types accumulate (each call is a new row). Findings and verdicts also append, but their
    # identity is `issue_key` — latest row per key wins at read time — so they get dedicated
    # appenders rather than going through `add_log`.
    LOG_ARTEFACT_TYPES: frozenset[str] = frozenset(
        {ArtefactType.TASK_RUN, ArtefactType.COMMIT, ArtefactType.CODE_REFERENCE, ArtefactType.NOTE}
    )
    # Working-state types accumulate per turn; the resume reads the latest per (head_sha, key).
    WORKING_STATE_ARTEFACT_TYPES: frozenset[str] = frozenset(
        {
            ArtefactType.CHUNK_SET,
            ArtefactType.PERSPECTIVE_SELECTION,
            ArtefactType.PERSPECTIVE_RESULT,
            ArtefactType.PR_SNAPSHOT,
        }
    )

    # db_constraint=False keeps the migration lock-free on hot posthog_team.
    team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    # db_index=False: the (report, type) composite indexes below lead with report_id, so they serve
    # lookups and cascade deletes. A separate single-column index would be redundant.
    report = models.ForeignKey(ReviewReport, on_delete=models.CASCADE, related_name="artefacts", db_index=False)
    type = models.CharField(max_length=100, choices=review_report_artefact_type_choices)
    content = models.TextField()
    # Turn scope, denormalized from content.head_sha so resume loaders can filter in SQL instead of
    # parsing every historical row. Null when the content model carries no head_sha.
    head_sha = models.CharField(max_length=64, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True, null=True)
    # Attribution: exactly one of (created_by, task) is set on new rows, enforced at the write
    # helpers via `ArtefactAttribution`. SET_NULL so deleting a user/task degrades attribution to
    # "system/unknown" rather than destroying the report's work log. db_constraint=False keeps the
    # migration lock-free on hot posthog_user.
    created_by = models.ForeignKey(
        "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False
    )
    task = models.ForeignKey("tasks.Task", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")

    class Meta:
        indexes = [
            models.Index(fields=["report", "type"], name="reviewhog_art_rpt_type_idx"),
            # Latest-wins seeks: WHERE report=? AND type=? ORDER BY created_at DESC.
            models.Index(fields=["report", "type", "-created_at"], name="reviewhog_art_rpt_type_ct_idx"),
        ]

    @classmethod
    def _create(
        cls,
        *,
        team_id: int,
        report_id: str,
        content: ReviewArtefactContent,
        attribution: ArtefactAttribution,
    ) -> "ReviewReportArtefact":
        """Single write funnel: derive the row's type from the content model's class, map
        attribution to columns, and insert.

        Goes through `for_team` so it works outside request context (the cloud/Temporal
        orchestrator has no ambient team scope, and the fail-closed manager would otherwise raise).
        """
        # A task_run's content.task_id is the same association as the row's `task` FK — they must
        # not diverge. The FK comes from attribution, so require task attribution that matches.
        if isinstance(content, TaskRunArtefact) and content.task_id != attribution.task_id:
            raise ArtefactContentValidationError("task_run content.task_id must match the artefact's attributed task")
        return cls.objects.for_team(team_id).create(
            team_id=team_id,
            report_id=report_id,
            type=artefact_type_for(content),
            content=content.model_dump_json(),
            head_sha=getattr(content, "head_sha", None),
            created_by_id=attribution.user_id,
            task_id=attribution.task_id,
        )

    @classmethod
    def append_finding(
        cls, *, team_id: int, report_id: str, content: ReviewIssueFinding, attribution: ArtefactAttribution
    ) -> "ReviewReportArtefact":
        """Append an `issue_finding` (latest row per `issue_key` wins at read time)."""
        return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)

    @classmethod
    def append_dropped_finding(
        cls, *, team_id: int, report_id: str, content: DroppedFindingArtefact, attribution: ArtefactAttribution
    ) -> "ReviewReportArtefact":
        """Append a `dropped_finding` (one per finding a single-agent turn did not keep)."""
        return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)

    @classmethod
    def append_verdict(
        cls, *, team_id: int, report_id: str, content: ValidationVerdict, attribution: ArtefactAttribution
    ) -> "ReviewReportArtefact":
        """Append a `validation_verdict` (latest verdict per `issue_key` wins at read time)."""
        return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)

    @classmethod
    def add_finding_outcome(
        cls, *, team_id: int, report_id: str, content: FindingOutcomeArtefact, attribution: ArtefactAttribution
    ) -> "ReviewReportArtefact":
        """Append a `finding_outcome` (one per published finding; the durable classification record).

        Presence means the finding's outcome is decided and must never be re-decided; the report is
        only *done* once `ReviewReport.outcomes_emitted_at` is stamped after its events flushed.
        """
        return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)

    @classmethod
    def append_thread_verdict(
        cls, *, team_id: int, report_id: str, content: ThreadVerdictArtefact, attribution: ArtefactAttribution
    ) -> "ReviewReportArtefact":
        """Append a `thread_verdict` (latest row per `thread_id` wins at read time)."""
        return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)

    @classmethod
    def append_resolution_run(
        cls, *, team_id: int, report_id: str, content: ResolutionRunArtefact, attribution: ArtefactAttribution
    ) -> "ReviewReportArtefact":
        """Append a `resolution_run` (one per run, at prepare; the newest row is the latest run)."""
        return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)

    @classmethod
    def add_turn_marker(
        cls, *, team_id: int, report_id: str, content: TurnMarkerArtefact, attribution: ArtefactAttribution
    ) -> "ReviewReportArtefact":
        """Append a `turn_marker` (one per executed turn; the newest row of a retried turn wins)."""
        return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)

    @classmethod
    def add_log(
        cls, *, team_id: int, report_id: str, content: ReviewLogArtefactContent, attribution: ArtefactAttribution
    ) -> "ReviewReportArtefact":
        """Append a work-log entry (`task_run` / `commit` / `code_reference` / `note`); these accumulate."""
        if artefact_type_for(content) not in cls.LOG_ARTEFACT_TYPES:
            raise ValueError(f"{type(content).__name__} is not a log artefact content model")
        return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)

    @classmethod
    def add_working_state(
        cls, *, team_id: int, report_id: str, content: ReviewWorkingStateContent, attribution: ArtefactAttribution
    ) -> "ReviewReportArtefact":
        """Append per-turn pipeline working state (`chunk_set` / `perspective_result` / `pr_snapshot`).

        These accumulate; the DB-driven resume reads the latest row per (head_sha, key), so a
        resumed turn reuses completed sandbox work instead of re-running it.
        """
        if artefact_type_for(content) not in cls.WORKING_STATE_ARTEFACT_TYPES:
            raise ValueError(f"{type(content).__name__} is not a working-state artefact content model")
        return cls._create(team_id=team_id, report_id=report_id, content=content, attribution=attribution)


class ReviewSkillConfig(UUIDModel, TeamScopedRootMixin):
    """Per-(team, user, review-skill) enablement for ReviewHog.

    One generic table for which review skills run for a user, discriminated by the skill-name prefix:
    `review-hog-perspective-*` (the review perspectives — **multi-enable**, ≥1 must stay on), plus
    `review-hog-validation-*` (the validator) and `review-hog-blind-spots-*` (the blind-spot check) —
    both **single-active**: exactly one runs, the select endpoint flips the others off, falling back to
    the canonical default when none is set. `enabled=True` means "active for this user" in every case;
    the cardinality rules are enforced in app code, not the DB, the same way the perspective min-1
    floor is.

    A skill is any team `LLMSkill` carrying the prefix (canonical or custom — handled identically);
    canonicals auto-seed on first resolve, customs are switched on via the config API. The skill itself
    stays team-level; this row only gates whether it runs for this user's PRs. Mirrors Signals'
    `SignalScoutConfig` enable/disable, minus the schedule — ReviewHog is PR-triggered, not on a clock.
    `skill_name` is the identity (mirrors scouts keying on it, never `created_by`).
    """

    # db_constraint=False keeps the migration lock-free on hot posthog_team / posthog_user.
    team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    skill_name = models.CharField(max_length=200)
    enabled = models.BooleanField(default=True, db_default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=["team", "user", "skill_name"], name="uniq_review_skill_config_per_user"),
        ]
        indexes = [
            # The loaders seek WHERE team=? AND user=? AND enabled=true to resolve a run's skills.
            models.Index(fields=["team", "user", "enabled"], name="reviewhog_skillcfg_lookup_idx"),
        ]


class ReviewProjectSettings(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):
    """A project's ReviewHog rule: who gets automatic Flash, bot pull requests, and Full defaults.

    One row per root project, created on the first save. Without a row the defaults apply: automatic
    Flash only for people who opt in, no reviews of bot pull requests, and the code defaults for the
    Full review preferences. The rule's people lists are `ReviewRepositoryPerson` rows without a
    repository.
    """

    BotPullRequests = ReviewProjectSettingsBotPullRequests

    team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    flash_for = models.CharField(
        max_length=20,
        choices=AutomaticFlashFor.choices,
        default=AutomaticFlashFor.OFF.value,
        db_default=AutomaticFlashFor.OFF.value,
    )
    bot_prs = models.CharField(
        max_length=10,
        choices=BotPullRequests.choices,
        default=BotPullRequests.SKIP.value,
        db_default=BotPullRequests.SKIP.value,
    )
    # Project defaults for the Full review preferences (see `preferences.PROJECT_DEFAULT_FIELDS`).
    preferences = models.JSONField(default=dict, db_default={}, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=["team"], name="uniq_review_project_settings_per_team"),
        ]

    @classmethod
    def load(cls, team_id: int) -> "ReviewProjectSettings":
        """The project's row, or an unsaved instance carrying the defaults when none exists."""
        row = cls.objects.for_team(team_id).first()
        return row if row is not None else cls(team_id=team_id)

    @classmethod
    def ensure(cls, team_id: int) -> "ReviewProjectSettings":
        """The project's row, created with the defaults when none exists."""
        row, _created = cls.objects.for_team(team_id, canonical=True).get_or_create(team_id=team_id)
        return row

    @classmethod
    def save_changes(cls, team_id: int, changes: Mapping[str, object]) -> None:
        """Apply `changes` to the project rule and its Full review defaults. Omitted keys keep their value.

        Raises `InvalidPreference` for an invalid Full review default.
        """
        with transaction.atomic():
            row = cls.objects.for_team(team_id).select_for_update().get(id=cls.ensure(team_id).id)
            for field in ("flash_for", "bot_prs"):
                if field in changes:
                    setattr(row, field, changes[field])
            preference_changes = {
                key: changes[key] for key in ("urgency_threshold", "celebrate_clean_reviews") if key in changes
            }
            row.preferences = row.defaults.with_changes(preference_changes)
            row.save()

    @property
    def defaults(self) -> ReviewProjectDefaults:
        return ReviewProjectDefaults.resolve(self.preferences)


class ReviewUserSettings(UUIDModel, TeamScopedRootMixin):
    """Per-(team, user) ReviewHog preferences.

    One row per user per project, created on the first save. `preferences` holds only the keys the
    user changed; `preferences.ReviewPreferences` fills in the project and code defaults. Use
    `load_preferences` to read them. The boolean and choice columns are unused: their values moved
    into `preferences`, and the columns stay only so that no migration has to drop them.
    """

    UrgencyThreshold = UrgencyThreshold

    class FlashReasoningEffort(models.TextChoices):
        MEDIUM = "medium", "Medium"
        XHIGH = "xhigh", "Extra high"

    # FKs to the hot posthog_team / posthog_user tables use db_constraint=False so creating this
    # table takes no lock on the parents (app-level enforcement only).
    team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    preferences = models.JSONField(default=dict, db_default={}, blank=True)
    # Unused: values live in preferences.
    review_inbox_prs = models.BooleanField(default=False, db_default=False)
    # Unused: values live in preferences.
    stamphog_review_inbox_prs = models.BooleanField(default=False, db_default=False)
    # Unused: no label starts a review.
    review_labeled_prs = models.BooleanField(default=True, db_default=True)
    # Unused: values live in preferences.
    resolve_comments = models.BooleanField(default=True, db_default=True)
    # Unused: values live in preferences.
    celebrate_clean_reviews = models.BooleanField(default=True, db_default=True)
    # Unused: values live in preferences (`default_review_mode`).
    review_authored_prs = models.BooleanField(default=False, db_default=False)
    # Unused: Flash reviews use the default reasoning effort.
    flash_reasoning_effort = models.CharField(
        max_length=10,
        choices=FlashReasoningEffort.choices,
        default=FlashReasoningEffort.MEDIUM,
        db_default=FlashReasoningEffort.MEDIUM.value,
    )
    # Unused: values live in preferences.
    urgency_threshold = models.CharField(
        max_length=20,
        choices=UrgencyThreshold.choices,
        default=UrgencyThreshold.CONSIDER.value,
        db_default=UrgencyThreshold.CONSIDER.value,
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=["team", "user"], name="uniq_review_user_settings_per_user"),
        ]

    @classmethod
    def load(cls, team_id: int, user_id: int) -> "ReviewUserSettings":
        """The user's settings row, or an unsaved instance carrying the defaults when none exists."""
        row = cls.objects.for_team(team_id).filter(user_id=user_id).first()
        return row if row is not None else cls(team_id=team_id, user_id=user_id)

    @classmethod
    def load_many(cls, team_id: int, user_ids: list[int]) -> dict[int, "ReviewUserSettings"]:
        """`load` for several users in one query; users with no row get the same defaults."""
        rows = {row.user_id: row for row in cls.objects.for_team(team_id).filter(user_id__in=user_ids)}
        return {user_id: rows.get(user_id) or cls(team_id=team_id, user_id=user_id) for user_id in user_ids}

    @classmethod
    def load_preferences(cls, team_id: int, user_id: int) -> ReviewPreferences:
        """The user's effective preferences: their own values over the project and code defaults."""
        return cls.load_preferences_many(team_id, [user_id])[user_id]

    @classmethod
    def load_preferences_many(cls, team_id: int, user_ids: list[int]) -> dict[int, ReviewPreferences]:
        project = ReviewProjectSettings.load(team_id).defaults
        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.

    `all` takes every repository of the installation that no other project selected. At most one
    project can take all repositories of an installation. `selected` takes only the repositories
    this project selected (`ReviewRepository.selected`). Read `ownership.py` for the resolution.
    """

    activity_logging_on_delete = True

    Scope = ReviewInstallationClaimScope

    team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    # The GitHub App installation id, as `Integration.integration_id` stores it.
    installation_id = models.CharField(max_length=64)
    scope = models.CharField(max_length=10, choices=Scope.choices)
    created_by = models.ForeignKey(
        "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=["team", "installation_id"], name="uniq_review_installation_claim"),
            models.UniqueConstraint(
                fields=["installation_id"],
                condition=models.Q(scope="all"),
                name="uniq_review_installation_claim_all",
            ),
        ]


class ReviewRepository(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):
    """A GitHub repository that one project has settings for.

    `selected` includes the repository into this project, also when another project takes all
    repositories of the installation. `flash_for` is the repository exception: null follows the
    project rule (`ReviewProjectSettings.flash_for`). `review_drafts` lets draft pull requests get
    their automatic review when they open. A row that is not selected, has no exception and does not
    review drafts has no meaning and is deleted. A repository has at most one row across all projects, so it
    belongs to one project only.
    """

    activity_logging_on_delete = True

    # db_constraint=False keeps the migration lock-free on hot posthog_team / posthog_user.
    team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    # The installation that last reported the repository. Not part of the identity: a reinstall of
    # the GitHub App gets a new installation id for the same repositories.
    installation_id = models.CharField(max_length=64)
    # Null until a webhook or the repository list shows the id. Renames keep the id, so lookups
    # match the id first and then the name.
    github_repo_id = models.BigIntegerField(null=True, blank=True)
    # `owner/name` as GitHub spells it. GitHub treats the name case-insensitively, so every lookup
    # and the unique constraint compare it lowercased.
    full_name = models.CharField(max_length=200)
    selected = models.BooleanField(default=False, db_default=False)
    flash_for = models.CharField(max_length=20, choices=AutomaticFlashFor.choices, null=True, blank=True)
    review_drafts = models.BooleanField(default=False, db_default=False)
    created_by = models.ForeignKey(
        "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(Lower("full_name"), name="uniq_review_repository_name"),
            models.UniqueConstraint(
                fields=["github_repo_id"],
                condition=models.Q(github_repo_id__isnull=False),
                name="uniq_review_repository_github_id",
            ),
        ]


class ReviewRepositoryPerson(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):
    """A person on one of the two lists of the project rule, or of a repository exception.

    `repository` is null for the lists of the project rule. The lists are separate, so a change of
    `flash_for` does not turn listed people into excepted people. Only the list that matches
    `flash_for` has an effect.
    """

    activity_logging_on_delete = True

    Kind = ReviewRepositoryPersonKind

    team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    repository = models.ForeignKey(ReviewRepository, on_delete=models.CASCADE, related_name="+", null=True, blank=True)
    user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    kind = models.CharField(max_length=20, choices=Kind.choices)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["repository", "user", "kind"],
                condition=models.Q(repository__isnull=False),
                name="uniq_review_repository_person",
            ),
            models.UniqueConstraint(
                fields=["team", "user", "kind"],
                condition=models.Q(repository__isnull=True),
                name="uniq_review_project_person",
            ),
        ]


class ReviewUserRepositoryChoice(UUIDModel, TeamScopedRootMixin):
    """A user's own automatic review choice for their PRs in one repository.

    Keyed by the repository itself, not by a `ReviewRepository` row, so a choice works in every
    repository the project reviews. A choice in a repository that another project reviews stays
    stored but has no effect. No row means the user's default applies, so there is no "follow" value.
    """

    Mode = ReviewUserRepositoryChoiceMode

    team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)
    # The installation that last reported the repository. Not part of the identity, as on `ReviewRepository`.
    installation_id = models.CharField(max_length=64)
    github_repo_id = models.BigIntegerField(null=True, blank=True)
    full_name = models.CharField(max_length=200)
    mode = models.CharField(max_length=10, choices=Mode.choices)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint("team", "user", Lower("full_name"), name="uniq_review_user_repository_choice"),
            models.UniqueConstraint(
                fields=["team", "user", "github_repo_id"],
                condition=models.Q(github_repo_id__isnull=False),
                name="uniq_review_user_repository_choice_id",
            ),
        ]